Merge branch 'MDL-65017-master' of git://github.com/jleyva/moodle
[moodle.git] / mod / forum / post.php
CommitLineData
cd4e6b17 1<?php
8f685009
SH
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 * Edit and save a new post to a discussion
19 *
01030f1b 20 * @package mod_forum
8f685009
SH
21 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2f67a9b3 23 */
501cdbd8 24
cd4e6b17 25require_once('../../config.php');
26require_once('lib.php');
516c5eca 27require_once($CFG->libdir.'/completionlib.php');
cd4e6b17 28
29$reply = optional_param('reply', 0, PARAM_INT);
30$forum = optional_param('forum', 0, PARAM_INT);
31$edit = optional_param('edit', 0, PARAM_INT);
32$delete = optional_param('delete', 0, PARAM_INT);
33$prune = optional_param('prune', 0, PARAM_INT);
34$name = optional_param('name', '', PARAM_CLEAN);
35$confirm = optional_param('confirm', 0, PARAM_INT);
36$groupid = optional_param('groupid', null, PARAM_INT);
9b4f09ba 37$subject = optional_param('subject', '', PARAM_TEXT);
9c3e3a90
P
38
39// Values posted via the inpage reply form.
9b4f09ba 40$prefilledpost = optional_param('post', '', PARAM_TEXT);
f6548dfb 41$prefilledpostformat = optional_param('postformat', FORMAT_MOODLE, PARAM_INT);
56e9b6d6 42$prefilledprivatereply = optional_param('privatereply', false, PARAM_BOOL);
cd4e6b17 43
44$PAGE->set_url('/mod/forum/post.php', array(
707dfd0c
JM
45 'reply' => $reply,
46 'forum' => $forum,
47 'edit' => $edit,
48 'delete' => $delete,
49 'prune' => $prune,
50 'name' => $name,
51 'confirm' => $confirm,
52 'groupid' => $groupid,
53));
54// These page_params will be passed as hidden variables later in the form.
55$pageparams = array('reply' => $reply, 'forum' => $forum, 'edit' => $edit);
cd4e6b17 56
bf0f06b1 57$sitecontext = context_system::instance();
cd4e6b17 58
15dc885a
AN
59$entityfactory = mod_forum\local\container::get_entity_factory();
60$vaultfactory = mod_forum\local\container::get_vault_factory();
61$managerfactory = mod_forum\local\container::get_manager_factory();
62$legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
63$urlfactory = mod_forum\local\container::get_url_factory();
64
65$forumvault = $vaultfactory->get_forum_vault();
66$forumdatamapper = $legacydatamapperfactory->get_forum_data_mapper();
64f93798 67
15dc885a
AN
68$discussionvault = $vaultfactory->get_discussion_vault();
69$discussiondatamapper = $legacydatamapperfactory->get_discussion_data_mapper();
70
71$postvault = $vaultfactory->get_post_vault();
72$postdatamapper = $legacydatamapperfactory->get_post_data_mapper();
73
74if (!isloggedin() or isguestuser()) {
dcee0b94 75 if (!isloggedin() and !get_local_referer()) {
707dfd0c 76 // No referer+not logged in - probably coming in via email See MDL-9052.
4f0c2d00
PS
77 require_login();
78 }
cd4e6b17 79
15dc885a
AN
80 if (!empty($forum)) {
81 // User is starting a new discussion in a forum.
82 $forumentity = $forumvault->get_from_id($forum);
83 if (empty($forumentity)) {
cd4e6b17 84 print_error('invalidforumid', 'forum');
556963f5 85 }
15dc885a
AN
86 } else if (!empty($reply)) {
87 // User is writing a new reply.
88 $forumentity = $forumvault->get_from_post_id($reply);
89 if (empty($forumentity)) {
cd4e6b17 90 print_error('invalidparentpostid', 'forum');
556963f5 91 }
cd4e6b17 92 }
65bcf17b 93
15dc885a
AN
94 $forum = $forumdatamapper->to_legacy_object($forumentity);
95 $modcontext = $forumentity->get_context();
96 $course = $forumentity->get_course_record();
97 if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
98 print_error("invalidcoursemodule");
cd4e6b17 99 }
d3558659 100
184bcf11
SH
101 $PAGE->set_cm($cm, $course, $forum);
102 $PAGE->set_context($modcontext);
cd4e6b17 103 $PAGE->set_title($course->shortname);
104 $PAGE->set_heading($course->fullname);
dcee0b94 105 $referer = get_local_referer(false);
48d38fad 106
cd4e6b17 107 echo $OUTPUT->header();
dd0607b7 108 echo $OUTPUT->confirm(get_string('noguestpost', 'forum').'<br /><br />'.get_string('liketologin'), get_login_url(), $referer);
cd4e6b17 109 echo $OUTPUT->footer();
110 exit;
111}
65bcf17b 112
707dfd0c 113require_login(0, false); // Script is useless unless they're logged in.
65bcf17b 114
bc4c7337 115$canreplyprivately = false;
313d8b6e 116
15dc885a
AN
117if (!empty($forum)) {
118 // User is starting a new discussion in a forum.
119 $forumentity = $forumvault->get_from_id($forum);
120 if (empty($forumentity)) {
cd4e6b17 121 print_error('invalidforumid', 'forum');
122 }
15dc885a
AN
123
124 $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
125 $forum = $forumdatamapper->to_legacy_object($forumentity);
126 $course = $forumentity->get_course_record();
127 if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
cd4e6b17 128 print_error("invalidcoursemodule");
129 }
2b63df96 130
f67b5c99 131 // Retrieve the contexts.
15dc885a 132 $modcontext = $forumentity->get_context();
bf0f06b1 133 $coursecontext = context_course::instance($course->id);
80602101 134
15dc885a
AN
135 if ($forumentity->is_in_group_mode() && null === $groupid) {
136 $groupid = groups_get_activity_group($cm);
137 }
138
139 if (!$capabilitymanager->can_create_discussions($USER, $groupid)) {
4f0c2d00
PS
140 if (!isguestuser()) {
141 if (!is_enrolled($coursecontext)) {
45ff8a80 142 if (enrol_selfenrol_available($course->id)) {
f0202ae9 143 $SESSION->wantsurl = qualified_me();
dcee0b94 144 $SESSION->enrolcancel = get_local_referer(false);
9542b156
MN
145 redirect(new moodle_url('/enrol/index.php', array('id' => $course->id,
146 'returnurl' => '/mod/forum/view.php?f=' . $forum->id)),
147 get_string('youneedtoenrol'));
54ab8769 148 }
4f0c2d00 149 }
3b27b0fe 150 }
4f0c2d00 151 print_error('nopostforum', 'forum');
cd4e6b17 152 }
2b63df96 153
f67b5c99 154 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $modcontext)) {
15dc885a
AN
155 redirect(
156 $urlfactory->get_course_url_from_forum($forumentity),
157 get_string('activityiscurrentlyhidden'),
158 null,
b0c785e2 159 \core\output\notification::NOTIFY_ERROR
15dc885a 160 );
cd4e6b17 161 }
2b63df96 162
dcee0b94 163 $SESSION->fromurl = get_local_referer(false);
501cdbd8 164
cd4e6b17 165 // Load up the $post variable.
89d35c49 166
39790bd8 167 $post = new stdClass();
cd4e6b17 168 $post->course = $course->id;
169 $post->forum = $forum->id;
707dfd0c 170 $post->discussion = 0; // Ie discussion # not defined yet.
cd4e6b17 171 $post->parent = 0;
9b4f09ba 172 $post->subject = $subject;
cd4e6b17 173 $post->userid = $USER->id;
9b4f09ba 174 $post->message = $prefilledpost;
20e5da7d 175 $post->messageformat = editors_get_preferred_format();
cd4e6b17 176 $post->messagetrust = 0;
15dc885a 177 $post->groupid = $groupid;
501cdbd8 178
46691973
EM
179 // Unsetting this will allow the correct return URL to be calculated later.
180 unset($SESSION->fromdiscussion);
bd4128e9 181
15dc885a
AN
182} else if (!empty($reply)) {
183 // User is writing a new reply.
4cabf99f 184
15dc885a
AN
185 $parententity = $postvault->get_from_id($reply);
186 if (empty($parententity)) {
cd4e6b17 187 print_error('invalidparentpostid', 'forum');
188 }
15dc885a
AN
189
190 $discussionentity = $discussionvault->get_from_id($parententity->get_discussion_id());
191 if (empty($discussionentity)) {
cd4e6b17 192 print_error('notpartofdiscussion', 'forum');
193 }
15dc885a
AN
194
195 $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
196 if (empty($forumentity)) {
cd4e6b17 197 print_error('invalidforumid', 'forum');
198 }
15dc885a
AN
199
200 $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
201 $parent = $postdatamapper->to_legacy_object($parententity);
202 $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
203 $forum = $forumdatamapper->to_legacy_object($forumentity);
204 $course = $forumentity->get_course_record();
205 $modcontext = $forumentity->get_context();
206 $coursecontext = context_course::instance($course->id);
207
208 if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
cd4e6b17 209 print_error('invalidcoursemodule');
210 }
ea3caf69 211
707dfd0c 212 // Ensure lang, theme, etc. is set up properly. MDL-6926.
34563b35 213 $PAGE->set_cm($cm, $course, $forum);
cd4e6b17 214
15dc885a 215 if (!$capabilitymanager->can_reply_to_post($USER, $discussionentity, $parententity)) {
6a176a74 216 if (!isguestuser()) {
4f0c2d00 217 if (!is_enrolled($coursecontext)) { // User is a guest here!
f0202ae9 218 $SESSION->wantsurl = qualified_me();
dcee0b94 219 $SESSION->enrolcancel = get_local_referer(false);
9542b156
MN
220 redirect(new moodle_url('/enrol/index.php', array('id' => $course->id,
221 'returnurl' => '/mod/forum/view.php?f=' . $forum->id)),
222 get_string('youneedtoenrol'));
4f0c2d00 223 }
bdb4a87d
P
224
225 // The forum has been locked. Just redirect back to the discussion page.
226 if (forum_discussion_is_locked($forum, $discussion)) {
227 redirect(new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id)));
228 }
6c506ca7 229 }
4f0c2d00 230 print_error('nopostforum', 'forum');
cd4e6b17 231 }
2b63df96 232
707dfd0c 233 // Make sure user can post here.
cd4e6b17 234 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
707dfd0c 235 $groupmode = $cm->groupmode;
cd4e6b17 236 } else {
237 $groupmode = $course->groupmode;
238 }
239 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
240 if ($discussion->groupid == -1) {
241 print_error('nopostforum', 'forum');
242 } else {
243 if (!groups_is_member($discussion->groupid)) {
89d35c49 244 print_error('nopostforum', 'forum');
80602101 245 }
02509fe6 246 }
cd4e6b17 247 }
4136c239 248
f67b5c99 249 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $modcontext)) {
cd4e6b17 250 print_error("activityiscurrentlyhidden");
251 }
02509fe6 252
15dc885a 253 if ($parententity->is_private_reply()) {
bc4c7337
AN
254 print_error('cannotreplytoprivatereply', 'forum');
255 }
256
743d66bf 257 // We always are going to honor the preferred format. We are creating a new post.
f6548dfb 258 $preferredformat = editors_get_preferred_format();
743d66bf
EL
259
260 // Only if there are prefilled contents coming.
261 if (!empty($prefilledpost)) {
262 // If the prefilled post is not HTML and the preferred format is HTML, convert to it.
263 if ($prefilledpostformat != FORMAT_HTML and $preferredformat == FORMAT_HTML) {
264 $prefilledpost = format_text($prefilledpost, $prefilledpostformat, ['context' => $modcontext]);
265 }
f6548dfb
SA
266 }
267
cd4e6b17 268 // Load up the $post variable.
39790bd8 269 $post = new stdClass();
cd4e6b17 270 $post->course = $course->id;
271 $post->forum = $forum->id;
272 $post->discussion = $parent->discussion;
273 $post->parent = $parent->id;
9b4f09ba 274 $post->subject = $subject ? $subject : $parent->subject;
cd4e6b17 275 $post->userid = $USER->id;
bc4c7337 276 $post->parentpostauthor = $parent->userid;
9b4f09ba 277 $post->message = $prefilledpost;
743d66bf 278 $post->messageformat = $preferredformat;
56e9b6d6 279 $post->isprivatereply = $prefilledprivatereply;
15dc885a 280 $canreplyprivately = $capabilitymanager->can_reply_privately_to_post($USER, $parententity);
501cdbd8 281
cd4e6b17 282 $post->groupid = ($discussion->groupid == -1) ? 0 : $discussion->groupid;
4136c239 283
cd4e6b17 284 $strre = get_string('re', 'forum');
285 if (!(substr($post->subject, 0, strlen($strre)) == $strre)) {
286 $post->subject = $strre.' '.$post->subject;
287 }
501cdbd8 288
46691973 289 // Unsetting this will allow the correct return URL to be calculated later.
cd4e6b17 290 unset($SESSION->fromdiscussion);
0e52f01f 291
15dc885a
AN
292} else if (!empty($edit)) {
293 // User is editing their own post.
b8be40ce 294
15dc885a
AN
295 $postentity = $postvault->get_from_id($edit);
296 if (empty($postentity)) {
cd4e6b17 297 print_error('invalidpostid', 'forum');
298 }
15dc885a
AN
299 if ($postentity->has_parent()) {
300 $parententity = $postvault->get_from_id($postentity->get_parent_id());
301 $parent = $postdatamapper->to_legacy_object($parententity);
cd4e6b17 302 }
2b63df96 303
15dc885a
AN
304 $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
305 if (empty($discussionentity)) {
cd4e6b17 306 print_error('notpartofdiscussion', 'forum');
307 }
15dc885a
AN
308
309 $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
310 if (empty($forumentity)) {
cd4e6b17 311 print_error('invalidforumid', 'forum');
312 }
15dc885a
AN
313
314 $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
315 $post = $postdatamapper->to_legacy_object($postentity);
316 $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
317 $forum = $forumdatamapper->to_legacy_object($forumentity);
318 $course = $forumentity->get_course_record();
319 $modcontext = $forumentity->get_context();
320 $coursecontext = context_course::instance($course->id);
321
cd4e6b17 322 if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
323 print_error('invalidcoursemodule');
cd4e6b17 324 }
34563b35
SH
325
326 $PAGE->set_cm($cm, $course, $forum);
54ab8769 327
cd4e6b17 328 if (!($forum->type == 'news' && !$post->parent && $discussion->timestart > time())) {
329 if (((time() - $post->created) > $CFG->maxeditingtime) and
707dfd0c 330 !has_capability('mod/forum:editanypost', $modcontext)) {
cd4e6b17 331 print_error('maxtimehaspassed', 'forum', '', format_time($CFG->maxeditingtime));
6e89ca55 332 }
cd4e6b17 333 }
334 if (($post->userid <> $USER->id) and
707dfd0c 335 !has_capability('mod/forum:editanypost', $modcontext)) {
cd4e6b17 336 print_error('cannoteditposts', 'forum');
337 }
501cdbd8 338
cd4e6b17 339 // Load up the $post variable.
340 $post->edit = $edit;
341 $post->course = $course->id;
342 $post->forum = $forum->id;
343 $post->groupid = ($discussion->groupid == -1) ? 0 : $discussion->groupid;
15dc885a 344 if ($postentity->has_parent()) {
bc4c7337
AN
345 $canreplyprivately = forum_user_can_reply_privately($modcontext, $parent);
346 }
501cdbd8 347
cd4e6b17 348 $post = trusttext_pre_edit($post, 'message', $modcontext);
501cdbd8 349
46691973 350 // Unsetting this will allow the correct return URL to be calculated later.
cd4e6b17 351 unset($SESSION->fromdiscussion);
64f93798 352
15dc885a
AN
353} else if (!empty($delete)) {
354 // User is deleting a post.
dcf6d93c 355
15dc885a
AN
356 $postentity = $postvault->get_from_id($delete);
357 if (empty($postentity)) {
cd4e6b17 358 print_error('invalidpostid', 'forum');
359 }
15dc885a
AN
360
361 $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
362 if (empty($discussionentity)) {
cd4e6b17 363 print_error('notpartofdiscussion', 'forum');
364 }
15dc885a
AN
365
366 $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
367 if (empty($forumentity)) {
cd4e6b17 368 print_error('invalidforumid', 'forum');
369 }
15dc885a
AN
370
371 $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
15dc885a 372 $course = $forumentity->get_course_record();
b12dbcd4 373 $cm = $forumentity->get_course_module_record();
15dc885a 374 $modcontext = $forumentity->get_context();
501cdbd8 375
cd4e6b17 376 require_login($course, false, $cm);
2b63df96 377
15dc885a
AN
378 $replycount = $postvault->get_reply_count_for_post_id_in_discussion_id(
379 $USER, $postentity->get_id(), $discussionentity->get_id(), true);
64f93798 380
15dc885a 381 if (!empty($confirm) && confirm_sesskey()) {
b12dbcd4
JL
382 // Do further checks and delete the post.
383 $hasreplies = $replycount > 0;
384
385 try {
386 $capabilitymanager->validate_delete_post($USER, $discussionentity, $postentity, $hasreplies);
387
15dc885a 388 if (!$postentity->has_parent()) {
b12dbcd4
JL
389 forum_delete_discussion(
390 $discussiondatamapper->to_legacy_object($discussionentity),
391 false,
392 $forumentity->get_course_record(),
393 $forumentity->get_course_module_record(),
394 $forumdatamapper->to_legacy_object($forumentity)
71595d00
DP
395 );
396
9f832722 397 redirect(
15dc885a
AN
398 $urlfactory->get_forum_view_url_from_forum($forumentity),
399 get_string('eventdiscussiondeleted', 'forum'),
9f832722
DW
400 null,
401 \core\output\notification::NOTIFY_SUCCESS
402 );
15dc885a 403 } else {
b12dbcd4
JL
404 forum_delete_post(
405 $postdatamapper->to_legacy_object($postentity),
406 has_capability('mod/forum:deleteanypost', $modcontext),
407 $forumentity->get_course_record(),
408 $forumentity->get_course_module_record(),
409 $forumdatamapper->to_legacy_object($forumentity)
410 );
69d79bc3 411
b12dbcd4 412 if ($forumentity->get_type() == 'single') {
15dc885a
AN
413 // Single discussion forums are an exception.
414 // We show the forum itself since it only has one discussion thread.
415 $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
501cdbd8 416 } else {
15dc885a 417 $discussionurl = $urlfactory->get_discussion_view_url_from_discussion($discussionentity);
501cdbd8 418 }
501cdbd8 419
9f832722
DW
420 redirect(
421 forum_go_back_to($discussionurl),
15dc885a 422 get_string('eventpostdeleted', 'forum'),
9f832722
DW
423 null,
424 \core\output\notification::NOTIFY_SUCCESS
425 );
cd4e6b17 426 }
b12dbcd4
JL
427 } catch (Exception $e) {
428 redirect(
429 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
430 $e->getMessage(),
431 null,
432 \core\output\notification::NOTIFY_ERROR
433 );
cd4e6b17 434 }
501cdbd8 435
15dc885a 436 } else {
b12dbcd4
JL
437
438 if (!$capabilitymanager->can_delete_post($USER, $discussionentity, $postentity)) {
439 redirect(
440 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
441 get_string('cannotdeletepost', 'forum'),
442 null,
443 \core\output\notification::NOTIFY_ERROR
444 );
445 }
446
447 $post = $postdatamapper->to_legacy_object($postentity);
448 $forum = $forumdatamapper->to_legacy_object($forumentity);
449
15dc885a 450 // User just asked to delete something.
cd4e6b17 451 forum_set_return();
b4c07395
RW
452 $PAGE->navbar->add(get_string('delete', 'forum'));
453 $PAGE->set_title($course->shortname);
454 $PAGE->set_heading($course->fullname);
09d40d65 455
cd4e6b17 456 if ($replycount) {
457 if (!has_capability('mod/forum:deleteanypost', $modcontext)) {
15dc885a
AN
458 redirect(
459 forum_go_back_to($urlfactory->get_view_post_url_from_post($postentity)),
10b1b829 460 get_string('couldnotdeletereplies', 'forum'),
15dc885a 461 null,
b0c785e2 462 \core\output\notification::NOTIFY_ERROR
15dc885a 463 );
b82faacd 464 }
15dc885a 465
cd4e6b17 466 echo $OUTPUT->header();
66e2b9f8 467 echo $OUTPUT->heading(format_string($forum->name), 2);
707dfd0c
JM
468 echo $OUTPUT->confirm(get_string("deletesureplural", "forum", $replycount + 1),
469 "post.php?delete=$delete&confirm=$delete",
470 $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
8f0cd6ef 471
313d8b6e 472 $postentities = [$postentity];
cd4e6b17 473 if (empty($post->edit)) {
313d8b6e 474 $postvault = $vaultfactory->get_post_vault();
bc4c7337
AN
475 $replies = $postvault->get_replies_to_post(
476 $USER,
477 $postentity,
15dc885a
AN
478 // Note: All replies are fetched here as the user has deleteanypost.
479 true,
bc4c7337
AN
480 'created ASC'
481 );
313d8b6e 482 $postentities = array_merge($postentities, $replies);
cd4e6b17 483 }
313d8b6e
RW
484
485 $rendererfactory = mod_forum\local\container::get_renderer_factory();
486 $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(FORUM_MODE_NESTED, true);
15dc885a 487 echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], $postentities);
cd4e6b17 488 } else {
489 echo $OUTPUT->header();
66e2b9f8 490 echo $OUTPUT->heading(format_string($forum->name), 2);
cd4e6b17 491 echo $OUTPUT->confirm(get_string("deletesure", "forum", $replycount),
707dfd0c
JM
492 "post.php?delete=$delete&confirm=$delete",
493 $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
313d8b6e
RW
494
495 $rendererfactory = mod_forum\local\container::get_renderer_factory();
496 $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(null, true);
497 echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], [$postentity]);
501cdbd8 498 }
501cdbd8 499
cd4e6b17 500 }
501 echo $OUTPUT->footer();
502 die;
501cdbd8 503
15dc885a
AN
504} else if (!empty($prune)) {
505 // Pruning.
8f0cd6ef 506
15dc885a
AN
507 $postentity = $postvault->get_from_id($prune);
508 if (empty($postentity)) {
cd4e6b17 509 print_error('invalidpostid', 'forum');
510 }
15dc885a
AN
511
512 $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
513 if (empty($discussionentity)) {
cd4e6b17 514 print_error('notpartofdiscussion', 'forum');
515 }
15dc885a
AN
516
517 $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
518 if (empty($forumentity)) {
cd4e6b17 519 print_error('invalidforumid', 'forum');
520 }
15dc885a
AN
521
522 $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
523 $post = $postdatamapper->to_legacy_object($postentity);
524 $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
525 $forum = $forumdatamapper->to_legacy_object($forumentity);
526 $course = $forumentity->get_course_record();
527 $modcontext = $forumentity->get_context();
528 $coursecontext = context_course::instance($course->id);
529
530 if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
cd4e6b17 531 print_error('invalidcoursemodule');
cd4e6b17 532 }
15dc885a
AN
533
534 if (!$postentity->has_parent()) {
535 redirect(
536 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
537 get_string('alreadyfirstpost', 'forum'),
538 null,
539 \core\output\notification::NOTIFY_ERROR
540 );
541 }
542 if (!$capabilitymanager->can_split_post($USER, $discussionentity, $postentity)) {
543 redirect(
544 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
545 get_string('cannotsplit', 'forum'),
546 null,
547 \core\output\notification::NOTIFY_ERROR
548 );
cd4e6b17 549 }
8f0cd6ef 550
069d0f17
MM
551 $PAGE->set_cm($cm);
552 $PAGE->set_context($modcontext);
553
554 $prunemform = new mod_forum_prune_form(null, array('prune' => $prune, 'confirm' => $prune));
8f0cd6ef 555
069d0f17 556 if ($prunemform->is_cancelled()) {
15dc885a 557 redirect(forum_go_back_to($urlfactory->get_discussion_view_url_from_discussion($discussionentity)));
069d0f17
MM
558 } else if ($fromform = $prunemform->get_data()) {
559 // User submits the data.
39790bd8 560 $newdiscussion = new stdClass();
cd4e6b17 561 $newdiscussion->course = $discussion->course;
562 $newdiscussion->forum = $discussion->forum;
563 $newdiscussion->name = $name;
564 $newdiscussion->firstpost = $post->id;
565 $newdiscussion->userid = $discussion->userid;
566 $newdiscussion->groupid = $discussion->groupid;
567 $newdiscussion->assessed = $discussion->assessed;
568 $newdiscussion->usermodified = $post->userid;
569 $newdiscussion->timestart = $discussion->timestart;
570 $newdiscussion->timeend = $discussion->timeend;
8f0cd6ef 571
cd4e6b17 572 $newid = $DB->insert_record('forum_discussions', $newdiscussion);
d078ee9b 573
39790bd8 574 $newpost = new stdClass();
cd4e6b17 575 $newpost->id = $post->id;
576 $newpost->parent = 0;
577 $newpost->subject = $name;
d078ee9b 578
cd4e6b17 579 $DB->update_record("forum_posts", $newpost);
15dc885a 580 $postentity = $postvault->get_from_id($postentity->get_id());
8f0cd6ef 581
cd4e6b17 582 forum_change_discussionid($post->id, $newid);
cf84431b 583
069d0f17 584 // Update last post in each discussion.
cd4e6b17 585 forum_discussion_update_last_post($discussion->id);
586 forum_discussion_update_last_post($newid);
4e6a816a 587
2d3f692b 588 // Fire events to reflect the split..
97802bea
DP
589 $params = array(
590 'context' => $modcontext,
591 'objectid' => $discussion->id,
592 'other' => array(
593 'forumid' => $forum->id,
594 )
595 );
596 $event = \mod_forum\event\discussion_updated::create($params);
597 $event->trigger();
598
2d3f692b
DP
599 $params = array(
600 'context' => $modcontext,
601 'objectid' => $newid,
602 'other' => array(
603 'forumid' => $forum->id,
604 )
605 );
606 $event = \mod_forum\event\discussion_created::create($params);
607 $event->trigger();
608
609 $params = array(
610 'context' => $modcontext,
611 'objectid' => $post->id,
612 'other' => array(
613 'discussionid' => $newid,
614 'forumid' => $forum->id,
615 'forumtype' => $forum->type,
616 )
617 );
618 $event = \mod_forum\event\post_updated::create($params);
619 $event->add_record_snapshot('forum_discussions', $discussion);
620 $event->trigger();
cf84431b 621
9f832722 622 redirect(
15dc885a
AN
623 forum_go_back_to($urlfactory->get_discussion_view_url_from_post($postentity)),
624 get_string('discussionsplit', 'forum'),
9f832722
DW
625 null,
626 \core\output\notification::NOTIFY_SUCCESS
627 );
069d0f17
MM
628 } else {
629 // Display the prune form.
cd4e6b17 630 $course = $DB->get_record('course', array('id' => $forum->course));
707dfd0c
JM
631 $subjectstr = format_string($post->subject, true);
632 $PAGE->navbar->add($subjectstr, new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id)));
cd4e6b17 633 $PAGE->navbar->add(get_string("prune", "forum"));
634 $PAGE->set_title(format_string($discussion->name).": ".format_string($post->subject));
b4c07395 635 $PAGE->set_heading($course->fullname);
cd4e6b17 636 echo $OUTPUT->header();
66e2b9f8
AD
637 echo $OUTPUT->heading(format_string($forum->name), 2);
638 echo $OUTPUT->heading(get_string('pruneheading', 'forum'), 3);
8f0cd6ef 639
069d0f17 640 $prunemform->display();
501cdbd8 641
313d8b6e
RW
642 $postentity = $entityfactory->get_post_from_stdclass($post);
643 $discussionentity = $entityfactory->get_discussion_from_stdclass($discussion);
644 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $modcontext, $cm, $course);
645 $rendererfactory = mod_forum\local\container::get_renderer_factory();
646 $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(null, true);
647 echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], [$postentity]);
501cdbd8 648 }
069d0f17 649
cd4e6b17 650 echo $OUTPUT->footer();
651 die;
652} else {
653 print_error('unknowaction');
501cdbd8 654
cd4e6b17 655}
656
707dfd0c 657// From now on user must be logged on properly.
12fab708 658
cd4e6b17 659require_login($course, false, $cm);
12fab708 660
cd4e6b17 661if (isguestuser()) {
707dfd0c 662 // Just in case.
cd4e6b17 663 print_error('noguest');
664}
665
f5ad424b 666$thresholdwarning = forum_check_throttling($forum, $cm);
bc4c7337
AN
667$mformpost = new mod_forum_post_form('post.php', [
668 'course' => $course,
669 'cm' => $cm,
670 'coursecontext' => $coursecontext,
671 'modcontext' => $modcontext,
672 'forum' => $forum,
673 'post' => $post,
674 'subscribe' => \mod_forum\subscriptions::is_subscribed($USER->id, $forum, null, $cm),
675 'thresholdwarning' => $thresholdwarning,
676 'edit' => $edit,
677 'canreplyprivately' => $canreplyprivately,
678 ], 'post', '', array('id' => 'mformforum'));
cd4e6b17 679
680$draftitemid = file_get_submitted_draft_itemid('attachments');
707dfd0c
JM
681$postid = empty($post->id) ? null : $post->id;
682$attachoptions = mod_forum_post_form::attachment_options($forum);
683file_prepare_draft_area($draftitemid, $modcontext->id, 'mod_forum', 'attachment', $postid, $attachoptions);
cd4e6b17 684
707dfd0c 685// Load data into form NOW!
cd4e6b17 686
707dfd0c 687if ($USER->id != $post->userid) { // Not the original author, so add a message to the end.
fffd3703 688 $data = new stdClass();
6cab66bb 689 $data->date = userdate($post->created);
cd4e6b17 690 if ($post->messageformat == FORMAT_HTML) {
691 $data->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'&course='.$post->course.'">'.
707dfd0c 692 fullname($USER).'</a>';
dd4502af 693 $post->message .= '<p><span class="edited">('.get_string('editedby', 'forum', $data).')</span></p>';
cd4e6b17 694 } else {
695 $data->name = fullname($USER);
696 $post->message .= "\n\n(".get_string('editedby', 'forum', $data).')';
12fab708 697 }
fffd3703 698 unset($data);
cd4e6b17 699}
c58efbf5 700
0da2ae21 701$formheading = '';
cd4e6b17 702if (!empty($parent)) {
703 $heading = get_string("yourreply", "forum");
0da2ae21 704 $formheading = get_string('reply', 'forum');
cd4e6b17 705} else {
706 if ($forum->type == 'qanda') {
707 $heading = get_string('yournewquestion', 'forum');
708 } else {
709 $heading = get_string('yournewtopic', 'forum');
710 }
711}
712
5e95223e 713$postid = empty($post->id) ? null : $post->id;
707dfd0c
JM
714$draftideditor = file_get_submitted_draft_itemid('message');
715$editoropts = mod_forum_post_form::editor_options($modcontext, $postid);
716$currenttext = file_prepare_draft_area($draftideditor, $modcontext->id, 'mod_forum', 'post', $postid, $editoropts, $post->message);
cb28132d
P
717$discussionid = isset($discussion) ? $discussion->id : null;
718$discussionsubscribe = \mod_forum\subscriptions::get_user_default_subscription($forum, $coursecontext, $cm, $discussionid);
be773fd6 719
707dfd0c
JM
720$mformpost->set_data(
721 array(
722 'attachments' => $draftitemid,
723 'general' => $heading,
724 'subject' => $post->subject,
725 'message' => array(
726 'text' => $currenttext,
b6c3b130
EL
727 'format' => !isset($post->messageformat) || !is_numeric($post->messageformat) ?
728 editors_get_preferred_format() : $post->messageformat,
707dfd0c
JM
729 'itemid' => $draftideditor
730 ),
731 'discussionsubscribe' => $discussionsubscribe,
732 'mailnow' => !empty($post->mailnow),
733 'userid' => $post->userid,
734 'parent' => $post->parent,
735 'discussion' => $post->discussion,
56e9b6d6 736 'course' => $course->id,
d7ddc44f 737 'isprivatereply' => $post->isprivatereply ?? false
707dfd0c
JM
738 ) +
739
740 $pageparams +
741
742 (isset($post->format) ? array('format' => $post->format) : array()) +
743
744 (isset($discussion->timestart) ? array('timestart' => $discussion->timestart) : array()) +
745
746 (isset($discussion->timeend) ? array('timeend' => $discussion->timeend) : array()) +
747
748 (isset($discussion->pinned) ? array('pinned' => $discussion->pinned) : array()) +
749
750 (isset($post->groupid) ? array('groupid' => $post->groupid) : array()) +
751
752 (isset($discussion->id) ? array('discussion' => $discussion->id) : array())
753);
754
9c3e3a90
P
755// If we are being redirected via a no_submit_button press OR if the message is being prefilled.
756// then set the initial 'dirty' state.
757// - A prefilled post will exist when being redirected from the inpage reply form.
758// - A no_submit_button press occurs when being redirected from the inpage add new discussion post form.
759$dirty = $prefilledpost ? true : false;
760if ($mformpost->no_submit_button_pressed()) {
761 $data = $mformpost->get_submitted_data();
762
763 // If a no submit button has been pressed but the default values haven't been then reset the form change.
e7bf69e0 764 if (!$dirty && isset($data->message['text']) && !empty(trim($data->message['text']))) {
9c3e3a90
P
765 $dirty = true;
766 }
767
e7bf69e0 768 if (!$dirty && isset($data->message['message']) && !empty(trim($data->message['message']))) {
9c3e3a90
P
769 $dirty = true;
770 }
771}
772$mformpost->set_initial_dirty_state($dirty);
773
707dfd0c 774if ($mformpost->is_cancelled()) {
15dc885a
AN
775 if (!isset($discussion->id) || $forum->type === 'single') {
776 // Single forums don't have a discussion page.
777 redirect($urlfactory->get_forum_view_url_from_forum($forumentity));
f3206dfc 778 } else {
15dc885a 779 redirect($urlfactory->get_discussion_view_url_from_discussion($discussionentity));
f3206dfc 780 }
04cfb5c1 781} else if ($mformpost->is_submitted() && !$mformpost->no_submit_button_pressed() && $fromform = $mformpost->get_data()) {
cd4e6b17 782
783 if (empty($SESSION->fromurl)) {
15dc885a 784 $errordestination = $urlfactory->get_forum_view_url_from_forum($forumentity);
cd4e6b17 785 } else {
786 $errordestination = $SESSION->fromurl;
30a9aff5 787 }
04cfb5c1 788
cd4e6b17 789 $fromform->itemid = $fromform->message['itemid'];
790 $fromform->messageformat = $fromform->message['format'];
791 $fromform->message = $fromform->message['text'];
792 // WARNING: the $fromform->message array has been overwritten, do not use it anymore!
793 $fromform->messagetrust = trusttext_trusted($modcontext);
4cabf99f 794
418831e0
MH
795 // Clean message text.
796 $fromform = trusttext_pre_edit($fromform, 'message', $modcontext);
797
15dc885a
AN
798 if ($fromform->edit) {
799 // Updating a post.
cd4e6b17 800 unset($fromform->groupid);
801 $fromform->id = $fromform->edit;
802 $message = '';
2b63df96 803
15dc885a
AN
804 if (!$capabilitymanager->can_edit_post($USER, $discussionentity, $postentity)) {
805 redirect(
806 $urlfactory->get_view_post_url_from_post($postentity),
807 get_string('cannotupdatepost', 'forum'),
808 null,
809 \core\output\notification::ERROR
810 );
12fab708 811 }
12fab708 812
15dc885a
AN
813 if (isset($fromform->groupinfo) && $capabilitymanager->can_move_discussions($USER)) {
814 // If the user has access to all groups and they are changing the group, then update the post.
a0243017
DM
815 if (empty($fromform->groupinfo)) {
816 $fromform->groupinfo = -1;
817 }
344e1263 818
15dc885a
AN
819 if (!$capabilitymanager->can_create_discussions($USER, $fromform->groupinfo)) {
820 redirect(
821 $urlfactory->get_view_post_url_from_post($postentity),
822 get_string('cannotupdatepost', 'forum'),
823 null,
824 \core\output\notification::ERROR
825 );
344e1263
AN
826 }
827
15dc885a
AN
828 if ($discussionentity->get_group_id() != $fromform->groupinfo) {
829 $DB->set_field('forum_discussions', 'groupid', $fromform->groupinfo, array('firstpost' => $fromform->id));
830 }
2edcf21a 831 }
15dc885a 832
5f219cf1 833 // When editing first post/discussion.
70ed77c5 834 if (!$postentity->has_parent()) {
15dc885a 835 if ($capabilitymanager->can_pin_discussions($USER)) {
5f219cf1
BK
836 // Can change pinned if we have capability.
837 $fromform->pinned = !empty($fromform->pinned) ? FORUM_DISCUSSION_PINNED : FORUM_DISCUSSION_UNPINNED;
838 } else {
839 // We don't have the capability to change so keep to previous value.
840 unset($fromform->pinned);
841 }
842 }
15dc885a 843 $updatepost = $fromform;
cd4e6b17 844 $updatepost->forum = $forum->id;
707dfd0c 845 if (!forum_update_post($updatepost, $mformpost)) {
cd4e6b17 846 print_error("couldnotupdate", "forum", $errordestination);
12fab708 847 }
12fab708 848
15dc885a 849 if ('single' == $forumentity->get_type() && !$postentity->has_parent()) {
707dfd0c 850 // Updating first post of single discussion type -> updating forum intro.
cd4e6b17 851 $forum->intro = $updatepost->message;
852 $forum->timemodified = time();
853 $DB->update_record("forum", $forum);
854 }
12fab708 855
15dc885a 856 if ($USER->id === $postentity->get_author_id()) {
2e48384d 857 $message .= get_string("postupdated", "forum");
c2c071a2 858 } else {
15dc885a 859 $realuser = \core_user::get_user($postentity->get_author_id());
2e48384d 860 $message .= get_string("editedpostupdated", "forum", fullname($realuser));
c2c071a2 861 }
12fab708 862
d954b54f 863 $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
15dc885a
AN
864 if ('single' == $forumentity->get_type()) {
865 // Single discussion forums are an exception.
866 // We show the forum itself since it only has one discussion thread.
867 $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
2b63df96 868 } else {
15dc885a 869 $discussionurl = $urlfactory->get_view_post_url_from_post($postentity);
2b63df96 870 }
2d3f692b
DP
871
872 $params = array(
873 'context' => $modcontext,
874 'objectid' => $fromform->id,
875 'other' => array(
876 'discussionid' => $discussion->id,
877 'forumid' => $forum->id,
878 'forumtype' => $forum->type,
879 )
880 );
881
15dc885a
AN
882 if ($USER->id !== $postentity->get_author_id()) {
883 $params['relateduserid'] = $postentity->get_author_id();
2d3f692b
DP
884 }
885
886 $event = \mod_forum\event\post_updated::create($params);
2d3f692b
DP
887 $event->add_record_snapshot('forum_discussions', $discussion);
888 $event->trigger();
2b63df96 889
d954b54f 890 redirect(
707dfd0c
JM
891 forum_go_back_to($discussionurl),
892 $message . $subscribemessage,
893 null,
894 \core\output\notification::NOTIFY_SUCCESS
895 );
65bcf17b 896
15dc885a
AN
897 } else if ($fromform->discussion) {
898 // Adding a new post to an existing discussion
34e29871
MN
899 // Before we add this we must check that the user will not exceed the blocking threshold.
900 forum_check_blocking_threshold($thresholdwarning);
901
cd4e6b17 902 unset($fromform->groupid);
903 $message = '';
904 $addpost = $fromform;
707dfd0c
JM
905 $addpost->forum = $forum->id;
906 if ($fromform->id = forum_add_new_post($addpost, $mformpost)) {
15dc885a 907 $postentity = $postvault->get_from_id($fromform->id);
3e95e09b 908 $fromform->deleted = 0;
d954b54f 909 $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
cd4e6b17 910
911 if (!empty($fromform->mailnow)) {
912 $message .= get_string("postmailnow", "forum");
cd4e6b17 913 } else {
914 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
915 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
916 }
917
2b63df96 918 if ($forum->type == 'single') {
15dc885a
AN
919 // Single discussion forums are an exception.
920 // We show the forum itself since it only has one discussion thread.
921 $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
2b63df96 922 } else {
15dc885a 923 $discussionurl = $urlfactory->get_view_post_url_from_post($postentity);
cd4e6b17 924 }
2d3f692b
DP
925
926 $params = array(
927 'context' => $modcontext,
928 'objectid' => $fromform->id,
929 'other' => array(
930 'discussionid' => $discussion->id,
931 'forumid' => $forum->id,
932 'forumtype' => $forum->type,
933 )
934 );
935 $event = \mod_forum\event\post_created::create($params);
936 $event->add_record_snapshot('forum_posts', $fromform);
937 $event->add_record_snapshot('forum_discussions', $discussion);
938 $event->trigger();
cd4e6b17 939
707dfd0c
JM
940 // Update completion state.
941 $completion = new completion_info($course);
942 if ($completion->is_enabled($cm) &&
cd4e6b17 943 ($forum->completionreplies || $forum->completionposts)) {
707dfd0c 944 $completion->update_state($cm, COMPLETION_COMPLETE);
2b63df96 945 }
2b63df96 946
d954b54f 947 redirect(
707dfd0c
JM
948 forum_go_back_to($discussionurl),
949 $message . $subscribemessage,
950 null,
951 \core\output\notification::NOTIFY_SUCCESS
952 );
2b63df96 953
cd4e6b17 954 } else {
955 print_error("couldnotadd", "forum", $errordestination);
956 }
957 exit;
2b63df96 958
15dc885a
AN
959 } else {
960 // Adding a new discussion.
344e1263 961 // The location to redirect to after successfully posting.
4626c848 962 $redirectto = new moodle_url('/mod/forum/view.php', array('f' => $fromform->forum));
344e1263 963
cd4e6b17 964 $fromform->mailnow = empty($fromform->mailnow) ? 0 : 1;
6606c00f 965
cd4e6b17 966 $discussion = $fromform;
2587313a 967 $discussion->name = $fromform->subject;
2893812e 968 $discussion->timelocked = 0;
2b63df96 969
6606c00f 970 $newstopic = false;
cd4e6b17 971 if ($forum->type == 'news' && !$fromform->parent) {
972 $newstopic = true;
973 }
5f219cf1 974
15dc885a 975 if (!empty($fromform->pinned) && $capabilitymanager->can_pin_discussions($USER)) {
5f219cf1 976 $discussion->pinned = FORUM_DISCUSSION_PINNED;
70ed77c5
MG
977 } else {
978 $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
5f219cf1 979 }
2b63df96 980
2587313a
DC
981 $allowedgroups = array();
982 $groupstopostto = array();
2b63df96 983
2587313a
DC
984 // If we are posting a copy to all groups the user has access to.
985 if (isset($fromform->posttomygroups)) {
344e1263 986 // Post to each of my groups.
eabbc98c 987 require_capability('mod/forum:canposttomygroups', $modcontext);
344e1263
AN
988
989 // Fetch all of this user's groups.
990 // Note: all groups are returned when in visible groups mode so we must manually filter.
2587313a 991 $allowedgroups = groups_get_activity_allowed_groups($cm);
344e1263 992 foreach ($allowedgroups as $groupid => $group) {
15dc885a 993 if ($capabilitymanager->can_create_discussions($USER, $groupid)) {
344e1263
AN
994 $groupstopostto[] = $groupid;
995 }
89d35c49 996 }
344e1263
AN
997 } else if (isset($fromform->groupinfo)) {
998 // Use the value provided in the dropdown group selection.
999 $groupstopostto[] = $fromform->groupinfo;
1000 $redirectto->param('group', $fromform->groupinfo);
1001 } else if (isset($fromform->groupid) && !empty($fromform->groupid)) {
1002 // Use the value provided in the hidden form element instead.
1003 $groupstopostto[] = $fromform->groupid;
1004 $redirectto->param('group', $fromform->groupid);
1005 } else {
1006 // Use the value for all participants instead.
1007 $groupstopostto[] = -1;
2587313a 1008 }
89d35c49 1009
2587313a
DC
1010 // Before we post this we must check that the user will not exceed the blocking threshold.
1011 forum_check_blocking_threshold($thresholdwarning);
2b63df96 1012
2587313a 1013 foreach ($groupstopostto as $group) {
15dc885a 1014 if (!$capabilitymanager->can_create_discussions($USER, $groupid)) {
2587313a 1015 print_error('cannotcreatediscussion', 'forum');
2b63df96 1016 }
1017
2587313a
DC
1018 $discussion->groupid = $group;
1019 $message = '';
707dfd0c 1020 if ($discussion->id = forum_add_discussion($discussion, $mformpost)) {
501cdbd8 1021
2587313a
DC
1022 $params = array(
1023 'context' => $modcontext,
1024 'objectid' => $discussion->id,
1025 'other' => array(
1026 'forumid' => $forum->id,
1027 )
1028 );
1029 $event = \mod_forum\event\discussion_created::create($params);
1030 $event->add_record_snapshot('forum_discussions', $discussion);
1031 $event->trigger();
1032
2587313a
DC
1033 if ($fromform->mailnow) {
1034 $message .= get_string("postmailnow", "forum");
2587313a
DC
1035 } else {
1036 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
1037 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
1038 }
1039
d954b54f 1040 $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
2587313a
DC
1041 } else {
1042 print_error("couldnotadd", "forum", $errordestination);
1043 }
501cdbd8 1044 }
501cdbd8 1045
2587313a
DC
1046 // Update completion status.
1047 $completion = new completion_info($course);
1048 if ($completion->is_enabled($cm) &&
707dfd0c 1049 ($forum->completiondiscussions || $forum->completionposts)) {
2587313a
DC
1050 $completion->update_state($cm, COMPLETION_COMPLETE);
1051 }
1052
344e1263 1053 // Redirect back to the discussion.
d954b54f 1054 redirect(
707dfd0c
JM
1055 forum_go_back_to($redirectto->out()),
1056 $message . $subscribemessage,
1057 null,
1058 \core\output\notification::NOTIFY_SUCCESS
1059 );
cef1ce6a 1060 }
cd4e6b17 1061}
8dec2253 1062
15ca5e5e 1063
15dc885a
AN
1064// This section is only shown after all checks are in place, and the forumentity and any relevant discussion and post
1065// entity are available.
65bcf17b 1066
15dc885a
AN
1067if (!empty($discussionentity)) {
1068 $titlesubject = format_string($discussionentity->get_name(), true);
1069} else if ('news' == $forumentity->get_type()) {
1070 $titlesubject = get_string("addanewtopic", "forum");
cd4e6b17 1071} else {
15dc885a 1072 $titlesubject = get_string("addanewdiscussion", "forum");
cd4e6b17 1073}
1074
1075if (empty($post->edit)) {
1076 $post->edit = '';
1077}
1078
1079if (empty($discussion->name)) {
1080 if (empty($discussion)) {
39790bd8 1081 $discussion = new stdClass();
098d27d4 1082 }
cd4e6b17 1083 $discussion->name = $forum->name;
1084}
15dc885a
AN
1085
1086$strdiscussionname = '';
1087if ('single' == $forumentity->get_type()) {
cd4e6b17 1088 // There is only one discussion thread for this forum type. We should
1089 // not show the discussion name (same as forum name in this case) in
1090 // the breadcrumbs.
1091 $strdiscussionname = '';
15dc885a 1092} else if (!empty($discussionentity)) {
cd4e6b17 1093 // Show the discussion name in the breadcrumbs.
15dc885a 1094 $strdiscussionname = format_string($discussionentity->get_name()) . ': ';
cd4e6b17 1095}
1096
707dfd0c 1097$forcefocus = empty($reply) ? null : 'message';
cd4e6b17 1098
1099if (!empty($discussion->id)) {
15dc885a 1100 $PAGE->navbar->add($titlesubject, $urlfactory->get_discussion_view_url_from_discussion($discussionentity));
cd4e6b17 1101}
1102
1103if ($post->parent) {
b4c07395
RW
1104 $PAGE->navbar->add(get_string('reply', 'forum'));
1105}
1106
1107if ($edit) {
1108 $PAGE->navbar->add(get_string('edit', 'forum'));
cd4e6b17 1109}
1110
15dc885a 1111$PAGE->set_title("{$course->shortname}: {$strdiscussionname}{$titlesubject}");
cd4e6b17 1112$PAGE->set_heading($course->fullname);
cd4e6b17 1113
1114echo $OUTPUT->header();
66e2b9f8 1115echo $OUTPUT->heading(format_string($forum->name), 2);
098d27d4 1116
707dfd0c 1117// Checkup.
15dc885a 1118if (!empty($parententity) && !$capabilitymanager->can_view_post($USER, $discussionentity, $parententity)) {
cd4e6b17 1119 print_error('cannotreply', 'forum');
1120}
15dc885a
AN
1121
1122if (empty($parententity) && empty($edit) && !$capabilitymanager->can_create_discussions($USER, $groupid)) {
cd4e6b17 1123 print_error('cannotcreatediscussion', 'forum');
1124}
1125
15dc885a
AN
1126if (!empty($discussionentity) && 'qanda' == $forumentity->get_type()) {
1127 $displaywarning = $capabilitymanager->must_post_before_viewing_discussion($USER, $discussionentity);
1128 $displaywarning = $displaywarning && !forum_user_has_posted($forumentity->get_id(), $discussionentity->get_id(), $USER->id);
1129 if ($displaywarning) {
1130 echo $OUTPUT->notification(get_string('qandanotify', 'forum'));
1131 }
cd4e6b17 1132}
1133
eaa8f5ad
MN
1134// If there is a warning message and we are not editing a post we need to handle the warning.
1135if (!empty($thresholdwarning) && !$edit) {
1136 // Here we want to throw an exception if they are no longer allowed to post.
34e29871 1137 forum_check_blocking_threshold($thresholdwarning);
f5ad424b 1138}
cd4e6b17 1139
15dc885a
AN
1140if (!empty($parententity)) {
1141 $postentities = [$parententity];
313d8b6e 1142
cd4e6b17 1143 if (empty($post->edit)) {
15dc885a 1144 if ('qanda' != $forumentity->get_type() || forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
bc4c7337
AN
1145 $replies = $postvault->get_replies_to_post(
1146 $USER,
15dc885a 1147 $parententity,
bc4c7337
AN
1148 $capabilitymanager->can_view_any_private_reply($USER),
1149 'created ASC'
1150 );
313d8b6e 1151 $postentities = array_merge($postentities, $replies);
21da9db8 1152 }
501cdbd8 1153 }
313d8b6e
RW
1154
1155 $rendererfactory = mod_forum\local\container::get_renderer_factory();
1156 $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(FORUM_MODE_THREADED, true);
15dc885a 1157 echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], $postentities);
cd4e6b17 1158} else {
1159 if (!empty($forum->intro)) {
1160 echo $OUTPUT->box(format_module_intro('forum', $forum, $cm->id), 'generalbox', 'intro');
1161 }
1162}
501cdbd8 1163
f3bf0ed5
JM
1164// Call print disclosure for enabled plagiarism plugins.
1165if (!empty($CFG->enableplagiarism)) {
1166 require_once($CFG->libdir.'/plagiarismlib.php');
1167 echo plagiarism_print_disclosure($cm->id);
1168}
1169
0da2ae21
FM
1170if (!empty($formheading)) {
1171 echo $OUTPUT->heading($formheading, 2, array('class' => 'accesshide'));
1172}
d2ba493c 1173
15dc885a
AN
1174if (!empty($postentity)) {
1175 $data = (object) [
1176 'tags' => core_tag_tag::get_item_tags_array('mod_forum', 'forum_posts', $postentity->get_id())
1177 ];
707dfd0c 1178 $mformpost->set_data($data);
d2ba493c
AH
1179}
1180
707dfd0c 1181$mformpost->display();
501cdbd8 1182
cd4e6b17 1183echo $OUTPUT->footer();