MDL-55188 events: First deprecation of eventslib.php
[moodle.git] / course / renderer.php
blob01677a5d78b44c15042cc12d6dea27f0d2d4fd6a
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 if ($format != 'navbar') {
439 $output .= $this->output->help_icon("coursesearch", "core");
441 $output .= html_writer::end_tag('form');
443 return $output;
447 * Renders html for completion box on course page
449 * If completion is disabled, returns empty string
450 * If completion is automatic, returns an icon of the current completion state
451 * If completion is manual, returns a form (with an icon inside) that allows user to
452 * toggle completion
454 * @param stdClass $course course object
455 * @param completion_info $completioninfo completion info for the course, it is recommended
456 * to fetch once for all modules in course/section for performance
457 * @param cm_info $mod module to show completion for
458 * @param array $displayoptions display options, not used in core
459 * @return string
461 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
462 global $CFG, $DB;
463 $output = '';
464 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
465 return $output;
467 if ($completioninfo === null) {
468 $completioninfo = new completion_info($course);
470 $completion = $completioninfo->is_enabled($mod);
471 if ($completion == COMPLETION_TRACKING_NONE) {
472 if ($this->page->user_is_editing()) {
473 $output .= html_writer::span('&nbsp;', 'filler');
475 return $output;
478 $completiondata = $completioninfo->get_data($mod, true);
479 $completionicon = '';
481 if ($this->page->user_is_editing()) {
482 switch ($completion) {
483 case COMPLETION_TRACKING_MANUAL :
484 $completionicon = 'manual-enabled'; break;
485 case COMPLETION_TRACKING_AUTOMATIC :
486 $completionicon = 'auto-enabled'; break;
488 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
489 switch($completiondata->completionstate) {
490 case COMPLETION_INCOMPLETE:
491 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
492 break;
493 case COMPLETION_COMPLETE:
494 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
495 break;
497 } else { // Automatic
498 switch($completiondata->completionstate) {
499 case COMPLETION_INCOMPLETE:
500 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
501 break;
502 case COMPLETION_COMPLETE:
503 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
504 break;
505 case COMPLETION_COMPLETE_PASS:
506 $completionicon = 'auto-pass'; break;
507 case COMPLETION_COMPLETE_FAIL:
508 $completionicon = 'auto-fail'; break;
511 if ($completionicon) {
512 $formattedname = $mod->get_formatted_name();
513 if ($completiondata->overrideby) {
514 $args = new stdClass();
515 $args->modname = $formattedname;
516 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
517 $args->overrideuser = fullname($overridebyuser);
518 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
519 } else {
520 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
523 if ($this->page->user_is_editing()) {
524 // When editing, the icon is just an image.
525 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
526 array('title' => $imgalt, 'class' => 'iconsmall'));
527 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
528 array('class' => 'autocompletion'));
529 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
530 $newstate =
531 $completiondata->completionstate == COMPLETION_COMPLETE
532 ? COMPLETION_INCOMPLETE
533 : COMPLETION_COMPLETE;
534 // In manual mode the icon is a toggle form...
536 // If this completion state is used by the
537 // conditional activities system, we need to turn
538 // off the JS.
539 $extraclass = '';
540 if (!empty($CFG->enableavailability) &&
541 core_availability\info::completion_value_used($course, $mod->id)) {
542 $extraclass = ' preventjs';
544 $output .= html_writer::start_tag('form', array('method' => 'post',
545 'action' => new moodle_url('/course/togglecompletion.php'),
546 'class' => 'togglecompletion'. $extraclass));
547 $output .= html_writer::start_tag('div');
548 $output .= html_writer::empty_tag('input', array(
549 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
550 $output .= html_writer::empty_tag('input', array(
551 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
552 $output .= html_writer::empty_tag('input', array(
553 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
554 $output .= html_writer::empty_tag('input', array(
555 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
556 $output .= html_writer::tag('button',
557 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
558 array('class' => 'btn btn-link', 'title' => $imgalt));
559 $output .= html_writer::end_tag('div');
560 $output .= html_writer::end_tag('form');
561 } else {
562 // In auto mode, the icon is just an image.
563 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
564 array('title' => $imgalt));
565 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
566 array('class' => 'autocompletion'));
569 return $output;
573 * Checks if course module has any conditions that may make it unavailable for
574 * all or some of the students
576 * This function is internal and is only used to create CSS classes for the module name/text
578 * @param cm_info $mod
579 * @return bool
581 protected function is_cm_conditionally_hidden(cm_info $mod) {
582 global $CFG;
583 $conditionalhidden = false;
584 if (!empty($CFG->enableavailability)) {
585 $info = new \core_availability\info_module($mod);
586 $conditionalhidden = !$info->is_available_for_all();
588 return $conditionalhidden;
592 * Renders html to display a name with the link to the course module on a course page
594 * If module is unavailable for user but still needs to be displayed
595 * in the list, just the name is returned without a link
597 * Note, that for course modules that never have separate pages (i.e. labels)
598 * this function return an empty string
600 * @param cm_info $mod
601 * @param array $displayoptions
602 * @return string
604 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
605 if (!$mod->is_visible_on_course_page() || !$mod->url) {
606 // Nothing to be displayed to the user.
607 return '';
610 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
611 $groupinglabel = $mod->get_grouping_label($textclasses);
613 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
614 // to get the display title of the activity.
615 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
616 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
617 $groupinglabel;
621 * Returns the CSS classes for the activity name/content
623 * For items which are hidden, unavailable or stealth but should be displayed
624 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
625 * Students will also see as dimmed activities names that are not yet available
626 * but should still be displayed (without link) with availability info.
628 * @param cm_info $mod
629 * @return array array of two elements ($linkclasses, $textclasses)
631 protected function course_section_cm_classes(cm_info $mod) {
632 $linkclasses = '';
633 $textclasses = '';
634 if ($mod->uservisible) {
635 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
636 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
637 has_capability('moodle/course:viewhiddenactivities', $mod->context);
638 if ($accessiblebutdim) {
639 $linkclasses .= ' dimmed';
640 $textclasses .= ' dimmed_text';
641 if ($conditionalhidden) {
642 $linkclasses .= ' conditionalhidden';
643 $textclasses .= ' conditionalhidden';
646 if ($mod->is_stealth()) {
647 // Stealth activity is the one that is not visible on course page.
648 // It still may be displayed to the users who can manage it.
649 $linkclasses .= ' stealth';
650 $textclasses .= ' stealth';
652 } else {
653 $linkclasses .= ' dimmed';
654 $textclasses .= ' dimmed dimmed_text';
656 return array($linkclasses, $textclasses);
660 * Renders html to display a name with the link to the course module on a course page
662 * If module is unavailable for user but still needs to be displayed
663 * in the list, just the name is returned without a link
665 * Note, that for course modules that never have separate pages (i.e. labels)
666 * this function return an empty string
668 * @param cm_info $mod
669 * @param array $displayoptions
670 * @return string
672 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
673 $output = '';
674 $url = $mod->url;
675 if (!$mod->is_visible_on_course_page() || !$url) {
676 // Nothing to be displayed to the user.
677 return $output;
680 //Accessibility: for files get description via icon, this is very ugly hack!
681 $instancename = $mod->get_formatted_name();
682 $altname = $mod->modfullname;
683 // Avoid unnecessary duplication: if e.g. a forum name already
684 // includes the word forum (or Forum, etc) then it is unhelpful
685 // to include that in the accessible description that is added.
686 if (false !== strpos(core_text::strtolower($instancename),
687 core_text::strtolower($altname))) {
688 $altname = '';
690 // File type after name, for alphabetic lists (screen reader).
691 if ($altname) {
692 $altname = get_accesshide(' '.$altname);
695 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
697 // Get on-click attribute value if specified and decode the onclick - it
698 // has already been encoded for display (puke).
699 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
701 // Display link itself.
702 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
703 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
704 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
705 if ($mod->uservisible) {
706 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick));
707 } else {
708 // We may be displaying this just in order to show information
709 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
710 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
712 return $output;
716 * Renders html to display the module content on the course page (i.e. text of the labels)
718 * @param cm_info $mod
719 * @param array $displayoptions
720 * @return string
722 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
723 $output = '';
724 if (!$mod->is_visible_on_course_page()) {
725 // nothing to be displayed to the user
726 return $output;
728 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
729 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
730 if ($mod->url && $mod->uservisible) {
731 if ($content) {
732 // If specified, display extra content after link.
733 $output = html_writer::tag('div', $content, array('class' =>
734 trim('contentafterlink ' . $textclasses)));
736 } else {
737 $groupinglabel = $mod->get_grouping_label($textclasses);
739 // No link, so display only content.
740 $output = html_writer::tag('div', $content . $groupinglabel,
741 array('class' => 'contentwithoutlink ' . $textclasses));
743 return $output;
747 * Displays availability info for a course section or course module
749 * @param string $text
750 * @param string $additionalclasses
751 * @return string
753 public function availability_info($text, $additionalclasses = '') {
755 $data = ['text' => $text, 'classes' => $additionalclasses];
756 $additionalclasses = array_filter(explode(' ', $additionalclasses));
758 if (in_array('ishidden', $additionalclasses)) {
759 $data['ishidden'] = 1;
761 } else if (in_array('isstealth', $additionalclasses)) {
762 $data['isstealth'] = 1;
764 } else if (in_array('isrestricted', $additionalclasses)) {
765 $data['isrestricted'] = 1;
767 if (in_array('isfullinfo', $additionalclasses)) {
768 $data['isfullinfo'] = 1;
772 return $this->render_from_template('core/availability_info', $data);
776 * Renders HTML to show course module availability information (for someone who isn't allowed
777 * to see the activity itself, or for staff)
779 * @param cm_info $mod
780 * @param array $displayoptions
781 * @return string
783 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
784 global $CFG;
785 $output = '';
786 if (!$mod->is_visible_on_course_page()) {
787 return $output;
789 if (!$mod->uservisible) {
790 // this is a student who is not allowed to see the module but might be allowed
791 // to see availability info (i.e. "Available from ...")
792 if (!empty($mod->availableinfo)) {
793 $formattedinfo = \core_availability\info::format_info(
794 $mod->availableinfo, $mod->get_course());
795 $output = $this->availability_info($formattedinfo, 'isrestricted');
797 return $output;
799 // this is a teacher who is allowed to see module but still should see the
800 // information that module is not available to all/some students
801 $modcontext = context_module::instance($mod->id);
802 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
803 if ($canviewhidden && !$mod->visible) {
804 // This module is hidden but current user has capability to see it.
805 // Do not display the availability info if the whole section is hidden.
806 if ($mod->get_section_info()->visible) {
807 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
809 } else if ($mod->is_stealth()) {
810 // This module is available but is normally not displayed on the course page
811 // (this user can see it because they can manage it).
812 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
814 if ($canviewhidden && !empty($CFG->enableavailability)) {
815 // Display information about conditional availability.
816 // Don't add availability information if user is not editing and activity is hidden.
817 if ($mod->visible || $this->page->user_is_editing()) {
818 $hidinfoclass = 'isrestricted isfullinfo';
819 if (!$mod->visible) {
820 $hidinfoclass .= ' hide';
822 $ci = new \core_availability\info_module($mod);
823 $fullinfo = $ci->get_full_information();
824 if ($fullinfo) {
825 $formattedinfo = \core_availability\info::format_info(
826 $fullinfo, $mod->get_course());
827 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
831 return $output;
835 * Renders HTML to display one course module for display within a section.
837 * This function calls:
838 * {@link core_course_renderer::course_section_cm()}
840 * @param stdClass $course
841 * @param completion_info $completioninfo
842 * @param cm_info $mod
843 * @param int|null $sectionreturn
844 * @param array $displayoptions
845 * @return String
847 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
848 $output = '';
849 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
850 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
851 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
853 return $output;
857 * Renders HTML to display one course module in a course section
859 * This includes link, content, availability, completion info and additional information
860 * that module type wants to display (i.e. number of unread forum posts)
862 * This function calls:
863 * {@link core_course_renderer::course_section_cm_name()}
864 * {@link core_course_renderer::course_section_cm_text()}
865 * {@link core_course_renderer::course_section_cm_availability()}
866 * {@link core_course_renderer::course_section_cm_completion()}
867 * {@link course_get_cm_edit_actions()}
868 * {@link core_course_renderer::course_section_cm_edit_actions()}
870 * @param stdClass $course
871 * @param completion_info $completioninfo
872 * @param cm_info $mod
873 * @param int|null $sectionreturn
874 * @param array $displayoptions
875 * @return string
877 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
878 $output = '';
879 // We return empty string (because course module will not be displayed at all)
880 // if:
881 // 1) The activity is not visible to users
882 // and
883 // 2) The 'availableinfo' is empty, i.e. the activity was
884 // hidden in a way that leaves no info, such as using the
885 // eye icon.
886 if (!$mod->is_visible_on_course_page()) {
887 return $output;
890 $indentclasses = 'mod-indent';
891 if (!empty($mod->indent)) {
892 $indentclasses .= ' mod-indent-'.$mod->indent;
893 if ($mod->indent > 15) {
894 $indentclasses .= ' mod-indent-huge';
898 $output .= html_writer::start_tag('div');
900 if ($this->page->user_is_editing()) {
901 $output .= course_get_cm_move($mod, $sectionreturn);
904 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
906 // This div is used to indent the content.
907 $output .= html_writer::div('', $indentclasses);
909 // Start a wrapper for the actual content to keep the indentation consistent
910 $output .= html_writer::start_tag('div');
912 // Display the link to the module (or do nothing if module has no url)
913 $cmname = $this->course_section_cm_name($mod, $displayoptions);
915 if (!empty($cmname)) {
916 // Start the div for the activity title, excluding the edit icons.
917 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
918 $output .= $cmname;
921 // Module can put text after the link (e.g. forum unread)
922 $output .= $mod->afterlink;
924 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
925 $output .= html_writer::end_tag('div'); // .activityinstance
928 // If there is content but NO link (eg label), then display the
929 // content here (BEFORE any icons). In this case cons must be
930 // displayed after the content so that it makes more sense visually
931 // and for accessibility reasons, e.g. if you have a one-line label
932 // it should work similarly (at least in terms of ordering) to an
933 // activity.
934 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
935 $url = $mod->url;
936 if (empty($url)) {
937 $output .= $contentpart;
940 $modicons = '';
941 if ($this->page->user_is_editing()) {
942 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
943 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
944 $modicons .= $mod->afterediticons;
947 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
949 if (!empty($modicons)) {
950 $output .= html_writer::span($modicons, 'actions');
953 // Show availability info (if module is not available).
954 $output .= $this->course_section_cm_availability($mod, $displayoptions);
956 // If there is content AND a link, then display the content here
957 // (AFTER any icons). Otherwise it was displayed before
958 if (!empty($url)) {
959 $output .= $contentpart;
962 $output .= html_writer::end_tag('div'); // $indentclasses
964 // End of indentation div.
965 $output .= html_writer::end_tag('div');
967 $output .= html_writer::end_tag('div');
968 return $output;
972 * Message displayed to the user when they try to access unavailable activity following URL
974 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
975 * notification only. It also does not check if module is visible on course page or not.
977 * The message will be displayed inside notification!
979 * @param cm_info $cm
980 * @return string
982 public function course_section_cm_unavailable_error_message(cm_info $cm) {
983 if ($cm->uservisible) {
984 return null;
986 if (!$cm->availableinfo) {
987 return get_string('activityiscurrentlyhidden');
990 $altname = get_accesshide(' ' . $cm->modfullname);
991 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
992 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
993 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
994 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
995 return html_writer::div($name, 'activityinstance-error') .
996 html_writer::div($formattedinfo, 'availabilityinfo-error');
1000 * Renders HTML to display a list of course modules in a course section
1001 * Also displays "move here" controls in Javascript-disabled mode
1003 * This function calls {@link core_course_renderer::course_section_cm()}
1005 * @param stdClass $course course object
1006 * @param int|stdClass|section_info $section relative section number or section object
1007 * @param int $sectionreturn section number to return to
1008 * @param int $displayoptions
1009 * @return void
1011 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1012 global $USER;
1014 $output = '';
1015 $modinfo = get_fast_modinfo($course);
1016 if (is_object($section)) {
1017 $section = $modinfo->get_section_info($section->section);
1018 } else {
1019 $section = $modinfo->get_section_info($section);
1021 $completioninfo = new completion_info($course);
1023 // check if we are currently in the process of moving a module with JavaScript disabled
1024 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1025 if ($ismoving) {
1026 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1027 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1030 // Get the list of modules visible to user (excluding the module being moved if there is one)
1031 $moduleshtml = array();
1032 if (!empty($modinfo->sections[$section->section])) {
1033 foreach ($modinfo->sections[$section->section] as $modnumber) {
1034 $mod = $modinfo->cms[$modnumber];
1036 if ($ismoving and $mod->id == $USER->activitycopy) {
1037 // do not display moving mod
1038 continue;
1041 if ($modulehtml = $this->course_section_cm_list_item($course,
1042 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1043 $moduleshtml[$modnumber] = $modulehtml;
1048 $sectionoutput = '';
1049 if (!empty($moduleshtml) || $ismoving) {
1050 foreach ($moduleshtml as $modnumber => $modulehtml) {
1051 if ($ismoving) {
1052 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1053 $sectionoutput .= html_writer::tag('li',
1054 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1055 array('class' => 'movehere'));
1058 $sectionoutput .= $modulehtml;
1061 if ($ismoving) {
1062 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1063 $sectionoutput .= html_writer::tag('li',
1064 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1065 array('class' => 'movehere'));
1069 // Always output the section module list.
1070 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1072 return $output;
1076 * Displays a custom list of courses with paging bar if necessary
1078 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1079 * appears under the list.
1081 * If both $paginationurl and $totalcount are specified, and $totalcount is
1082 * bigger than count($courses), a paging bar is displayed above and under the
1083 * courses list.
1085 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1086 * @param bool $showcategoryname whether to add category name to the course description
1087 * @param string $additionalclasses additional CSS classes to add to the div.courses
1088 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1089 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1090 * @param int $page current page number (defaults to 0 referring to the first page)
1091 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1092 * @return string
1094 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1095 global $CFG;
1096 // create instance of coursecat_helper to pass display options to function rendering courses list
1097 $chelper = new coursecat_helper();
1098 if ($showcategoryname) {
1099 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1100 } else {
1101 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1103 if ($totalcount !== null && $paginationurl !== null) {
1104 // add options to display pagination
1105 if ($perpage === null) {
1106 $perpage = $CFG->coursesperpage;
1108 $chelper->set_courses_display_options(array(
1109 'limit' => $perpage,
1110 'offset' => ((int)$page) * $perpage,
1111 'paginationurl' => $paginationurl,
1113 } else if ($paginationurl !== null) {
1114 // add options to display 'View more' link
1115 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1116 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1118 $chelper->set_attributes(array('class' => $additionalclasses));
1119 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1120 return $content;
1124 * Displays one course in the list of courses.
1126 * This is an internal function, to display an information about just one course
1127 * please use {@link core_course_renderer::course_info_box()}
1129 * @param coursecat_helper $chelper various display options
1130 * @param course_in_list|stdClass $course
1131 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1132 * depend on the course position in list - first/last/even/odd)
1133 * @return string
1135 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1136 global $CFG;
1137 if (!isset($this->strings->summary)) {
1138 $this->strings->summary = get_string('summary');
1140 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1141 return '';
1143 if ($course instanceof stdClass) {
1144 require_once($CFG->libdir. '/coursecatlib.php');
1145 $course = new course_in_list($course);
1147 $content = '';
1148 $classes = trim('coursebox clearfix '. $additionalclasses);
1149 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1150 $nametag = 'h3';
1151 } else {
1152 $classes .= ' collapsed';
1153 $nametag = 'div';
1156 // .coursebox
1157 $content .= html_writer::start_tag('div', array(
1158 'class' => $classes,
1159 'data-courseid' => $course->id,
1160 'data-type' => self::COURSECAT_TYPE_COURSE,
1163 $content .= html_writer::start_tag('div', array('class' => 'info'));
1165 // course name
1166 $coursename = $chelper->get_course_formatted_name($course);
1167 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1168 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1169 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1170 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1171 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1172 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1173 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1174 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1175 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1176 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1177 // Make sure JS file to expand course content is included.
1178 $this->coursecat_include_js();
1181 $content .= html_writer::end_tag('div'); // .moreinfo
1183 // print enrolmenticons
1184 if ($icons = enrol_get_course_info_icons($course)) {
1185 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1186 foreach ($icons as $pix_icon) {
1187 $content .= $this->render($pix_icon);
1189 $content .= html_writer::end_tag('div'); // .enrolmenticons
1192 $content .= html_writer::end_tag('div'); // .info
1194 $content .= html_writer::start_tag('div', array('class' => 'content'));
1195 $content .= $this->coursecat_coursebox_content($chelper, $course);
1196 $content .= html_writer::end_tag('div'); // .content
1198 $content .= html_writer::end_tag('div'); // .coursebox
1199 return $content;
1203 * Returns HTML to display course content (summary, course contacts and optionally category name)
1205 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1207 * @param coursecat_helper $chelper various display options
1208 * @param stdClass|course_in_list $course
1209 * @return string
1211 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1212 global $CFG;
1213 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1214 return '';
1216 if ($course instanceof stdClass) {
1217 require_once($CFG->libdir. '/coursecatlib.php');
1218 $course = new course_in_list($course);
1220 $content = '';
1222 // display course summary
1223 if ($course->has_summary()) {
1224 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1225 $content .= $chelper->get_course_formatted_summary($course,
1226 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1227 $content .= html_writer::end_tag('div'); // .summary
1230 // display course overview files
1231 $contentimages = $contentfiles = '';
1232 foreach ($course->get_course_overviewfiles() as $file) {
1233 $isimage = $file->is_valid_image();
1234 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1235 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1236 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1237 if ($isimage) {
1238 $contentimages .= html_writer::tag('div',
1239 html_writer::empty_tag('img', array('src' => $url)),
1240 array('class' => 'courseimage'));
1241 } else {
1242 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1243 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1244 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1245 $contentfiles .= html_writer::tag('span',
1246 html_writer::link($url, $filename),
1247 array('class' => 'coursefile fp-filename-icon'));
1250 $content .= $contentimages. $contentfiles;
1252 // display course contacts. See course_in_list::get_course_contacts()
1253 if ($course->has_course_contacts()) {
1254 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1255 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1256 $name = $coursecontact['rolename'].': '.
1257 html_writer::link(new moodle_url('/user/view.php',
1258 array('id' => $userid, 'course' => SITEID)),
1259 $coursecontact['username']);
1260 $content .= html_writer::tag('li', $name);
1262 $content .= html_writer::end_tag('ul'); // .teachers
1265 // display course category if necessary (for example in search results)
1266 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1267 require_once($CFG->libdir. '/coursecatlib.php');
1268 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1269 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1270 $content .= get_string('category').': '.
1271 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1272 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1273 $content .= html_writer::end_tag('div'); // .coursecat
1277 return $content;
1281 * Renders the list of courses
1283 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1284 * method from outside of the class
1286 * If list of courses is specified in $courses; the argument $chelper is only used
1287 * to retrieve display options and attributes, only methods get_show_courses(),
1288 * get_courses_display_option() and get_and_erase_attributes() are called.
1290 * @param coursecat_helper $chelper various display options
1291 * @param array $courses the list of courses to display
1292 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1293 * defaulted to count($courses)
1294 * @return string
1296 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1297 global $CFG;
1298 if ($totalcount === null) {
1299 $totalcount = count($courses);
1301 if (!$totalcount) {
1302 // Courses count is cached during courses retrieval.
1303 return '';
1306 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1307 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1308 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1309 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1310 } else {
1311 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1315 // prepare content of paging bar if it is needed
1316 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1317 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1318 if ($totalcount > count($courses)) {
1319 // there are more results that can fit on one page
1320 if ($paginationurl) {
1321 // the option paginationurl was specified, display pagingbar
1322 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1323 $page = $chelper->get_courses_display_option('offset') / $perpage;
1324 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1325 $paginationurl->out(false, array('perpage' => $perpage)));
1326 if ($paginationallowall) {
1327 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1328 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1330 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1331 // the option for 'View more' link was specified, display more link
1332 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1333 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1334 array('class' => 'paging paging-morelink'));
1336 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1337 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1338 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1339 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1342 // display list of courses
1343 $attributes = $chelper->get_and_erase_attributes('courses');
1344 $content = html_writer::start_tag('div', $attributes);
1346 if (!empty($pagingbar)) {
1347 $content .= $pagingbar;
1350 $coursecount = 0;
1351 foreach ($courses as $course) {
1352 $coursecount ++;
1353 $classes = ($coursecount%2) ? 'odd' : 'even';
1354 if ($coursecount == 1) {
1355 $classes .= ' first';
1357 if ($coursecount >= count($courses)) {
1358 $classes .= ' last';
1360 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1363 if (!empty($pagingbar)) {
1364 $content .= $pagingbar;
1366 if (!empty($morelink)) {
1367 $content .= $morelink;
1370 $content .= html_writer::end_tag('div'); // .courses
1371 return $content;
1375 * Renders the list of subcategories in a category
1377 * @param coursecat_helper $chelper various display options
1378 * @param coursecat $coursecat
1379 * @param int $depth depth of the category in the current tree
1380 * @return string
1382 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1383 global $CFG;
1384 $subcategories = array();
1385 if (!$chelper->get_categories_display_option('nodisplay')) {
1386 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1388 $totalcount = $coursecat->get_children_count();
1389 if (!$totalcount) {
1390 // Note that we call coursecat::get_children_count() AFTER coursecat::get_children() to avoid extra DB requests.
1391 // Categories count is cached during children categories retrieval.
1392 return '';
1395 // prepare content of paging bar or more link if it is needed
1396 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1397 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1398 if ($totalcount > count($subcategories)) {
1399 if ($paginationurl) {
1400 // the option 'paginationurl was specified, display pagingbar
1401 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1402 $page = $chelper->get_categories_display_option('offset') / $perpage;
1403 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1404 $paginationurl->out(false, array('perpage' => $perpage)));
1405 if ($paginationallowall) {
1406 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1407 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1409 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1410 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1411 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1412 $viewmoreurl->param('categoryid', $coursecat->id);
1414 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1415 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1416 array('class' => 'paging paging-morelink'));
1418 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1419 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1420 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1421 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1424 // display list of subcategories
1425 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1427 if (!empty($pagingbar)) {
1428 $content .= $pagingbar;
1431 foreach ($subcategories as $subcategory) {
1432 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1435 if (!empty($pagingbar)) {
1436 $content .= $pagingbar;
1438 if (!empty($morelink)) {
1439 $content .= $morelink;
1442 $content .= html_writer::end_tag('div');
1443 return $content;
1447 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1449 protected function coursecat_include_js() {
1450 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1451 return;
1454 // We must only load this module once.
1455 $this->page->requires->yui_module('moodle-course-categoryexpander',
1456 'Y.Moodle.course.categoryexpander.init');
1460 * Returns HTML to display the subcategories and courses in the given category
1462 * This method is re-used by AJAX to expand content of not loaded category
1464 * @param coursecat_helper $chelper various display options
1465 * @param coursecat $coursecat
1466 * @param int $depth depth of the category in the current tree
1467 * @return string
1469 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1470 $content = '';
1471 // Subcategories
1472 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1474 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1475 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1476 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1477 if ($showcoursesauto && $depth) {
1478 // this is definitely collapsed mode
1479 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1482 // Courses
1483 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1484 $courses = array();
1485 if (!$chelper->get_courses_display_option('nodisplay')) {
1486 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1488 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1489 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1490 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1491 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1494 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1497 if ($showcoursesauto) {
1498 // restore the show_courses back to AUTO
1499 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1502 return $content;
1506 * Returns HTML to display a course category as a part of a tree
1508 * This is an internal function, to display a particular category and all its contents
1509 * use {@link core_course_renderer::course_category()}
1511 * @param coursecat_helper $chelper various display options
1512 * @param coursecat $coursecat
1513 * @param int $depth depth of this category in the current tree
1514 * @return string
1516 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1517 // open category tag
1518 $classes = array('category');
1519 if (empty($coursecat->visible)) {
1520 $classes[] = 'dimmed_category';
1522 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1523 // do not load content
1524 $categorycontent = '';
1525 $classes[] = 'notloaded';
1526 if ($coursecat->get_children_count() ||
1527 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1528 $classes[] = 'with_children';
1529 $classes[] = 'collapsed';
1531 } else {
1532 // load category content
1533 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1534 $classes[] = 'loaded';
1535 if (!empty($categorycontent)) {
1536 $classes[] = 'with_children';
1537 // Category content loaded with children.
1538 $this->categoryexpandedonload = true;
1542 // Make sure JS file to expand category content is included.
1543 $this->coursecat_include_js();
1545 $content = html_writer::start_tag('div', array(
1546 'class' => join(' ', $classes),
1547 'data-categoryid' => $coursecat->id,
1548 'data-depth' => $depth,
1549 'data-showcourses' => $chelper->get_show_courses(),
1550 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1553 // category name
1554 $categoryname = $coursecat->get_formatted_name();
1555 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1556 array('categoryid' => $coursecat->id)),
1557 $categoryname);
1558 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1559 && ($coursescount = $coursecat->get_courses_count())) {
1560 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1561 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1563 $content .= html_writer::start_tag('div', array('class' => 'info'));
1565 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1566 $content .= html_writer::end_tag('div'); // .info
1568 // add category content to the output
1569 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1571 $content .= html_writer::end_tag('div'); // .category
1573 // Return the course category tree HTML
1574 return $content;
1578 * Returns HTML to display a tree of subcategories and courses in the given category
1580 * @param coursecat_helper $chelper various display options
1581 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1582 * @return string
1584 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1585 // Reset the category expanded flag for this course category tree first.
1586 $this->categoryexpandedonload = false;
1587 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1588 if (empty($categorycontent)) {
1589 return '';
1592 // Start content generation
1593 $content = '';
1594 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1595 $content .= html_writer::start_tag('div', $attributes);
1597 if ($coursecat->get_children_count()) {
1598 $classes = array(
1599 'collapseexpand',
1602 // Check if the category content contains subcategories with children's content loaded.
1603 if ($this->categoryexpandedonload) {
1604 $classes[] = 'collapse-all';
1605 $linkname = get_string('collapseall');
1606 } else {
1607 $linkname = get_string('expandall');
1610 // Only show the collapse/expand if there are children to expand.
1611 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1612 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1613 $content .= html_writer::end_tag('div');
1614 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1617 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1619 $content .= html_writer::end_tag('div'); // .course_category_tree
1621 return $content;
1625 * Renders HTML to display particular course category - list of it's subcategories and courses
1627 * Invoked from /course/index.php
1629 * @param int|stdClass|coursecat $category
1631 public function course_category($category) {
1632 global $CFG;
1633 require_once($CFG->libdir. '/coursecatlib.php');
1634 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1635 $site = get_site();
1636 $output = '';
1638 if (can_edit_in_category($coursecat->id)) {
1639 // Add 'Manage' button if user has permissions to edit this category.
1640 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1641 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1642 $this->page->set_button($managebutton);
1644 if (!$coursecat->id) {
1645 if (coursecat::count_all() == 1) {
1646 // There exists only one category in the system, do not display link to it
1647 $coursecat = coursecat::get_default();
1648 $strfulllistofcourses = get_string('fulllistofcourses');
1649 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1650 } else {
1651 $strcategories = get_string('categories');
1652 $this->page->set_title("$site->shortname: $strcategories");
1654 } else {
1655 $title = $site->shortname;
1656 if (coursecat::count_all() > 1) {
1657 $title .= ": ". $coursecat->get_formatted_name();
1659 $this->page->set_title($title);
1661 // Print the category selector
1662 if (coursecat::count_all() > 1) {
1663 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1664 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1665 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1666 $select->set_label(get_string('categories').':');
1667 $output .= $this->render($select);
1668 $output .= html_writer::end_tag('div'); // .categorypicker
1672 // Print current category description
1673 $chelper = new coursecat_helper();
1674 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1675 $output .= $this->box($description, array('class' => 'generalbox info'));
1678 // Prepare parameters for courses and categories lists in the tree
1679 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1680 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1682 $coursedisplayoptions = array();
1683 $catdisplayoptions = array();
1684 $browse = optional_param('browse', null, PARAM_ALPHA);
1685 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1686 $page = optional_param('page', 0, PARAM_INT);
1687 $baseurl = new moodle_url('/course/index.php');
1688 if ($coursecat->id) {
1689 $baseurl->param('categoryid', $coursecat->id);
1691 if ($perpage != $CFG->coursesperpage) {
1692 $baseurl->param('perpage', $perpage);
1694 $coursedisplayoptions['limit'] = $perpage;
1695 $catdisplayoptions['limit'] = $perpage;
1696 if ($browse === 'courses' || !$coursecat->has_children()) {
1697 $coursedisplayoptions['offset'] = $page * $perpage;
1698 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1699 $catdisplayoptions['nodisplay'] = true;
1700 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1701 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1702 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1703 $coursedisplayoptions['nodisplay'] = true;
1704 $catdisplayoptions['offset'] = $page * $perpage;
1705 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1706 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1707 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1708 } else {
1709 // we have a category that has both subcategories and courses, display pagination separately
1710 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1711 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1713 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1714 // Add course search form.
1715 $output .= $this->course_search_form();
1717 // Display course category tree.
1718 $output .= $this->coursecat_tree($chelper, $coursecat);
1720 // Add action buttons
1721 $output .= $this->container_start('buttons');
1722 $context = get_category_or_system_context($coursecat->id);
1723 if (has_capability('moodle/course:create', $context)) {
1724 // Print link to create a new course, for the 1st available category.
1725 if ($coursecat->id) {
1726 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1727 } else {
1728 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1730 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1732 ob_start();
1733 if (coursecat::count_all() == 1) {
1734 print_course_request_buttons(context_system::instance());
1735 } else {
1736 print_course_request_buttons($context);
1738 $output .= ob_get_contents();
1739 ob_end_clean();
1740 $output .= $this->container_end();
1742 return $output;
1746 * Serves requests to /course/category.ajax.php
1748 * In this renderer implementation it may expand the category content or
1749 * course content.
1751 * @return string
1752 * @throws coding_exception
1754 public function coursecat_ajax() {
1755 global $DB, $CFG;
1756 require_once($CFG->libdir. '/coursecatlib.php');
1758 $type = required_param('type', PARAM_INT);
1760 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1761 // This is a request for a category list of some kind.
1762 $categoryid = required_param('categoryid', PARAM_INT);
1763 $showcourses = required_param('showcourses', PARAM_INT);
1764 $depth = required_param('depth', PARAM_INT);
1766 $category = coursecat::get($categoryid);
1768 $chelper = new coursecat_helper();
1769 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1770 $coursedisplayoptions = array(
1771 'limit' => $CFG->coursesperpage,
1772 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1774 $catdisplayoptions = array(
1775 'limit' => $CFG->coursesperpage,
1776 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1778 $chelper->set_show_courses($showcourses)->
1779 set_courses_display_options($coursedisplayoptions)->
1780 set_categories_display_options($catdisplayoptions);
1782 return $this->coursecat_category_content($chelper, $category, $depth);
1783 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1784 // This is a request for the course information.
1785 $courseid = required_param('courseid', PARAM_INT);
1787 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1789 $chelper = new coursecat_helper();
1790 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1791 return $this->coursecat_coursebox_content($chelper, $course);
1792 } else {
1793 throw new coding_exception('Invalid request type');
1798 * Renders html to display search result page
1800 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1801 * @return string
1803 public function search_courses($searchcriteria) {
1804 global $CFG;
1805 $content = '';
1806 if (!empty($searchcriteria)) {
1807 // print search results
1808 require_once($CFG->libdir. '/coursecatlib.php');
1810 $displayoptions = array('sort' => array('displayname' => 1));
1811 // take the current page and number of results per page from query
1812 $perpage = optional_param('perpage', 0, PARAM_RAW);
1813 if ($perpage !== 'all') {
1814 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1815 $page = optional_param('page', 0, PARAM_INT);
1816 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1818 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1819 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1820 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1822 $class = 'course-search-result';
1823 foreach ($searchcriteria as $key => $value) {
1824 if (!empty($value)) {
1825 $class .= ' course-search-result-'. $key;
1828 $chelper = new coursecat_helper();
1829 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1830 set_courses_display_options($displayoptions)->
1831 set_search_criteria($searchcriteria)->
1832 set_attributes(array('class' => $class));
1834 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1835 $totalcount = coursecat::search_courses_count($searchcriteria);
1836 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1838 if (!$totalcount) {
1839 if (!empty($searchcriteria['search'])) {
1840 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1841 } else {
1842 $content .= $this->heading(get_string('novalidcourses'));
1844 } else {
1845 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1846 $content .= $courseslist;
1849 if (!empty($searchcriteria['search'])) {
1850 // print search form only if there was a search by search string, otherwise it is confusing
1851 $content .= $this->box_start('generalbox mdl-align');
1852 $content .= $this->course_search_form($searchcriteria['search']);
1853 $content .= $this->box_end();
1855 } else {
1856 // just print search form
1857 $content .= $this->box_start('generalbox mdl-align');
1858 $content .= $this->course_search_form();
1859 $content .= $this->box_end();
1861 return $content;
1865 * Renders html to print list of courses tagged with particular tag
1867 * @param int $tagid id of the tag
1868 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1869 * are displayed on the page and the per-page limit may be bigger
1870 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1871 * to display items in the same context first
1872 * @param int $ctx context id where to search for records
1873 * @param bool $rec search in subcontexts as well
1874 * @param array $displayoptions
1875 * @return string empty string if no courses are marked with this tag or rendered list of courses
1877 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1878 global $CFG;
1879 require_once($CFG->libdir . '/coursecatlib.php');
1880 if (empty($displayoptions)) {
1881 $displayoptions = array();
1883 $showcategories = coursecat::count_all() > 1;
1884 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1885 $chelper = new coursecat_helper();
1886 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1887 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1888 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1889 set_search_criteria($searchcriteria)->
1890 set_courses_display_options($displayoptions)->
1891 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1892 // (we set the same css class as in search results by tagid)
1893 if ($totalcount = coursecat::search_courses_count($searchcriteria)) {
1894 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1895 if ($exclusivemode) {
1896 return $this->coursecat_courses($chelper, $courses, $totalcount);
1897 } else {
1898 $tagfeed = new core_tag\output\tagfeed();
1899 $img = $this->output->pix_icon('i/course', '');
1900 foreach ($courses as $course) {
1901 $url = course_get_url($course);
1902 $imgwithlink = html_writer::link($url, $img);
1903 $coursename = html_writer::link($url, $course->get_formatted_name());
1904 $details = '';
1905 if ($showcategories && ($cat = coursecat::get($course->category, IGNORE_MISSING))) {
1906 $details = get_string('category').': '.
1907 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1908 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1910 $tagfeed->add($imgwithlink, $coursename, $details);
1912 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1915 return '';
1919 * Returns HTML to display one remote course
1921 * @param stdClass $course remote course information, contains properties:
1922 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1923 * @return string
1925 protected function frontpage_remote_course(stdClass $course) {
1926 $url = new moodle_url('/auth/mnet/jump.php', array(
1927 'hostid' => $course->hostid,
1928 'wantsurl' => '/course/view.php?id='. $course->remoteid
1931 $output = '';
1932 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1933 $output .= html_writer::start_tag('div', array('class' => 'info'));
1934 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1935 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1936 $output .= html_writer::end_tag('h3'); // .name
1937 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1938 $output .= html_writer::end_tag('div'); // .info
1939 $output .= html_writer::start_tag('div', array('class' => 'content'));
1940 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1941 $options = new stdClass();
1942 $options->noclean = true;
1943 $options->para = false;
1944 $options->overflowdiv = true;
1945 $output .= format_text($course->summary, $course->summaryformat, $options);
1946 $output .= html_writer::end_tag('div'); // .summary
1947 $addinfo = format_string($course->hostname) . ' : '
1948 . format_string($course->cat_name) . ' : '
1949 . format_string($course->shortname);
1950 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1951 $output .= html_writer::end_tag('div'); // .content
1952 $output .= html_writer::end_tag('div'); // .coursebox
1953 return $output;
1957 * Returns HTML to display one remote host
1959 * @param array $host host information, contains properties: name, url, count
1960 * @return string
1962 protected function frontpage_remote_host($host) {
1963 $output = '';
1964 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1965 $output .= html_writer::start_tag('div', array('class' => 'info'));
1966 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1967 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1968 $output .= html_writer::end_tag('h3'); // .name
1969 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1970 $output .= html_writer::end_tag('div'); // .info
1971 $output .= html_writer::start_tag('div', array('class' => 'content'));
1972 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1973 $output .= $host['count'] . ' ' . get_string('courses');
1974 $output .= html_writer::end_tag('div'); // .content
1975 $output .= html_writer::end_tag('div'); // .coursebox
1976 return $output;
1980 * Returns HTML to print list of courses user is enrolled to for the frontpage
1982 * Also lists remote courses or remote hosts if MNET authorisation is used
1984 * @return string
1986 public function frontpage_my_courses() {
1987 global $USER, $CFG, $DB;
1989 if (!isloggedin() or isguestuser()) {
1990 return '';
1993 $output = '';
1994 $courses = enrol_get_my_courses('summary, summaryformat');
1995 $rhosts = array();
1996 $rcourses = array();
1997 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1998 $rcourses = get_my_remotecourses($USER->id);
1999 $rhosts = get_my_remotehosts();
2002 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2004 $chelper = new coursecat_helper();
2005 if (count($courses) > $CFG->frontpagecourselimit) {
2006 // There are more enrolled courses than we can display, display link to 'My courses'.
2007 $totalcount = count($courses);
2008 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2009 $chelper->set_courses_display_options(array(
2010 'viewmoreurl' => new moodle_url('/my/'),
2011 'viewmoretext' => new lang_string('mycourses')
2013 } else {
2014 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2015 $chelper->set_courses_display_options(array(
2016 'viewmoreurl' => new moodle_url('/course/index.php'),
2017 'viewmoretext' => new lang_string('fulllistofcourses')
2019 $totalcount = $DB->count_records('course') - 1;
2021 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2022 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2023 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2025 // MNET
2026 if (!empty($rcourses)) {
2027 // at the IDP, we know of all the remote courses
2028 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2029 foreach ($rcourses as $course) {
2030 $output .= $this->frontpage_remote_course($course);
2032 $output .= html_writer::end_tag('div'); // .courses
2033 } elseif (!empty($rhosts)) {
2034 // non-IDP, we know of all the remote servers, but not courses
2035 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2036 foreach ($rhosts as $host) {
2037 $output .= $this->frontpage_remote_host($host);
2039 $output .= html_writer::end_tag('div'); // .courses
2042 return $output;
2046 * Returns HTML to print list of available courses for the frontpage
2048 * @return string
2050 public function frontpage_available_courses() {
2051 global $CFG;
2052 require_once($CFG->libdir. '/coursecatlib.php');
2054 $chelper = new coursecat_helper();
2055 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2056 set_courses_display_options(array(
2057 'recursive' => true,
2058 'limit' => $CFG->frontpagecourselimit,
2059 'viewmoreurl' => new moodle_url('/course/index.php'),
2060 'viewmoretext' => new lang_string('fulllistofcourses')));
2062 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2063 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
2064 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
2065 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2066 // Print link to create a new course, for the 1st available category.
2067 return $this->add_new_course_button();
2069 return $this->coursecat_courses($chelper, $courses, $totalcount);
2073 * Returns HTML to the "add new course" button for the page
2075 * @return string
2077 public function add_new_course_button() {
2078 global $CFG;
2079 // Print link to create a new course, for the 1st available category.
2080 $output = $this->container_start('buttons');
2081 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2082 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2083 $output .= $this->container_end('buttons');
2084 return $output;
2088 * Returns HTML to print tree with course categories and courses for the frontpage
2090 * @return string
2092 public function frontpage_combo_list() {
2093 global $CFG;
2094 require_once($CFG->libdir. '/coursecatlib.php');
2095 $chelper = new coursecat_helper();
2096 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2097 set_categories_display_options(array(
2098 'limit' => $CFG->coursesperpage,
2099 'viewmoreurl' => new moodle_url('/course/index.php',
2100 array('browse' => 'categories', 'page' => 1))
2101 ))->
2102 set_courses_display_options(array(
2103 'limit' => $CFG->coursesperpage,
2104 'viewmoreurl' => new moodle_url('/course/index.php',
2105 array('browse' => 'courses', 'page' => 1))
2106 ))->
2107 set_attributes(array('class' => 'frontpage-category-combo'));
2108 return $this->coursecat_tree($chelper, coursecat::get(0));
2112 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2114 * @return string
2116 public function frontpage_categories_list() {
2117 global $CFG;
2118 require_once($CFG->libdir. '/coursecatlib.php');
2119 $chelper = new coursecat_helper();
2120 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2121 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2122 set_categories_display_options(array(
2123 'limit' => $CFG->coursesperpage,
2124 'viewmoreurl' => new moodle_url('/course/index.php',
2125 array('browse' => 'categories', 'page' => 1))
2126 ))->
2127 set_attributes(array('class' => 'frontpage-category-names'));
2128 return $this->coursecat_tree($chelper, coursecat::get(0));
2132 * Renders the activity navigation.
2134 * Defer to template.
2136 * @param \core_course\output\activity_navigation $page
2137 * @return string html for the page
2139 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2140 $data = $page->export_for_template($this->output);
2141 return $this->output->render_from_template('core_course/activity_navigation', $data);
2145 * Display the selector to advertise or publish a course
2146 * @param int $courseid
2148 public function publicationselector($courseid) {
2149 $text = '';
2151 $advertiseurl = new moodle_url("/course/publish/metadata.php",
2152 array('sesskey' => sesskey(), 'id' => $courseid, 'advertise' => true));
2153 $advertisebutton = new single_button($advertiseurl, get_string('advertise', 'hub'));
2154 $text .= $this->output->render($advertisebutton);
2155 $text .= html_writer::tag('div', get_string('advertisepublication_help', 'hub'),
2156 array('class' => 'publishhelp'));
2158 $text .= html_writer::empty_tag('br'); // TODO Delete.
2160 $uploadurl = new moodle_url("/course/publish/metadata.php",
2161 array('sesskey' => sesskey(), 'id' => $courseid, 'share' => true));
2162 $uploadbutton = new single_button($uploadurl, get_string('share', 'hub'));
2163 $text .= $this->output->render($uploadbutton);
2164 $text .= html_writer::tag('div', get_string('sharepublication_help', 'hub'),
2165 array('class' => 'publishhelp'));
2167 return $text;
2171 * Display the listing of hub where a course is registered on
2172 * @param int $courseid
2173 * @param array $publications
2175 public function registeredonhublisting($courseid, $publications) {
2176 global $CFG;
2177 $table = new html_table();
2178 $table->head = array(get_string('type', 'hub'),
2179 get_string('date'), get_string('status', 'hub'), get_string('operation', 'hub'));
2180 $table->size = array('20%', '30%', '%20', '%25');
2182 $brtag = html_writer::empty_tag('br');
2184 foreach ($publications as $publication) {
2186 $params = array('id' => $publication->courseid, 'publicationid' => $publication->id);
2187 $cancelurl = new moodle_url("/course/publish/index.php", $params);
2188 $cancelbutton = new single_button($cancelurl, get_string('removefromhub', 'hub'));
2189 $cancelbutton->class = 'centeredbutton';
2190 $cancelbuttonhtml = $this->output->render($cancelbutton);
2192 if ($publication->enrollable) {
2193 $params = array('sesskey' => sesskey(), 'id' => $publication->courseid, 'publicationid' => $publication->id);
2194 $updateurl = new moodle_url("/course/publish/metadata.php", $params);
2195 $updatebutton = new single_button($updateurl, get_string('update', 'hub'));
2196 $updatebutton->class = 'centeredbutton';
2197 $updatebuttonhtml = $this->output->render($updatebutton);
2199 $operations = $updatebuttonhtml . $brtag . $cancelbuttonhtml;
2200 } else {
2201 $operations = $cancelbuttonhtml;
2204 // If the publication check time if bigger than May 2010, it has been checked.
2205 if ($publication->timechecked > 1273127954) {
2206 if ($publication->status == 0) {
2207 $status = get_string('statusunpublished', 'hub');
2208 } else {
2209 $status = get_string('statuspublished', 'hub');
2210 if (!empty($publication->link)) {
2211 $status = html_writer::link($publication->link, $status);
2215 $status .= $brtag . html_writer::tag('a', get_string('updatestatus', 'hub'),
2216 array('href' => $CFG->wwwroot . '/course/publish/index.php?id='
2217 . $courseid . "&updatestatusid=" . $publication->id
2218 . "&sesskey=" . sesskey())) .
2219 $brtag . get_string('lasttimechecked', 'hub') . ": "
2220 . format_time(time() - $publication->timechecked);
2221 } else {
2222 $status = get_string('neverchecked', 'hub') . $brtag
2223 . html_writer::tag('a', get_string('updatestatus', 'hub'),
2224 array('href' => $CFG->wwwroot . '/course/publish/index.php?id='
2225 . $courseid . "&updatestatusid=" . $publication->id
2226 . "&sesskey=" . sesskey()));
2228 // Add button cells.
2229 $cells = array($publication->enrollable ?
2230 get_string('advertised', 'hub') : get_string('shared', 'hub'),
2231 userdate($publication->timepublished,
2232 get_string('strftimedatetimeshort')), $status, $operations);
2233 $row = new html_table_row($cells);
2234 $table->data[] = $row;
2237 $contenthtml = html_writer::table($table);
2239 return $contenthtml;
2243 * Display unpublishing confirmation page
2244 * @param stdClass $publication
2245 * $publication->courseshortname
2246 * $publication->courseid
2247 * $publication->hubname
2248 * $publication->huburl
2249 * $publication->id
2251 public function confirmunpublishing($publication) {
2252 $optionsyes = array('sesskey' => sesskey(), 'id' => $publication->courseid,
2253 'hubcourseid' => $publication->hubcourseid,
2254 'cancel' => true, 'publicationid' => $publication->id, 'confirm' => true);
2255 $optionsno = array('sesskey' => sesskey(), 'id' => $publication->courseid);
2256 $publication->hubname = html_writer::tag('a', 'Moodle.net',
2257 array('href' => HUB_MOODLEORGHUBURL));
2258 $formcontinue = new single_button(new moodle_url("/course/publish/index.php",
2259 $optionsyes), get_string('unpublish', 'hub'), 'post');
2260 $formcancel = new single_button(new moodle_url("/course/publish/index.php",
2261 $optionsno), get_string('cancel'), 'get');
2262 return $this->output->confirm(get_string('unpublishconfirmation', 'hub', $publication),
2263 $formcontinue, $formcancel);
2267 * Display waiting information about backup size during uploading backup process
2268 * @param object $backupfile the backup stored_file
2269 * @return $html string
2271 public function sendingbackupinfo($backupfile) {
2272 $sizeinfo = new stdClass();
2273 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2274 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2275 array('class' => 'courseuploadtextinfo'));
2276 return $html;
2280 * Display upload successfull message and a button to the publish index page
2281 * @param int $id the course id
2282 * @return $html string
2284 public function sentbackupinfo($id) {
2285 $html = html_writer::tag('div', get_string('sent', 'hub'),
2286 array('class' => 'courseuploadtextinfo'));
2287 $publishindexurl = new moodle_url('/course/publish/index.php',
2288 array('sesskey' => sesskey(), 'id' => $id,
2289 'published' => true));
2290 $continue = $this->output->render(
2291 new single_button($publishindexurl, get_string('continue')));
2292 $html .= html_writer::tag('div', $continue, array('class' => 'sharecoursecontinue'));
2293 return $html;
2297 * Hub information (logo - name - description - link)
2298 * @param object $hubinfo
2299 * @return string html code
2301 public function hubinfo($hubinfo) {
2302 $screenshothtml = html_writer::empty_tag('img',
2303 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2304 $hubdescription = html_writer::tag('div', $screenshothtml,
2305 array('class' => 'hubscreenshot'));
2307 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2308 array('class' => 'hublink', 'href' => $hubinfo['url'],
2309 'onclick' => 'this.target="_blank"'));
2311 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2312 array('class' => 'hubdescription'));
2313 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2315 return $hubdescription;
2319 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2321 * This may be disabled in settings
2323 * @return string
2325 public function frontpage_section1() {
2326 global $SITE, $USER;
2328 $output = '';
2329 $editing = $this->page->user_is_editing();
2331 if ($editing) {
2332 // Make sure section with number 1 exists.
2333 course_create_sections_if_missing($SITE, 1);
2336 $modinfo = get_fast_modinfo($SITE);
2337 $section = $modinfo->get_section_info(1);
2338 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2339 $output .= $this->box_start('generalbox sitetopic');
2341 // If currently moving a file then show the current clipboard.
2342 if (ismoving($SITE->id)) {
2343 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2344 $output .= '<p><font size="2">';
2345 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2346 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2347 $output .= '</font></p>';
2350 $context = context_course::instance(SITEID);
2352 // If the section name is set we show it.
2353 if (trim($section->name) !== '') {
2354 $output .= $this->heading(
2355 format_string($section->name, true, array('context' => $context)),
2357 'sectionname'
2361 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2362 'pluginfile.php',
2363 $context->id,
2364 'course',
2365 'section',
2366 $section->id);
2367 $summaryformatoptions = new stdClass();
2368 $summaryformatoptions->noclean = true;
2369 $summaryformatoptions->overflowdiv = true;
2371 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2373 if ($editing && has_capability('moodle/course:update', $context)) {
2374 $streditsummary = get_string('editsummary');
2375 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2376 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', $streditsummary)) .
2377 "<br /><br />";
2380 $output .= $this->course_section_cm_list($SITE, $section);
2382 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2383 $output .= $this->box_end();
2386 return $output;
2390 * Output news for the frontpage (extract from site-wide news forum)
2392 * @param stdClass $newsforum record from db table 'forum' that represents the site news forum
2393 * @return string
2395 protected function frontpage_news($newsforum) {
2396 global $CFG, $SITE, $SESSION, $USER;
2397 require_once($CFG->dirroot .'/mod/forum/lib.php');
2399 $output = '';
2401 if (isloggedin()) {
2402 $SESSION->fromdiscussion = $CFG->wwwroot;
2403 $subtext = '';
2404 if (\mod_forum\subscriptions::is_subscribed($USER->id, $newsforum)) {
2405 if (!\mod_forum\subscriptions::is_forcesubscribed($newsforum)) {
2406 $subtext = get_string('unsubscribe', 'forum');
2408 } else {
2409 $subtext = get_string('subscribe', 'forum');
2411 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $newsforum->id, 'sesskey' => sesskey()));
2412 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2415 ob_start();
2416 forum_print_latest_discussions($SITE, $newsforum, $SITE->newsitems, 'plain', 'p.modified DESC');
2417 $output .= ob_get_contents();
2418 ob_end_clean();
2420 return $output;
2424 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2426 * @param string $skipdivid
2427 * @param string $contentsdivid
2428 * @param string $header Header of the part
2429 * @param string $contents Contents of the part
2430 * @return string
2432 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2433 $output = html_writer::link('#' . $skipdivid,
2434 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2435 array('class' => 'skip-block skip'));
2437 // Wrap frontpage part in div container.
2438 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2439 $output .= $this->heading($header);
2441 $output .= $contents;
2443 // End frontpage part div container.
2444 $output .= html_writer::end_tag('div');
2446 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2447 return $output;
2451 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2453 * @return string
2455 public function frontpage() {
2456 global $CFG, $SITE;
2458 $output = '';
2460 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2461 $frontpagelayout = $CFG->frontpageloggedin;
2462 } else {
2463 $frontpagelayout = $CFG->frontpage;
2466 foreach (explode(',', $frontpagelayout) as $v) {
2467 switch ($v) {
2468 // Display the main part of the front page.
2469 case FRONTPAGENEWS:
2470 if ($SITE->newsitems) {
2471 // Print forums only when needed.
2472 require_once($CFG->dirroot .'/mod/forum/lib.php');
2473 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2474 ($forumcontents = $this->frontpage_news($newsforum))) {
2475 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2476 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2477 $newsforumcm->get_formatted_name(), $forumcontents);
2480 break;
2482 case FRONTPAGEENROLLEDCOURSELIST:
2483 $mycourseshtml = $this->frontpage_my_courses();
2484 if (!empty($mycourseshtml)) {
2485 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2486 get_string('mycourses'), $mycourseshtml);
2487 break;
2489 // No "break" here. If there are no enrolled courses - continue to 'Available courses'.
2491 case FRONTPAGEALLCOURSELIST:
2492 $availablecourseshtml = $this->frontpage_available_courses();
2493 if (!empty($availablecourseshtml)) {
2494 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2495 get_string('availablecourses'), $availablecourseshtml);
2497 break;
2499 case FRONTPAGECATEGORYNAMES:
2500 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2501 get_string('categories'), $this->frontpage_categories_list());
2502 break;
2504 case FRONTPAGECATEGORYCOMBO:
2505 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2506 get_string('courses'), $this->frontpage_combo_list());
2507 break;
2509 case FRONTPAGECOURSESEARCH:
2510 $output .= $this->box($this->course_search_form('', 'short'), 'mdl-align');
2511 break;
2514 $output .= '<br />';
2517 return $output;
2522 * Class storing display options and functions to help display course category and/or courses lists
2524 * This is a wrapper for coursecat objects that also stores display options
2525 * and functions to retrieve sorted and paginated lists of categories/courses.
2527 * If theme overrides methods in core_course_renderers that access this class
2528 * it may as well not use this class at all or extend it.
2530 * @package core
2531 * @copyright 2013 Marina Glancy
2532 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2534 class coursecat_helper {
2535 /** @var string [none, collapsed, expanded] how (if) display courses list */
2536 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2537 /** @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) */
2538 protected $subcatdepth = 1;
2539 /** @var array options to display courses list */
2540 protected $coursesdisplayoptions = array();
2541 /** @var array options to display subcategories list */
2542 protected $categoriesdisplayoptions = array();
2543 /** @var array additional HTML attributes */
2544 protected $attributes = array();
2545 /** @var array search criteria if the list is a search result */
2546 protected $searchcriteria = null;
2549 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2551 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2552 * @return coursecat_helper
2554 public function set_show_courses($showcourses) {
2555 $this->showcourses = $showcourses;
2556 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2557 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2558 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2559 return $this;
2563 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2565 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2567 public function get_show_courses() {
2568 return $this->showcourses;
2572 * Sets the maximum depth to expand subcategories in the tree
2574 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2576 * @param int $subcatdepth
2577 * @return coursecat_helper
2579 public function set_subcat_depth($subcatdepth) {
2580 $this->subcatdepth = $subcatdepth;
2581 return $this;
2585 * Returns the maximum depth to expand subcategories in the tree
2587 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2589 * @return int
2591 public function get_subcat_depth() {
2592 return $this->subcatdepth;
2596 * Sets options to display list of courses
2598 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2600 * Options that coursecat::get_courses() accept:
2601 * - recursive - return courses from subcategories as well. Use with care,
2602 * this may be a huge list!
2603 * - summary - preloads fields 'summary' and 'summaryformat'
2604 * - coursecontacts - preloads course contacts
2605 * - isenrolled - preloads indication whether this user is enrolled in the course
2606 * - sort - list of fields to sort. Example
2607 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2608 * will sort by idnumber asc, shortname asc and id desc.
2609 * Default: array('sortorder' => 1)
2610 * Only cached fields may be used for sorting!
2611 * - offset
2612 * - limit - maximum number of children to return, 0 or null for no limit
2614 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2616 * Also renderer can set here any additional options it wants to pass between renderer functions.
2618 * @param array $options
2619 * @return coursecat_helper
2621 public function set_courses_display_options($options) {
2622 $this->coursesdisplayoptions = $options;
2623 $this->set_show_courses($this->showcourses); // this will calculate special display options
2624 return $this;
2628 * Sets one option to display list of courses
2630 * @see coursecat_helper::set_courses_display_options()
2632 * @param string $key
2633 * @param mixed $value
2634 * @return coursecat_helper
2636 public function set_courses_display_option($key, $value) {
2637 $this->coursesdisplayoptions[$key] = $value;
2638 return $this;
2642 * Return the specified option to display list of courses
2644 * @param string $optionname option name
2645 * @param mixed $defaultvalue default value for option if it is not specified
2646 * @return mixed
2648 public function get_courses_display_option($optionname, $defaultvalue = null) {
2649 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2650 return $this->coursesdisplayoptions[$optionname];
2651 } else {
2652 return $defaultvalue;
2657 * Returns all options to display the courses
2659 * This array is usually passed to {@link coursecat::get_courses()} or
2660 * {@link coursecat::search_courses()}
2662 * @return array
2664 public function get_courses_display_options() {
2665 return $this->coursesdisplayoptions;
2669 * Sets options to display list of subcategories
2671 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2672 * Any other options may be used by renderer functions
2674 * @param array $options
2675 * @return coursecat_helper
2677 public function set_categories_display_options($options) {
2678 $this->categoriesdisplayoptions = $options;
2679 return $this;
2683 * Return the specified option to display list of subcategories
2685 * @param string $optionname option name
2686 * @param mixed $defaultvalue default value for option if it is not specified
2687 * @return mixed
2689 public function get_categories_display_option($optionname, $defaultvalue = null) {
2690 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2691 return $this->categoriesdisplayoptions[$optionname];
2692 } else {
2693 return $defaultvalue;
2698 * Returns all options to display list of subcategories
2700 * This array is usually passed to {@link coursecat::get_children()}
2702 * @return array
2704 public function get_categories_display_options() {
2705 return $this->categoriesdisplayoptions;
2709 * Sets additional general options to pass between renderer functions, usually HTML attributes
2711 * @param array $attributes
2712 * @return coursecat_helper
2714 public function set_attributes($attributes) {
2715 $this->attributes = $attributes;
2716 return $this;
2720 * Return all attributes and erases them so they are not applied again
2722 * @param string $classname adds additional class name to the beginning of $attributes['class']
2723 * @return array
2725 public function get_and_erase_attributes($classname) {
2726 $attributes = $this->attributes;
2727 $this->attributes = array();
2728 if (empty($attributes['class'])) {
2729 $attributes['class'] = '';
2731 $attributes['class'] = $classname . ' '. $attributes['class'];
2732 return $attributes;
2736 * Sets the search criteria if the course is a search result
2738 * Search string will be used to highlight terms in course name and description
2740 * @param array $searchcriteria
2741 * @return coursecat_helper
2743 public function set_search_criteria($searchcriteria) {
2744 $this->searchcriteria = $searchcriteria;
2745 return $this;
2749 * Returns formatted and filtered description of the given category
2751 * @param coursecat $coursecat category
2752 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2753 * if context is not specified it will be added automatically
2754 * @return string|null
2756 public function get_category_formatted_description($coursecat, $options = null) {
2757 if ($coursecat->id && !empty($coursecat->description)) {
2758 if (!isset($coursecat->descriptionformat)) {
2759 $descriptionformat = FORMAT_MOODLE;
2760 } else {
2761 $descriptionformat = $coursecat->descriptionformat;
2763 if ($options === null) {
2764 $options = array('noclean' => true, 'overflowdiv' => true);
2765 } else {
2766 $options = (array)$options;
2768 $context = context_coursecat::instance($coursecat->id);
2769 if (!isset($options['context'])) {
2770 $options['context'] = $context;
2772 $text = file_rewrite_pluginfile_urls($coursecat->description,
2773 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2774 return format_text($text, $descriptionformat, $options);
2776 return null;
2780 * Returns given course's summary with proper embedded files urls and formatted
2782 * @param course_in_list $course
2783 * @param array|stdClass $options additional formatting options
2784 * @return string
2786 public function get_course_formatted_summary($course, $options = array()) {
2787 global $CFG;
2788 require_once($CFG->libdir. '/filelib.php');
2789 if (!$course->has_summary()) {
2790 return '';
2792 $options = (array)$options;
2793 $context = context_course::instance($course->id);
2794 if (!isset($options['context'])) {
2795 // TODO see MDL-38521
2796 // option 1 (current), page context - no code required
2797 // option 2, system context
2798 // $options['context'] = context_system::instance();
2799 // option 3, course context:
2800 // $options['context'] = $context;
2801 // option 4, course category context:
2802 // $options['context'] = $context->get_parent_context();
2804 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2805 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2806 if (!empty($this->searchcriteria['search'])) {
2807 $summary = highlight($this->searchcriteria['search'], $summary);
2809 return $summary;
2813 * Returns course name as it is configured to appear in courses lists formatted to course context
2815 * @param course_in_list $course
2816 * @param array|stdClass $options additional formatting options
2817 * @return string
2819 public function get_course_formatted_name($course, $options = array()) {
2820 $options = (array)$options;
2821 if (!isset($options['context'])) {
2822 $options['context'] = context_course::instance($course->id);
2824 $name = format_string(get_course_display_name_for_list($course), true, $options);
2825 if (!empty($this->searchcriteria['search'])) {
2826 $name = highlight($this->searchcriteria['search'], $name);
2828 return $name;