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