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