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