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