Merge branch 'MDL-66818-39' of git://github.com/lameze/moodle into MOODLE_39_STABLE
[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;
e4ffa5f3 40use forum_portfolio_caller;
47d38303
RW
41use core\output\notification;
42use context;
43use context_module;
44use html_writer;
45use moodle_exception;
46use moodle_page;
47use moodle_url;
48use rating_manager;
49use renderer_base;
50use single_button;
51use single_select;
52use stdClass;
53use url_select;
54
55require_once($CFG->dirroot . '/mod/forum/lib.php');
e4ffa5f3 56require_once($CFG->dirroot . '/mod/forum/locallib.php');
47d38303
RW
57
58/**
59 * Discussion renderer class.
60 *
61 * @copyright 2019 Ryan Wyllie <ryan@moodle.com>
62 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
63 */
64class discussion {
54d38a73
MG
65 /** @var forum_entity $forum The forum that the discussion belongs to */
66 private $forum;
67 /** @var discussion_entity $discussion The discussion entity */
47d38303
RW
68 private $discussion;
69 /** @var stdClass $discussionrecord Legacy discussion record */
70 private $discussionrecord;
47d38303
RW
71 /** @var stdClass $forumrecord Legacy forum record */
72 private $forumrecord;
73 /** @var int $displaymode The display mode to render the discussion in */
74 private $displaymode;
75 /** @var renderer_base $renderer Renderer base */
76 private $renderer;
77 /** @var posts_renderer $postsrenderer A posts renderer */
78 private $postsrenderer;
79 /** @var moodle_page $page The page this discussion is being rendered for */
80 private $page;
81 /** @var legacy_data_mapper_factory $legacydatamapperfactory Legacy data mapper factory */
82 private $legacydatamapperfactory;
83 /** @var exporter_factory $exporterfactory Exporter factory */
84 private $exporterfactory;
85 /** @var vault_factory $vaultfactory Vault factory */
86 private $vaultfactory;
fe8e8ad4
RW
87 /** @var url_factory $urlfactory URL factory */
88 private $urlfactory;
89 /** @var entity_factory $entityfactory Entity factory */
90 private $entityfactory;
47d38303
RW
91 /** @var capability_manager $capabilitymanager Capability manager */
92 private $capabilitymanager;
93 /** @var rating_manager $ratingmanager Rating manager */
94 private $ratingmanager;
95 /** @var moodle_url $baseurl The base URL for the discussion */
96 private $baseurl;
97 /** @var array $notifications List of HTML notifications to display */
98 private $notifications;
99 /** @var sorter_entity $exportedpostsorter Sorter for the exported posts */
100 private $exportedpostsorter;
13cd05ac
P
101 /** @var callable $postprocessfortemplate Function to process exported posts before template rendering */
102 private $postprocessfortemplate;
47d38303
RW
103
104 /**
105 * Constructor.
106 *
47d38303 107 * @param forum_entity $forum The forum that the discussion belongs to
54d38a73 108 * @param discussion_entity $discussion The discussion entity
47d38303
RW
109 * @param int $displaymode The display mode to render the discussion in
110 * @param renderer_base $renderer Renderer base
111 * @param posts_renderer $postsrenderer A posts renderer
112 * @param moodle_page $page The page this discussion is being rendered for
113 * @param legacy_data_mapper_factory $legacydatamapperfactory Legacy data mapper factory
114 * @param exporter_factory $exporterfactory Exporter factory
115 * @param vault_factory $vaultfactory Vault factory
fe8e8ad4
RW
116 * @param url_factory $urlfactory URL factory
117 * @param entity_factory $entityfactory Entity factory
47d38303
RW
118 * @param capability_manager $capabilitymanager Capability manager
119 * @param rating_manager $ratingmanager Rating manager
120 * @param sorter_entity $exportedpostsorter Sorter for the exported posts
121 * @param moodle_url $baseurl The base URL for the discussion
122 * @param array $notifications List of HTML notifications to display
fe8e8ad4 123 * @param callable|null $postprocessfortemplate Post processing for template callback
47d38303
RW
124 */
125 public function __construct(
47d38303 126 forum_entity $forum,
54d38a73 127 discussion_entity $discussion,
47d38303
RW
128 int $displaymode,
129 renderer_base $renderer,
130 posts_renderer $postsrenderer,
131 moodle_page $page,
132 legacy_data_mapper_factory $legacydatamapperfactory,
133 exporter_factory $exporterfactory,
134 vault_factory $vaultfactory,
fe8e8ad4
RW
135 url_factory $urlfactory,
136 entity_factory $entityfactory,
47d38303
RW
137 capability_manager $capabilitymanager,
138 rating_manager $ratingmanager,
139 sorter_entity $exportedpostsorter,
140 moodle_url $baseurl,
13cd05ac
P
141 array $notifications = [],
142 callable $postprocessfortemplate = null
47d38303 143 ) {
47d38303 144 $this->forum = $forum;
54d38a73 145 $this->discussion = $discussion;
47d38303
RW
146 $this->displaymode = $displaymode;
147 $this->renderer = $renderer;
148 $this->postsrenderer = $postsrenderer;
149 $this->page = $page;
150 $this->baseurl = $baseurl;
151 $this->legacydatamapperfactory = $legacydatamapperfactory;
152 $this->exporterfactory = $exporterfactory;
153 $this->vaultfactory = $vaultfactory;
fe8e8ad4
RW
154 $this->urlfactory = $urlfactory;
155 $this->entityfactory = $entityfactory;
47d38303
RW
156 $this->capabilitymanager = $capabilitymanager;
157 $this->ratingmanager = $ratingmanager;
158 $this->notifications = $notifications;
54d38a73 159
47d38303 160 $this->exportedpostsorter = $exportedpostsorter;
13cd05ac 161 $this->postprocessfortemplate = $postprocessfortemplate;
47d38303
RW
162
163 $forumdatamapper = $this->legacydatamapperfactory->get_forum_data_mapper();
164 $this->forumrecord = $forumdatamapper->to_legacy_object($forum);
165
166 $discussiondatamapper = $this->legacydatamapperfactory->get_discussion_data_mapper();
167 $this->discussionrecord = $discussiondatamapper->to_legacy_object($discussion);
168 }
169
170 /**
171 * Render the discussion for the given user in the specified display mode.
172 *
173 * @param stdClass $user The user viewing the discussion
174 * @param post_entity $firstpost The first post in the discussion
175 * @param array $replies List of replies to the first post
176 * @return string HTML for the discussion
177 */
178 public function render(
179 stdClass $user,
180 post_entity $firstpost,
181 array $replies
182 ) : string {
183 global $CFG;
184
185 $displaymode = $this->displaymode;
186 $capabilitymanager = $this->capabilitymanager;
fe8e8ad4
RW
187 $urlfactory = $this->urlfactory;
188 $entityfactory = $this->entityfactory;
47d38303
RW
189
190 // Make sure we can render.
191 if (!$capabilitymanager->can_view_discussions($user)) {
192 throw new moodle_exception('noviewdiscussionspermission', 'mod_forum');
193 }
194
195 $posts = array_merge([$firstpost], array_values($replies));
196
13cd05ac
P
197 if ($this->postprocessfortemplate !== null) {
198 $exporteddiscussion = ($this->postprocessfortemplate) ($this->discussion, $user, $this->forum);
199 } else {
200 $exporteddiscussion = $this->get_exported_discussion($user);
201 }
202
4b6e0328
AN
203 $hasanyactions = false;
204 $hasanyactions = $hasanyactions || $capabilitymanager->can_favourite_discussion($user);
205 $hasanyactions = $hasanyactions || $capabilitymanager->can_pin_discussions($user);
206 $hasanyactions = $hasanyactions || $capabilitymanager->can_manage_forum($user);
207
47d38303 208 $exporteddiscussion = array_merge($exporteddiscussion, [
54d38a73 209 'notifications' => $this->get_notifications($user),
47d38303 210 'html' => [
4b6e0328 211 'hasanyactions' => $hasanyactions,
47d38303 212 'posts' => $this->postsrenderer->render($user, [$this->forum], [$this->discussion], $posts),
667e5fd9 213 'modeselectorform' => $this->get_display_mode_selector_html($displaymode, $user),
47d38303
RW
214 'subscribe' => null,
215 'movediscussion' => null,
216 'pindiscussion' => null,
217 'neighbourlinks' => $this->get_neighbour_links_html(),
218 'exportdiscussion' => !empty($CFG->enableportfolios) ? $this->get_export_discussion_html() : null
219 ]
220 ]);
221
222 $capabilities = (array) $exporteddiscussion['capabilities'];
223
47d38303
RW
224 if ($capabilities['move']) {
225 $exporteddiscussion['html']['movediscussion'] = $this->get_move_discussion_html();
226 }
227
38d96b65
RW
228 if (!empty($user->id)) {
229 $loggedinuser = $entityfactory->get_author_from_stdClass($user);
230 $exporteddiscussion['loggedinuser'] = [
231 'firstname' => $loggedinuser->get_first_name(),
232 'fullname' => $loggedinuser->get_full_name(),
233 'profileimageurl' => ($urlfactory->get_author_profile_image_url($loggedinuser, null))->out(false)
234 ];
235 }
236
2602c7bf
RW
237 if ($this->displaymode === FORUM_MODE_NESTED_V2) {
238 $template = 'mod_forum/forum_discussion_nested_v2';
fe8e8ad4
RW
239 } else {
240 $template = 'mod_forum/forum_discussion';
241 }
242
243 return $this->renderer->render_from_template($template, $exporteddiscussion);
47d38303
RW
244 }
245
246 /**
247 * Get the groups details for all groups available to the forum.
248 *
249 * @return stdClass[]
250 */
251 private function get_groups_available_in_forum() : array {
252 $course = $this->forum->get_course_record();
253 $coursemodule = $this->forum->get_course_module_record();
254
255 return groups_get_all_groups($course->id, 0, $coursemodule->groupingid);
256 }
257
258 /**
259 * Get the exported discussion.
260 *
261 * @param stdClass $user The user viewing the discussion
262 * @return array
263 */
264 private function get_exported_discussion(stdClass $user) : array {
265 $discussionexporter = $this->exporterfactory->get_discussion_exporter(
266 $user,
267 $this->forum,
268 $this->discussion,
269 $this->get_groups_available_in_forum()
270 );
271
272 return (array) $discussionexporter->export($this->renderer);
273 }
274
275 /**
276 * Get the HTML for the display mode selector.
277 *
278 * @param int $displaymode The current display mode
667e5fd9 279 * @param stdClass $user The current user
47d38303
RW
280 * @return string
281 */
667e5fd9 282 private function get_display_mode_selector_html(int $displaymode, stdClass $user) : string {
47d38303
RW
283 $baseurl = $this->baseurl;
284 $select = new single_select(
285 $baseurl,
286 'mode',
667e5fd9 287 forum_get_layout_modes(get_user_preferences('forum_useexperimentalui', false, $user)),
47d38303
RW
288 $displaymode,
289 null,
290 'mode'
291 );
292 $select->set_label(get_string('displaymode', 'forum'), ['class' => 'accesshide']);
293
294 return $this->renderer->render($select);
295 }
296
47d38303
RW
297 /**
298 * Get the HTML to render the move discussion selector and button.
299 *
300 * @return string
301 */
14572292 302 private function get_move_discussion_html() : ?string {
47d38303
RW
303 global $DB;
304
305 $forum = $this->forum;
306 $discussion = $this->discussion;
307 $courseid = $forum->get_course_id();
308
309 // Popup menu to move discussions to other forums. The discussion in a
310 // single discussion forum can't be moved.
311 $modinfo = get_fast_modinfo($courseid);
312 if (isset($modinfo->instances['forum'])) {
313 $forummenu = [];
314 // Check forum types and eliminate simple discussions.
315 $forumcheck = $DB->get_records('forum', ['course' => $courseid], '', 'id, type');
316 foreach ($modinfo->instances['forum'] as $forumcm) {
317 if (!$forumcm->uservisible || !has_capability('mod/forum:startdiscussion',
318 context_module::instance($forumcm->id))) {
319 continue;
320 }
321 $section = $forumcm->sectionnum;
322 $sectionname = get_section_name($courseid, $section);
323 if (empty($forummenu[$section])) {
324 $forummenu[$section] = [$sectionname => []];
325 }
326 $forumidcompare = $forumcm->instance != $forum->get_id();
327 $forumtypecheck = $forumcheck[$forumcm->instance]->type !== 'single';
328
329 if ($forumidcompare and $forumtypecheck) {
330 $url = "/mod/forum/discuss.php?d={$discussion->get_id()}&move=$forumcm->instance&sesskey=".sesskey();
331 $forummenu[$section][$sectionname][$url] = format_string($forumcm->name);
332 }
333 }
334 if (!empty($forummenu)) {
335 $html = '<div class="movediscussionoption">';
959b996c
JP
336
337 $movebutton = get_string('move');
2602c7bf 338 if ($this->displaymode === FORUM_MODE_NESTED_V2) {
959b996c
JP
339 // Move discussion selector will be rendered on the settings drawer. We won't output the button in this mode.
340 $movebutton = null;
341 }
47d38303
RW
342 $select = new url_select($forummenu, '',
343 ['/mod/forum/discuss.php?d=' . $discussion->get_id() => get_string("movethisdiscussionto", "forum")],
959b996c 344 'forummenu', $movebutton);
8092e7cf
AN
345 $select->set_label(get_string('movethisdiscussionlabel', 'mod_forum'), [
346 'class' => 'sr-only',
347 ]);
47d38303
RW
348 $html .= $this->renderer->render($select);
349 $html .= "</div>";
350 return $html;
351 }
352 }
353
354 return null;
355 }
356
47d38303
RW
357 /**
358 * Get the HTML to render the export discussion button.
359 *
360 * @return string|null
361 */
362 private function get_export_discussion_html() : ?string {
363 global $CFG;
364
365 require_once($CFG->libdir . '/portfoliolib.php');
366 $discussion = $this->discussion;
e4ffa5f3 367
368 // We use the portfolio caller to work out if user should be allowed to see this button.
369 $caller = new forum_portfolio_caller(['discussionid' => $discussion->get_id()]);
370 $caller->set_formats_from_button([]);
371 $caller->load_data();
372 if (!$caller->check_permissions()) {
373 return null;
374 }
375
47d38303
RW
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}