MDL-64821 mod_forum: render new forum display mode when selected
[moodle.git] / mod / forum / classes / local / renderers / discussion.php
CommitLineData
47d38303
RW
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Discussion renderer.
19 *
20 * @package mod_forum
21 * @copyright 2019 Ryan Wyllie <ryan@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace mod_forum\local\renderers;
26
27defined('MOODLE_INTERNAL') || die();
28
29use mod_forum\local\entities\discussion as discussion_entity;
30use mod_forum\local\entities\forum as forum_entity;
31use mod_forum\local\entities\post as post_entity;
32use mod_forum\local\entities\sorter as sorter_entity;
fe8e8ad4 33use mod_forum\local\factories\entity as entity_factory;
47d38303
RW
34use mod_forum\local\factories\legacy_data_mapper as legacy_data_mapper_factory;
35use mod_forum\local\factories\exporter as exporter_factory;
fe8e8ad4 36use mod_forum\local\factories\url as url_factory;
47d38303
RW
37use mod_forum\local\factories\vault as vault_factory;
38use mod_forum\local\managers\capability as capability_manager;
39use mod_forum\local\renderers\posts as posts_renderer;
40use core\output\notification;
41use context;
42use context_module;
43use html_writer;
44use moodle_exception;
45use moodle_page;
46use moodle_url;
47use rating_manager;
48use renderer_base;
49use single_button;
50use single_select;
51use stdClass;
52use url_select;
53
54require_once($CFG->dirroot . '/mod/forum/lib.php');
55
56/**
57 * Discussion renderer class.
58 *
59 * @copyright 2019 Ryan Wyllie <ryan@moodle.com>
60 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
61 */
62class discussion {
54d38a73
MG
63 /** @var forum_entity $forum The forum that the discussion belongs to */
64 private $forum;
65 /** @var discussion_entity $discussion The discussion entity */
47d38303
RW
66 private $discussion;
67 /** @var stdClass $discussionrecord Legacy discussion record */
68 private $discussionrecord;
47d38303
RW
69 /** @var stdClass $forumrecord Legacy forum record */
70 private $forumrecord;
71 /** @var int $displaymode The display mode to render the discussion in */
72 private $displaymode;
73 /** @var renderer_base $renderer Renderer base */
74 private $renderer;
75 /** @var posts_renderer $postsrenderer A posts renderer */
76 private $postsrenderer;
77 /** @var moodle_page $page The page this discussion is being rendered for */
78 private $page;
79 /** @var legacy_data_mapper_factory $legacydatamapperfactory Legacy data mapper factory */
80 private $legacydatamapperfactory;
81 /** @var exporter_factory $exporterfactory Exporter factory */
82 private $exporterfactory;
83 /** @var vault_factory $vaultfactory Vault factory */
84 private $vaultfactory;
fe8e8ad4
RW
85 /** @var url_factory $urlfactory URL factory */
86 private $urlfactory;
87 /** @var entity_factory $entityfactory Entity factory */
88 private $entityfactory;
47d38303
RW
89 /** @var capability_manager $capabilitymanager Capability manager */
90 private $capabilitymanager;
91 /** @var rating_manager $ratingmanager Rating manager */
92 private $ratingmanager;
93 /** @var moodle_url $baseurl The base URL for the discussion */
94 private $baseurl;
95 /** @var array $notifications List of HTML notifications to display */
96 private $notifications;
97 /** @var sorter_entity $exportedpostsorter Sorter for the exported posts */
98 private $exportedpostsorter;
13cd05ac
P
99 /** @var callable $postprocessfortemplate Function to process exported posts before template rendering */
100 private $postprocessfortemplate;
47d38303
RW
101
102 /**
103 * Constructor.
104 *
47d38303 105 * @param forum_entity $forum The forum that the discussion belongs to
54d38a73 106 * @param discussion_entity $discussion The discussion entity
47d38303
RW
107 * @param int $displaymode The display mode to render the discussion in
108 * @param renderer_base $renderer Renderer base
109 * @param posts_renderer $postsrenderer A posts renderer
110 * @param moodle_page $page The page this discussion is being rendered for
111 * @param legacy_data_mapper_factory $legacydatamapperfactory Legacy data mapper factory
112 * @param exporter_factory $exporterfactory Exporter factory
113 * @param vault_factory $vaultfactory Vault factory
fe8e8ad4
RW
114 * @param url_factory $urlfactory URL factory
115 * @param entity_factory $entityfactory Entity factory
47d38303
RW
116 * @param capability_manager $capabilitymanager Capability manager
117 * @param rating_manager $ratingmanager Rating manager
118 * @param sorter_entity $exportedpostsorter Sorter for the exported posts
119 * @param moodle_url $baseurl The base URL for the discussion
120 * @param array $notifications List of HTML notifications to display
fe8e8ad4 121 * @param callable|null $postprocessfortemplate Post processing for template callback
47d38303
RW
122 */
123 public function __construct(
47d38303 124 forum_entity $forum,
54d38a73 125 discussion_entity $discussion,
47d38303
RW
126 int $displaymode,
127 renderer_base $renderer,
128 posts_renderer $postsrenderer,
129 moodle_page $page,
130 legacy_data_mapper_factory $legacydatamapperfactory,
131 exporter_factory $exporterfactory,
132 vault_factory $vaultfactory,
fe8e8ad4
RW
133 url_factory $urlfactory,
134 entity_factory $entityfactory,
47d38303
RW
135 capability_manager $capabilitymanager,
136 rating_manager $ratingmanager,
137 sorter_entity $exportedpostsorter,
138 moodle_url $baseurl,
13cd05ac
P
139 array $notifications = [],
140 callable $postprocessfortemplate = null
47d38303 141 ) {
47d38303 142 $this->forum = $forum;
54d38a73 143 $this->discussion = $discussion;
47d38303
RW
144 $this->displaymode = $displaymode;
145 $this->renderer = $renderer;
146 $this->postsrenderer = $postsrenderer;
147 $this->page = $page;
148 $this->baseurl = $baseurl;
149 $this->legacydatamapperfactory = $legacydatamapperfactory;
150 $this->exporterfactory = $exporterfactory;
151 $this->vaultfactory = $vaultfactory;
fe8e8ad4
RW
152 $this->urlfactory = $urlfactory;
153 $this->entityfactory = $entityfactory;
47d38303
RW
154 $this->capabilitymanager = $capabilitymanager;
155 $this->ratingmanager = $ratingmanager;
156 $this->notifications = $notifications;
54d38a73 157
47d38303 158 $this->exportedpostsorter = $exportedpostsorter;
13cd05ac 159 $this->postprocessfortemplate = $postprocessfortemplate;
47d38303
RW
160
161 $forumdatamapper = $this->legacydatamapperfactory->get_forum_data_mapper();
162 $this->forumrecord = $forumdatamapper->to_legacy_object($forum);
163
164 $discussiondatamapper = $this->legacydatamapperfactory->get_discussion_data_mapper();
165 $this->discussionrecord = $discussiondatamapper->to_legacy_object($discussion);
166 }
167
168 /**
169 * Render the discussion for the given user in the specified display mode.
170 *
171 * @param stdClass $user The user viewing the discussion
172 * @param post_entity $firstpost The first post in the discussion
173 * @param array $replies List of replies to the first post
174 * @return string HTML for the discussion
175 */
176 public function render(
177 stdClass $user,
178 post_entity $firstpost,
179 array $replies
180 ) : string {
181 global $CFG;
182
183 $displaymode = $this->displaymode;
184 $capabilitymanager = $this->capabilitymanager;
fe8e8ad4
RW
185 $urlfactory = $this->urlfactory;
186 $entityfactory = $this->entityfactory;
187 $loggedinauthor = $entityfactory->get_author_from_stdClass($user);
47d38303
RW
188
189 // Make sure we can render.
190 if (!$capabilitymanager->can_view_discussions($user)) {
191 throw new moodle_exception('noviewdiscussionspermission', 'mod_forum');
192 }
193
194 $posts = array_merge([$firstpost], array_values($replies));
195
13cd05ac
P
196 if ($this->postprocessfortemplate !== null) {
197 $exporteddiscussion = ($this->postprocessfortemplate) ($this->discussion, $user, $this->forum);
198 } else {
199 $exporteddiscussion = $this->get_exported_discussion($user);
200 }
201
4b6e0328
AN
202 $hasanyactions = false;
203 $hasanyactions = $hasanyactions || $capabilitymanager->can_favourite_discussion($user);
204 $hasanyactions = $hasanyactions || $capabilitymanager->can_pin_discussions($user);
205 $hasanyactions = $hasanyactions || $capabilitymanager->can_manage_forum($user);
206
47d38303 207 $exporteddiscussion = array_merge($exporteddiscussion, [
fe8e8ad4
RW
208 'loggedinuser' => [
209 'firstname' => $loggedinauthor->get_first_name(),
210 'fullname' => $loggedinauthor->get_full_name(),
211 'profileimageurl' => ($urlfactory->get_author_profile_image_url($loggedinauthor, null))->out(false)
212 ],
54d38a73 213 'notifications' => $this->get_notifications($user),
47d38303 214 'html' => [
4b6e0328 215 'hasanyactions' => $hasanyactions,
47d38303
RW
216 'posts' => $this->postsrenderer->render($user, [$this->forum], [$this->discussion], $posts),
217 'modeselectorform' => $this->get_display_mode_selector_html($displaymode),
218 'subscribe' => null,
219 'movediscussion' => null,
220 'pindiscussion' => null,
221 'neighbourlinks' => $this->get_neighbour_links_html(),
222 'exportdiscussion' => !empty($CFG->enableportfolios) ? $this->get_export_discussion_html() : null
223 ]
224 ]);
225
226 $capabilities = (array) $exporteddiscussion['capabilities'];
227
228 if ($capabilities['subscribe']) {
229 $exporteddiscussion['html']['subscribe'] = $this->get_subscription_button_html();
230 }
231
232 if ($capabilities['move']) {
233 $exporteddiscussion['html']['movediscussion'] = $this->get_move_discussion_html();
234 }
235
fe8e8ad4
RW
236 if ($this->displaymode === FORUM_MODE_MODERN) {
237 $template = 'mod_forum/forum_discussion_modern';
238 } else {
239 $template = 'mod_forum/forum_discussion';
240 }
241
242 return $this->renderer->render_from_template($template, $exporteddiscussion);
47d38303
RW
243 }
244
245 /**
246 * Get the groups details for all groups available to the forum.
247 *
248 * @return stdClass[]
249 */
250 private function get_groups_available_in_forum() : array {
251 $course = $this->forum->get_course_record();
252 $coursemodule = $this->forum->get_course_module_record();
253
254 return groups_get_all_groups($course->id, 0, $coursemodule->groupingid);
255 }
256
257 /**
258 * Get the exported discussion.
259 *
260 * @param stdClass $user The user viewing the discussion
261 * @return array
262 */
263 private function get_exported_discussion(stdClass $user) : array {
264 $discussionexporter = $this->exporterfactory->get_discussion_exporter(
265 $user,
266 $this->forum,
267 $this->discussion,
268 $this->get_groups_available_in_forum()
269 );
270
271 return (array) $discussionexporter->export($this->renderer);
272 }
273
274 /**
275 * Get the HTML for the display mode selector.
276 *
277 * @param int $displaymode The current display mode
278 * @return string
279 */
280 private function get_display_mode_selector_html(int $displaymode) : string {
281 $baseurl = $this->baseurl;
282 $select = new single_select(
283 $baseurl,
284 'mode',
285 forum_get_layout_modes(),
286 $displaymode,
287 null,
288 'mode'
289 );
290 $select->set_label(get_string('displaymode', 'forum'), ['class' => 'accesshide']);
291
292 return $this->renderer->render($select);
293 }
294
295 /**
296 * Get the HTML to render the subscription button.
297 *
298 * @return string
299 */
300 private function get_subscription_button_html() : string {
301 global $PAGE;
302
303 $forumrecord = $this->forumrecord;
304 $discussion = $this->discussion;
305 $html = html_writer::div(
306 forum_get_discussion_subscription_icon($forumrecord, $discussion->get_id(), null, true),
307 'discussionsubscription'
308 );
309 $html .= forum_get_discussion_subscription_icon_preloaders();
310 // Add the subscription toggle JS.
311 $PAGE->requires->yui_module('moodle-mod_forum-subscriptiontoggle', 'Y.M.mod_forum.subscriptiontoggle.init');
312 return $html;
313 }
314
315 /**
316 * Get the HTML to render the move discussion selector and button.
317 *
318 * @return string
319 */
14572292 320 private function get_move_discussion_html() : ?string {
47d38303
RW
321 global $DB;
322
323 $forum = $this->forum;
324 $discussion = $this->discussion;
325 $courseid = $forum->get_course_id();
326
327 // Popup menu to move discussions to other forums. The discussion in a
328 // single discussion forum can't be moved.
329 $modinfo = get_fast_modinfo($courseid);
330 if (isset($modinfo->instances['forum'])) {
331 $forummenu = [];
332 // Check forum types and eliminate simple discussions.
333 $forumcheck = $DB->get_records('forum', ['course' => $courseid], '', 'id, type');
334 foreach ($modinfo->instances['forum'] as $forumcm) {
335 if (!$forumcm->uservisible || !has_capability('mod/forum:startdiscussion',
336 context_module::instance($forumcm->id))) {
337 continue;
338 }
339 $section = $forumcm->sectionnum;
340 $sectionname = get_section_name($courseid, $section);
341 if (empty($forummenu[$section])) {
342 $forummenu[$section] = [$sectionname => []];
343 }
344 $forumidcompare = $forumcm->instance != $forum->get_id();
345 $forumtypecheck = $forumcheck[$forumcm->instance]->type !== 'single';
346
347 if ($forumidcompare and $forumtypecheck) {
348 $url = "/mod/forum/discuss.php?d={$discussion->get_id()}&move=$forumcm->instance&sesskey=".sesskey();
349 $forummenu[$section][$sectionname][$url] = format_string($forumcm->name);
350 }
351 }
352 if (!empty($forummenu)) {
353 $html = '<div class="movediscussionoption">';
354 $select = new url_select($forummenu, '',
355 ['/mod/forum/discuss.php?d=' . $discussion->get_id() => get_string("movethisdiscussionto", "forum")],
356 'forummenu', get_string('move'));
357 $html .= $this->renderer->render($select);
358 $html .= "</div>";
359 return $html;
360 }
361 }
362
363 return null;
364 }
365
47d38303
RW
366 /**
367 * Get the HTML to render the export discussion button.
368 *
369 * @return string|null
370 */
371 private function get_export_discussion_html() : ?string {
372 global $CFG;
373
374 require_once($CFG->libdir . '/portfoliolib.php');
375 $discussion = $this->discussion;
376 $button = new \portfolio_add_button();
377 $button->set_callback_options('forum_portfolio_caller', ['discussionid' => $discussion->get_id()], 'mod_forum');
378 $button = $button->to_html(PORTFOLIO_ADD_FULL_FORM, get_string('exportdiscussion', 'mod_forum'));
379 return $button ?: null;
380 }
381
382 /**
383 * Get a list of notification HTML to render in the page.
384 *
54d38a73 385 * @param stdClass $user The user viewing the discussion
47d38303
RW
386 * @return string[]
387 */
54d38a73 388 private function get_notifications($user) : array {
47d38303
RW
389 $notifications = $this->notifications;
390 $discussion = $this->discussion;
391 $forum = $this->forum;
392 $renderer = $this->renderer;
393
cbf63d8e
SR
394 if ($forum->is_cutoff_date_reached()) {
395 $notifications[] = (new notification(
396 get_string('cutoffdatereached', 'forum'),
82482e3d
SR
397 notification::NOTIFY_INFO
398 ))->set_show_closebutton();
399 } else if ($forum->is_due_date_reached()) {
400 $notifications[] = (new notification(
401 get_string('thisforumisdue', 'forum', userdate($forum->get_due_date())),
cbf63d8e
SR
402 notification::NOTIFY_INFO
403 ))->set_show_closebutton();
404 } else if ($forum->has_due_date()) {
405 $notifications[] = (new notification(
406 get_string('thisforumhasduedate', 'forum', userdate($forum->get_due_date())),
407 notification::NOTIFY_INFO
408 ))->set_show_closebutton();
409 }
410
47d38303
RW
411 if ($forum->is_discussion_locked($discussion)) {
412 $notifications[] = (new notification(
413 get_string('discussionlocked', 'forum'),
414 notification::NOTIFY_INFO
415 ))
416 ->set_extra_classes(['discussionlocked'])
417 ->set_show_closebutton();
418 }
54d38a73
MG
419
420 if ($forum->get_type() == 'qanda') {
421 if ($this->capabilitymanager->must_post_before_viewing_discussion($user, $discussion)) {
422 $notifications[] = (new notification(
423 get_string('qandanotify', 'forum')
424 ))->set_show_closebutton(true);
425 }
426 }
47d38303
RW
427
428 if ($forum->has_blocking_enabled()) {
429 $notifications[] = (new notification(
430 get_string('thisforumisthrottled', 'forum', [
431 'blockafter' => $forum->get_block_after(),
432 'blockperiod' => get_string('secondstotime' . $forum->get_block_period())
433 ])
434 ))->set_show_closebutton();
435 }
436
437 return array_map(function($notification) {
438 return $notification->export_for_template($this->renderer);
439 }, $notifications);
440 }
441
442 /**
443 * Get HTML to display the neighbour links.
444 *
445 * @return string
446 */
447 private function get_neighbour_links_html() : string {
448 $forum = $this->forum;
449 $coursemodule = $forum->get_course_module_record();
450 $neighbours = forum_get_discussion_neighbours($coursemodule, $this->discussionrecord, $this->forumrecord);
451 return $this->renderer->neighbouring_discussion_navigation($neighbours['prev'], $neighbours['next']);
452 }
453}