MDL-68177 course: split course_info_box into different methods
[moodle.git] / course / renderer.php
CommitLineData
24e27ac0
SH
1<?php
2
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.
14//
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/>.
17
18/**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
21 *
22 * This renderer should contain methods useful to courses, and categories.
23 *
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
28
29/**
30 * The core course renderer
31 *
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
34 */
35class core_course_renderer extends plugin_renderer_base {
43e389ea
MG
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;
24e27ac0 42
53c1b936
ARN
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
45
24e27ac0
SH
46 /**
47 * A cache of strings
48 * @var stdClass
49 */
50 protected $strings;
51
3a0e3c34
JP
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
57 */
58 protected $categoryexpandedonload = false;
59
24e27ac0
SH
60 /**
61 * Override the constructor so that we can initialise the string cache
62 *
63 * @param moodle_page $page
64 * @param string $target
65 */
66 public function __construct(moodle_page $page, $target) {
67 $this->strings = new stdClass;
68 parent::__construct($page, $target);
a03dfb7d
MG
69 }
70
71 /**
fdac806a 72 * @deprecated since 3.2
a03dfb7d
MG
73 */
74 protected function add_modchoosertoggle() {
db03bff7 75 throw new coding_exception('core_course_renderer::add_modchoosertoggle() can not be used anymore.');
24e27ac0
SH
76 }
77
cb76fec0
PS
78 /**
79 * Renders course info box.
80 *
442f12f8 81 * @param stdClass $course
cb76fec0
PS
82 * @return string
83 */
84 public function course_info_box(stdClass $course) {
cb76fec0
PS
85 $content = '';
86 $content .= $this->output->box_start('generalbox info');
e2d70cca
MG
87 $chelper = new coursecat_helper();
88 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
89 $content .= $this->coursecat_coursebox($chelper, $course);
cb76fec0 90 $content .= $this->output->box_end();
cb76fec0
PS
91 return $content;
92 }
93
24e27ac0 94 /**
09ae7ee0 95 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
24e27ac0 96 *
09ae7ee0 97 * @deprecated since 2.5
24e27ac0 98 *
09ae7ee0
MG
99 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
100 *
101 * @param array $ignored argument ignored
24e27ac0
SH
102 * @return string
103 */
09ae7ee0
MG
104 public final function course_category_tree(array $ignored) {
105 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
106 return $this->frontpage_combo_list();
24e27ac0
SH
107 }
108
109 /**
110 * Renderers a category for use with course_category_tree
111 *
09ae7ee0
MG
112 * @deprecated since 2.5
113 *
114 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
115 *
24e27ac0
SH
116 * @param array $category
117 * @param int $depth
118 * @return string
119 */
09ae7ee0
MG
120 protected final function course_category_tree_category(stdClass $category, $depth=1) {
121 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
122 return '';
24e27ac0 123 }
01e0e704 124
4f2378d9
FM
125 /**
126 * Render a modchooser.
127 *
128 * @param renderable $modchooser The chooser.
129 * @return string
130 */
131 public function render_modchooser(renderable $modchooser) {
132 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
133 }
134
01e0e704
ARN
135 /**
136 * Build the HTML for the module chooser javascript popup
137 *
138 * @param array $modules A set of modules as returned form @see
139 * get_module_metadata
140 * @param object $course The course that will be displayed
141 * @return string The composed HTML for the module
142 */
143 public function course_modchooser($modules, $course) {
cd2efd12 144 debugging('course_modchooser() is deprecated. Please use course_activitychooser() instead.', DEBUG_DEVELOPER);
05b27f21
MM
145
146 return $this->course_activitychooser($course->id);
01e0e704
ARN
147 }
148
cd2efd12
MG
149 /**
150 * Build the HTML for the module chooser javascript popup.
151 *
152 * @param int $courseid The course id to fetch modules for.
153 * @return string
154 */
155 public function course_activitychooser($courseid) {
156
157 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
158 return '';
159 }
160
05b27f21 161 $this->page->requires->js_call_amd('core_course/activitychooser', 'init', [$courseid]);
cd2efd12
MG
162
163 return '';
164 }
165
01e0e704
ARN
166 /**
167 * Build the HTML for a specified set of modules
168 *
169 * @param array $modules A set of modules as used by the
170 * course_modchooser_module function
171 * @return string The composed HTML for the module
172 */
173 protected function course_modchooser_module_types($modules) {
4f2378d9
FM
174 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
175 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
176 return '';
01e0e704
ARN
177 }
178
179 /**
180 * Return the HTML for the specified module adding any required classes
181 *
182 * @param object $module An object containing the title, and link. An
183 * icon, and help text may optionally be specified. If the module
184 * contains subtypes in the types option, then these will also be
185 * displayed.
186 * @param array $classes Additional classes to add to the encompassing
187 * div element
188 * @return string The composed HTML for the module
189 */
190 protected function course_modchooser_module($module, $classes = array('option')) {
4f2378d9
FM
191 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
192 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
193 return '';
01e0e704
ARN
194 }
195
196 protected function course_modchooser_title($title, $identifier = null) {
4f2378d9
FM
197 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
198 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
199 return '';
01e0e704 200 }
f558b291
MG
201
202 /**
203 * Renders HTML for displaying the sequence of course module editing buttons
204 *
205 * @see course_get_cm_edit_actions()
206 *
b59f2e3b
SH
207 * @param action_link[] $actions Array of action_link objects
208 * @param cm_info $mod The module we are displaying actions for.
209 * @param array $displayoptions additional display options:
210 * ownerselector => A JS/CSS selector that can be used to find an cm node.
211 * If specified the owning node will be given the class 'action-menu-shown' when the action
212 * menu is being displayed.
f803ce26
SH
213 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
214 * the action menu to when it is being displayed.
215 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
f558b291
MG
216 * @return string
217 */
b59f2e3b 218 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
10fc1569
SH
219 global $CFG;
220
b59f2e3b
SH
221 if (empty($actions)) {
222 return '';
e282c679 223 }
b59f2e3b
SH
224
225 if (isset($displayoptions['ownerselector'])) {
226 $ownerselector = $displayoptions['ownerselector'];
227 } else if ($mod) {
228 $ownerselector = '#module-'.$mod->id;
229 } else {
230 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
231 $ownerselector = 'li.activity';
232 }
233
f803ce26
SH
234 if (isset($displayoptions['constraintselector'])) {
235 $constraint = $displayoptions['constraintselector'];
236 } else {
237 $constraint = '.course-content';
238 }
239
b59f2e3b
SH
240 $menu = new action_menu();
241 $menu->set_owner_selector($ownerselector);
ae3fd8eb 242 $menu->set_constraint($constraint);
9577caae 243 $menu->set_alignment(action_menu::TR, action_menu::BR);
a83d83e4 244 $menu->set_menu_trigger(get_string('edit'));
a83d83e4 245
e282c679 246 foreach ($actions as $action) {
3665af78 247 if ($action instanceof action_menu_link) {
cf69a00a 248 $action->add_class('cm-edit-action');
f558b291 249 }
cf69a00a 250 $menu->add($action);
f558b291 251 }
b59f2e3b 252 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
a83d83e4
AN
253
254 // Prioritise the menu ahead of all other actions.
255 $menu->prioritise = true;
256
b59f2e3b 257 return $this->render($menu);
f558b291 258 }
9a6aa5c1
MG
259
260 /**
261 * Renders HTML for the menus to add activities and resources to the current course
262 *
263 * @param stdClass $course
264 * @param int $section relative section number (field course_sections.section)
265 * @param int $sectionreturn The section to link back to
266 * @param array $displayoptions additional display options, for example blocks add
267 * option 'inblock' => true, suggesting to display controls vertically
268 * @return string
269 */
270 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
aa4d7e13
JD
271 global $CFG, $USER;
272
273 // The returned control HTML can be one of the following:
274 // - Only the non-ajax control (select menus of activities and resources) with a noscript fallback for non js clients.
275 // - Only the ajax control (the link which when clicked produces the activity chooser modal). No noscript fallback.
276 // - [Behat only]: The non-ajax control and optionally the ajax control (depending on site settings). If included, the link
277 // takes priority and the non-ajax control is wrapped in a <noscript>.
278 // Behat requires the third case because some features run with JS, some do not. We must include the noscript fallback.
279 $behatsite = defined('BEHAT_SITE_RUNNING');
280 $nonajaxcontrol = '';
281 $ajaxcontrol = '';
282 $courseajaxenabled = course_ajax_enabled($course);
283 $userchooserenabled = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
284
285 // Decide what combination of controls to output:
286 // During behat runs, both controls can be used in conjunction to provide non-js fallback.
287 // During normal use only one control or the other will be output. No non-js fallback is needed.
288 $rendernonajaxcontrol = $behatsite || !$courseajaxenabled || !$userchooserenabled || $course->id != $this->page->course->id;
289 $renderajaxcontrol = $courseajaxenabled && $userchooserenabled && $course->id == $this->page->course->id;
290
291 // The non-ajax control, which includes an entirely non-js (<noscript>) fallback too.
292 if ($rendernonajaxcontrol) {
293 $vertical = !empty($displayoptions['inblock']);
294
295 // Check to see if user can add menus.
296 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
2f040002 297 || !$this->page->user_is_editing()) {
aa4d7e13
JD
298 return '';
299 }
2f040002 300
aa4d7e13
JD
301 // Retrieve all modules with associated metadata.
302 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
303 $urlparams = ['section' => $section];
304 if (!is_null($sectionreturn)) {
305 $urlparams['sr'] = $sectionreturn;
306 }
307 $modules = $contentitemservice->get_content_items_for_user_in_course($USER, $course, $urlparams);
9a6aa5c1 308
aa4d7e13
JD
309 // Return if there are no content items to add.
310 if (empty($modules)) {
311 return '';
312 }
9a6aa5c1 313
aa4d7e13
JD
314 // We'll sort resources and activities into two lists.
315 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
316
317 foreach ($modules as $module) {
318 $activityclass = MOD_CLASS_ACTIVITY;
319 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
320 $activityclass = MOD_CLASS_RESOURCE;
321 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
322 // System modules cannot be added by user, do not add to dropdown.
323 continue;
324 }
325 $link = $module->link;
326 $activities[$activityclass][$link] = $module->title;
9a6aa5c1 327 }
9a6aa5c1 328
aa4d7e13
JD
329 $straddactivity = get_string('addactivity');
330 $straddresource = get_string('addresource');
331 $sectionname = get_section_name($course, $section);
332 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
333 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
9a6aa5c1 334
aa4d7e13
JD
335 $nonajaxcontrol = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-'
336 . $section));
9a6aa5c1 337
aa4d7e13
JD
338 if (!$vertical) {
339 $nonajaxcontrol .= html_writer::start_tag('div', array('class' => 'horizontal'));
340 }
9a6aa5c1 341
aa4d7e13
JD
342 if (!empty($activities[MOD_CLASS_RESOURCE])) {
343 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array('' => $straddresource), "ressection$section");
344 $select->set_help_icon('resources');
345 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
346 $nonajaxcontrol .= $this->output->render($select);
347 }
9a6aa5c1 348
aa4d7e13
JD
349 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
350 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array('' => $straddactivity), "section$section");
351 $select->set_help_icon('activities');
352 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
353 $nonajaxcontrol .= $this->output->render($select);
354 }
9a6aa5c1 355
aa4d7e13
JD
356 if (!$vertical) {
357 $nonajaxcontrol .= html_writer::end_tag('div');
358 }
9a6aa5c1 359
aa4d7e13
JD
360 $nonajaxcontrol .= html_writer::end_tag('div');
361 }
9a6aa5c1 362
aa4d7e13
JD
363 // The ajax control - the 'Add an activity or resource' link.
364 if ($renderajaxcontrol) {
365 // The module chooser link.
9a6aa5c1 366 $straddeither = get_string('addresourceoractivity');
aa4d7e13
JD
367 $ajaxcontrol = html_writer::start_tag('div', array('class' => 'mdl-right'));
368 $ajaxcontrol .= html_writer::start_tag('div', array('class' => 'section-modchooser'));
9a6aa5c1
MG
369 $icon = $this->output->pix_icon('t/add', '');
370 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
aa4d7e13 371 $ajaxcontrol .= html_writer::tag('button', $icon . $span, array(
cd2efd12
MG
372 'class' => 'section-modchooser-link btn btn-link',
373 'data-action' => 'open-chooser',
374 'data-sectionid' => $section,
cd2efd12
MG
375 )
376 );
aa4d7e13
JD
377 $ajaxcontrol .= html_writer::end_tag('div');
378 $ajaxcontrol .= html_writer::end_tag('div');
379
380 // Load the JS for the modal.
381 $this->course_activitychooser($course->id);
382 }
383
384 // Behat only: If both controls are being included in the HTML,
385 // show the link by default and only fall back to the selects if js is disabled.
386 if ($behatsite && $renderajaxcontrol) {
387 $nonajaxcontrol = html_writer::tag('div', $nonajaxcontrol, array('class' => 'hiddenifjs addresourcedropdown'));
388 $ajaxcontrol = html_writer::tag('div', $ajaxcontrol, array('class' => 'visibleifjs addresourcemodchooser'));
9a6aa5c1
MG
389 }
390
aa4d7e13
JD
391 // If behat is running, we should have the non-ajax control + the ajax control.
392 // Otherwise, we'll have one or the other.
393 return $ajaxcontrol . $nonajaxcontrol;
9a6aa5c1 394 }
7e29340f 395
f4b571ab 396 /**
9825951b 397 * Renders html to display a course search form.
f4b571ab
MG
398 *
399 * @param string $value default value to populate the search field
400 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
401 * @return string
402 */
9825951b 403 public function course_search_form($value = '', $format = 'plain') {
f4b571ab
MG
404 static $count = 0;
405 $formid = 'coursesearch';
406 if ((++$count) > 1) {
407 $formid .= $count;
408 }
409
410 switch ($format) {
411 case 'navbar' :
412 $formid = 'coursesearchnavbar';
413 $inputid = 'navsearchbox';
414 $inputsize = 20;
415 break;
416 case 'short' :
417 $inputid = 'shortsearchbox';
418 $inputsize = 12;
419 break;
420 default :
421 $inputid = 'coursesearchbox';
422 $inputsize = 30;
423 }
424
36667548
SG
425 $data = new stdClass();
426 $data->searchurl = \core_search\manager::get_course_search_url()->out(false);
427 $data->id = $formid;
428 $data->inputid = $inputid;
429 $data->inputsize = $inputsize;
430 $data->value = $value;
431 $data->areaids = 'core_course-course';
432
aab977e0 433 if ($format != 'navbar') {
9825951b
MM
434 $helpicon = new \help_icon('coursesearch', 'core');
435 $data->helpicon = $helpicon->export_for_template($this);
aab977e0 436 }
f4b571ab 437
9825951b 438 return $this->render_from_template('core_course/course_search_form', $data);
f4b571ab
MG
439 }
440
7e29340f
MG
441 /**
442 * Renders html for completion box on course page
443 *
444 * If completion is disabled, returns empty string
445 * If completion is automatic, returns an icon of the current completion state
446 * If completion is manual, returns a form (with an icon inside) that allows user to
447 * toggle completion
448 *
449 * @param stdClass $course course object
450 * @param completion_info $completioninfo completion info for the course, it is recommended
451 * to fetch once for all modules in course/section for performance
452 * @param cm_info $mod module to show completion for
453 * @param array $displayoptions display options, not used in core
454 * @return string
455 */
456 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
d6cea5cc 457 global $CFG, $DB, $USER;
7e29340f 458 $output = '';
d6cea5cc
AB
459
460 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
461 $isediting = $this->page->user_is_editing();
462
1c885118 463 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
7e29340f
MG
464 return $output;
465 }
466 if ($completioninfo === null) {
467 $completioninfo = new completion_info($course);
468 }
469 $completion = $completioninfo->is_enabled($mod);
d6cea5cc 470
7e29340f 471 if ($completion == COMPLETION_TRACKING_NONE) {
d6cea5cc 472 if ($isediting) {
26dd99d2
AN
473 $output .= html_writer::span('&nbsp;', 'filler');
474 }
7e29340f
MG
475 return $output;
476 }
477
7e29340f
MG
478 $completionicon = '';
479
d6cea5cc 480 if ($isediting || !$istrackeduser) {
7e29340f
MG
481 switch ($completion) {
482 case COMPLETION_TRACKING_MANUAL :
483 $completionicon = 'manual-enabled'; break;
484 case COMPLETION_TRACKING_AUTOMATIC :
485 $completionicon = 'auto-enabled'; break;
486 }
d6cea5cc
AB
487 } else {
488 $completiondata = $completioninfo->get_data($mod, true);
489 if ($completion == COMPLETION_TRACKING_MANUAL) {
490 switch($completiondata->completionstate) {
491 case COMPLETION_INCOMPLETE:
492 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
493 break;
494 case COMPLETION_COMPLETE:
495 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
496 break;
497 }
498 } else { // Automatic
499 switch($completiondata->completionstate) {
500 case COMPLETION_INCOMPLETE:
501 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
502 break;
503 case COMPLETION_COMPLETE:
504 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
505 break;
506 case COMPLETION_COMPLETE_PASS:
507 $completionicon = 'auto-pass'; break;
508 case COMPLETION_COMPLETE_FAIL:
509 $completionicon = 'auto-fail'; break;
510 }
7e29340f
MG
511 }
512 }
513 if ($completionicon) {
c21b42e7 514 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
d6cea5cc 515 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
6f4adc6b
JD
516 $args = new stdClass();
517 $args->modname = $formattedname;
8fbc41d8 518 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
6f4adc6b
JD
519 $args->overrideuser = fullname($overridebyuser);
520 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
521 } else {
522 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
523 }
8d90aec2 524
d6cea5cc 525 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
8d90aec2
AN
526 // When editing, the icon is just an image.
527 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
528 array('title' => $imgalt, 'class' => 'iconsmall'));
529 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
530 array('class' => 'autocompletion'));
531 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
7e29340f
MG
532 $newstate =
533 $completiondata->completionstate == COMPLETION_COMPLETE
534 ? COMPLETION_INCOMPLETE
535 : COMPLETION_COMPLETE;
536 // In manual mode the icon is a toggle form...
537
538 // If this completion state is used by the
539 // conditional activities system, we need to turn
540 // off the JS.
541 $extraclass = '';
542 if (!empty($CFG->enableavailability) &&
00c832d7 543 core_availability\info::completion_value_used($course, $mod->id)) {
7e29340f
MG
544 $extraclass = ' preventjs';
545 }
546 $output .= html_writer::start_tag('form', array('method' => 'post',
547 'action' => new moodle_url('/course/togglecompletion.php'),
548 'class' => 'togglecompletion'. $extraclass));
549 $output .= html_writer::start_tag('div');
550 $output .= html_writer::empty_tag('input', array(
551 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
552 $output .= html_writer::empty_tag('input', array(
553 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
554 $output .= html_writer::empty_tag('input', array(
c21b42e7 555 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
7e29340f
MG
556 $output .= html_writer::empty_tag('input', array(
557 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
663640f5 558 $output .= html_writer::tag('button',
d2d82a9d 559 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
7219f590 560 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
7e29340f
MG
561 $output .= html_writer::end_tag('div');
562 $output .= html_writer::end_tag('form');
563 } else {
8d90aec2 564 // In auto mode, the icon is just an image.
7e29340f
MG
565 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
566 array('title' => $imgalt));
567 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
568 array('class' => 'autocompletion'));
569 }
570 }
571 return $output;
572 }
ed513fad
MG
573
574 /**
575 * Checks if course module has any conditions that may make it unavailable for
576 * all or some of the students
577 *
578 * This function is internal and is only used to create CSS classes for the module name/text
579 *
580 * @param cm_info $mod
581 * @return bool
582 */
583 protected function is_cm_conditionally_hidden(cm_info $mod) {
584 global $CFG;
585 $conditionalhidden = false;
586 if (!empty($CFG->enableavailability)) {
00c832d7 587 $info = new \core_availability\info_module($mod);
588 $conditionalhidden = !$info->is_available_for_all();
ed513fad
MG
589 }
590 return $conditionalhidden;
591 }
592
593 /**
594 * Renders html to display a name with the link to the course module on a course page
595 *
596 * If module is unavailable for user but still needs to be displayed
597 * in the list, just the name is returned without a link
598 *
599 * Note, that for course modules that never have separate pages (i.e. labels)
600 * this function return an empty string
601 *
602 * @param cm_info $mod
603 * @param array $displayoptions
604 * @return string
605 */
606 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
8341055e 607 if (!$mod->is_visible_on_course_page() || !$mod->url) {
f59f89b4
MG
608 // Nothing to be displayed to the user.
609 return '';
610 }
611
8341055e
MG
612 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
613 $groupinglabel = $mod->get_grouping_label($textclasses);
614
f59f89b4
MG
615 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
616 // to get the display title of the activity.
617 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
8341055e
MG
618 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
619 $groupinglabel;
620 }
621
622 /**
623 * Returns the CSS classes for the activity name/content
624 *
625 * For items which are hidden, unavailable or stealth but should be displayed
626 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
627 * Students will also see as dimmed activities names that are not yet available
628 * but should still be displayed (without link) with availability info.
629 *
630 * @param cm_info $mod
631 * @return array array of two elements ($linkclasses, $textclasses)
632 */
633 protected function course_section_cm_classes(cm_info $mod) {
634 $linkclasses = '';
635 $textclasses = '';
636 if ($mod->uservisible) {
637 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
638 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
639 has_capability('moodle/course:viewhiddenactivities', $mod->context);
640 if ($accessiblebutdim) {
641 $linkclasses .= ' dimmed';
642 $textclasses .= ' dimmed_text';
643 if ($conditionalhidden) {
644 $linkclasses .= ' conditionalhidden';
645 $textclasses .= ' conditionalhidden';
646 }
647 }
648 if ($mod->is_stealth()) {
649 // Stealth activity is the one that is not visible on course page.
650 // It still may be displayed to the users who can manage it.
651 $linkclasses .= ' stealth';
652 $textclasses .= ' stealth';
653 }
654 } else {
655 $linkclasses .= ' dimmed';
e20b490d 656 $textclasses .= ' dimmed dimmed_text';
8341055e
MG
657 }
658 return array($linkclasses, $textclasses);
f59f89b4
MG
659 }
660
661 /**
662 * Renders html to display a name with the link to the course module on a course page
663 *
664 * If module is unavailable for user but still needs to be displayed
665 * in the list, just the name is returned without a link
666 *
667 * Note, that for course modules that never have separate pages (i.e. labels)
668 * this function return an empty string
669 *
670 * @param cm_info $mod
671 * @param array $displayoptions
672 * @return string
673 */
674 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
ed513fad 675 $output = '';
73ee2fda 676 $url = $mod->url;
8341055e
MG
677 if (!$mod->is_visible_on_course_page() || !$url) {
678 // Nothing to be displayed to the user.
ed513fad
MG
679 return $output;
680 }
681
682 //Accessibility: for files get description via icon, this is very ugly hack!
683 $instancename = $mod->get_formatted_name();
ed513fad
MG
684 $altname = $mod->modfullname;
685 // Avoid unnecessary duplication: if e.g. a forum name already
686 // includes the word forum (or Forum, etc) then it is unhelpful
687 // to include that in the accessible description that is added.
2f1e464a
PS
688 if (false !== strpos(core_text::strtolower($instancename),
689 core_text::strtolower($altname))) {
ed513fad
MG
690 $altname = '';
691 }
692 // File type after name, for alphabetic lists (screen reader).
693 if ($altname) {
694 $altname = get_accesshide(' '.$altname);
695 }
696
8341055e 697 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
ed513fad
MG
698
699 // Get on-click attribute value if specified and decode the onclick - it
700 // has already been encoded for display (puke).
73ee2fda 701 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
ed513fad 702
ed513fad
MG
703 // Display link itself.
704 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
8adb1b1e 705 'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
ed513fad
MG
706 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
707 if ($mod->uservisible) {
8341055e 708 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick));
ed513fad
MG
709 } else {
710 // We may be displaying this just in order to show information
8341055e
MG
711 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
712 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
ed513fad
MG
713 }
714 return $output;
715 }
716
717 /**
718 * Renders html to display the module content on the course page (i.e. text of the labels)
719 *
720 * @param cm_info $mod
721 * @param array $displayoptions
722 * @return string
723 */
724 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
725 $output = '';
8341055e 726 if (!$mod->is_visible_on_course_page()) {
ed513fad
MG
727 // nothing to be displayed to the user
728 return $output;
729 }
730 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
8341055e
MG
731 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
732 if ($mod->url && $mod->uservisible) {
ed513fad
MG
733 if ($content) {
734 // If specified, display extra content after link.
735 $output = html_writer::tag('div', $content, array('class' =>
736 trim('contentafterlink ' . $textclasses)));
737 }
738 } else {
0556eaa9
JB
739 $groupinglabel = $mod->get_grouping_label($textclasses);
740
ed513fad 741 // No link, so display only content.
8341055e 742 $output = html_writer::tag('div', $content . $groupinglabel,
4c9e8ea7 743 array('class' => 'contentwithoutlink ' . $textclasses));
ed513fad
MG
744 }
745 return $output;
746 }
747
8341055e
MG
748 /**
749 * Displays availability info for a course section or course module
750 *
751 * @param string $text
752 * @param string $additionalclasses
753 * @return string
754 */
755 public function availability_info($text, $additionalclasses = '') {
7352805d 756
8341055e 757 $data = ['text' => $text, 'classes' => $additionalclasses];
7352805d
DM
758 $additionalclasses = array_filter(explode(' ', $additionalclasses));
759
760 if (in_array('ishidden', $additionalclasses)) {
761 $data['ishidden'] = 1;
762
763 } else if (in_array('isstealth', $additionalclasses)) {
764 $data['isstealth'] = 1;
765
766 } else if (in_array('isrestricted', $additionalclasses)) {
767 $data['isrestricted'] = 1;
768
769 if (in_array('isfullinfo', $additionalclasses)) {
770 $data['isfullinfo'] = 1;
771 }
772 }
773
8341055e
MG
774 return $this->render_from_template('core/availability_info', $data);
775 }
776
ed513fad
MG
777 /**
778 * Renders HTML to show course module availability information (for someone who isn't allowed
779 * to see the activity itself, or for staff)
780 *
781 * @param cm_info $mod
782 * @param array $displayoptions
783 * @return string
784 */
785 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
786 global $CFG;
8341055e
MG
787 $output = '';
788 if (!$mod->is_visible_on_course_page()) {
789 return $output;
790 }
ed513fad
MG
791 if (!$mod->uservisible) {
792 // this is a student who is not allowed to see the module but might be allowed
793 // to see availability info (i.e. "Available from ...")
00c832d7 794 if (!empty($mod->availableinfo)) {
795 $formattedinfo = \core_availability\info::format_info(
796 $mod->availableinfo, $mod->get_course());
7352805d 797 $output = $this->availability_info($formattedinfo, 'isrestricted');
ed513fad
MG
798 }
799 return $output;
800 }
801 // this is a teacher who is allowed to see module but still should see the
802 // information that module is not available to all/some students
803 $modcontext = context_module::instance($mod->id);
804 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
8341055e
MG
805 if ($canviewhidden && !$mod->visible) {
806 // This module is hidden but current user has capability to see it.
807 // Do not display the availability info if the whole section is hidden.
808 if ($mod->get_section_info()->visible) {
809 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
810 }
811 } else if ($mod->is_stealth()) {
812 // This module is available but is normally not displayed on the course page
813 // (this user can see it because they can manage it).
814 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
815 }
ed513fad 816 if ($canviewhidden && !empty($CFG->enableavailability)) {
8341055e 817 // Display information about conditional availability.
ed513fad
MG
818 // Don't add availability information if user is not editing and activity is hidden.
819 if ($mod->visible || $this->page->user_is_editing()) {
7352805d 820 $hidinfoclass = 'isrestricted isfullinfo';
ed513fad 821 if (!$mod->visible) {
7352805d 822 $hidinfoclass .= ' hide';
ed513fad 823 }
00c832d7 824 $ci = new \core_availability\info_module($mod);
ed513fad 825 $fullinfo = $ci->get_full_information();
00c832d7 826 if ($fullinfo) {
827 $formattedinfo = \core_availability\info::format_info(
828 $fullinfo, $mod->get_course());
8341055e 829 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
ed513fad
MG
830 }
831 }
832 }
8341055e 833 return $output;
ed513fad 834 }
c58a25d6 835
9ce4fa2f
AN
836 /**
837 * Renders HTML to display one course module for display within a section.
838 *
839 * This function calls:
840 * {@link core_course_renderer::course_section_cm()}
841 *
842 * @param stdClass $course
843 * @param completion_info $completioninfo
844 * @param cm_info $mod
845 * @param int|null $sectionreturn
846 * @param array $displayoptions
847 * @return String
848 */
849 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
850 $output = '';
851 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
73ee2fda 852 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
9ce4fa2f
AN
853 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
854 }
855 return $output;
856 }
857
c58a25d6
MG
858 /**
859 * Renders HTML to display one course module in a course section
860 *
861 * This includes link, content, availability, completion info and additional information
862 * that module type wants to display (i.e. number of unread forum posts)
863 *
864 * This function calls:
865 * {@link core_course_renderer::course_section_cm_name()}
c58a25d6
MG
866 * {@link core_course_renderer::course_section_cm_text()}
867 * {@link core_course_renderer::course_section_cm_availability()}
868 * {@link core_course_renderer::course_section_cm_completion()}
869 * {@link course_get_cm_edit_actions()}
870 * {@link core_course_renderer::course_section_cm_edit_actions()}
33919cca 871 *
c58a25d6
MG
872 * @param stdClass $course
873 * @param completion_info $completioninfo
874 * @param cm_info $mod
875 * @param int|null $sectionreturn
876 * @param array $displayoptions
877 * @return string
878 */
879 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
880 $output = '';
881 // We return empty string (because course module will not be displayed at all)
882 // if:
883 // 1) The activity is not visible to users
884 // and
00c832d7 885 // 2) The 'availableinfo' is empty, i.e. the activity was
c58a25d6
MG
886 // hidden in a way that leaves no info, such as using the
887 // eye icon.
8341055e 888 if (!$mod->is_visible_on_course_page()) {
c58a25d6
MG
889 return $output;
890 }
891
b59f2e3b 892 $indentclasses = 'mod-indent';
c58a25d6
MG
893 if (!empty($mod->indent)) {
894 $indentclasses .= ' mod-indent-'.$mod->indent;
895 if ($mod->indent > 15) {
896 $indentclasses .= ' mod-indent-huge';
897 }
898 }
4657ba81
AN
899
900 $output .= html_writer::start_tag('div');
901
902 if ($this->page->user_is_editing()) {
903 $output .= course_get_cm_move($mod, $sectionreturn);
904 }
905
4c9e8ea7 906 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
c58a25d6 907
4c9e8ea7
AN
908 // This div is used to indent the content.
909 $output .= html_writer::div('', $indentclasses);
910
911 // Start a wrapper for the actual content to keep the indentation consistent
912 $output .= html_writer::start_tag('div');
c58a25d6
MG
913
914 // Display the link to the module (or do nothing if module has no url)
4c9e8ea7
AN
915 $cmname = $this->course_section_cm_name($mod, $displayoptions);
916
917 if (!empty($cmname)) {
918 // Start the div for the activity title, excluding the edit icons.
919 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
920 $output .= $cmname;
921
c58a25d6 922
4c9e8ea7 923 // Module can put text after the link (e.g. forum unread)
73ee2fda 924 $output .= $mod->afterlink;
c58a25d6 925
4c9e8ea7
AN
926 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
927 $output .= html_writer::end_tag('div'); // .activityinstance
928 }
c58a25d6
MG
929
930 // If there is content but NO link (eg label), then display the
931 // content here (BEFORE any icons). In this case cons must be
932 // displayed after the content so that it makes more sense visually
933 // and for accessibility reasons, e.g. if you have a one-line label
934 // it should work similarly (at least in terms of ordering) to an
935 // activity.
936 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
73ee2fda 937 $url = $mod->url;
c58a25d6
MG
938 if (empty($url)) {
939 $output .= $contentpart;
940 }
941
26dd99d2 942 $modicons = '';
b59f2e3b
SH
943 if ($this->page->user_is_editing()) {
944 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
26dd99d2 945 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
73ee2fda 946 $modicons .= $mod->afterediticons;
b59f2e3b 947 }
c58a25d6 948
26dd99d2
AN
949 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
950
951 if (!empty($modicons)) {
99cac461 952 $output .= html_writer::div($modicons, 'actions');
26dd99d2 953 }
c58a25d6 954
084c2ef1
MG
955 // Show availability info (if module is not available).
956 $output .= $this->course_section_cm_availability($mod, $displayoptions);
957
c58a25d6
MG
958 // If there is content AND a link, then display the content here
959 // (AFTER any icons). Otherwise it was displayed before
960 if (!empty($url)) {
961 $output .= $contentpart;
962 }
963
4c9e8ea7
AN
964 $output .= html_writer::end_tag('div'); // $indentclasses
965
966 // End of indentation div.
967 $output .= html_writer::end_tag('div');
4657ba81
AN
968
969 $output .= html_writer::end_tag('div');
c58a25d6
MG
970 return $output;
971 }
972
592f3ae2
MG
973 /**
974 * Message displayed to the user when they try to access unavailable activity following URL
975 *
976 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
977 * notification only. It also does not check if module is visible on course page or not.
978 *
979 * The message will be displayed inside notification!
980 *
981 * @param cm_info $cm
982 * @return string
983 */
2c3a34f0 984 public function course_section_cm_unavailable_error_message(cm_info $cm) {
592f3ae2
MG
985 if ($cm->uservisible) {
986 return null;
987 }
988 if (!$cm->availableinfo) {
989 return get_string('activityiscurrentlyhidden');
990 }
991
992 $altname = get_accesshide(' ' . $cm->modfullname);
993 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
994 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
995 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
996 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
997 return html_writer::div($name, 'activityinstance-error') .
998 html_writer::div($formattedinfo, 'availabilityinfo-error');
999 }
1000
c58a25d6
MG
1001 /**
1002 * Renders HTML to display a list of course modules in a course section
1003 * Also displays "move here" controls in Javascript-disabled mode
1004 *
1005 * This function calls {@link core_course_renderer::course_section_cm()}
1006 *
1007 * @param stdClass $course course object
1008 * @param int|stdClass|section_info $section relative section number or section object
1009 * @param int $sectionreturn section number to return to
1010 * @param int $displayoptions
1011 * @return void
1012 */
1013 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1014 global $USER;
1015
1016 $output = '';
1017 $modinfo = get_fast_modinfo($course);
1018 if (is_object($section)) {
1019 $section = $modinfo->get_section_info($section->section);
1020 } else {
1021 $section = $modinfo->get_section_info($section);
1022 }
1023 $completioninfo = new completion_info($course);
1024
1025 // check if we are currently in the process of moving a module with JavaScript disabled
1026 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1027 if ($ismoving) {
1028 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1029 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1030 }
1031
1032 // Get the list of modules visible to user (excluding the module being moved if there is one)
1033 $moduleshtml = array();
1034 if (!empty($modinfo->sections[$section->section])) {
1035 foreach ($modinfo->sections[$section->section] as $modnumber) {
1036 $mod = $modinfo->cms[$modnumber];
1037
1038 if ($ismoving and $mod->id == $USER->activitycopy) {
1039 // do not display moving mod
1040 continue;
1041 }
1042
9ce4fa2f 1043 if ($modulehtml = $this->course_section_cm_list_item($course,
c58a25d6
MG
1044 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1045 $moduleshtml[$modnumber] = $modulehtml;
1046 }
1047 }
1048 }
1049
1a3f52a1 1050 $sectionoutput = '';
c58a25d6 1051 if (!empty($moduleshtml) || $ismoving) {
c58a25d6
MG
1052 foreach ($moduleshtml as $modnumber => $modulehtml) {
1053 if ($ismoving) {
1054 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
33b6b8c9
JF
1055 $sectionoutput .= html_writer::tag('li',
1056 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1057 array('class' => 'movehere'));
c58a25d6
MG
1058 }
1059
1a3f52a1 1060 $sectionoutput .= $modulehtml;
c58a25d6
MG
1061 }
1062
1063 if ($ismoving) {
1064 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
584539c0 1065 $sectionoutput .= html_writer::tag('li',
33b6b8c9
JF
1066 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1067 array('class' => 'movehere'));
c58a25d6 1068 }
c58a25d6
MG
1069 }
1070
1a3f52a1
AN
1071 // Always output the section module list.
1072 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1073
c58a25d6
MG
1074 return $output;
1075 }
43e389ea 1076
9176cdb6
MG
1077 /**
1078 * Displays a custom list of courses with paging bar if necessary
1079 *
1080 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1081 * appears under the list.
1082 *
1083 * If both $paginationurl and $totalcount are specified, and $totalcount is
1084 * bigger than count($courses), a paging bar is displayed above and under the
1085 * courses list.
1086 *
442f12f8 1087 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
9176cdb6
MG
1088 * @param bool $showcategoryname whether to add category name to the course description
1089 * @param string $additionalclasses additional CSS classes to add to the div.courses
1090 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1091 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1092 * @param int $page current page number (defaults to 0 referring to the first page)
1093 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1094 * @return string
1095 */
1096 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1097 global $CFG;
1098 // create instance of coursecat_helper to pass display options to function rendering courses list
1099 $chelper = new coursecat_helper();
1100 if ($showcategoryname) {
1101 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1102 } else {
1103 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1104 }
1105 if ($totalcount !== null && $paginationurl !== null) {
1106 // add options to display pagination
1107 if ($perpage === null) {
1108 $perpage = $CFG->coursesperpage;
1109 }
1110 $chelper->set_courses_display_options(array(
1111 'limit' => $perpage,
1112 'offset' => ((int)$page) * $perpage,
1113 'paginationurl' => $paginationurl,
1114 ));
1115 } else if ($paginationurl !== null) {
1116 // add options to display 'View more' link
1117 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1118 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1119 }
1120 $chelper->set_attributes(array('class' => $additionalclasses));
1121 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1122 return $content;
1123 }
1124
ebd08abc
MM
1125 /**
1126 * Returns HTML to display course name.
1127 *
1128 * @param coursecat_helper $chelper
1129 * @param core_course_list_element $course
1130 * @return string
1131 */
1132 protected function course_name(coursecat_helper $chelper, core_course_list_element $course): string {
1133 $content = '';
1134 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1135 $nametag = 'h3';
1136 } else {
1137 $nametag = 'div';
1138 }
1139 $coursename = $chelper->get_course_formatted_name($course);
1140 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', ['id' => $course->id]),
1141 $coursename, ['class' => $course->visible ? '' : 'dimmed']);
1142 $content .= html_writer::tag($nametag, $coursenamelink, ['class' => 'coursename']);
1143 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1144 $content .= html_writer::start_tag('div', ['class' => 'moreinfo']);
1145 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1146 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1147 || $course->has_custom_fields()) {
1148 $url = new moodle_url('/course/info.php', ['id' => $course->id]);
1149 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1150 $content .= html_writer::link($url, $image, ['title' => $this->strings->summary]);
1151 // Make sure JS file to expand course content is included.
1152 $this->coursecat_include_js();
1153 }
1154 }
1155 $content .= html_writer::end_tag('div');
1156 return $content;
1157 }
1158
1159 /**
1160 * Returns HTML to display course enrolment icons.
1161 *
1162 * @param core_course_list_element $course
1163 * @return string
1164 */
1165 protected function course_enrolment_icons(core_course_list_element $course): string {
1166 $content = '';
1167 if ($icons = enrol_get_course_info_icons($course)) {
1168 $content .= html_writer::start_tag('div', ['class' => 'enrolmenticons']);
1169 foreach ($icons as $icon) {
1170 $content .= $this->render($icon);
1171 }
1172 $content .= html_writer::end_tag('div');
1173 }
1174 return $content;
1175 }
1176
43e389ea
MG
1177 /**
1178 * Displays one course in the list of courses.
1179 *
1180 * This is an internal function, to display an information about just one course
1181 * please use {@link core_course_renderer::course_info_box()}
1182 *
1183 * @param coursecat_helper $chelper various display options
442f12f8 1184 * @param core_course_list_element|stdClass $course
43e389ea
MG
1185 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1186 * depend on the course position in list - first/last/even/odd)
1187 * @return string
1188 */
1189 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
43e389ea
MG
1190 if (!isset($this->strings->summary)) {
1191 $this->strings->summary = get_string('summary');
1192 }
1193 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1194 return '';
1195 }
1196 if ($course instanceof stdClass) {
442f12f8 1197 $course = new core_course_list_element($course);
43e389ea
MG
1198 }
1199 $content = '';
1200 $classes = trim('coursebox clearfix '. $additionalclasses);
ebd08abc 1201 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
43e389ea 1202 $classes .= ' collapsed';
43e389ea 1203 }
53c1b936
ARN
1204
1205 // .coursebox
1206 $content .= html_writer::start_tag('div', array(
1207 'class' => $classes,
1208 'data-courseid' => $course->id,
1209 'data-type' => self::COURSECAT_TYPE_COURSE,
1210 ));
43e389ea
MG
1211
1212 $content .= html_writer::start_tag('div', array('class' => 'info'));
ebd08abc
MM
1213 $content .= $this->course_name($chelper, $course);
1214 $content .= $this->course_enrolment_icons($course);
1215 $content .= html_writer::end_tag('div');
43e389ea
MG
1216
1217 $content .= html_writer::start_tag('div', array('class' => 'content'));
1218 $content .= $this->coursecat_coursebox_content($chelper, $course);
ebd08abc 1219 $content .= html_writer::end_tag('div');
43e389ea
MG
1220
1221 $content .= html_writer::end_tag('div'); // .coursebox
1222 return $content;
1223 }
1224
1225 /**
ebd08abc 1226 * Returns HTML to display course summary.
43e389ea 1227 *
ebd08abc
MM
1228 * @param coursecat_helper $chelper
1229 * @param core_course_list_element $course
43e389ea
MG
1230 * @return string
1231 */
ebd08abc 1232 protected function course_summary(coursecat_helper $chelper, core_course_list_element $course): string {
43e389ea 1233 $content = '';
43e389ea 1234 if ($course->has_summary()) {
ebd08abc 1235 $content .= html_writer::start_tag('div', ['class' => 'summary']);
43e389ea 1236 $content .= $chelper->get_course_formatted_summary($course,
ebd08abc
MM
1237 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1238 $content .= html_writer::end_tag('div');
43e389ea 1239 }
ebd08abc
MM
1240 return $content;
1241 }
1242
1243 /**
1244 * Returns HTML to display course contacts.
1245 *
1246 * @param core_course_list_element $course
1247 * @return string
1248 */
1249 protected function course_contacts(core_course_list_element $course) {
1250 $content = '';
1251 if ($course->has_course_contacts()) {
1252 $content .= html_writer::start_tag('ul', ['class' => 'teachers']);
1253 foreach ($course->get_course_contacts() as $coursecontact) {
1254 $rolenames = array_map(function ($role) {
1255 return $role->displayname;
1256 }, $coursecontact['roles']);
1257 $name = implode(", ", $rolenames).': '.
1258 html_writer::link(new moodle_url('/user/view.php',
1259 ['id' => $coursecontact['user']->id, 'course' => SITEID]),
1260 $coursecontact['username']);
1261 $content .= html_writer::tag('li', $name);
1262 }
1263 $content .= html_writer::end_tag('ul');
1264 }
1265 return $content;
1266 }
1267
1268 /**
1269 * Returns HTML to display course overview files.
1270 *
1271 * @param core_course_list_element $course
1272 * @return string
1273 */
1274 protected function course_overview_files(core_course_list_element $course): string {
1275 global $CFG;
43e389ea 1276
545b3930 1277 $contentimages = $contentfiles = '';
d1f8c1bd
MG
1278 foreach ($course->get_course_overviewfiles() as $file) {
1279 $isimage = $file->is_valid_image();
ebd08abc
MM
1280 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php",
1281 '/' . $file->get_contextid() . '/' . $file->get_component() . '/' .
1282 $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
d1f8c1bd 1283 if ($isimage) {
545b3930 1284 $contentimages .= html_writer::tag('div',
ebd08abc
MM
1285 html_writer::empty_tag('img', ['src' => $url]),
1286 ['class' => 'courseimage']);
d1f8c1bd 1287 } else {
545b3930 1288 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
ebd08abc
MM
1289 $filename = html_writer::tag('span', $image, ['class' => 'fp-icon']).
1290 html_writer::tag('span', $file->get_filename(), ['class' => 'fp-filename']);
545b3930 1291 $contentfiles .= html_writer::tag('span',
ebd08abc
MM
1292 html_writer::link($url, $filename),
1293 ['class' => 'coursefile fp-filename-icon']);
43e389ea 1294 }
43e389ea 1295 }
ebd08abc
MM
1296 return $contentimages . $contentfiles;
1297 }
43e389ea 1298
ebd08abc
MM
1299 /**
1300 * Returns HTML to display course category name.
1301 *
1302 * @param coursecat_helper $chelper
1303 * @param core_course_list_element $course
1304 * @return string
1305 */
1306 protected function course_category_name(coursecat_helper $chelper, core_course_list_element $course): string {
1307 $content = '';
1308 // Display course category if necessary (for example in search results).
8a3d804a 1309 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
442f12f8 1310 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
ebd08abc 1311 $content .= html_writer::start_tag('div', ['class' => 'coursecat']);
8a3d804a 1312 $content .= get_string('category').': '.
ebd08abc
MM
1313 html_writer::link(new moodle_url('/course/index.php', ['categoryid' => $cat->id]),
1314 $cat->get_formatted_name(), ['class' => $cat->visible ? '' : 'dimmed']);
1315 $content .= html_writer::end_tag('div');
8a3d804a 1316 }
43e389ea 1317 }
ebd08abc
MM
1318 return $content;
1319 }
43e389ea 1320
ebd08abc
MM
1321 /**
1322 * Returns HTML to display course custom fields.
1323 *
1324 * @param core_course_list_element $course
1325 * @return string
1326 */
1327 protected function course_custom_fields(core_course_list_element $course): string {
1328 $content = '';
c1e15d20
MG
1329 if ($course->has_custom_fields()) {
1330 $handler = core_course\customfield\course_handler::create();
1331 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1332 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1333 }
ebd08abc
MM
1334 return $content;
1335 }
c1e15d20 1336
ebd08abc
MM
1337 /**
1338 * Returns HTML to display course content (summary, course contacts and optionally category name)
1339 *
1340 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1341 *
1342 * @param coursecat_helper $chelper various display options
1343 * @param stdClass|core_course_list_element $course
1344 * @return string
1345 */
1346 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1347 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1348 return '';
1349 }
1350 if ($course instanceof stdClass) {
1351 $course = new core_course_list_element($course);
1352 }
1353 $content = $this->course_summary($chelper, $course);
1354 $content .= $this->course_overview_files($course);
1355 $content .= $this->course_contacts($course);
1356 $content .= $this->course_category_name($chelper, $course);
1357 $content .= $this->course_custom_fields($course);
43e389ea
MG
1358 return $content;
1359 }
1360
1361 /**
1362 * Renders the list of courses
1363 *
1364 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1365 * method from outside of the class
1366 *
1367 * If list of courses is specified in $courses; the argument $chelper is only used
1368 * to retrieve display options and attributes, only methods get_show_courses(),
1369 * get_courses_display_option() and get_and_erase_attributes() are called.
1370 *
1371 * @param coursecat_helper $chelper various display options
1372 * @param array $courses the list of courses to display
1373 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1374 * defaulted to count($courses)
1375 * @return string
1376 */
1377 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1378 global $CFG;
1379 if ($totalcount === null) {
1380 $totalcount = count($courses);
1381 }
1382 if (!$totalcount) {
1383 // Courses count is cached during courses retrieval.
1384 return '';
1385 }
1386
1387 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1388 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1389 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1390 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1391 } else {
1392 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1393 }
1394 }
1395
1396 // prepare content of paging bar if it is needed
1397 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1398 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1399 if ($totalcount > count($courses)) {
1400 // there are more results that can fit on one page
1401 if ($paginationurl) {
1402 // the option paginationurl was specified, display pagingbar
1403 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1404 $page = $chelper->get_courses_display_option('offset') / $perpage;
1405 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1406 $paginationurl->out(false, array('perpage' => $perpage)));
1407 if ($paginationallowall) {
1408 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1409 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1410 }
1411 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1412 // the option for 'View more' link was specified, display more link
1413 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1414 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1415 array('class' => 'paging paging-morelink'));
1416 }
1417 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1418 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1419 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1420 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1421 }
1422
1423 // display list of courses
1424 $attributes = $chelper->get_and_erase_attributes('courses');
1425 $content = html_writer::start_tag('div', $attributes);
1426
1427 if (!empty($pagingbar)) {
1428 $content .= $pagingbar;
1429 }
1430
1431 $coursecount = 0;
1432 foreach ($courses as $course) {
1433 $coursecount ++;
1434 $classes = ($coursecount%2) ? 'odd' : 'even';
1435 if ($coursecount == 1) {
1436 $classes .= ' first';
1437 }
1438 if ($coursecount >= count($courses)) {
1439 $classes .= ' last';
1440 }
1441 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1442 }
1443
1444 if (!empty($pagingbar)) {
1445 $content .= $pagingbar;
1446 }
1447 if (!empty($morelink)) {
1448 $content .= $morelink;
1449 }
1450
1451 $content .= html_writer::end_tag('div'); // .courses
1452 return $content;
1453 }
1454
1455 /**
1456 * Renders the list of subcategories in a category
1457 *
1458 * @param coursecat_helper $chelper various display options
442f12f8 1459 * @param core_course_category $coursecat
43e389ea
MG
1460 * @param int $depth depth of the category in the current tree
1461 * @return string
1462 */
1463 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1464 global $CFG;
1465 $subcategories = array();
1466 if (!$chelper->get_categories_display_option('nodisplay')) {
1467 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1468 }
1469 $totalcount = $coursecat->get_children_count();
1470 if (!$totalcount) {
442f12f8
MG
1471 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1472 // to avoid extra DB requests.
43e389ea
MG
1473 // Categories count is cached during children categories retrieval.
1474 return '';
1475 }
1476
1477 // prepare content of paging bar or more link if it is needed
1478 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1479 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1480 if ($totalcount > count($subcategories)) {
1481 if ($paginationurl) {
1482 // the option 'paginationurl was specified, display pagingbar
1483 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1484 $page = $chelper->get_categories_display_option('offset') / $perpage;
1485 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1486 $paginationurl->out(false, array('perpage' => $perpage)));
1487 if ($paginationallowall) {
1488 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1489 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1490 }
1491 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1492 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
30142c19
MG
1493 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1494 $viewmoreurl->param('categoryid', $coursecat->id);
43e389ea
MG
1495 }
1496 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1497 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1498 array('class' => 'paging paging-morelink'));
1499 }
1500 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1501 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1502 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1503 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1504 }
1505
1506 // display list of subcategories
1507 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1508
1509 if (!empty($pagingbar)) {
1510 $content .= $pagingbar;
1511 }
1512
1513 foreach ($subcategories as $subcategory) {
1514 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1515 }
1516
1517 if (!empty($pagingbar)) {
1518 $content .= $pagingbar;
1519 }
1520 if (!empty($morelink)) {
1521 $content .= $morelink;
1522 }
1523
1524 $content .= html_writer::end_tag('div');
1525 return $content;
1526 }
1527
53c1b936
ARN
1528 /**
1529 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1530 */
1531 protected function coursecat_include_js() {
b8459bba
TH
1532 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1533 return;
53c1b936 1534 }
b8459bba
TH
1535
1536 // We must only load this module once.
b8459bba
TH
1537 $this->page->requires->yui_module('moodle-course-categoryexpander',
1538 'Y.Moodle.course.categoryexpander.init');
53c1b936
ARN
1539 }
1540
43e389ea
MG
1541 /**
1542 * Returns HTML to display the subcategories and courses in the given category
1543 *
1544 * This method is re-used by AJAX to expand content of not loaded category
1545 *
1546 * @param coursecat_helper $chelper various display options
442f12f8 1547 * @param core_course_category $coursecat
43e389ea
MG
1548 * @param int $depth depth of the category in the current tree
1549 * @return string
1550 */
1551 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1552 $content = '';
1553 // Subcategories
1554 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1555
1556 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1557 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1558 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1559 if ($showcoursesauto && $depth) {
1560 // this is definitely collapsed mode
1561 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1562 }
1563
1564 // Courses
1565 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
545b3930
MG
1566 $courses = array();
1567 if (!$chelper->get_courses_display_option('nodisplay')) {
1568 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1569 }
43e389ea
MG
1570 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1571 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
30142c19
MG
1572 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1573 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
43e389ea
MG
1574 }
1575 }
1576 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1577 }
1578
1579 if ($showcoursesauto) {
1580 // restore the show_courses back to AUTO
1581 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1582 }
1583
1584 return $content;
1585 }
1586
1587 /**
1588 * Returns HTML to display a course category as a part of a tree
1589 *
1590 * This is an internal function, to display a particular category and all its contents
1591 * use {@link core_course_renderer::course_category()}
1592 *
1593 * @param coursecat_helper $chelper various display options
442f12f8 1594 * @param core_course_category $coursecat
43e389ea
MG
1595 * @param int $depth depth of this category in the current tree
1596 * @return string
1597 */
1598 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1599 // open category tag
1600 $classes = array('category');
1601 if (empty($coursecat->visible)) {
1602 $classes[] = 'dimmed_category';
1603 }
1604 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1605 // do not load content
1606 $categorycontent = '';
1607 $classes[] = 'notloaded';
1608 if ($coursecat->get_children_count() ||
1609 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1610 $classes[] = 'with_children';
1611 $classes[] = 'collapsed';
1612 }
1613 } else {
1614 // load category content
1615 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1616 $classes[] = 'loaded';
1617 if (!empty($categorycontent)) {
1618 $classes[] = 'with_children';
3a0e3c34
JP
1619 // Category content loaded with children.
1620 $this->categoryexpandedonload = true;
43e389ea
MG
1621 }
1622 }
2ae7e4dd
AN
1623
1624 // Make sure JS file to expand category content is included.
1625 $this->coursecat_include_js();
1626
53c1b936
ARN
1627 $content = html_writer::start_tag('div', array(
1628 'class' => join(' ', $classes),
43e389ea 1629 'data-categoryid' => $coursecat->id,
53c1b936
ARN
1630 'data-depth' => $depth,
1631 'data-showcourses' => $chelper->get_show_courses(),
1632 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1633 ));
43e389ea
MG
1634
1635 // category name
1636 $categoryname = $coursecat->get_formatted_name();
30142c19
MG
1637 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1638 array('categoryid' => $coursecat->id)),
43e389ea
MG
1639 $categoryname);
1640 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1641 && ($coursescount = $coursecat->get_courses_count())) {
1642 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1643 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1644 }
1645 $content .= html_writer::start_tag('div', array('class' => 'info'));
faf6010b 1646
1647 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
43e389ea
MG
1648 $content .= html_writer::end_tag('div'); // .info
1649
1650 // add category content to the output
1651 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1652
1653 $content .= html_writer::end_tag('div'); // .category
1654
1655 // Return the course category tree HTML
1656 return $content;
1657 }
1658
1659 /**
1660 * Returns HTML to display a tree of subcategories and courses in the given category
1661 *
1662 * @param coursecat_helper $chelper various display options
442f12f8 1663 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
43e389ea
MG
1664 * @return string
1665 */
1666 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
3a0e3c34
JP
1667 // Reset the category expanded flag for this course category tree first.
1668 $this->categoryexpandedonload = false;
43e389ea
MG
1669 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1670 if (empty($categorycontent)) {
1671 return '';
1672 }
1673
43e389ea
MG
1674 // Start content generation
1675 $content = '';
1676 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
53c1b936
ARN
1677 $content .= html_writer::start_tag('div', $attributes);
1678
1679 if ($coursecat->get_children_count()) {
1680 $classes = array(
1681 'collapseexpand',
53c1b936 1682 );
af28ceb9 1683
3a0e3c34
JP
1684 // Check if the category content contains subcategories with children's content loaded.
1685 if ($this->categoryexpandedonload) {
1686 $classes[] = 'collapse-all';
1687 $linkname = get_string('collapseall');
1688 } else {
1689 $linkname = get_string('expandall');
1690 }
1691
53c1b936
ARN
1692 // Only show the collapse/expand if there are children to expand.
1693 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
3a0e3c34 1694 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
43e389ea 1695 $content .= html_writer::end_tag('div');
53c1b936 1696 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
43e389ea
MG
1697 }
1698
53c1b936
ARN
1699 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1700
43e389ea
MG
1701 $content .= html_writer::end_tag('div'); // .course_category_tree
1702
1703 return $content;
1704 }
8e57a6df
MG
1705
1706 /**
1707 * Renders HTML to display particular course category - list of it's subcategories and courses
1708 *
1709 * Invoked from /course/index.php
1710 *
442f12f8 1711 * @param int|stdClass|core_course_category $category
8e57a6df
MG
1712 */
1713 public function course_category($category) {
1714 global $CFG;
beff3806
MG
1715 $usertop = core_course_category::user_top();
1716 if (empty($category)) {
1717 $coursecat = $usertop;
1718 } else if (is_object($category) && $category instanceof core_course_category) {
1719 $coursecat = $category;
1720 } else {
1721 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1722 }
8e57a6df
MG
1723 $site = get_site();
1724 $output = '';
1725
beff3806 1726 if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
cc6b20fb 1727 // Add 'Manage' button if user has permissions to edit this category.
efbd5696
MG
1728 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1729 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
cc6b20fb
WL
1730 $this->page->set_button($managebutton);
1731 }
beff3806
MG
1732
1733 if (core_course_category::is_simple_site()) {
1734 // There is only one category in the system, do not display link to it.
1735 $strfulllistofcourses = get_string('fulllistofcourses');
1736 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1737 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1738 $strcategories = get_string('categories');
1739 $this->page->set_title("$site->shortname: $strcategories");
8e57a6df 1740 } else {
beff3806
MG
1741 $strfulllistofcourses = get_string('fulllistofcourses');
1742 $this->page->set_title("$site->shortname: $strfulllistofcourses");
8e57a6df
MG
1743
1744 // Print the category selector
beff3806
MG
1745 $categorieslist = core_course_category::make_categories_list();
1746 if (count($categorieslist) > 1) {
f04dda10
MN
1747 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1748 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
442f12f8 1749 core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
f04dda10
MN
1750 $select->set_label(get_string('categories').':');
1751 $output .= $this->render($select);
1752 $output .= html_writer::end_tag('div'); // .categorypicker
1753 }
8e57a6df
MG
1754 }
1755
1756 // Print current category description
1757 $chelper = new coursecat_helper();
1758 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1759 $output .= $this->box($description, array('class' => 'generalbox info'));
1760 }
1761
1762 // Prepare parameters for courses and categories lists in the tree
1763 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1764 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1765
1766 $coursedisplayoptions = array();
1767 $catdisplayoptions = array();
1768 $browse = optional_param('browse', null, PARAM_ALPHA);
1769 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1770 $page = optional_param('page', 0, PARAM_INT);
30142c19 1771 $baseurl = new moodle_url('/course/index.php');
8e57a6df 1772 if ($coursecat->id) {
30142c19
MG
1773 $baseurl->param('categoryid', $coursecat->id);
1774 }
1775 if ($perpage != $CFG->coursesperpage) {
1776 $baseurl->param('perpage', $perpage);
8e57a6df 1777 }
30142c19
MG
1778 $coursedisplayoptions['limit'] = $perpage;
1779 $catdisplayoptions['limit'] = $perpage;
beff3806 1780 if ($browse === 'courses' || !$coursecat->get_children_count()) {
8e57a6df 1781 $coursedisplayoptions['offset'] = $page * $perpage;
30142c19 1782 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
8e57a6df 1783 $catdisplayoptions['nodisplay'] = true;
30142c19 1784 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
57bc1beb 1785 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
beff3806 1786 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
8e57a6df 1787 $coursedisplayoptions['nodisplay'] = true;
8e57a6df 1788 $catdisplayoptions['offset'] = $page * $perpage;
30142c19
MG
1789 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1790 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
8e57a6df
MG
1791 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1792 } else {
1793 // we have a category that has both subcategories and courses, display pagination separately
8e57a6df
MG
1794 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1795 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1796 }
1797 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
cc6b20fb
WL
1798 // Add course search form.
1799 $output .= $this->course_search_form();
8e57a6df 1800
cc6b20fb 1801 // Display course category tree.
8e57a6df
MG
1802 $output .= $this->coursecat_tree($chelper, $coursecat);
1803
8e57a6df
MG
1804 // Add action buttons
1805 $output .= $this->container_start('buttons');
beff3806
MG
1806 if ($coursecat->is_uservisible()) {
1807 $context = get_category_or_system_context($coursecat->id);
1808 if (has_capability('moodle/course:create', $context)) {
1809 // Print link to create a new course, for the 1st available category.
1810 if ($coursecat->id) {
1811 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1812 } else {
1813 $url = new moodle_url('/course/edit.php',
1814 array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1815 }
1816 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
8e57a6df 1817 }
beff3806 1818 ob_start();
8e57a6df 1819 print_course_request_buttons($context);
beff3806
MG
1820 $output .= ob_get_contents();
1821 ob_end_clean();
8e57a6df 1822 }
8e57a6df
MG
1823 $output .= $this->container_end();
1824
1825 return $output;
1826 }
60047003 1827
53c1b936
ARN
1828 /**
1829 * Serves requests to /course/category.ajax.php
1830 *
1831 * In this renderer implementation it may expand the category content or
1832 * course content.
1833 *
1834 * @return string
1835 * @throws coding_exception
1836 */
1837 public function coursecat_ajax() {
1838 global $DB, $CFG;
53c1b936
ARN
1839
1840 $type = required_param('type', PARAM_INT);
1841
1842 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1843 // This is a request for a category list of some kind.
1844 $categoryid = required_param('categoryid', PARAM_INT);
1845 $showcourses = required_param('showcourses', PARAM_INT);
1846 $depth = required_param('depth', PARAM_INT);
1847
442f12f8 1848 $category = core_course_category::get($categoryid);
53c1b936
ARN
1849
1850 $chelper = new coursecat_helper();
1851 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1852 $coursedisplayoptions = array(
1853 'limit' => $CFG->coursesperpage,
1854 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1855 );
1856 $catdisplayoptions = array(
1857 'limit' => $CFG->coursesperpage,
1858 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1859 );
1860 $chelper->set_show_courses($showcourses)->
1861 set_courses_display_options($coursedisplayoptions)->
1862 set_categories_display_options($catdisplayoptions);
1863
1864 return $this->coursecat_category_content($chelper, $category, $depth);
1865 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1866 // This is a request for the course information.
1867 $courseid = required_param('courseid', PARAM_INT);
1868
1869 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1870
1871 $chelper = new coursecat_helper();
1872 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1873 return $this->coursecat_coursebox_content($chelper, $course);
1874 } else {
1875 throw new coding_exception('Invalid request type');
1876 }
1877 }
1878
60047003
MG
1879 /**
1880 * Renders html to display search result page
1881 *
1882 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1883 * @return string
1884 */
1885 public function search_courses($searchcriteria) {
1886 global $CFG;
1887 $content = '';
1888 if (!empty($searchcriteria)) {
1889 // print search results
1890
1891 $displayoptions = array('sort' => array('displayname' => 1));
1892 // take the current page and number of results per page from query
1893 $perpage = optional_param('perpage', 0, PARAM_RAW);
1894 if ($perpage !== 'all') {
1895 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1896 $page = optional_param('page', 0, PARAM_INT);
1897 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1898 }
1899 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1900 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1901 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1902
1903 $class = 'course-search-result';
1904 foreach ($searchcriteria as $key => $value) {
1905 if (!empty($value)) {
1906 $class .= ' course-search-result-'. $key;
1907 }
1908 }
1909 $chelper = new coursecat_helper();
1910 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1911 set_courses_display_options($displayoptions)->
1912 set_search_criteria($searchcriteria)->
1913 set_attributes(array('class' => $class));
1914
442f12f8
MG
1915 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1916 $totalcount = core_course_category::search_courses_count($searchcriteria);
60047003
MG
1917 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1918
1919 if (!$totalcount) {
1920 if (!empty($searchcriteria['search'])) {
1921 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1922 } else {
1923 $content .= $this->heading(get_string('novalidcourses'));
1924 }
1925 } else {
1926 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1927 $content .= $courseslist;
1928 }
1929
1930 if (!empty($searchcriteria['search'])) {
1931 // print search form only if there was a search by search string, otherwise it is confusing
1932 $content .= $this->box_start('generalbox mdl-align');
1933 $content .= $this->course_search_form($searchcriteria['search']);
1934 $content .= $this->box_end();
1935 }
1936 } else {
1937 // just print search form
1938 $content .= $this->box_start('generalbox mdl-align');
1939 $content .= $this->course_search_form();
60047003
MG
1940 $content .= $this->box_end();
1941 }
1942 return $content;
1943 }
9e76429d
MG
1944
1945 /**
1946 * Renders html to print list of courses tagged with particular tag
1947 *
1948 * @param int $tagid id of the tag
74fa9f76
MG
1949 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1950 * are displayed on the page and the per-page limit may be bigger
1951 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1952 * to display items in the same context first
1953 * @param int $ctx context id where to search for records
1954 * @param bool $rec search in subcontexts as well
1955 * @param array $displayoptions
9e76429d
MG
1956 * @return string empty string if no courses are marked with this tag or rendered list of courses
1957 */
74fa9f76 1958 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
9e76429d 1959 global $CFG;
74fa9f76
MG
1960 if (empty($displayoptions)) {
1961 $displayoptions = array();
1962 }
beff3806 1963 $showcategories = !core_course_category::is_simple_site();
74fa9f76 1964 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
9e76429d 1965 $chelper = new coursecat_helper();
74fa9f76
MG
1966 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1967 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1968 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1969 set_search_criteria($searchcriteria)->
9e76429d
MG
1970 set_courses_display_options($displayoptions)->
1971 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1972 // (we set the same css class as in search results by tagid)
442f12f8
MG
1973 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1974 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
74fa9f76
MG
1975 if ($exclusivemode) {
1976 return $this->coursecat_courses($chelper, $courses, $totalcount);
1977 } else {
1978 $tagfeed = new core_tag\output\tagfeed();
1979 $img = $this->output->pix_icon('i/course', '');
1980 foreach ($courses as $course) {
1981 $url = course_get_url($course);
1982 $imgwithlink = html_writer::link($url, $img);
1983 $coursename = html_writer::link($url, $course->get_formatted_name());
1984 $details = '';
442f12f8 1985 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
74fa9f76
MG
1986 $details = get_string('category').': '.
1987 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1988 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1989 }
1990 $tagfeed->add($imgwithlink, $coursename, $details);
1991 }
1992 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1993 }
9e76429d
MG
1994 }
1995 return '';
1996 }
99a36456
MG
1997
1998 /**
1999 * Returns HTML to display one remote course
2000 *
2001 * @param stdClass $course remote course information, contains properties:
2002 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
2003 * @return string
2004 */
2005 protected function frontpage_remote_course(stdClass $course) {
2006 $url = new moodle_url('/auth/mnet/jump.php', array(
2007 'hostid' => $course->hostid,
2008 'wantsurl' => '/course/view.php?id='. $course->remoteid
2009 ));
2010
2011 $output = '';
2012 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
2013 $output .= html_writer::start_tag('div', array('class' => 'info'));
2014 $output .= html_writer::start_tag('h3', array('class' => 'name'));
2015 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
2016 $output .= html_writer::end_tag('h3'); // .name
2017 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
2018 $output .= html_writer::end_tag('div'); // .info
2019 $output .= html_writer::start_tag('div', array('class' => 'content'));
2020 $output .= html_writer::start_tag('div', array('class' => 'summary'));
2021 $options = new stdClass();
2022 $options->noclean = true;
2023 $options->para = false;
2024 $options->overflowdiv = true;
2025 $output .= format_text($course->summary, $course->summaryformat, $options);
2026 $output .= html_writer::end_tag('div'); // .summary
2027 $addinfo = format_string($course->hostname) . ' : '
2028 . format_string($course->cat_name) . ' : '
2029 . format_string($course->shortname);
2030 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
2031 $output .= html_writer::end_tag('div'); // .content
2032 $output .= html_writer::end_tag('div'); // .coursebox
2033 return $output;
2034 }
2035
2036 /**
2037 * Returns HTML to display one remote host
2038 *
2039 * @param array $host host information, contains properties: name, url, count
2040 * @return string
2041 */
2042 protected function frontpage_remote_host($host) {
2043 $output = '';
2044 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
2045 $output .= html_writer::start_tag('div', array('class' => 'info'));
2046 $output .= html_writer::start_tag('h3', array('class' => 'name'));
2047 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
2048 $output .= html_writer::end_tag('h3'); // .name
2049 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
2050 $output .= html_writer::end_tag('div'); // .info
2051 $output .= html_writer::start_tag('div', array('class' => 'content'));
2052 $output .= html_writer::start_tag('div', array('class' => 'summary'));
2053 $output .= $host['count'] . ' ' . get_string('courses');
2054 $output .= html_writer::end_tag('div'); // .content
2055 $output .= html_writer::end_tag('div'); // .coursebox
2056 return $output;
2057 }
2058
2059 /**
2060 * Returns HTML to print list of courses user is enrolled to for the frontpage
2061 *
2062 * Also lists remote courses or remote hosts if MNET authorisation is used
2063 *
2064 * @return string
2065 */
2066 public function frontpage_my_courses() {
2067 global $USER, $CFG, $DB;
2068
2069 if (!isloggedin() or isguestuser()) {
2070 return '';
2071 }
2072
2073 $output = '';
04985346 2074 $courses = enrol_get_my_courses('summary, summaryformat');
99a36456
MG
2075 $rhosts = array();
2076 $rcourses = array();
2077 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2078 $rcourses = get_my_remotecourses($USER->id);
2079 $rhosts = get_my_remotehosts();
2080 }
2081
2082 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2083
2084 $chelper = new coursecat_helper();
beff3806 2085 $totalcount = count($courses);
0fd26350
MG
2086 if (count($courses) > $CFG->frontpagecourselimit) {
2087 // There are more enrolled courses than we can display, display link to 'My courses'.
0fd26350
MG
2088 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2089 $chelper->set_courses_display_options(array(
2090 'viewmoreurl' => new moodle_url('/my/'),
2091 'viewmoretext' => new lang_string('mycourses')
2092 ));
beff3806 2093 } else if (core_course_category::top()->is_uservisible()) {
0fd26350
MG
2094 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2095 $chelper->set_courses_display_options(array(
99a36456
MG
2096 'viewmoreurl' => new moodle_url('/course/index.php'),
2097 'viewmoretext' => new lang_string('fulllistofcourses')
0fd26350
MG
2098 ));
2099 $totalcount = $DB->count_records('course') - 1;
2100 }
2101 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
99a36456 2102 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
99a36456
MG
2103 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2104
2105 // MNET
2106 if (!empty($rcourses)) {
2107 // at the IDP, we know of all the remote courses
2108 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2109 foreach ($rcourses as $course) {
2110 $output .= $this->frontpage_remote_course($course);
2111 }
2112 $output .= html_writer::end_tag('div'); // .courses
2113 } elseif (!empty($rhosts)) {
2114 // non-IDP, we know of all the remote servers, but not courses
2115 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2116 foreach ($rhosts as $host) {
2117 $output .= $this->frontpage_remote_host($host);
2118 }
2119 $output .= html_writer::end_tag('div'); // .courses
2120 }
2121 }
2122 return $output;
2123 }
2124
2125 /**
2126 * Returns HTML to print list of available courses for the frontpage
2127 *
2128 * @return string
2129 */
2130 public function frontpage_available_courses() {
2131 global $CFG;
99a36456
MG
2132
2133 $chelper = new coursecat_helper();
2134 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2135 set_courses_display_options(array(
2136 'recursive' => true,
0fd26350 2137 'limit' => $CFG->frontpagecourselimit,
99a36456
MG
2138 'viewmoreurl' => new moodle_url('/course/index.php'),
2139 'viewmoretext' => new lang_string('fulllistofcourses')));
2140
2141 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
beff3806
MG
2142 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2143 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
ee11f4a7 2144 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
0fd26350 2145 // Print link to create a new course, for the 1st available category.
ee11f4a7 2146 return $this->add_new_course_button();
0fd26350 2147 }
99a36456
MG
2148 return $this->coursecat_courses($chelper, $courses, $totalcount);
2149 }
2150
ee11f4a7
JF
2151 /**
2152 * Returns HTML to the "add new course" button for the page
2153 *
2154 * @return string
2155 */
2156 public function add_new_course_button() {
2157 global $CFG;
2158 // Print link to create a new course, for the 1st available category.
2159 $output = $this->container_start('buttons');
2160 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2161 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2162 $output .= $this->container_end('buttons');
2163 return $output;
2164 }
2165
99a36456
MG
2166 /**
2167 * Returns HTML to print tree with course categories and courses for the frontpage
2168 *
2169 * @return string
2170 */
2171 public function frontpage_combo_list() {
2172 global $CFG;
beff3806
MG
2173 // TODO MDL-10965 improve.
2174 $tree = core_course_category::top();
2175 if (!$tree->get_children_count()) {
2176 return '';
2177 }
99a36456
MG
2178 $chelper = new coursecat_helper();
2179 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2180 set_categories_display_options(array(
2181 'limit' => $CFG->coursesperpage,
30142c19 2182 'viewmoreurl' => new moodle_url('/course/index.php',
99a36456
MG
2183 array('browse' => 'categories', 'page' => 1))
2184 ))->
2185 set_courses_display_options(array(
2186 'limit' => $CFG->coursesperpage,
30142c19 2187 'viewmoreurl' => new moodle_url('/course/index.php',
99a36456
MG
2188 array('browse' => 'courses', 'page' => 1))
2189 ))->
2190 set_attributes(array('class' => 'frontpage-category-combo'));
beff3806 2191 return $this->coursecat_tree($chelper, $tree);
99a36456
MG
2192 }
2193
2194 /**
2195 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2196 *
2197 * @return string
2198 */
2199 public function frontpage_categories_list() {
2200 global $CFG;
beff3806
MG
2201 // TODO MDL-10965 improve.
2202 $tree = core_course_category::top();
2203 if (!$tree->get_children_count()) {
2204 return '';
2205 }
99a36456
MG
2206 $chelper = new coursecat_helper();
2207 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2208 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2209 set_categories_display_options(array(
2210 'limit' => $CFG->coursesperpage,
30142c19 2211 'viewmoreurl' => new moodle_url('/course/index.php',
99a36456
MG
2212 array('browse' => 'categories', 'page' => 1))
2213 ))->
2214 set_attributes(array('class' => 'frontpage-category-names'));
beff3806 2215 return $this->coursecat_tree($chelper, $tree);
99a36456 2216 }
d8cb4615
MN
2217
2218 /**
2219 * Renders the activity navigation.
2220 *
2221 * Defer to template.
2222 *
2223 * @param \core_course\output\activity_navigation $page
2224 * @return string html for the page
2225 */
2226 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2227 $data = $page->export_for_template($this->output);
2228 return $this->output->render_from_template('core_course/activity_navigation', $data);
2229 }
3127fe10 2230
3127fe10
MG
2231 /**
2232 * Display waiting information about backup size during uploading backup process
2233 * @param object $backupfile the backup stored_file
2234 * @return $html string
2235 */
2236 public function sendingbackupinfo($backupfile) {
2237 $sizeinfo = new stdClass();
2238 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2239 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2240 array('class' => 'courseuploadtextinfo'));
2241 return $html;
2242 }
2243
3127fe10
MG
2244 /**
2245 * Hub information (logo - name - description - link)
2246 * @param object $hubinfo
2247 * @return string html code
2248 */
2249 public function hubinfo($hubinfo) {
2250 $screenshothtml = html_writer::empty_tag('img',
2251 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2252 $hubdescription = html_writer::tag('div', $screenshothtml,
2253 array('class' => 'hubscreenshot'));
2254
2255 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2256 array('class' => 'hublink', 'href' => $hubinfo['url'],
2257 'onclick' => 'this.target="_blank"'));
2258
2259 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2260 array('class' => 'hubdescription'));
2261 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2262
2263 return $hubdescription;
2264 }
a400dd2d
MG
2265
2266 /**
2267 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2268 *
2269 * This may be disabled in settings
2270 *
2271 * @return string
2272 */
2273 public function frontpage_section1() {
2274 global $SITE, $USER;
2275
2276 $output = '';
2277 $editing = $this->page->user_is_editing();
2278
2279 if ($editing) {
2280 // Make sure section with number 1 exists.
2281 course_create_sections_if_missing($SITE, 1);
2282 }
2283
2284 $modinfo = get_fast_modinfo($SITE);
2285 $section = $modinfo->get_section_info(1);
2286 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2287 $output .= $this->box_start('generalbox sitetopic');
2288
2289 // If currently moving a file then show the current clipboard.
2290 if (ismoving($SITE->id)) {
2291 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2292 $output .= '<p><font size="2">';
2293 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2294 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2295 $output .= '</font></p>';
2296 }
2297
2298 $context = context_course::instance(SITEID);
2299
2300 // If the section name is set we show it.
2301 if (trim($section->name) !== '') {
2302 $output .= $this->heading(
2303 format_string($section->name, true, array('context' => $context)),
2304 2,
2305 'sectionname'
2306 );
2307 }
2308
2309 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2310 'pluginfile.php',
2311 $context->id,
2312 'course',
2313 'section',
2314 $section->id);
2315 $summaryformatoptions = new stdClass();
2316 $summaryformatoptions->noclean = true;
2317 $summaryformatoptions->overflowdiv = true;
2318
2319 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2320
2321 if ($editing && has_capability('moodle/course:update', $context)) {
2322 $streditsummary = get_string('editsummary');
2323 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2324 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', $streditsummary)) .
2325 "<br /><br />";
2326 }
2327
2328 $output .= $this->course_section_cm_list($SITE, $section);
2329
2330 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2331 $output .= $this->box_end();
2332 }
2333
2334 return $output;
2335 }
dcce3575
MG
2336
2337 /**
2338 * Output news for the frontpage (extract from site-wide news forum)
2339 *
23f5e65e 2340 * @param stdClass $forum record from db table 'forum' that represents the site news forum
dcce3575
MG
2341 * @return string
2342 */
23f5e65e 2343 protected function frontpage_news($forum) {
dcce3575
MG
2344 global $CFG, $SITE, $SESSION, $USER;
2345 require_once($CFG->dirroot .'/mod/forum/lib.php');
2346
2347 $output = '';
2348
2349 if (isloggedin()) {
2350 $SESSION->fromdiscussion = $CFG->wwwroot;
2351 $subtext = '';
23f5e65e
AN
2352 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2353 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
dcce3575
MG
2354 $subtext = get_string('unsubscribe', 'forum');
2355 }
2356 } else {
2357 $subtext = get_string('subscribe', 'forum');
2358 }
23f5e65e 2359 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
dcce3575
MG
2360 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2361 }
2362
23f5e65e
AN
2363 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2364 $context = context_module::instance($coursemodule->id);
dcce3575 2365
23f5e65e
AN
2366 $entityfactory = mod_forum\local\container::get_entity_factory();
2367 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2368
2369 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2370 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2371 $cm = \cm_info::create($coursemodule);
2372 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
dcce3575
MG
2373 }
2374
2375 /**
2376 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2377 *
2378 * @param string $skipdivid
2379 * @param string $contentsdivid
2380 * @param string $header Header of the part
2381 * @param string $contents Contents of the part
2382 * @return string
2383 */
2384 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
beff3806
MG
2385 if (strval($contents) === '') {
2386 return '';
2387 }
dcce3575
MG
2388 $output = html_writer::link('#' . $skipdivid,
2389 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2390 array('class' => 'skip-block skip'));
2391
2392 // Wrap frontpage part in div container.
2393 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2394 $output .= $this->heading($header);
2395
2396 $output .= $contents;
2397
2398 // End frontpage part div container.
2399 $output .= html_writer::end_tag('div');
2400
2401 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2402 return $output;
2403 }
2404
2405 /**
2406 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2407 *
2408 * @return string
2409 */
2410 public function frontpage() {
2411 global $CFG, $SITE;
2412
2413 $output = '';
2414
2415 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2416 $frontpagelayout = $CFG->frontpageloggedin;
2417 } else {
2418 $frontpagelayout = $CFG->frontpage;
2419 }
2420
2421 foreach (explode(',', $frontpagelayout) as $v) {
2422 switch ($v) {
2423 // Display the main part of the front page.
2424 case FRONTPAGENEWS:
2425 if ($SITE->newsitems) {
2426 // Print forums only when needed.
2427 require_once($CFG->dirroot .'/mod/forum/lib.php');
2428 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2429 ($forumcontents = $this->frontpage_news($newsforum))) {
2430 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2431 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2432 $newsforumcm->get_formatted_name(), $forumcontents);
2433 }
2434 }
2435 break;
2436
2437 case FRONTPAGEENROLLEDCOURSELIST:
2438 $mycourseshtml = $this->frontpage_my_courses();
2439 if (!empty($mycourseshtml)) {
2440 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2441 get_string('mycourses'), $mycourseshtml);
dcce3575 2442 }
8b9fc069 2443 break;
dcce3575
MG
2444
2445 case FRONTPAGEALLCOURSELIST:
2446 $availablecourseshtml = $this->frontpage_available_courses();
beff3806
MG
2447 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2448 get_string('availablecourses'), $availablecourseshtml);
dcce3575
MG
2449 break;
2450
2451 case FRONTPAGECATEGORYNAMES:
2452 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2453 get_string('categories'), $this->frontpage_categories_list());
2454 break;
2455
2456 case FRONTPAGECATEGORYCOMBO:
2457 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2458 get_string('courses'), $this->frontpage_combo_list());
2459 break;
2460
2461 case FRONTPAGECOURSESEARCH:
2462 $output .= $this->box($this->course_search_form('', 'short'), 'mdl-align');
2463 break;
2464
2465 }
2466 $output .= '<br />';
2467 }
2468
2469 return $output;
2470 }
43e389ea
MG
2471}
2472
2473/**
2474 * Class storing display options and functions to help display course category and/or courses lists
2475 *
442f12f8 2476 * This is a wrapper for core_course_category objects that also stores display options
43e389ea
MG
2477 * and functions to retrieve sorted and paginated lists of categories/courses.
2478 *
2479 * If theme overrides methods in core_course_renderers that access this class
2480 * it may as well not use this class at all or extend it.
2481 *
2482 * @package core
2483 * @copyright 2013 Marina Glancy
2484 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2485 */
2486class coursecat_helper {
2487 /** @var string [none, collapsed, expanded] how (if) display courses list */
2488 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2489 /** @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) */
2490 protected $subcatdepth = 1;
2491 /** @var array options to display courses list */
2492 protected $coursesdisplayoptions = array();
2493 /** @var array options to display subcategories list */
2494 protected $categoriesdisplayoptions = array();
2495 /** @var array additional HTML attributes */
2496 protected $attributes = array();
2497 /** @var array search criteria if the list is a search result */
2498 protected $searchcriteria = null;
2499
2500 /**
2501 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2502 *
2503 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2504 * @return coursecat_helper
2505 */
2506 public function set_show_courses($showcourses) {
2507 $this->showcourses = $showcourses;
442f12f8
MG
2508 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2509 // and core_course_category::search_courses().
43e389ea
MG
2510 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2511 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
c1e15d20 2512 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
43e389ea
MG
2513 return $this;
2514 }
2515
2516 /**
2517 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2518 *
2519 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2520 */
2521 public function get_show_courses() {
2522 return $this->showcourses;
2523 }
2524
2525 /**
2526 * Sets the maximum depth to expand subcategories in the tree
2527 *
2528 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2529 *
2530 * @param int $subcatdepth
2531 * @return coursecat_helper
2532 */
2533 public function set_subcat_depth($subcatdepth) {
2534 $this->subcatdepth = $subcatdepth;
2535 return $this;
2536 }
2537
2538 /**
2539 * Returns the maximum depth to expand subcategories in the tree
2540 *
2541 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2542 *
2543 * @return int
2544 */
2545 public function get_subcat_depth() {
2546 return $this->subcatdepth;
2547 }
2548
2549 /**
2550 * Sets options to display list of courses
2551 *
442f12f8 2552 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
43e389ea 2553 *
442f12f8 2554 * Options that core_course_category::get_courses() accept:
43e389ea
MG
2555 * - recursive - return courses from subcategories as well. Use with care,
2556 * this may be a huge list!
2557 * - summary - preloads fields 'summary' and 'summaryformat'
2558 * - coursecontacts - preloads course contacts
c1e15d20 2559 * - customfields - preloads custom fields data
43e389ea
MG
2560 * - isenrolled - preloads indication whether this user is enrolled in the course
2561 * - sort - list of fields to sort. Example
2562 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2563 * will sort by idnumber asc, shortname asc and id desc.
2564 * Default: array('sortorder' => 1)
2565 * Only cached fields may be used for sorting!
2566 * - offset
2567 * - limit - maximum number of children to return, 0 or null for no limit
2568 *
2569 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2570 *
2571 * Also renderer can set here any additional options it wants to pass between renderer functions.
2572 *
2573 * @param array $options
2574 * @return coursecat_helper
2575 */
2576 public function set_courses_display_options($options) {
2577 $this->coursesdisplayoptions = $options;
2578 $this->set_show_courses($this->showcourses); // this will calculate special display options
2579 return $this;
2580 }
2581
2582 /**
2583 * Sets one option to display list of courses
2584 *
2585 * @see coursecat_helper::set_courses_display_options()
2586 *
2587 * @param string $key
2588 * @param mixed $value
2589 * @return coursecat_helper
2590 */
2591 public function set_courses_display_option($key, $value) {
2592 $this->coursesdisplayoptions[$key] = $value;
2593 return $this;
2594 }
2595
2596 /**
2597 * Return the specified option to display list of courses
2598 *
2599 * @param string $optionname option name
2600 * @param mixed $defaultvalue default value for option if it is not specified
2601 * @return mixed
2602 */
2603 public function get_courses_display_option($optionname, $defaultvalue = null) {
2604 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2605 return $this->coursesdisplayoptions[$optionname];
2606 } else {
2607 return $defaultvalue;
2608 }
2609 }
2610
2611 /**
2612 * Returns all options to display the courses
2613 *
442f12f8
MG
2614 * This array is usually passed to {@link core_course_category::get_courses()} or
2615 * {@link core_course_category::search_courses()}
43e389ea
MG
2616 *
2617 * @return array
2618 */
2619 public function get_courses_display_options() {
2620 return $this->coursesdisplayoptions;
2621 }
2622
2623 /**
2624 * Sets options to display list of subcategories
2625 *
442f12f8 2626 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
43e389ea
MG
2627 * Any other options may be used by renderer functions
2628 *
2629 * @param array $options
2630 * @return coursecat_helper
2631 */
2632 public function set_categories_display_options($options) {
2633 $this->categoriesdisplayoptions = $options;
2634 return $this;
2635 }
2636
2637 /**
2638 * Return the specified option to display list of subcategories
2639 *
2640 * @param string $optionname option name
2641 * @param mixed $defaultvalue default value for option if it is not specified
2642 * @return mixed
2643 */
2644 public function get_categories_display_option($optionname, $defaultvalue = null) {
2645 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2646 return $this->categoriesdisplayoptions[$optionname];
2647 } else {
2648 return $defaultvalue;
2649 }
2650 }
2651
2652 /**
2653 * Returns all options to display list of subcategories
2654 *
442f12f8 2655 * This array is usually passed to {@link core_course_category::get_children()}
43e389ea
MG
2656 *
2657 * @return array
2658 */
2659 public function get_categories_display_options() {
2660 return $this->categoriesdisplayoptions;
2661 }
2662
2663 /**
2664 * Sets additional general options to pass between renderer functions, usually HTML attributes
2665 *
2666 * @param array $attributes
2667 * @return coursecat_helper
2668 */
2669 public function set_attributes($attributes) {
2670 $this->attributes = $attributes;
2671 return $this;
2672 }
2673
2674 /**
2675 * Return all attributes and erases them so they are not applied again
2676 *
2677 * @param string $classname adds additional class name to the beginning of $attributes['class']
2678 * @return array
2679 */
2680 public function get_and_erase_attributes($classname) {
2681 $attributes = $this->attributes;
2682 $this->attributes = array();
2683 if (empty($attributes['class'])) {
2684 $attributes['class'] = '';
2685 }
2686 $attributes['class'] = $classname . ' '. $attributes['class'];
2687 return $attributes;
2688 }
2689
2690 /**
2691 * Sets the search criteria if the course is a search result
2692 *
2693 * Search string will be used to highlight terms in course name and description
2694 *
2695 * @param array $searchcriteria
2696 * @return coursecat_helper
2697 */
2698 public function set_search_criteria($searchcriteria) {
2699 $this->searchcriteria = $searchcriteria;
2700 return $this;
2701 }
2702
2703 /**
2704 * Returns formatted and filtered description of the given category
2705 *
442f12f8 2706 * @param core_course_category $coursecat category
43e389ea
MG
2707 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2708 * if context is not specified it will be added automatically
2709 * @return string|null
2710 */
2711 public function get_category_formatted_description($coursecat, $options = null) {
beff3806 2712 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
43e389ea
MG
2713 if (!isset($coursecat->descriptionformat)) {
2714 $descriptionformat = FORMAT_MOODLE;
2715 } else {
2716 $descriptionformat = $coursecat->descriptionformat;
2717 }
2718 if ($options === null) {
2719 $options = array('noclean' => true, 'overflowdiv' => true);
2720 } else {
2721 $options = (array)$options;
2722 }
2723 $context = context_coursecat::instance($coursecat->id);
2724 if (!isset($options['context'])) {
2725 $options['context'] = $context;
2726 }
2727 $text = file_rewrite_pluginfile_urls($coursecat->description,
2728 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2729 return format_text($text, $descriptionformat, $options);
2730 }
2731 return null;
2732 }
2733
2734 /**
2735 * Returns given course's summary with proper embedded files urls and formatted
2736 *
442f12f8 2737 * @param core_course_list_element $course
43e389ea
MG
2738 * @param array|stdClass $options additional formatting options
2739 * @return string
2740 */
2741 public function get_course_formatted_summary($course, $options = array()) {
2742 global $CFG;
2743 require_once($CFG->libdir. '/filelib.php');
2744 if (!$course->has_summary()) {
2745 return '';
2746 }
2747 $options = (array)$options;
2748 $context = context_course::instance($course->id);
2749 if (!isset($options['context'])) {
2750 // TODO see MDL-38521
2751 // option 1 (current), page context - no code required
2752 // option 2, system context
2753 // $options['context'] = context_system::instance();
2754 // option 3, course context:
2755 // $options['context'] = $context;
2756 // option 4, course category context:
2757 // $options['context'] = $context->get_parent_context();
2758 }
2759 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2760 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2761 if (!empty($this->searchcriteria['search'])) {
2762 $summary = highlight($this->searchcriteria['search'], $summary);
2763 }
2764 return $summary;
2765 }
2766
2767 /**
2768 * Returns course name as it is configured to appear in courses lists formatted to course context
2769 *
442f12f8 2770 * @param core_course_list_element $course
43e389ea
MG
2771 * @param array|stdClass $options additional formatting options
2772 * @return string
2773 */
2774 public function get_course_formatted_name($course, $options = array()) {
2775 $options = (array)$options;
2776 if (!isset($options['context'])) {
2777 $options['context'] = context_course::instance($course->id);
2778 }
2779 $name = format_string(get_course_display_name_for_list($course), true, $options);
2780 if (!empty($this->searchcriteria['search'])) {
2781 $name = highlight($this->searchcriteria['search'], $name);
2782 }
2783 return $name;
2784 }
f4c23f03 2785}