Merge branch 'wip-MDL-61814-master' of git://github.com/abgreeve/moodle
[moodle.git] / course / renderer.php
blob68767ffa8a87ebe8a5b08547232888032f1b4a3e
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
46 /**
47 * A cache of strings
48 * @var stdClass
50 protected $strings;
52 /**
53 * Whether a category content is being initially rendered with children. This is mainly used by the
54 * core_course_renderer::corsecat_tree() to render the appropriate action for the Expand/Collapse all link on
55 * page load.
56 * @var bool
58 protected $categoryexpandedonload = false;
60 /**
61 * Override the constructor so that we can initialise the string cache
63 * @param moodle_page $page
64 * @param string $target
66 public function __construct(moodle_page $page, $target) {
67 $this->strings = new stdClass;
68 parent::__construct($page, $target);
71 /**
72 * Adds the item in course settings navigation to toggle modchooser
74 * Theme can overwrite as an empty function to exclude it (for example if theme does not
75 * use modchooser at all)
77 * @deprecated since 3.2
79 protected function add_modchoosertoggle() {
80 debugging('core_course_renderer::add_modchoosertoggle() is deprecated.', DEBUG_DEVELOPER);
82 global $CFG;
84 // Only needs to be done once per page.
85 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchoosertoggle')) {
86 return;
89 if ($this->page->state > moodle_page::STATE_PRINTING_HEADER ||
90 $this->page->course->id == SITEID ||
91 !$this->page->user_is_editing() ||
92 !($context = context_course::instance($this->page->course->id)) ||
93 !has_capability('moodle/course:manageactivities', $context) ||
94 !course_ajax_enabled($this->page->course) ||
95 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
96 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
97 // Too late, or we are on site page, or we could not find the
98 // adjacent nodes in course settings menu, or we are not allowed to edit.
99 return;
102 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
103 // We are on the course page, retain the current page params e.g. section.
104 $modchoosertoggleurl = clone($this->page->url);
105 } else {
106 // Edit on the main course page.
107 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
108 'return' => $this->page->url->out_as_local_url(false)));
110 $modchoosertoggleurl->param('sesskey', sesskey());
111 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
112 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
113 $modchoosertoggleurl->param('modchooser', 'off');
114 } else {
115 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
116 $modchoosertoggleurl->param('modchooser', 'on');
118 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
120 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
121 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
122 $turneditingnode->remove();
123 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
125 $modchoosertoggle->add_class('modchoosertoggle');
126 $modchoosertoggle->add_class('visibleifjs');
127 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
131 * Renders course info box.
133 * @param stdClass|course_in_list $course
134 * @return string
136 public function course_info_box(stdClass $course) {
137 $content = '';
138 $content .= $this->output->box_start('generalbox info');
139 $chelper = new coursecat_helper();
140 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
141 $content .= $this->coursecat_coursebox($chelper, $course);
142 $content .= $this->output->box_end();
143 return $content;
147 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
149 * @deprecated since 2.5
151 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
153 * @param array $ignored argument ignored
154 * @return string
156 public final function course_category_tree(array $ignored) {
157 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
158 return $this->frontpage_combo_list();
162 * Renderers a category for use with course_category_tree
164 * @deprecated since 2.5
166 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
168 * @param array $category
169 * @param int $depth
170 * @return string
172 protected final function course_category_tree_category(stdClass $category, $depth=1) {
173 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
174 return '';
178 * Render a modchooser.
180 * @param renderable $modchooser The chooser.
181 * @return string
183 public function render_modchooser(renderable $modchooser) {
184 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
188 * Build the HTML for the module chooser javascript popup
190 * @param array $modules A set of modules as returned form @see
191 * get_module_metadata
192 * @param object $course The course that will be displayed
193 * @return string The composed HTML for the module
195 public function course_modchooser($modules, $course) {
196 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
197 return '';
199 $modchooser = new \core_course\output\modchooser($course, $modules);
200 return $this->render($modchooser);
204 * Build the HTML for a specified set of modules
206 * @param array $modules A set of modules as used by the
207 * course_modchooser_module function
208 * @return string The composed HTML for the module
210 protected function course_modchooser_module_types($modules) {
211 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
212 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
213 return '';
217 * Return the HTML for the specified module adding any required classes
219 * @param object $module An object containing the title, and link. An
220 * icon, and help text may optionally be specified. If the module
221 * contains subtypes in the types option, then these will also be
222 * displayed.
223 * @param array $classes Additional classes to add to the encompassing
224 * div element
225 * @return string The composed HTML for the module
227 protected function course_modchooser_module($module, $classes = array('option')) {
228 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
229 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
230 return '';
233 protected function course_modchooser_title($title, $identifier = null) {
234 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
235 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
236 return '';
240 * Renders HTML for displaying the sequence of course module editing buttons
242 * @see course_get_cm_edit_actions()
244 * @param action_link[] $actions Array of action_link objects
245 * @param cm_info $mod The module we are displaying actions for.
246 * @param array $displayoptions additional display options:
247 * ownerselector => A JS/CSS selector that can be used to find an cm node.
248 * If specified the owning node will be given the class 'action-menu-shown' when the action
249 * menu is being displayed.
250 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
251 * the action menu to when it is being displayed.
252 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
253 * @return string
255 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
256 global $CFG;
258 if (empty($actions)) {
259 return '';
262 if (isset($displayoptions['ownerselector'])) {
263 $ownerselector = $displayoptions['ownerselector'];
264 } else if ($mod) {
265 $ownerselector = '#module-'.$mod->id;
266 } else {
267 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
268 $ownerselector = 'li.activity';
271 if (isset($displayoptions['constraintselector'])) {
272 $constraint = $displayoptions['constraintselector'];
273 } else {
274 $constraint = '.course-content';
277 $menu = new action_menu();
278 $menu->set_owner_selector($ownerselector);
279 $menu->set_constraint($constraint);
280 $menu->set_alignment(action_menu::TR, action_menu::BR);
281 $menu->set_menu_trigger(get_string('edit'));
283 foreach ($actions as $action) {
284 if ($action instanceof action_menu_link) {
285 $action->add_class('cm-edit-action');
287 $menu->add($action);
289 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
291 // Prioritise the menu ahead of all other actions.
292 $menu->prioritise = true;
294 return $this->render($menu);
298 * Renders HTML for the menus to add activities and resources to the current course
300 * @param stdClass $course
301 * @param int $section relative section number (field course_sections.section)
302 * @param int $sectionreturn The section to link back to
303 * @param array $displayoptions additional display options, for example blocks add
304 * option 'inblock' => true, suggesting to display controls vertically
305 * @return string
307 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
308 global $CFG;
310 $vertical = !empty($displayoptions['inblock']);
312 // check to see if user can add menus and there are modules to add
313 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
314 || !$this->page->user_is_editing()
315 || !($modnames = get_module_types_names()) || empty($modnames)) {
316 return '';
319 // Retrieve all modules with associated metadata
320 $modules = get_module_metadata($course, $modnames, $sectionreturn);
321 $urlparams = array('section' => $section);
323 // We'll sort resources and activities into two lists
324 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
326 foreach ($modules as $module) {
327 $activityclass = MOD_CLASS_ACTIVITY;
328 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
329 $activityclass = MOD_CLASS_RESOURCE;
330 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
331 // System modules cannot be added by user, do not add to dropdown.
332 continue;
334 $link = $module->link->out(true, $urlparams);
335 $activities[$activityclass][$link] = $module->title;
338 $straddactivity = get_string('addactivity');
339 $straddresource = get_string('addresource');
340 $sectionname = get_section_name($course, $section);
341 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
342 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
344 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
346 if (!$vertical) {
347 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
350 if (!empty($activities[MOD_CLASS_RESOURCE])) {
351 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
352 $select->set_help_icon('resources');
353 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
354 $output .= $this->output->render($select);
357 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
358 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
359 $select->set_help_icon('activities');
360 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
361 $output .= $this->output->render($select);
364 if (!$vertical) {
365 $output .= html_writer::end_tag('div');
368 $output .= html_writer::end_tag('div');
370 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
371 // modchooser can be added only for the current course set on the page!
372 $straddeither = get_string('addresourceoractivity');
373 // The module chooser link
374 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
375 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
376 $icon = $this->output->pix_icon('t/add', '');
377 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
378 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
379 $modchooser.= html_writer::end_tag('div');
380 $modchooser.= html_writer::end_tag('div');
382 // Wrap the normal output in a noscript div
383 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
384 if ($usemodchooser) {
385 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
386 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
387 } else {
388 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
389 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
390 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
392 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
395 return $output;
399 * Renders html to display a course search form
401 * @param string $value default value to populate the search field
402 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
403 * @return string
405 function course_search_form($value = '', $format = 'plain') {
406 static $count = 0;
407 $formid = 'coursesearch';
408 if ((++$count) > 1) {
409 $formid .= $count;
412 switch ($format) {
413 case 'navbar' :
414 $formid = 'coursesearchnavbar';
415 $inputid = 'navsearchbox';
416 $inputsize = 20;
417 break;
418 case 'short' :
419 $inputid = 'shortsearchbox';
420 $inputsize = 12;
421 break;
422 default :
423 $inputid = 'coursesearchbox';
424 $inputsize = 30;
427 $strsearchcourses= get_string("searchcourses");
428 $searchurl = new moodle_url('/course/search.php');
430 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
431 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
432 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
433 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
434 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
435 $output .= html_writer::empty_tag('input', array('type' => 'submit',
436 'value' => get_string('go')));
437 $output .= html_writer::end_tag('fieldset');
438 $output .= html_writer::end_tag('form');
440 return $output;
444 * Renders html for completion box on course page
446 * If completion is disabled, returns empty string
447 * If completion is automatic, returns an icon of the current completion state
448 * If completion is manual, returns a form (with an icon inside) that allows user to
449 * toggle completion
451 * @param stdClass $course course object
452 * @param completion_info $completioninfo completion info for the course, it is recommended
453 * to fetch once for all modules in course/section for performance
454 * @param cm_info $mod module to show completion for
455 * @param array $displayoptions display options, not used in core
456 * @return string
458 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
459 global $CFG, $DB;
460 $output = '';
461 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
462 return $output;
464 if ($completioninfo === null) {
465 $completioninfo = new completion_info($course);
467 $completion = $completioninfo->is_enabled($mod);
468 if ($completion == COMPLETION_TRACKING_NONE) {
469 if ($this->page->user_is_editing()) {
470 $output .= html_writer::span('&nbsp;', 'filler');
472 return $output;
475 $completiondata = $completioninfo->get_data($mod, true);
476 $completionicon = '';
478 if ($this->page->user_is_editing()) {
479 switch ($completion) {
480 case COMPLETION_TRACKING_MANUAL :
481 $completionicon = 'manual-enabled'; break;
482 case COMPLETION_TRACKING_AUTOMATIC :
483 $completionicon = 'auto-enabled'; break;
485 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
486 switch($completiondata->completionstate) {
487 case COMPLETION_INCOMPLETE:
488 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
489 break;
490 case COMPLETION_COMPLETE:
491 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
492 break;
494 } else { // Automatic
495 switch($completiondata->completionstate) {
496 case COMPLETION_INCOMPLETE:
497 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
498 break;
499 case COMPLETION_COMPLETE:
500 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
501 break;
502 case COMPLETION_COMPLETE_PASS:
503 $completionicon = 'auto-pass'; break;
504 case COMPLETION_COMPLETE_FAIL:
505 $completionicon = 'auto-fail'; break;
508 if ($completionicon) {
509 $formattedname = $mod->get_formatted_name();
510 if ($completiondata->overrideby) {
511 $args = new stdClass();
512 $args->modname = $formattedname;
513 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
514 $args->overrideuser = fullname($overridebyuser);
515 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
516 } else {
517 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
520 if ($this->page->user_is_editing()) {
521 // When editing, the icon is just an image.
522 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
523 array('title' => $imgalt, 'class' => 'iconsmall'));
524 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
525 array('class' => 'autocompletion'));
526 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
527 $newstate =
528 $completiondata->completionstate == COMPLETION_COMPLETE
529 ? COMPLETION_INCOMPLETE
530 : COMPLETION_COMPLETE;
531 // In manual mode the icon is a toggle form...
533 // If this completion state is used by the
534 // conditional activities system, we need to turn
535 // off the JS.
536 $extraclass = '';
537 if (!empty($CFG->enableavailability) &&
538 core_availability\info::completion_value_used($course, $mod->id)) {
539 $extraclass = ' preventjs';
541 $output .= html_writer::start_tag('form', array('method' => 'post',
542 'action' => new moodle_url('/course/togglecompletion.php'),
543 'class' => 'togglecompletion'. $extraclass));
544 $output .= html_writer::start_tag('div');
545 $output .= html_writer::empty_tag('input', array(
546 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
547 $output .= html_writer::empty_tag('input', array(
548 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
549 $output .= html_writer::empty_tag('input', array(
550 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
551 $output .= html_writer::empty_tag('input', array(
552 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
553 $output .= html_writer::tag('button',
554 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt), array('class' => 'btn btn-link'));
555 $output .= html_writer::end_tag('div');
556 $output .= html_writer::end_tag('form');
557 } else {
558 // In auto mode, the icon is just an image.
559 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
560 array('title' => $imgalt));
561 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
562 array('class' => 'autocompletion'));
565 return $output;
569 * Checks if course module has any conditions that may make it unavailable for
570 * all or some of the students
572 * This function is internal and is only used to create CSS classes for the module name/text
574 * @param cm_info $mod
575 * @return bool
577 protected function is_cm_conditionally_hidden(cm_info $mod) {
578 global $CFG;
579 $conditionalhidden = false;
580 if (!empty($CFG->enableavailability)) {
581 $info = new \core_availability\info_module($mod);
582 $conditionalhidden = !$info->is_available_for_all();
584 return $conditionalhidden;
588 * Renders html to display a name with the link to the course module on a course page
590 * If module is unavailable for user but still needs to be displayed
591 * in the list, just the name is returned without a link
593 * Note, that for course modules that never have separate pages (i.e. labels)
594 * this function return an empty string
596 * @param cm_info $mod
597 * @param array $displayoptions
598 * @return string
600 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
601 if (!$mod->is_visible_on_course_page() || !$mod->url) {
602 // Nothing to be displayed to the user.
603 return '';
606 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
607 $groupinglabel = $mod->get_grouping_label($textclasses);
609 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
610 // to get the display title of the activity.
611 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
612 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
613 $groupinglabel;
617 * Returns the CSS classes for the activity name/content
619 * For items which are hidden, unavailable or stealth but should be displayed
620 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
621 * Students will also see as dimmed activities names that are not yet available
622 * but should still be displayed (without link) with availability info.
624 * @param cm_info $mod
625 * @return array array of two elements ($linkclasses, $textclasses)
627 protected function course_section_cm_classes(cm_info $mod) {
628 $linkclasses = '';
629 $textclasses = '';
630 if ($mod->uservisible) {
631 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
632 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
633 has_capability('moodle/course:viewhiddenactivities', $mod->context);
634 if ($accessiblebutdim) {
635 $linkclasses .= ' dimmed';
636 $textclasses .= ' dimmed_text';
637 if ($conditionalhidden) {
638 $linkclasses .= ' conditionalhidden';
639 $textclasses .= ' conditionalhidden';
642 if ($mod->is_stealth()) {
643 // Stealth activity is the one that is not visible on course page.
644 // It still may be displayed to the users who can manage it.
645 $linkclasses .= ' stealth';
646 $textclasses .= ' stealth';
648 } else {
649 $linkclasses .= ' dimmed';
650 $textclasses .= ' dimmed dimmed_text';
652 return array($linkclasses, $textclasses);
656 * Renders html to display a name with the link to the course module on a course page
658 * If module is unavailable for user but still needs to be displayed
659 * in the list, just the name is returned without a link
661 * Note, that for course modules that never have separate pages (i.e. labels)
662 * this function return an empty string
664 * @param cm_info $mod
665 * @param array $displayoptions
666 * @return string
668 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
669 $output = '';
670 $url = $mod->url;
671 if (!$mod->is_visible_on_course_page() || !$url) {
672 // Nothing to be displayed to the user.
673 return $output;
676 //Accessibility: for files get description via icon, this is very ugly hack!
677 $instancename = $mod->get_formatted_name();
678 $altname = $mod->modfullname;
679 // Avoid unnecessary duplication: if e.g. a forum name already
680 // includes the word forum (or Forum, etc) then it is unhelpful
681 // to include that in the accessible description that is added.
682 if (false !== strpos(core_text::strtolower($instancename),
683 core_text::strtolower($altname))) {
684 $altname = '';
686 // File type after name, for alphabetic lists (screen reader).
687 if ($altname) {
688 $altname = get_accesshide(' '.$altname);
691 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
693 // Get on-click attribute value if specified and decode the onclick - it
694 // has already been encoded for display (puke).
695 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
697 // Display link itself.
698 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
699 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
700 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
701 if ($mod->uservisible) {
702 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick));
703 } else {
704 // We may be displaying this just in order to show information
705 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
706 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
708 return $output;
712 * Renders html to display the module content on the course page (i.e. text of the labels)
714 * @param cm_info $mod
715 * @param array $displayoptions
716 * @return string
718 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
719 $output = '';
720 if (!$mod->is_visible_on_course_page()) {
721 // nothing to be displayed to the user
722 return $output;
724 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
725 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
726 if ($mod->url && $mod->uservisible) {
727 if ($content) {
728 // If specified, display extra content after link.
729 $output = html_writer::tag('div', $content, array('class' =>
730 trim('contentafterlink ' . $textclasses)));
732 } else {
733 $groupinglabel = $mod->get_grouping_label($textclasses);
735 // No link, so display only content.
736 $output = html_writer::tag('div', $content . $groupinglabel,
737 array('class' => 'contentwithoutlink ' . $textclasses));
739 return $output;
743 * Displays availability info for a course section or course module
745 * @param string $text
746 * @param string $additionalclasses
747 * @return string
749 public function availability_info($text, $additionalclasses = '') {
751 $data = ['text' => $text, 'classes' => $additionalclasses];
752 $additionalclasses = array_filter(explode(' ', $additionalclasses));
754 if (in_array('ishidden', $additionalclasses)) {
755 $data['ishidden'] = 1;
757 } else if (in_array('isstealth', $additionalclasses)) {
758 $data['isstealth'] = 1;
760 } else if (in_array('isrestricted', $additionalclasses)) {
761 $data['isrestricted'] = 1;
763 if (in_array('isfullinfo', $additionalclasses)) {
764 $data['isfullinfo'] = 1;
768 return $this->render_from_template('core/availability_info', $data);
772 * Renders HTML to show course module availability information (for someone who isn't allowed
773 * to see the activity itself, or for staff)
775 * @param cm_info $mod
776 * @param array $displayoptions
777 * @return string
779 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
780 global $CFG;
781 $output = '';
782 if (!$mod->is_visible_on_course_page()) {
783 return $output;
785 if (!$mod->uservisible) {
786 // this is a student who is not allowed to see the module but might be allowed
787 // to see availability info (i.e. "Available from ...")
788 if (!empty($mod->availableinfo)) {
789 $formattedinfo = \core_availability\info::format_info(
790 $mod->availableinfo, $mod->get_course());
791 $output = $this->availability_info($formattedinfo, 'isrestricted');
793 return $output;
795 // this is a teacher who is allowed to see module but still should see the
796 // information that module is not available to all/some students
797 $modcontext = context_module::instance($mod->id);
798 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
799 if ($canviewhidden && !$mod->visible) {
800 // This module is hidden but current user has capability to see it.
801 // Do not display the availability info if the whole section is hidden.
802 if ($mod->get_section_info()->visible) {
803 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
805 } else if ($mod->is_stealth()) {
806 // This module is available but is normally not displayed on the course page
807 // (this user can see it because they can manage it).
808 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
810 if ($canviewhidden && !empty($CFG->enableavailability)) {
811 // Display information about conditional availability.
812 // Don't add availability information if user is not editing and activity is hidden.
813 if ($mod->visible || $this->page->user_is_editing()) {
814 $hidinfoclass = 'isrestricted isfullinfo';
815 if (!$mod->visible) {
816 $hidinfoclass .= ' hide';
818 $ci = new \core_availability\info_module($mod);
819 $fullinfo = $ci->get_full_information();
820 if ($fullinfo) {
821 $formattedinfo = \core_availability\info::format_info(
822 $fullinfo, $mod->get_course());
823 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
827 return $output;
831 * Renders HTML to display one course module for display within a section.
833 * This function calls:
834 * {@link core_course_renderer::course_section_cm()}
836 * @param stdClass $course
837 * @param completion_info $completioninfo
838 * @param cm_info $mod
839 * @param int|null $sectionreturn
840 * @param array $displayoptions
841 * @return String
843 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
844 $output = '';
845 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
846 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
847 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
849 return $output;
853 * Renders HTML to display one course module in a course section
855 * This includes link, content, availability, completion info and additional information
856 * that module type wants to display (i.e. number of unread forum posts)
858 * This function calls:
859 * {@link core_course_renderer::course_section_cm_name()}
860 * {@link core_course_renderer::course_section_cm_text()}
861 * {@link core_course_renderer::course_section_cm_availability()}
862 * {@link core_course_renderer::course_section_cm_completion()}
863 * {@link course_get_cm_edit_actions()}
864 * {@link core_course_renderer::course_section_cm_edit_actions()}
866 * @param stdClass $course
867 * @param completion_info $completioninfo
868 * @param cm_info $mod
869 * @param int|null $sectionreturn
870 * @param array $displayoptions
871 * @return string
873 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
874 $output = '';
875 // We return empty string (because course module will not be displayed at all)
876 // if:
877 // 1) The activity is not visible to users
878 // and
879 // 2) The 'availableinfo' is empty, i.e. the activity was
880 // hidden in a way that leaves no info, such as using the
881 // eye icon.
882 if (!$mod->is_visible_on_course_page()) {
883 return $output;
886 $indentclasses = 'mod-indent';
887 if (!empty($mod->indent)) {
888 $indentclasses .= ' mod-indent-'.$mod->indent;
889 if ($mod->indent > 15) {
890 $indentclasses .= ' mod-indent-huge';
894 $output .= html_writer::start_tag('div');
896 if ($this->page->user_is_editing()) {
897 $output .= course_get_cm_move($mod, $sectionreturn);
900 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
902 // This div is used to indent the content.
903 $output .= html_writer::div('', $indentclasses);
905 // Start a wrapper for the actual content to keep the indentation consistent
906 $output .= html_writer::start_tag('div');
908 // Display the link to the module (or do nothing if module has no url)
909 $cmname = $this->course_section_cm_name($mod, $displayoptions);
911 if (!empty($cmname)) {
912 // Start the div for the activity title, excluding the edit icons.
913 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
914 $output .= $cmname;
917 // Module can put text after the link (e.g. forum unread)
918 $output .= $mod->afterlink;
920 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
921 $output .= html_writer::end_tag('div'); // .activityinstance
924 // If there is content but NO link (eg label), then display the
925 // content here (BEFORE any icons). In this case cons must be
926 // displayed after the content so that it makes more sense visually
927 // and for accessibility reasons, e.g. if you have a one-line label
928 // it should work similarly (at least in terms of ordering) to an
929 // activity.
930 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
931 $url = $mod->url;
932 if (empty($url)) {
933 $output .= $contentpart;
936 $modicons = '';
937 if ($this->page->user_is_editing()) {
938 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
939 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
940 $modicons .= $mod->afterediticons;
943 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
945 if (!empty($modicons)) {
946 $output .= html_writer::span($modicons, 'actions');
949 // Show availability info (if module is not available).
950 $output .= $this->course_section_cm_availability($mod, $displayoptions);
952 // If there is content AND a link, then display the content here
953 // (AFTER any icons). Otherwise it was displayed before
954 if (!empty($url)) {
955 $output .= $contentpart;
958 $output .= html_writer::end_tag('div'); // $indentclasses
960 // End of indentation div.
961 $output .= html_writer::end_tag('div');
963 $output .= html_writer::end_tag('div');
964 return $output;
968 * Message displayed to the user when they try to access unavailable activity following URL
970 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
971 * notification only. It also does not check if module is visible on course page or not.
973 * The message will be displayed inside notification!
975 * @param cm_info $cm
976 * @return string
978 public function course_section_cm_unavailable_error_message(cm_info $cm) {
979 if ($cm->uservisible) {
980 return null;
982 if (!$cm->availableinfo) {
983 return get_string('activityiscurrentlyhidden');
986 $altname = get_accesshide(' ' . $cm->modfullname);
987 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
988 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
989 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
990 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
991 return html_writer::div($name, 'activityinstance-error') .
992 html_writer::div($formattedinfo, 'availabilityinfo-error');
996 * Renders HTML to display a list of course modules in a course section
997 * Also displays "move here" controls in Javascript-disabled mode
999 * This function calls {@link core_course_renderer::course_section_cm()}
1001 * @param stdClass $course course object
1002 * @param int|stdClass|section_info $section relative section number or section object
1003 * @param int $sectionreturn section number to return to
1004 * @param int $displayoptions
1005 * @return void
1007 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1008 global $USER;
1010 $output = '';
1011 $modinfo = get_fast_modinfo($course);
1012 if (is_object($section)) {
1013 $section = $modinfo->get_section_info($section->section);
1014 } else {
1015 $section = $modinfo->get_section_info($section);
1017 $completioninfo = new completion_info($course);
1019 // check if we are currently in the process of moving a module with JavaScript disabled
1020 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1021 if ($ismoving) {
1022 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1023 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1026 // Get the list of modules visible to user (excluding the module being moved if there is one)
1027 $moduleshtml = array();
1028 if (!empty($modinfo->sections[$section->section])) {
1029 foreach ($modinfo->sections[$section->section] as $modnumber) {
1030 $mod = $modinfo->cms[$modnumber];
1032 if ($ismoving and $mod->id == $USER->activitycopy) {
1033 // do not display moving mod
1034 continue;
1037 if ($modulehtml = $this->course_section_cm_list_item($course,
1038 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1039 $moduleshtml[$modnumber] = $modulehtml;
1044 $sectionoutput = '';
1045 if (!empty($moduleshtml) || $ismoving) {
1046 foreach ($moduleshtml as $modnumber => $modulehtml) {
1047 if ($ismoving) {
1048 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1049 $sectionoutput .= html_writer::tag('li',
1050 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1051 array('class' => 'movehere'));
1054 $sectionoutput .= $modulehtml;
1057 if ($ismoving) {
1058 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1059 $sectionoutput .= html_writer::tag('li',
1060 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1061 array('class' => 'movehere'));
1065 // Always output the section module list.
1066 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1068 return $output;
1072 * Displays a custom list of courses with paging bar if necessary
1074 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1075 * appears under the list.
1077 * If both $paginationurl and $totalcount are specified, and $totalcount is
1078 * bigger than count($courses), a paging bar is displayed above and under the
1079 * courses list.
1081 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1082 * @param bool $showcategoryname whether to add category name to the course description
1083 * @param string $additionalclasses additional CSS classes to add to the div.courses
1084 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1085 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1086 * @param int $page current page number (defaults to 0 referring to the first page)
1087 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1088 * @return string
1090 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1091 global $CFG;
1092 // create instance of coursecat_helper to pass display options to function rendering courses list
1093 $chelper = new coursecat_helper();
1094 if ($showcategoryname) {
1095 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1096 } else {
1097 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1099 if ($totalcount !== null && $paginationurl !== null) {
1100 // add options to display pagination
1101 if ($perpage === null) {
1102 $perpage = $CFG->coursesperpage;
1104 $chelper->set_courses_display_options(array(
1105 'limit' => $perpage,
1106 'offset' => ((int)$page) * $perpage,
1107 'paginationurl' => $paginationurl,
1109 } else if ($paginationurl !== null) {
1110 // add options to display 'View more' link
1111 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1112 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1114 $chelper->set_attributes(array('class' => $additionalclasses));
1115 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1116 return $content;
1120 * Displays one course in the list of courses.
1122 * This is an internal function, to display an information about just one course
1123 * please use {@link core_course_renderer::course_info_box()}
1125 * @param coursecat_helper $chelper various display options
1126 * @param course_in_list|stdClass $course
1127 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1128 * depend on the course position in list - first/last/even/odd)
1129 * @return string
1131 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1132 global $CFG;
1133 if (!isset($this->strings->summary)) {
1134 $this->strings->summary = get_string('summary');
1136 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1137 return '';
1139 if ($course instanceof stdClass) {
1140 require_once($CFG->libdir. '/coursecatlib.php');
1141 $course = new course_in_list($course);
1143 $content = '';
1144 $classes = trim('coursebox clearfix '. $additionalclasses);
1145 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1146 $nametag = 'h3';
1147 } else {
1148 $classes .= ' collapsed';
1149 $nametag = 'div';
1152 // .coursebox
1153 $content .= html_writer::start_tag('div', array(
1154 'class' => $classes,
1155 'data-courseid' => $course->id,
1156 'data-type' => self::COURSECAT_TYPE_COURSE,
1159 $content .= html_writer::start_tag('div', array('class' => 'info'));
1161 // course name
1162 $coursename = $chelper->get_course_formatted_name($course);
1163 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1164 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1165 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1166 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1167 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1168 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1169 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1170 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1171 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1172 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1173 // Make sure JS file to expand course content is included.
1174 $this->coursecat_include_js();
1177 $content .= html_writer::end_tag('div'); // .moreinfo
1179 // print enrolmenticons
1180 if ($icons = enrol_get_course_info_icons($course)) {
1181 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1182 foreach ($icons as $pix_icon) {
1183 $content .= $this->render($pix_icon);
1185 $content .= html_writer::end_tag('div'); // .enrolmenticons
1188 $content .= html_writer::end_tag('div'); // .info
1190 $content .= html_writer::start_tag('div', array('class' => 'content'));
1191 $content .= $this->coursecat_coursebox_content($chelper, $course);
1192 $content .= html_writer::end_tag('div'); // .content
1194 $content .= html_writer::end_tag('div'); // .coursebox
1195 return $content;
1199 * Returns HTML to display course content (summary, course contacts and optionally category name)
1201 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1203 * @param coursecat_helper $chelper various display options
1204 * @param stdClass|course_in_list $course
1205 * @return string
1207 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1208 global $CFG;
1209 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1210 return '';
1212 if ($course instanceof stdClass) {
1213 require_once($CFG->libdir. '/coursecatlib.php');
1214 $course = new course_in_list($course);
1216 $content = '';
1218 // display course summary
1219 if ($course->has_summary()) {
1220 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1221 $content .= $chelper->get_course_formatted_summary($course,
1222 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1223 $content .= html_writer::end_tag('div'); // .summary
1226 // display course overview files
1227 $contentimages = $contentfiles = '';
1228 foreach ($course->get_course_overviewfiles() as $file) {
1229 $isimage = $file->is_valid_image();
1230 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1231 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1232 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1233 if ($isimage) {
1234 $contentimages .= html_writer::tag('div',
1235 html_writer::empty_tag('img', array('src' => $url)),
1236 array('class' => 'courseimage'));
1237 } else {
1238 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1239 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1240 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1241 $contentfiles .= html_writer::tag('span',
1242 html_writer::link($url, $filename),
1243 array('class' => 'coursefile fp-filename-icon'));
1246 $content .= $contentimages. $contentfiles;
1248 // display course contacts. See course_in_list::get_course_contacts()
1249 if ($course->has_course_contacts()) {
1250 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1251 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1252 $name = $coursecontact['rolename'].': '.
1253 html_writer::link(new moodle_url('/user/view.php',
1254 array('id' => $userid, 'course' => SITEID)),
1255 $coursecontact['username']);
1256 $content .= html_writer::tag('li', $name);
1258 $content .= html_writer::end_tag('ul'); // .teachers
1261 // display course category if necessary (for example in search results)
1262 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1263 require_once($CFG->libdir. '/coursecatlib.php');
1264 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1265 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1266 $content .= get_string('category').': '.
1267 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1268 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1269 $content .= html_writer::end_tag('div'); // .coursecat
1273 return $content;
1277 * Renders the list of courses
1279 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1280 * method from outside of the class
1282 * If list of courses is specified in $courses; the argument $chelper is only used
1283 * to retrieve display options and attributes, only methods get_show_courses(),
1284 * get_courses_display_option() and get_and_erase_attributes() are called.
1286 * @param coursecat_helper $chelper various display options
1287 * @param array $courses the list of courses to display
1288 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1289 * defaulted to count($courses)
1290 * @return string
1292 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1293 global $CFG;
1294 if ($totalcount === null) {
1295 $totalcount = count($courses);
1297 if (!$totalcount) {
1298 // Courses count is cached during courses retrieval.
1299 return '';
1302 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1303 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1304 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1305 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1306 } else {
1307 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1311 // prepare content of paging bar if it is needed
1312 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1313 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1314 if ($totalcount > count($courses)) {
1315 // there are more results that can fit on one page
1316 if ($paginationurl) {
1317 // the option paginationurl was specified, display pagingbar
1318 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1319 $page = $chelper->get_courses_display_option('offset') / $perpage;
1320 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1321 $paginationurl->out(false, array('perpage' => $perpage)));
1322 if ($paginationallowall) {
1323 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1324 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1326 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1327 // the option for 'View more' link was specified, display more link
1328 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1329 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1330 array('class' => 'paging paging-morelink'));
1332 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1333 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1334 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1335 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1338 // display list of courses
1339 $attributes = $chelper->get_and_erase_attributes('courses');
1340 $content = html_writer::start_tag('div', $attributes);
1342 if (!empty($pagingbar)) {
1343 $content .= $pagingbar;
1346 $coursecount = 0;
1347 foreach ($courses as $course) {
1348 $coursecount ++;
1349 $classes = ($coursecount%2) ? 'odd' : 'even';
1350 if ($coursecount == 1) {
1351 $classes .= ' first';
1353 if ($coursecount >= count($courses)) {
1354 $classes .= ' last';
1356 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1359 if (!empty($pagingbar)) {
1360 $content .= $pagingbar;
1362 if (!empty($morelink)) {
1363 $content .= $morelink;
1366 $content .= html_writer::end_tag('div'); // .courses
1367 return $content;
1371 * Renders the list of subcategories in a category
1373 * @param coursecat_helper $chelper various display options
1374 * @param coursecat $coursecat
1375 * @param int $depth depth of the category in the current tree
1376 * @return string
1378 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1379 global $CFG;
1380 $subcategories = array();
1381 if (!$chelper->get_categories_display_option('nodisplay')) {
1382 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1384 $totalcount = $coursecat->get_children_count();
1385 if (!$totalcount) {
1386 // Note that we call coursecat::get_children_count() AFTER coursecat::get_children() to avoid extra DB requests.
1387 // Categories count is cached during children categories retrieval.
1388 return '';
1391 // prepare content of paging bar or more link if it is needed
1392 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1393 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1394 if ($totalcount > count($subcategories)) {
1395 if ($paginationurl) {
1396 // the option 'paginationurl was specified, display pagingbar
1397 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1398 $page = $chelper->get_categories_display_option('offset') / $perpage;
1399 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1400 $paginationurl->out(false, array('perpage' => $perpage)));
1401 if ($paginationallowall) {
1402 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1403 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1405 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1406 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1407 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1408 $viewmoreurl->param('categoryid', $coursecat->id);
1410 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1411 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1412 array('class' => 'paging paging-morelink'));
1414 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1415 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1416 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1417 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1420 // display list of subcategories
1421 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1423 if (!empty($pagingbar)) {
1424 $content .= $pagingbar;
1427 foreach ($subcategories as $subcategory) {
1428 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1431 if (!empty($pagingbar)) {
1432 $content .= $pagingbar;
1434 if (!empty($morelink)) {
1435 $content .= $morelink;
1438 $content .= html_writer::end_tag('div');
1439 return $content;
1443 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1445 protected function coursecat_include_js() {
1446 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1447 return;
1450 // We must only load this module once.
1451 $this->page->requires->yui_module('moodle-course-categoryexpander',
1452 'Y.Moodle.course.categoryexpander.init');
1456 * Returns HTML to display the subcategories and courses in the given category
1458 * This method is re-used by AJAX to expand content of not loaded category
1460 * @param coursecat_helper $chelper various display options
1461 * @param coursecat $coursecat
1462 * @param int $depth depth of the category in the current tree
1463 * @return string
1465 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1466 $content = '';
1467 // Subcategories
1468 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1470 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1471 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1472 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1473 if ($showcoursesauto && $depth) {
1474 // this is definitely collapsed mode
1475 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1478 // Courses
1479 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1480 $courses = array();
1481 if (!$chelper->get_courses_display_option('nodisplay')) {
1482 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1484 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1485 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1486 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1487 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1490 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1493 if ($showcoursesauto) {
1494 // restore the show_courses back to AUTO
1495 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1498 return $content;
1502 * Returns HTML to display a course category as a part of a tree
1504 * This is an internal function, to display a particular category and all its contents
1505 * use {@link core_course_renderer::course_category()}
1507 * @param coursecat_helper $chelper various display options
1508 * @param coursecat $coursecat
1509 * @param int $depth depth of this category in the current tree
1510 * @return string
1512 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1513 // open category tag
1514 $classes = array('category');
1515 if (empty($coursecat->visible)) {
1516 $classes[] = 'dimmed_category';
1518 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1519 // do not load content
1520 $categorycontent = '';
1521 $classes[] = 'notloaded';
1522 if ($coursecat->get_children_count() ||
1523 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1524 $classes[] = 'with_children';
1525 $classes[] = 'collapsed';
1527 } else {
1528 // load category content
1529 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1530 $classes[] = 'loaded';
1531 if (!empty($categorycontent)) {
1532 $classes[] = 'with_children';
1533 // Category content loaded with children.
1534 $this->categoryexpandedonload = true;
1538 // Make sure JS file to expand category content is included.
1539 $this->coursecat_include_js();
1541 $content = html_writer::start_tag('div', array(
1542 'class' => join(' ', $classes),
1543 'data-categoryid' => $coursecat->id,
1544 'data-depth' => $depth,
1545 'data-showcourses' => $chelper->get_show_courses(),
1546 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1549 // category name
1550 $categoryname = $coursecat->get_formatted_name();
1551 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1552 array('categoryid' => $coursecat->id)),
1553 $categoryname);
1554 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1555 && ($coursescount = $coursecat->get_courses_count())) {
1556 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1557 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1559 $content .= html_writer::start_tag('div', array('class' => 'info'));
1561 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1562 $content .= html_writer::end_tag('div'); // .info
1564 // add category content to the output
1565 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1567 $content .= html_writer::end_tag('div'); // .category
1569 // Return the course category tree HTML
1570 return $content;
1574 * Returns HTML to display a tree of subcategories and courses in the given category
1576 * @param coursecat_helper $chelper various display options
1577 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1578 * @return string
1580 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1581 // Reset the category expanded flag for this course category tree first.
1582 $this->categoryexpandedonload = false;
1583 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1584 if (empty($categorycontent)) {
1585 return '';
1588 // Start content generation
1589 $content = '';
1590 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1591 $content .= html_writer::start_tag('div', $attributes);
1593 if ($coursecat->get_children_count()) {
1594 $classes = array(
1595 'collapseexpand',
1598 // Check if the category content contains subcategories with children's content loaded.
1599 if ($this->categoryexpandedonload) {
1600 $classes[] = 'collapse-all';
1601 $linkname = get_string('collapseall');
1602 } else {
1603 $linkname = get_string('expandall');
1606 // Only show the collapse/expand if there are children to expand.
1607 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1608 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1609 $content .= html_writer::end_tag('div');
1610 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1613 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1615 $content .= html_writer::end_tag('div'); // .course_category_tree
1617 return $content;
1621 * Renders HTML to display particular course category - list of it's subcategories and courses
1623 * Invoked from /course/index.php
1625 * @param int|stdClass|coursecat $category
1627 public function course_category($category) {
1628 global $CFG;
1629 require_once($CFG->libdir. '/coursecatlib.php');
1630 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1631 $site = get_site();
1632 $output = '';
1634 if (can_edit_in_category($coursecat->id)) {
1635 // Add 'Manage' button if user has permissions to edit this category.
1636 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1637 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1638 $this->page->set_button($managebutton);
1640 if (!$coursecat->id) {
1641 if (coursecat::count_all() == 1) {
1642 // There exists only one category in the system, do not display link to it
1643 $coursecat = coursecat::get_default();
1644 $strfulllistofcourses = get_string('fulllistofcourses');
1645 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1646 } else {
1647 $strcategories = get_string('categories');
1648 $this->page->set_title("$site->shortname: $strcategories");
1650 } else {
1651 $title = $site->shortname;
1652 if (coursecat::count_all() > 1) {
1653 $title .= ": ". $coursecat->get_formatted_name();
1655 $this->page->set_title($title);
1657 // Print the category selector
1658 if (coursecat::count_all() > 1) {
1659 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1660 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1661 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1662 $select->set_label(get_string('categories').':');
1663 $output .= $this->render($select);
1664 $output .= html_writer::end_tag('div'); // .categorypicker
1668 // Print current category description
1669 $chelper = new coursecat_helper();
1670 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1671 $output .= $this->box($description, array('class' => 'generalbox info'));
1674 // Prepare parameters for courses and categories lists in the tree
1675 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1676 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1678 $coursedisplayoptions = array();
1679 $catdisplayoptions = array();
1680 $browse = optional_param('browse', null, PARAM_ALPHA);
1681 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1682 $page = optional_param('page', 0, PARAM_INT);
1683 $baseurl = new moodle_url('/course/index.php');
1684 if ($coursecat->id) {
1685 $baseurl->param('categoryid', $coursecat->id);
1687 if ($perpage != $CFG->coursesperpage) {
1688 $baseurl->param('perpage', $perpage);
1690 $coursedisplayoptions['limit'] = $perpage;
1691 $catdisplayoptions['limit'] = $perpage;
1692 if ($browse === 'courses' || !$coursecat->has_children()) {
1693 $coursedisplayoptions['offset'] = $page * $perpage;
1694 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1695 $catdisplayoptions['nodisplay'] = true;
1696 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1697 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1698 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1699 $coursedisplayoptions['nodisplay'] = true;
1700 $catdisplayoptions['offset'] = $page * $perpage;
1701 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1702 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1703 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1704 } else {
1705 // we have a category that has both subcategories and courses, display pagination separately
1706 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1707 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1709 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1710 // Add course search form.
1711 $output .= $this->course_search_form();
1713 // Display course category tree.
1714 $output .= $this->coursecat_tree($chelper, $coursecat);
1716 // Add action buttons
1717 $output .= $this->container_start('buttons');
1718 $context = get_category_or_system_context($coursecat->id);
1719 if (has_capability('moodle/course:create', $context)) {
1720 // Print link to create a new course, for the 1st available category.
1721 if ($coursecat->id) {
1722 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1723 } else {
1724 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1726 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1728 ob_start();
1729 if (coursecat::count_all() == 1) {
1730 print_course_request_buttons(context_system::instance());
1731 } else {
1732 print_course_request_buttons($context);
1734 $output .= ob_get_contents();
1735 ob_end_clean();
1736 $output .= $this->container_end();
1738 return $output;
1742 * Serves requests to /course/category.ajax.php
1744 * In this renderer implementation it may expand the category content or
1745 * course content.
1747 * @return string
1748 * @throws coding_exception
1750 public function coursecat_ajax() {
1751 global $DB, $CFG;
1752 require_once($CFG->libdir. '/coursecatlib.php');
1754 $type = required_param('type', PARAM_INT);
1756 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1757 // This is a request for a category list of some kind.
1758 $categoryid = required_param('categoryid', PARAM_INT);
1759 $showcourses = required_param('showcourses', PARAM_INT);
1760 $depth = required_param('depth', PARAM_INT);
1762 $category = coursecat::get($categoryid);
1764 $chelper = new coursecat_helper();
1765 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1766 $coursedisplayoptions = array(
1767 'limit' => $CFG->coursesperpage,
1768 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1770 $catdisplayoptions = array(
1771 'limit' => $CFG->coursesperpage,
1772 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1774 $chelper->set_show_courses($showcourses)->
1775 set_courses_display_options($coursedisplayoptions)->
1776 set_categories_display_options($catdisplayoptions);
1778 return $this->coursecat_category_content($chelper, $category, $depth);
1779 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1780 // This is a request for the course information.
1781 $courseid = required_param('courseid', PARAM_INT);
1783 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1785 $chelper = new coursecat_helper();
1786 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1787 return $this->coursecat_coursebox_content($chelper, $course);
1788 } else {
1789 throw new coding_exception('Invalid request type');
1794 * Renders html to display search result page
1796 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1797 * @return string
1799 public function search_courses($searchcriteria) {
1800 global $CFG;
1801 $content = '';
1802 if (!empty($searchcriteria)) {
1803 // print search results
1804 require_once($CFG->libdir. '/coursecatlib.php');
1806 $displayoptions = array('sort' => array('displayname' => 1));
1807 // take the current page and number of results per page from query
1808 $perpage = optional_param('perpage', 0, PARAM_RAW);
1809 if ($perpage !== 'all') {
1810 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1811 $page = optional_param('page', 0, PARAM_INT);
1812 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1814 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1815 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1816 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1818 $class = 'course-search-result';
1819 foreach ($searchcriteria as $key => $value) {
1820 if (!empty($value)) {
1821 $class .= ' course-search-result-'. $key;
1824 $chelper = new coursecat_helper();
1825 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1826 set_courses_display_options($displayoptions)->
1827 set_search_criteria($searchcriteria)->
1828 set_attributes(array('class' => $class));
1830 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1831 $totalcount = coursecat::search_courses_count($searchcriteria);
1832 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1834 if (!$totalcount) {
1835 if (!empty($searchcriteria['search'])) {
1836 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1837 } else {
1838 $content .= $this->heading(get_string('novalidcourses'));
1840 } else {
1841 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1842 $content .= $courseslist;
1845 if (!empty($searchcriteria['search'])) {
1846 // print search form only if there was a search by search string, otherwise it is confusing
1847 $content .= $this->box_start('generalbox mdl-align');
1848 $content .= $this->course_search_form($searchcriteria['search']);
1849 $content .= $this->box_end();
1851 } else {
1852 // just print search form
1853 $content .= $this->box_start('generalbox mdl-align');
1854 $content .= $this->course_search_form();
1855 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1856 $content .= $this->box_end();
1858 return $content;
1862 * Renders html to print list of courses tagged with particular tag
1864 * @param int $tagid id of the tag
1865 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1866 * are displayed on the page and the per-page limit may be bigger
1867 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1868 * to display items in the same context first
1869 * @param int $ctx context id where to search for records
1870 * @param bool $rec search in subcontexts as well
1871 * @param array $displayoptions
1872 * @return string empty string if no courses are marked with this tag or rendered list of courses
1874 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1875 global $CFG;
1876 require_once($CFG->libdir . '/coursecatlib.php');
1877 if (empty($displayoptions)) {
1878 $displayoptions = array();
1880 $showcategories = coursecat::count_all() > 1;
1881 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1882 $chelper = new coursecat_helper();
1883 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1884 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1885 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1886 set_search_criteria($searchcriteria)->
1887 set_courses_display_options($displayoptions)->
1888 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1889 // (we set the same css class as in search results by tagid)
1890 if ($totalcount = coursecat::search_courses_count($searchcriteria)) {
1891 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1892 if ($exclusivemode) {
1893 return $this->coursecat_courses($chelper, $courses, $totalcount);
1894 } else {
1895 $tagfeed = new core_tag\output\tagfeed();
1896 $img = $this->output->pix_icon('i/course', '');
1897 foreach ($courses as $course) {
1898 $url = course_get_url($course);
1899 $imgwithlink = html_writer::link($url, $img);
1900 $coursename = html_writer::link($url, $course->get_formatted_name());
1901 $details = '';
1902 if ($showcategories && ($cat = coursecat::get($course->category, IGNORE_MISSING))) {
1903 $details = get_string('category').': '.
1904 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1905 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1907 $tagfeed->add($imgwithlink, $coursename, $details);
1909 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1912 return '';
1916 * Returns HTML to display one remote course
1918 * @param stdClass $course remote course information, contains properties:
1919 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1920 * @return string
1922 protected function frontpage_remote_course(stdClass $course) {
1923 $url = new moodle_url('/auth/mnet/jump.php', array(
1924 'hostid' => $course->hostid,
1925 'wantsurl' => '/course/view.php?id='. $course->remoteid
1928 $output = '';
1929 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1930 $output .= html_writer::start_tag('div', array('class' => 'info'));
1931 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1932 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1933 $output .= html_writer::end_tag('h3'); // .name
1934 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1935 $output .= html_writer::end_tag('div'); // .info
1936 $output .= html_writer::start_tag('div', array('class' => 'content'));
1937 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1938 $options = new stdClass();
1939 $options->noclean = true;
1940 $options->para = false;
1941 $options->overflowdiv = true;
1942 $output .= format_text($course->summary, $course->summaryformat, $options);
1943 $output .= html_writer::end_tag('div'); // .summary
1944 $addinfo = format_string($course->hostname) . ' : '
1945 . format_string($course->cat_name) . ' : '
1946 . format_string($course->shortname);
1947 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1948 $output .= html_writer::end_tag('div'); // .content
1949 $output .= html_writer::end_tag('div'); // .coursebox
1950 return $output;
1954 * Returns HTML to display one remote host
1956 * @param array $host host information, contains properties: name, url, count
1957 * @return string
1959 protected function frontpage_remote_host($host) {
1960 $output = '';
1961 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1962 $output .= html_writer::start_tag('div', array('class' => 'info'));
1963 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1964 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1965 $output .= html_writer::end_tag('h3'); // .name
1966 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1967 $output .= html_writer::end_tag('div'); // .info
1968 $output .= html_writer::start_tag('div', array('class' => 'content'));
1969 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1970 $output .= $host['count'] . ' ' . get_string('courses');
1971 $output .= html_writer::end_tag('div'); // .content
1972 $output .= html_writer::end_tag('div'); // .coursebox
1973 return $output;
1977 * Returns HTML to print list of courses user is enrolled to for the frontpage
1979 * Also lists remote courses or remote hosts if MNET authorisation is used
1981 * @return string
1983 public function frontpage_my_courses() {
1984 global $USER, $CFG, $DB;
1986 if (!isloggedin() or isguestuser()) {
1987 return '';
1990 $output = '';
1991 $courses = enrol_get_my_courses('summary, summaryformat');
1992 $rhosts = array();
1993 $rcourses = array();
1994 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1995 $rcourses = get_my_remotecourses($USER->id);
1996 $rhosts = get_my_remotehosts();
1999 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2001 $chelper = new coursecat_helper();
2002 if (count($courses) > $CFG->frontpagecourselimit) {
2003 // There are more enrolled courses than we can display, display link to 'My courses'.
2004 $totalcount = count($courses);
2005 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2006 $chelper->set_courses_display_options(array(
2007 'viewmoreurl' => new moodle_url('/my/'),
2008 'viewmoretext' => new lang_string('mycourses')
2010 } else {
2011 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2012 $chelper->set_courses_display_options(array(
2013 'viewmoreurl' => new moodle_url('/course/index.php'),
2014 'viewmoretext' => new lang_string('fulllistofcourses')
2016 $totalcount = $DB->count_records('course') - 1;
2018 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2019 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2020 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2022 // MNET
2023 if (!empty($rcourses)) {
2024 // at the IDP, we know of all the remote courses
2025 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2026 foreach ($rcourses as $course) {
2027 $output .= $this->frontpage_remote_course($course);
2029 $output .= html_writer::end_tag('div'); // .courses
2030 } elseif (!empty($rhosts)) {
2031 // non-IDP, we know of all the remote servers, but not courses
2032 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2033 foreach ($rhosts as $host) {
2034 $output .= $this->frontpage_remote_host($host);
2036 $output .= html_writer::end_tag('div'); // .courses
2039 return $output;
2043 * Returns HTML to print list of available courses for the frontpage
2045 * @return string
2047 public function frontpage_available_courses() {
2048 global $CFG;
2049 require_once($CFG->libdir. '/coursecatlib.php');
2051 $chelper = new coursecat_helper();
2052 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2053 set_courses_display_options(array(
2054 'recursive' => true,
2055 'limit' => $CFG->frontpagecourselimit,
2056 'viewmoreurl' => new moodle_url('/course/index.php'),
2057 'viewmoretext' => new lang_string('fulllistofcourses')));
2059 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2060 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
2061 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
2062 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2063 // Print link to create a new course, for the 1st available category.
2064 return $this->add_new_course_button();
2066 return $this->coursecat_courses($chelper, $courses, $totalcount);
2070 * Returns HTML to the "add new course" button for the page
2072 * @return string
2074 public function add_new_course_button() {
2075 global $CFG;
2076 // Print link to create a new course, for the 1st available category.
2077 $output = $this->container_start('buttons');
2078 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2079 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2080 $output .= $this->container_end('buttons');
2081 return $output;
2085 * Returns HTML to print tree with course categories and courses for the frontpage
2087 * @return string
2089 public function frontpage_combo_list() {
2090 global $CFG;
2091 require_once($CFG->libdir. '/coursecatlib.php');
2092 $chelper = new coursecat_helper();
2093 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2094 set_categories_display_options(array(
2095 'limit' => $CFG->coursesperpage,
2096 'viewmoreurl' => new moodle_url('/course/index.php',
2097 array('browse' => 'categories', 'page' => 1))
2098 ))->
2099 set_courses_display_options(array(
2100 'limit' => $CFG->coursesperpage,
2101 'viewmoreurl' => new moodle_url('/course/index.php',
2102 array('browse' => 'courses', 'page' => 1))
2103 ))->
2104 set_attributes(array('class' => 'frontpage-category-combo'));
2105 return $this->coursecat_tree($chelper, coursecat::get(0));
2109 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2111 * @return string
2113 public function frontpage_categories_list() {
2114 global $CFG;
2115 require_once($CFG->libdir. '/coursecatlib.php');
2116 $chelper = new coursecat_helper();
2117 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2118 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2119 set_categories_display_options(array(
2120 'limit' => $CFG->coursesperpage,
2121 'viewmoreurl' => new moodle_url('/course/index.php',
2122 array('browse' => 'categories', 'page' => 1))
2123 ))->
2124 set_attributes(array('class' => 'frontpage-category-names'));
2125 return $this->coursecat_tree($chelper, coursecat::get(0));
2129 * Renders the activity navigation.
2131 * Defer to template.
2133 * @param \core_course\output\activity_navigation $page
2134 * @return string html for the page
2136 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2137 $data = $page->export_for_template($this->output);
2138 return $this->output->render_from_template('core_course/activity_navigation', $data);
2142 * Display the selector to advertise or publish a course
2143 * @param int $courseid
2145 public function publicationselector($courseid) {
2146 $text = '';
2148 $advertiseurl = new moodle_url("/course/publish/metadata.php",
2149 array('sesskey' => sesskey(), 'id' => $courseid, 'advertise' => true));
2150 $advertisebutton = new single_button($advertiseurl, get_string('advertise', 'hub'));
2151 $text .= $this->output->render($advertisebutton);
2152 $text .= html_writer::tag('div', get_string('advertisepublication_help', 'hub'),
2153 array('class' => 'publishhelp'));
2155 $text .= html_writer::empty_tag('br'); // TODO Delete.
2157 $uploadurl = new moodle_url("/course/publish/metadata.php",
2158 array('sesskey' => sesskey(), 'id' => $courseid, 'share' => true));
2159 $uploadbutton = new single_button($uploadurl, get_string('share', 'hub'));
2160 $text .= $this->output->render($uploadbutton);
2161 $text .= html_writer::tag('div', get_string('sharepublication_help', 'hub'),
2162 array('class' => 'publishhelp'));
2164 return $text;
2168 * Display the listing of hub where a course is registered on
2169 * @param int $courseid
2170 * @param array $publications
2172 public function registeredonhublisting($courseid, $publications) {
2173 global $CFG;
2174 $table = new html_table();
2175 $table->head = array(get_string('type', 'hub'),
2176 get_string('date'), get_string('status', 'hub'), get_string('operation', 'hub'));
2177 $table->size = array('20%', '30%', '%20', '%25');
2179 $brtag = html_writer::empty_tag('br');
2181 foreach ($publications as $publication) {
2183 $params = array('id' => $publication->courseid, 'publicationid' => $publication->id);
2184 $cancelurl = new moodle_url("/course/publish/index.php", $params);
2185 $cancelbutton = new single_button($cancelurl, get_string('removefromhub', 'hub'));
2186 $cancelbutton->class = 'centeredbutton';
2187 $cancelbuttonhtml = $this->output->render($cancelbutton);
2189 if ($publication->enrollable) {
2190 $params = array('sesskey' => sesskey(), 'id' => $publication->courseid, 'publicationid' => $publication->id);
2191 $updateurl = new moodle_url("/course/publish/metadata.php", $params);
2192 $updatebutton = new single_button($updateurl, get_string('update', 'hub'));
2193 $updatebutton->class = 'centeredbutton';
2194 $updatebuttonhtml = $this->output->render($updatebutton);
2196 $operations = $updatebuttonhtml . $brtag . $cancelbuttonhtml;
2197 } else {
2198 $operations = $cancelbuttonhtml;
2201 // If the publication check time if bigger than May 2010, it has been checked.
2202 if ($publication->timechecked > 1273127954) {
2203 if ($publication->status == 0) {
2204 $status = get_string('statusunpublished', 'hub');
2205 } else {
2206 $status = get_string('statuspublished', 'hub');
2207 if (!empty($publication->link)) {
2208 $status = html_writer::link($publication->link, $status);
2212 $status .= $brtag . html_writer::tag('a', get_string('updatestatus', 'hub'),
2213 array('href' => $CFG->wwwroot . '/course/publish/index.php?id='
2214 . $courseid . "&updatestatusid=" . $publication->id
2215 . "&sesskey=" . sesskey())) .
2216 $brtag . get_string('lasttimechecked', 'hub') . ": "
2217 . format_time(time() - $publication->timechecked);
2218 } else {
2219 $status = get_string('neverchecked', 'hub') . $brtag
2220 . html_writer::tag('a', get_string('updatestatus', 'hub'),
2221 array('href' => $CFG->wwwroot . '/course/publish/index.php?id='
2222 . $courseid . "&updatestatusid=" . $publication->id
2223 . "&sesskey=" . sesskey()));
2225 // Add button cells.
2226 $cells = array($publication->enrollable ?
2227 get_string('advertised', 'hub') : get_string('shared', 'hub'),
2228 userdate($publication->timepublished,
2229 get_string('strftimedatetimeshort')), $status, $operations);
2230 $row = new html_table_row($cells);
2231 $table->data[] = $row;
2234 $contenthtml = html_writer::table($table);
2236 return $contenthtml;
2240 * Display unpublishing confirmation page
2241 * @param stdClass $publication
2242 * $publication->courseshortname
2243 * $publication->courseid
2244 * $publication->hubname
2245 * $publication->huburl
2246 * $publication->id
2248 public function confirmunpublishing($publication) {
2249 $optionsyes = array('sesskey' => sesskey(), 'id' => $publication->courseid,
2250 'hubcourseid' => $publication->hubcourseid,
2251 'cancel' => true, 'publicationid' => $publication->id, 'confirm' => true);
2252 $optionsno = array('sesskey' => sesskey(), 'id' => $publication->courseid);
2253 $publication->hubname = html_writer::tag('a', 'Moodle.net',
2254 array('href' => HUB_MOODLEORGHUBURL));
2255 $formcontinue = new single_button(new moodle_url("/course/publish/index.php",
2256 $optionsyes), get_string('unpublish', 'hub'), 'post');
2257 $formcancel = new single_button(new moodle_url("/course/publish/index.php",
2258 $optionsno), get_string('cancel'), 'get');
2259 return $this->output->confirm(get_string('unpublishconfirmation', 'hub', $publication),
2260 $formcontinue, $formcancel);
2264 * Display waiting information about backup size during uploading backup process
2265 * @param object $backupfile the backup stored_file
2266 * @return $html string
2268 public function sendingbackupinfo($backupfile) {
2269 $sizeinfo = new stdClass();
2270 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2271 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2272 array('class' => 'courseuploadtextinfo'));
2273 return $html;
2277 * Display upload successfull message and a button to the publish index page
2278 * @param int $id the course id
2279 * @return $html string
2281 public function sentbackupinfo($id) {
2282 $html = html_writer::tag('div', get_string('sent', 'hub'),
2283 array('class' => 'courseuploadtextinfo'));
2284 $publishindexurl = new moodle_url('/course/publish/index.php',
2285 array('sesskey' => sesskey(), 'id' => $id,
2286 'published' => true));
2287 $continue = $this->output->render(
2288 new single_button($publishindexurl, get_string('continue')));
2289 $html .= html_writer::tag('div', $continue, array('class' => 'sharecoursecontinue'));
2290 return $html;
2294 * Hub information (logo - name - description - link)
2295 * @param object $hubinfo
2296 * @return string html code
2298 public function hubinfo($hubinfo) {
2299 $screenshothtml = html_writer::empty_tag('img',
2300 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2301 $hubdescription = html_writer::tag('div', $screenshothtml,
2302 array('class' => 'hubscreenshot'));
2304 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2305 array('class' => 'hublink', 'href' => $hubinfo['url'],
2306 'onclick' => 'this.target="_blank"'));
2308 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2309 array('class' => 'hubdescription'));
2310 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2312 return $hubdescription;
2317 * Class storing display options and functions to help display course category and/or courses lists
2319 * This is a wrapper for coursecat objects that also stores display options
2320 * and functions to retrieve sorted and paginated lists of categories/courses.
2322 * If theme overrides methods in core_course_renderers that access this class
2323 * it may as well not use this class at all or extend it.
2325 * @package core
2326 * @copyright 2013 Marina Glancy
2327 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2329 class coursecat_helper {
2330 /** @var string [none, collapsed, expanded] how (if) display courses list */
2331 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2332 /** @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) */
2333 protected $subcatdepth = 1;
2334 /** @var array options to display courses list */
2335 protected $coursesdisplayoptions = array();
2336 /** @var array options to display subcategories list */
2337 protected $categoriesdisplayoptions = array();
2338 /** @var array additional HTML attributes */
2339 protected $attributes = array();
2340 /** @var array search criteria if the list is a search result */
2341 protected $searchcriteria = null;
2344 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2346 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2347 * @return coursecat_helper
2349 public function set_show_courses($showcourses) {
2350 $this->showcourses = $showcourses;
2351 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2352 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2353 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2354 return $this;
2358 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2360 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2362 public function get_show_courses() {
2363 return $this->showcourses;
2367 * Sets the maximum depth to expand subcategories in the tree
2369 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2371 * @param int $subcatdepth
2372 * @return coursecat_helper
2374 public function set_subcat_depth($subcatdepth) {
2375 $this->subcatdepth = $subcatdepth;
2376 return $this;
2380 * Returns the maximum depth to expand subcategories in the tree
2382 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2384 * @return int
2386 public function get_subcat_depth() {
2387 return $this->subcatdepth;
2391 * Sets options to display list of courses
2393 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2395 * Options that coursecat::get_courses() accept:
2396 * - recursive - return courses from subcategories as well. Use with care,
2397 * this may be a huge list!
2398 * - summary - preloads fields 'summary' and 'summaryformat'
2399 * - coursecontacts - preloads course contacts
2400 * - isenrolled - preloads indication whether this user is enrolled in the course
2401 * - sort - list of fields to sort. Example
2402 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2403 * will sort by idnumber asc, shortname asc and id desc.
2404 * Default: array('sortorder' => 1)
2405 * Only cached fields may be used for sorting!
2406 * - offset
2407 * - limit - maximum number of children to return, 0 or null for no limit
2409 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2411 * Also renderer can set here any additional options it wants to pass between renderer functions.
2413 * @param array $options
2414 * @return coursecat_helper
2416 public function set_courses_display_options($options) {
2417 $this->coursesdisplayoptions = $options;
2418 $this->set_show_courses($this->showcourses); // this will calculate special display options
2419 return $this;
2423 * Sets one option to display list of courses
2425 * @see coursecat_helper::set_courses_display_options()
2427 * @param string $key
2428 * @param mixed $value
2429 * @return coursecat_helper
2431 public function set_courses_display_option($key, $value) {
2432 $this->coursesdisplayoptions[$key] = $value;
2433 return $this;
2437 * Return the specified option to display list of courses
2439 * @param string $optionname option name
2440 * @param mixed $defaultvalue default value for option if it is not specified
2441 * @return mixed
2443 public function get_courses_display_option($optionname, $defaultvalue = null) {
2444 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2445 return $this->coursesdisplayoptions[$optionname];
2446 } else {
2447 return $defaultvalue;
2452 * Returns all options to display the courses
2454 * This array is usually passed to {@link coursecat::get_courses()} or
2455 * {@link coursecat::search_courses()}
2457 * @return array
2459 public function get_courses_display_options() {
2460 return $this->coursesdisplayoptions;
2464 * Sets options to display list of subcategories
2466 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2467 * Any other options may be used by renderer functions
2469 * @param array $options
2470 * @return coursecat_helper
2472 public function set_categories_display_options($options) {
2473 $this->categoriesdisplayoptions = $options;
2474 return $this;
2478 * Return the specified option to display list of subcategories
2480 * @param string $optionname option name
2481 * @param mixed $defaultvalue default value for option if it is not specified
2482 * @return mixed
2484 public function get_categories_display_option($optionname, $defaultvalue = null) {
2485 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2486 return $this->categoriesdisplayoptions[$optionname];
2487 } else {
2488 return $defaultvalue;
2493 * Returns all options to display list of subcategories
2495 * This array is usually passed to {@link coursecat::get_children()}
2497 * @return array
2499 public function get_categories_display_options() {
2500 return $this->categoriesdisplayoptions;
2504 * Sets additional general options to pass between renderer functions, usually HTML attributes
2506 * @param array $attributes
2507 * @return coursecat_helper
2509 public function set_attributes($attributes) {
2510 $this->attributes = $attributes;
2511 return $this;
2515 * Return all attributes and erases them so they are not applied again
2517 * @param string $classname adds additional class name to the beginning of $attributes['class']
2518 * @return array
2520 public function get_and_erase_attributes($classname) {
2521 $attributes = $this->attributes;
2522 $this->attributes = array();
2523 if (empty($attributes['class'])) {
2524 $attributes['class'] = '';
2526 $attributes['class'] = $classname . ' '. $attributes['class'];
2527 return $attributes;
2531 * Sets the search criteria if the course is a search result
2533 * Search string will be used to highlight terms in course name and description
2535 * @param array $searchcriteria
2536 * @return coursecat_helper
2538 public function set_search_criteria($searchcriteria) {
2539 $this->searchcriteria = $searchcriteria;
2540 return $this;
2544 * Returns formatted and filtered description of the given category
2546 * @param coursecat $coursecat category
2547 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2548 * if context is not specified it will be added automatically
2549 * @return string|null
2551 public function get_category_formatted_description($coursecat, $options = null) {
2552 if ($coursecat->id && !empty($coursecat->description)) {
2553 if (!isset($coursecat->descriptionformat)) {
2554 $descriptionformat = FORMAT_MOODLE;
2555 } else {
2556 $descriptionformat = $coursecat->descriptionformat;
2558 if ($options === null) {
2559 $options = array('noclean' => true, 'overflowdiv' => true);
2560 } else {
2561 $options = (array)$options;
2563 $context = context_coursecat::instance($coursecat->id);
2564 if (!isset($options['context'])) {
2565 $options['context'] = $context;
2567 $text = file_rewrite_pluginfile_urls($coursecat->description,
2568 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2569 return format_text($text, $descriptionformat, $options);
2571 return null;
2575 * Returns given course's summary with proper embedded files urls and formatted
2577 * @param course_in_list $course
2578 * @param array|stdClass $options additional formatting options
2579 * @return string
2581 public function get_course_formatted_summary($course, $options = array()) {
2582 global $CFG;
2583 require_once($CFG->libdir. '/filelib.php');
2584 if (!$course->has_summary()) {
2585 return '';
2587 $options = (array)$options;
2588 $context = context_course::instance($course->id);
2589 if (!isset($options['context'])) {
2590 // TODO see MDL-38521
2591 // option 1 (current), page context - no code required
2592 // option 2, system context
2593 // $options['context'] = context_system::instance();
2594 // option 3, course context:
2595 // $options['context'] = $context;
2596 // option 4, course category context:
2597 // $options['context'] = $context->get_parent_context();
2599 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2600 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2601 if (!empty($this->searchcriteria['search'])) {
2602 $summary = highlight($this->searchcriteria['search'], $summary);
2604 return $summary;
2608 * Returns course name as it is configured to appear in courses lists formatted to course context
2610 * @param course_in_list $course
2611 * @param array|stdClass $options additional formatting options
2612 * @return string
2614 public function get_course_formatted_name($course, $options = array()) {
2615 $options = (array)$options;
2616 if (!isset($options['context'])) {
2617 $options['context'] = context_course::instance($course->id);
2619 $name = format_string(get_course_display_name_for_list($course), true, $options);
2620 if (!empty($this->searchcriteria['search'])) {
2621 $name = highlight($this->searchcriteria['search'], $name);
2623 return $name;