MDL-65466 forum: Fix discussion pinning when adding/editing discussion
[moodle.git] / mod / forum / post.php
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/>.
17 /**
18  * Edit and save a new post to a discussion
19  *
20  * @package   mod_forum
21  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
22  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 require_once('../../config.php');
26 require_once('lib.php');
27 require_once($CFG->libdir.'/completionlib.php');
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);
37 $subject = optional_param('subject', '', PARAM_TEXT);
38 $prefilledpost = optional_param('post', '', PARAM_TEXT);
40 $PAGE->set_url('/mod/forum/post.php', array(
41     'reply' => $reply,
42     'forum' => $forum,
43     'edit'  => $edit,
44     'delete' => $delete,
45     'prune' => $prune,
46     'name'  => $name,
47     'confirm' => $confirm,
48     'groupid' => $groupid,
49 ));
50 // These page_params will be passed as hidden variables later in the form.
51 $pageparams = array('reply' => $reply, 'forum' => $forum, 'edit' => $edit);
53 $sitecontext = context_system::instance();
55 $entityfactory = mod_forum\local\container::get_entity_factory();
56 $vaultfactory = mod_forum\local\container::get_vault_factory();
57 $managerfactory = mod_forum\local\container::get_manager_factory();
58 $legacydatamapperfactory = mod_forum\local\container::get_legacy_data_mapper_factory();
59 $urlfactory = mod_forum\local\container::get_url_factory();
61 $forumvault = $vaultfactory->get_forum_vault();
62 $forumdatamapper = $legacydatamapperfactory->get_forum_data_mapper();
64 $discussionvault = $vaultfactory->get_discussion_vault();
65 $discussiondatamapper = $legacydatamapperfactory->get_discussion_data_mapper();
67 $postvault = $vaultfactory->get_post_vault();
68 $postdatamapper = $legacydatamapperfactory->get_post_data_mapper();
70 if (!isloggedin() or isguestuser()) {
71     if (!isloggedin() and !get_local_referer()) {
72         // No referer+not logged in - probably coming in via email  See MDL-9052.
73         require_login();
74     }
76     if (!empty($forum)) {
77         // User is starting a new discussion in a forum.
78         $forumentity = $forumvault->get_from_id($forum);
79         if (empty($forumentity)) {
80             print_error('invalidforumid', 'forum');
81         }
82     } else if (!empty($reply)) {
83         // User is writing a new reply.
84         $forumentity = $forumvault->get_from_post_id($reply);
85         if (empty($forumentity)) {
86             print_error('invalidparentpostid', 'forum');
87         }
88     }
90     $forum = $forumdatamapper->to_legacy_object($forumentity);
91     $modcontext = $forumentity->get_context();
92     $course = $forumentity->get_course_record();
93     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
94         print_error("invalidcoursemodule");
95     }
97     $PAGE->set_cm($cm, $course, $forum);
98     $PAGE->set_context($modcontext);
99     $PAGE->set_title($course->shortname);
100     $PAGE->set_heading($course->fullname);
101     $referer = get_local_referer(false);
103     echo $OUTPUT->header();
104     echo $OUTPUT->confirm(get_string('noguestpost', 'forum').'<br /><br />'.get_string('liketologin'), get_login_url(), $referer);
105     echo $OUTPUT->footer();
106     exit;
109 require_login(0, false);   // Script is useless unless they're logged in.
111 $canreplyprivately = false;
113 if (!empty($forum)) {
114     // User is starting a new discussion in a forum.
115     $forumentity = $forumvault->get_from_id($forum);
116     if (empty($forumentity)) {
117         print_error('invalidforumid', 'forum');
118     }
120     $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
121     $forum = $forumdatamapper->to_legacy_object($forumentity);
122     $course = $forumentity->get_course_record();
123     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
124         print_error("invalidcoursemodule");
125     }
127     // Retrieve the contexts.
128     $modcontext = $forumentity->get_context();
129     $coursecontext = context_course::instance($course->id);
131     if ($forumentity->is_in_group_mode() && null === $groupid) {
132         $groupid = groups_get_activity_group($cm);
133     }
135     if (!$capabilitymanager->can_create_discussions($USER, $groupid)) {
136         if (!isguestuser()) {
137             if (!is_enrolled($coursecontext)) {
138                 if (enrol_selfenrol_available($course->id)) {
139                     $SESSION->wantsurl = qualified_me();
140                     $SESSION->enrolcancel = get_local_referer(false);
141                     redirect(new moodle_url('/enrol/index.php', array('id' => $course->id,
142                         'returnurl' => '/mod/forum/view.php?f=' . $forum->id)),
143                         get_string('youneedtoenrol'));
144                 }
145             }
146         }
147         print_error('nopostforum', 'forum');
148     }
150     if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $modcontext)) {
151         redirect(
152                 $urlfactory->get_course_url_from_forum($forumentity),
153                 get_string('activityiscurrentlyhidden'),
154                 null,
155                 \core\output\notice::NOTIFY_ERROR
156             );
157     }
159     $SESSION->fromurl = get_local_referer(false);
161     // Load up the $post variable.
163     $post = new stdClass();
164     $post->course        = $course->id;
165     $post->forum         = $forum->id;
166     $post->discussion    = 0;           // Ie discussion # not defined yet.
167     $post->parent        = 0;
168     $post->subject       = $subject;
169     $post->userid        = $USER->id;
170     $post->message       = $prefilledpost;
171     $post->messageformat = editors_get_preferred_format();
172     $post->messagetrust  = 0;
173     $post->groupid = $groupid;
175     // Unsetting this will allow the correct return URL to be calculated later.
176     unset($SESSION->fromdiscussion);
178 } else if (!empty($reply)) {
179     // User is writing a new reply.
181     $parententity = $postvault->get_from_id($reply);
182     if (empty($parententity)) {
183         print_error('invalidparentpostid', 'forum');
184     }
186     $discussionentity = $discussionvault->get_from_id($parententity->get_discussion_id());
187     if (empty($discussionentity)) {
188         print_error('notpartofdiscussion', 'forum');
189     }
191     $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
192     if (empty($forumentity)) {
193         print_error('invalidforumid', 'forum');
194     }
196     $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
197     $parent = $postdatamapper->to_legacy_object($parententity);
198     $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
199     $forum = $forumdatamapper->to_legacy_object($forumentity);
200     $course = $forumentity->get_course_record();
201     $modcontext = $forumentity->get_context();
202     $coursecontext = context_course::instance($course->id);
204     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
205         print_error('invalidcoursemodule');
206     }
208     // Ensure lang, theme, etc. is set up properly. MDL-6926.
209     $PAGE->set_cm($cm, $course, $forum);
211     if (!$capabilitymanager->can_reply_to_post($USER, $discussionentity, $parententity)) {
212         if (!isguestuser()) {
213             if (!is_enrolled($coursecontext)) {  // User is a guest here!
214                 $SESSION->wantsurl = qualified_me();
215                 $SESSION->enrolcancel = get_local_referer(false);
216                 redirect(new moodle_url('/enrol/index.php', array('id' => $course->id,
217                     'returnurl' => '/mod/forum/view.php?f=' . $forum->id)),
218                     get_string('youneedtoenrol'));
219             }
221             // The forum has been locked. Just redirect back to the discussion page.
222             if (forum_discussion_is_locked($forum, $discussion)) {
223                 redirect(new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id)));
224             }
225         }
226         print_error('nopostforum', 'forum');
227     }
229     // Make sure user can post here.
230     if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
231         $groupmode = $cm->groupmode;
232     } else {
233         $groupmode = $course->groupmode;
234     }
235     if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
236         if ($discussion->groupid == -1) {
237             print_error('nopostforum', 'forum');
238         } else {
239             if (!groups_is_member($discussion->groupid)) {
240                 print_error('nopostforum', 'forum');
241             }
242         }
243     }
245     if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $modcontext)) {
246         print_error("activityiscurrentlyhidden");
247     }
249     if ($parententity->is_private_reply()) {
250         print_error('cannotreplytoprivatereply', 'forum');
251     }
253     // Load up the $post variable.
254     $post = new stdClass();
255     $post->course      = $course->id;
256     $post->forum       = $forum->id;
257     $post->discussion  = $parent->discussion;
258     $post->parent      = $parent->id;
259     $post->subject     = $subject ? $subject : $parent->subject;
260     $post->userid      = $USER->id;
261     $post->parentpostauthor = $parent->userid;
262     $post->message     = $prefilledpost;
263     $canreplyprivately = $capabilitymanager->can_reply_privately_to_post($USER, $parententity);
265     $post->groupid = ($discussion->groupid == -1) ? 0 : $discussion->groupid;
267     $strre = get_string('re', 'forum');
268     if (!(substr($post->subject, 0, strlen($strre)) == $strre)) {
269         $post->subject = $strre.' '.$post->subject;
270     }
272     // Unsetting this will allow the correct return URL to be calculated later.
273     unset($SESSION->fromdiscussion);
275 } else if (!empty($edit)) {
276     // User is editing their own post.
278     $postentity = $postvault->get_from_id($edit);
279     if (empty($postentity)) {
280         print_error('invalidpostid', 'forum');
281     }
282     if ($postentity->has_parent()) {
283         $parententity = $postvault->get_from_id($postentity->get_parent_id());
284         $parent = $postdatamapper->to_legacy_object($parententity);
285     }
287     $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
288     if (empty($discussionentity)) {
289         print_error('notpartofdiscussion', 'forum');
290     }
292     $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
293     if (empty($forumentity)) {
294         print_error('invalidforumid', 'forum');
295     }
297     $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
298     $post = $postdatamapper->to_legacy_object($postentity);
299     $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
300     $forum = $forumdatamapper->to_legacy_object($forumentity);
301     $course = $forumentity->get_course_record();
302     $modcontext = $forumentity->get_context();
303     $coursecontext = context_course::instance($course->id);
305     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
306         print_error('invalidcoursemodule');
307     }
309     $PAGE->set_cm($cm, $course, $forum);
311     if (!($forum->type == 'news' && !$post->parent && $discussion->timestart > time())) {
312         if (((time() - $post->created) > $CFG->maxeditingtime) and
313             !has_capability('mod/forum:editanypost', $modcontext)) {
314             print_error('maxtimehaspassed', 'forum', '', format_time($CFG->maxeditingtime));
315         }
316     }
317     if (($post->userid <> $USER->id) and
318         !has_capability('mod/forum:editanypost', $modcontext)) {
319         print_error('cannoteditposts', 'forum');
320     }
322     // Load up the $post variable.
323     $post->edit   = $edit;
324     $post->course = $course->id;
325     $post->forum  = $forum->id;
326     $post->groupid = ($discussion->groupid == -1) ? 0 : $discussion->groupid;
327     if ($postentity->has_parent()) {
328         $canreplyprivately = forum_user_can_reply_privately($modcontext, $parent);
329     }
331     $post = trusttext_pre_edit($post, 'message', $modcontext);
333     // Unsetting this will allow the correct return URL to be calculated later.
334     unset($SESSION->fromdiscussion);
336 } else if (!empty($delete)) {
337     // User is deleting a post.
339     $postentity = $postvault->get_from_id($delete);
340     if (empty($postentity)) {
341         print_error('invalidpostid', 'forum');
342     }
344     $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
345     if (empty($discussionentity)) {
346         print_error('notpartofdiscussion', 'forum');
347     }
349     $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
350     if (empty($forumentity)) {
351         print_error('invalidforumid', 'forum');
352     }
354     $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
355     $post = $postdatamapper->to_legacy_object($postentity);
356     $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
357     $forum = $forumdatamapper->to_legacy_object($forumentity);
358     $course = $forumentity->get_course_record();
359     $modcontext = $forumentity->get_context();
360     $coursecontext = context_course::instance($course->id);
362     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
363         print_error('invalidcoursemodule');
364     }
366     require_login($course, false, $cm);
368     if (!$capabilitymanager->can_delete_post($USER, $discussionentity, $postentity)) {
369         redirect(
370                 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
371                 get_string('cannotdeletepost', 'forum'),
372                 null,
373                 \core\output\notice::NOTIFY_ERROR
374             );
375     }
377     $replycount = $postvault->get_reply_count_for_post_id_in_discussion_id(
378         $USER, $postentity->get_id(), $discussionentity->get_id(), true);
380     if (!empty($confirm) && confirm_sesskey()) {
381         // User has confirmed the delete.
382         // Check user capability to delete post.
383         $timepassed = time() - $post->created;
384         if ($post->totalscore) {
385             redirect(
386                     $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
387                     get_string('couldnotdeleteratings', 'rating'),
388                     null,
389                     \core\output\notice::NOTIFY_ERROR
390                 );
391         } else if ($replycount && !has_capability('mod/forum:deleteanypost', $modcontext)) {
392             redirect(
393                     $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
394                     get_string('couldnotdeletereplies', 'rating'),
395                     null,
396                     \core\output\notice::NOTIFY_ERROR
397                 );
398         } else {
399             if (!$postentity->has_parent()) {
400                 // Post is a discussion topic as well, so delete discussion.
401                 if ($forum->type == 'single') {
402                     redirect(
403                             $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
404                             get_string('cannotdeletediscussioninsinglediscussion', 'rating'),
405                             null,
406                             \core\output\notice::NOTIFY_ERROR
407                         );
408                 }
409                 forum_delete_discussion($discussion, false, $course, $cm, $forum);
411                 $params = array(
412                     'objectid' => $discussion->id,
413                     'context' => $modcontext,
414                     'other' => array(
415                         'forumid' => $forum->id,
416                     )
417                 );
419                 $event = \mod_forum\event\discussion_deleted::create($params);
420                 $event->add_record_snapshot('forum_discussions', $discussion);
421                 $event->trigger();
423                 redirect(
424                     $urlfactory->get_forum_view_url_from_forum($forumentity),
425                     get_string('eventdiscussiondeleted', 'forum'),
426                     null,
427                     \core\output\notification::NOTIFY_SUCCESS
428                 );
430             } else {
431                 $deleted = forum_delete_post($post, has_capability('mod/forum:deleteanypost', $modcontext), $course, $cm, $forum);
433                 if (!$deleted) {
434                     redirect(
435                             $urlfactory->get_discussion_view_url_from_post($postentity),
436                             get_string('errorwhiledelete', 'forum'),
437                             null,
438                             \core\output\notice::NOTIFY_ERROR
439                         );
440                 }
442                 if ($forum->type == 'single') {
443                     // Single discussion forums are an exception.
444                     // We show the forum itself since it only has one discussion thread.
445                     $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
446                 } else {
447                     $discussionurl = $urlfactory->get_discussion_view_url_from_discussion($discussionentity);
448                 }
450                 redirect(
451                     forum_go_back_to($discussionurl),
452                     get_string('eventpostdeleted', 'forum'),
453                     null,
454                     \core\output\notification::NOTIFY_SUCCESS
455                 );
456             }
457         }
460     } else {
461         // User just asked to delete something.
462         forum_set_return();
463         $PAGE->navbar->add(get_string('delete', 'forum'));
464         $PAGE->set_title($course->shortname);
465         $PAGE->set_heading($course->fullname);
467         if ($replycount) {
468             if (!has_capability('mod/forum:deleteanypost', $modcontext)) {
469                 redirect(
470                         forum_go_back_to($urlfactory->get_view_post_url_from_post($postentity)),
471                         get_string('couldnotdeletereplies', 'rating'),
472                         null,
473                         \core\output\notice::NOTIFY_ERROR
474                     );
475             }
477             echo $OUTPUT->header();
478             echo $OUTPUT->heading(format_string($forum->name), 2);
479             echo $OUTPUT->confirm(get_string("deletesureplural", "forum", $replycount + 1),
480                 "post.php?delete=$delete&confirm=$delete",
481                 $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
483             $postentities = [$postentity];
484             if (empty($post->edit)) {
485                 $postvault = $vaultfactory->get_post_vault();
486                 $replies = $postvault->get_replies_to_post(
487                         $USER,
488                         $postentity,
489                         // Note: All replies are fetched here as the user has deleteanypost.
490                         true,
491                         'created ASC'
492                     );
493                 $postentities = array_merge($postentities, $replies);
494             }
496             $rendererfactory = mod_forum\local\container::get_renderer_factory();
497             $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(FORUM_MODE_NESTED, true);
498             echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], $postentities);
499         } else {
500             echo $OUTPUT->header();
501             echo $OUTPUT->heading(format_string($forum->name), 2);
502             echo $OUTPUT->confirm(get_string("deletesure", "forum", $replycount),
503                 "post.php?delete=$delete&confirm=$delete",
504                 $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
506             $rendererfactory = mod_forum\local\container::get_renderer_factory();
507             $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(null, true);
508             echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], [$postentity]);
509         }
511     }
512     echo $OUTPUT->footer();
513     die;
515 } else if (!empty($prune)) {
516     // Pruning.
518     $postentity = $postvault->get_from_id($prune);
519     if (empty($postentity)) {
520         print_error('invalidpostid', 'forum');
521     }
523     $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
524     if (empty($discussionentity)) {
525         print_error('notpartofdiscussion', 'forum');
526     }
528     $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
529     if (empty($forumentity)) {
530         print_error('invalidforumid', 'forum');
531     }
533     $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
534     $post = $postdatamapper->to_legacy_object($postentity);
535     $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
536     $forum = $forumdatamapper->to_legacy_object($forumentity);
537     $course = $forumentity->get_course_record();
538     $modcontext = $forumentity->get_context();
539     $coursecontext = context_course::instance($course->id);
541     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
542         print_error('invalidcoursemodule');
543     }
545     if (!$postentity->has_parent()) {
546         redirect(
547                 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
548                 get_string('alreadyfirstpost', 'forum'),
549                 null,
550                 \core\output\notification::NOTIFY_ERROR
551             );
552     }
553     if (!$capabilitymanager->can_split_post($USER, $discussionentity, $postentity)) {
554         redirect(
555                 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
556                 get_string('cannotsplit', 'forum'),
557                 null,
558                 \core\output\notification::NOTIFY_ERROR
559             );
560     }
562     $PAGE->set_cm($cm);
563     $PAGE->set_context($modcontext);
565     $prunemform = new mod_forum_prune_form(null, array('prune' => $prune, 'confirm' => $prune));
567     if ($prunemform->is_cancelled()) {
568         redirect(forum_go_back_to($urlfactory->get_discussion_view_url_from_discussion($discussionentity)));
569     } else if ($fromform = $prunemform->get_data()) {
570         // User submits the data.
571         $newdiscussion = new stdClass();
572         $newdiscussion->course       = $discussion->course;
573         $newdiscussion->forum        = $discussion->forum;
574         $newdiscussion->name         = $name;
575         $newdiscussion->firstpost    = $post->id;
576         $newdiscussion->userid       = $discussion->userid;
577         $newdiscussion->groupid      = $discussion->groupid;
578         $newdiscussion->assessed     = $discussion->assessed;
579         $newdiscussion->usermodified = $post->userid;
580         $newdiscussion->timestart    = $discussion->timestart;
581         $newdiscussion->timeend      = $discussion->timeend;
583         $newid = $DB->insert_record('forum_discussions', $newdiscussion);
585         $newpost = new stdClass();
586         $newpost->id      = $post->id;
587         $newpost->parent  = 0;
588         $newpost->subject = $name;
590         $DB->update_record("forum_posts", $newpost);
591         $postentity = $postvault->get_from_id($postentity->get_id());
593         forum_change_discussionid($post->id, $newid);
595         // Update last post in each discussion.
596         forum_discussion_update_last_post($discussion->id);
597         forum_discussion_update_last_post($newid);
599         // Fire events to reflect the split..
600         $params = array(
601             'context' => $modcontext,
602             'objectid' => $discussion->id,
603             'other' => array(
604                 'forumid' => $forum->id,
605             )
606         );
607         $event = \mod_forum\event\discussion_updated::create($params);
608         $event->trigger();
610         $params = array(
611             'context' => $modcontext,
612             'objectid' => $newid,
613             'other' => array(
614                 'forumid' => $forum->id,
615             )
616         );
617         $event = \mod_forum\event\discussion_created::create($params);
618         $event->trigger();
620         $params = array(
621             'context' => $modcontext,
622             'objectid' => $post->id,
623             'other' => array(
624                 'discussionid' => $newid,
625                 'forumid' => $forum->id,
626                 'forumtype' => $forum->type,
627             )
628         );
629         $event = \mod_forum\event\post_updated::create($params);
630         $event->add_record_snapshot('forum_discussions', $discussion);
631         $event->trigger();
633         redirect(
634             forum_go_back_to($urlfactory->get_discussion_view_url_from_post($postentity)),
635             get_string('discussionsplit', 'forum'),
636             null,
637             \core\output\notification::NOTIFY_SUCCESS
638         );
639     } else {
640         // Display the prune form.
641         $course = $DB->get_record('course', array('id' => $forum->course));
642         $subjectstr = format_string($post->subject, true);
643         $PAGE->navbar->add($subjectstr, new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id)));
644         $PAGE->navbar->add(get_string("prune", "forum"));
645         $PAGE->set_title(format_string($discussion->name).": ".format_string($post->subject));
646         $PAGE->set_heading($course->fullname);
647         echo $OUTPUT->header();
648         echo $OUTPUT->heading(format_string($forum->name), 2);
649         echo $OUTPUT->heading(get_string('pruneheading', 'forum'), 3);
651         $prunemform->display();
653         $postentity = $entityfactory->get_post_from_stdclass($post);
654         $discussionentity = $entityfactory->get_discussion_from_stdclass($discussion);
655         $forumentity = $entityfactory->get_forum_from_stdclass($forum, $modcontext, $cm, $course);
656         $rendererfactory = mod_forum\local\container::get_renderer_factory();
657         $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(null, true);
658         echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], [$postentity]);
659     }
661     echo $OUTPUT->footer();
662     die;
663 } else {
664     print_error('unknowaction');
668 // From now on user must be logged on properly.
670 require_login($course, false, $cm);
672 if (isguestuser()) {
673     // Just in case.
674     print_error('noguest');
677 $thresholdwarning = forum_check_throttling($forum, $cm);
678 $mformpost = new mod_forum_post_form('post.php', [
679         'course' => $course,
680         'cm' => $cm,
681         'coursecontext' => $coursecontext,
682         'modcontext' => $modcontext,
683         'forum' => $forum,
684         'post' => $post,
685         'subscribe' => \mod_forum\subscriptions::is_subscribed($USER->id, $forum, null, $cm),
686         'thresholdwarning' => $thresholdwarning,
687         'edit' => $edit,
688         'canreplyprivately' => $canreplyprivately,
689     ], 'post', '', array('id' => 'mformforum'));
691 $draftitemid = file_get_submitted_draft_itemid('attachments');
692 $postid = empty($post->id) ? null : $post->id;
693 $attachoptions = mod_forum_post_form::attachment_options($forum);
694 file_prepare_draft_area($draftitemid, $modcontext->id, 'mod_forum', 'attachment', $postid, $attachoptions);
696 // Load data into form NOW!
698 if ($USER->id != $post->userid) {   // Not the original author, so add a message to the end.
699     $data = new stdClass();
700     $data->date = userdate($post->created);
701     if ($post->messageformat == FORMAT_HTML) {
702         $data->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'&course='.$post->course.'">'.
703             fullname($USER).'</a>';
704         $post->message .= '<p><span class="edited">('.get_string('editedby', 'forum', $data).')</span></p>';
705     } else {
706         $data->name = fullname($USER);
707         $post->message .= "\n\n(".get_string('editedby', 'forum', $data).')';
708     }
709     unset($data);
712 $formheading = '';
713 if (!empty($parent)) {
714     $heading = get_string("yourreply", "forum");
715     $formheading = get_string('reply', 'forum');
716 } else {
717     if ($forum->type == 'qanda') {
718         $heading = get_string('yournewquestion', 'forum');
719     } else {
720         $heading = get_string('yournewtopic', 'forum');
721     }
724 $postid = empty($post->id) ? null : $post->id;
725 $draftideditor = file_get_submitted_draft_itemid('message');
726 $editoropts = mod_forum_post_form::editor_options($modcontext, $postid);
727 $currenttext = file_prepare_draft_area($draftideditor, $modcontext->id, 'mod_forum', 'post', $postid, $editoropts, $post->message);
728 $discussionid = isset($discussion) ? $discussion->id : null;
729 $discussionsubscribe = \mod_forum\subscriptions::get_user_default_subscription($forum, $coursecontext, $cm, $discussionid);
731 $mformpost->set_data(
732     array(
733         'attachments' => $draftitemid,
734         'general' => $heading,
735         'subject' => $post->subject,
736         'message' => array(
737             'text' => $currenttext,
738             'format' => empty($post->messageformat) ? editors_get_preferred_format() : $post->messageformat,
739             'itemid' => $draftideditor
740         ),
741         'discussionsubscribe' => $discussionsubscribe,
742         'mailnow' => !empty($post->mailnow),
743         'userid' => $post->userid,
744         'parent' => $post->parent,
745         'discussion' => $post->discussion,
746         'course' => $course->id
747     ) +
749     $pageparams +
751     (isset($post->format) ? array('format' => $post->format) : array()) +
753     (isset($discussion->timestart) ? array('timestart' => $discussion->timestart) : array()) +
755     (isset($discussion->timeend) ? array('timeend' => $discussion->timeend) : array()) +
757     (isset($discussion->pinned) ? array('pinned' => $discussion->pinned) : array()) +
759     (isset($post->groupid) ? array('groupid' => $post->groupid) : array()) +
761     (isset($discussion->id) ? array('discussion' => $discussion->id) : array())
762 );
764 if ($mformpost->is_cancelled()) {
765     if (!isset($discussion->id) || $forum->type === 'single') {
766         // Single forums don't have a discussion page.
767         redirect($urlfactory->get_forum_view_url_from_forum($forumentity));
768     } else {
769         redirect($urlfactory->get_discussion_view_url_from_discussion($discussionentity));
770     }
771 } else if ($mformpost->is_submitted() && !$mformpost->no_submit_button_pressed()) {
773     if (empty($SESSION->fromurl)) {
774         $errordestination = $urlfactory->get_forum_view_url_from_forum($forumentity);
775     } else {
776         $errordestination = $SESSION->fromurl;
777     }
778     $fromform = $mformpost->get_data();
779     $fromform->itemid        = $fromform->message['itemid'];
780     $fromform->messageformat = $fromform->message['format'];
781     $fromform->message       = $fromform->message['text'];
782     // WARNING: the $fromform->message array has been overwritten, do not use it anymore!
783     $fromform->messagetrust  = trusttext_trusted($modcontext);
785     // Clean message text.
786     $fromform = trusttext_pre_edit($fromform, 'message', $modcontext);
788     if ($fromform->edit) {
789         // Updating a post.
790         unset($fromform->groupid);
791         $fromform->id = $fromform->edit;
792         $message = '';
794         if (!$capabilitymanager->can_edit_post($USER, $discussionentity, $postentity)) {
795             redirect(
796                     $urlfactory->get_view_post_url_from_post($postentity),
797                     get_string('cannotupdatepost', 'forum'),
798                     null,
799                     \core\output\notification::ERROR
800                 );
801         }
803         if (isset($fromform->groupinfo) && $capabilitymanager->can_move_discussions($USER)) {
804             // If the user has access to all groups and they are changing the group, then update the post.
805             if (empty($fromform->groupinfo)) {
806                 $fromform->groupinfo = -1;
807             }
809             if (!$capabilitymanager->can_create_discussions($USER, $fromform->groupinfo)) {
810                 redirect(
811                         $urlfactory->get_view_post_url_from_post($postentity),
812                         get_string('cannotupdatepost', 'forum'),
813                         null,
814                         \core\output\notification::ERROR
815                     );
816             }
818             if ($discussionentity->get_group_id() != $fromform->groupinfo) {
819                 $DB->set_field('forum_discussions', 'groupid', $fromform->groupinfo, array('firstpost' => $fromform->id));
820             }
821         }
823         // When editing first post/discussion.
824         if (!$postentity->has_parent()) {
825             if ($capabilitymanager->can_pin_discussions($USER)) {
826                 // Can change pinned if we have capability.
827                 $fromform->pinned = !empty($fromform->pinned) ? FORUM_DISCUSSION_PINNED : FORUM_DISCUSSION_UNPINNED;
828             } else {
829                 // We don't have the capability to change so keep to previous value.
830                 unset($fromform->pinned);
831             }
832         }
833         $updatepost = $fromform;
834         $updatepost->forum = $forum->id;
835         if (!forum_update_post($updatepost, $mformpost)) {
836             print_error("couldnotupdate", "forum", $errordestination);
837         }
839         if ('single' == $forumentity->get_type() && !$postentity->has_parent()) {
840             // Updating first post of single discussion type -> updating forum intro.
841             $forum->intro = $updatepost->message;
842             $forum->timemodified = time();
843             $DB->update_record("forum", $forum);
844         }
846         if ($USER->id === $postentity->get_author_id()) {
847             $message .= get_string("postupdated", "forum");
848         } else {
849             $realuser = \core_user::get_user($postentity->get_author_id());
850             $message .= get_string("editedpostupdated", "forum", fullname($realuser));
851         }
853         $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
854         if ('single' == $forumentity->get_type()) {
855             // Single discussion forums are an exception.
856             // We show the forum itself since it only has one discussion thread.
857             $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
858         } else {
859             $discussionurl = $urlfactory->get_view_post_url_from_post($postentity);
860         }
862         $params = array(
863             'context' => $modcontext,
864             'objectid' => $fromform->id,
865             'other' => array(
866                 'discussionid' => $discussion->id,
867                 'forumid' => $forum->id,
868                 'forumtype' => $forum->type,
869             )
870         );
872         if ($USER->id !== $postentity->get_author_id()) {
873             $params['relateduserid'] = $postentity->get_author_id();
874         }
876         $event = \mod_forum\event\post_updated::create($params);
877         $event->add_record_snapshot('forum_discussions', $discussion);
878         $event->trigger();
880         redirect(
881             forum_go_back_to($discussionurl),
882             $message . $subscribemessage,
883             null,
884             \core\output\notification::NOTIFY_SUCCESS
885         );
887     } else if ($fromform->discussion) {
888         // Adding a new post to an existing discussion
889         // Before we add this we must check that the user will not exceed the blocking threshold.
890         forum_check_blocking_threshold($thresholdwarning);
892         unset($fromform->groupid);
893         $message = '';
894         $addpost = $fromform;
895         $addpost->forum = $forum->id;
896         if ($fromform->id = forum_add_new_post($addpost, $mformpost)) {
897             $postentity = $postvault->get_from_id($fromform->id);
898             $fromform->deleted = 0;
899             $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
901             if (!empty($fromform->mailnow)) {
902                 $message .= get_string("postmailnow", "forum");
903             } else {
904                 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
905                 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
906             }
908             if ($forum->type == 'single') {
909                 // Single discussion forums are an exception.
910                 // We show the forum itself since it only has one discussion thread.
911                 $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
912             } else {
913                 $discussionurl = $urlfactory->get_view_post_url_from_post($postentity);
914             }
916             $params = array(
917                 'context' => $modcontext,
918                 'objectid' => $fromform->id,
919                 'other' => array(
920                     'discussionid' => $discussion->id,
921                     'forumid' => $forum->id,
922                     'forumtype' => $forum->type,
923                 )
924             );
925             $event = \mod_forum\event\post_created::create($params);
926             $event->add_record_snapshot('forum_posts', $fromform);
927             $event->add_record_snapshot('forum_discussions', $discussion);
928             $event->trigger();
930             // Update completion state.
931             $completion = new completion_info($course);
932             if ($completion->is_enabled($cm) &&
933                 ($forum->completionreplies || $forum->completionposts)) {
934                 $completion->update_state($cm, COMPLETION_COMPLETE);
935             }
937             redirect(
938                 forum_go_back_to($discussionurl),
939                 $message . $subscribemessage,
940                 null,
941                 \core\output\notification::NOTIFY_SUCCESS
942             );
944         } else {
945             print_error("couldnotadd", "forum", $errordestination);
946         }
947         exit;
949     } else {
950         // Adding a new discussion.
951         // The location to redirect to after successfully posting.
952         $redirectto = new moodle_url('/mod/forum/view.php', array('f' => $fromform->forum));
954         $fromform->mailnow = empty($fromform->mailnow) ? 0 : 1;
956         $discussion = $fromform;
957         $discussion->name = $fromform->subject;
958         $discussion->timelocked = 0;
960         $newstopic = false;
961         if ($forum->type == 'news' && !$fromform->parent) {
962             $newstopic = true;
963         }
965         if (!empty($fromform->pinned) && $capabilitymanager->can_pin_discussions($USER)) {
966             $discussion->pinned = FORUM_DISCUSSION_PINNED;
967         } else {
968             $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
969         }
971         $allowedgroups = array();
972         $groupstopostto = array();
974         // If we are posting a copy to all groups the user has access to.
975         if (isset($fromform->posttomygroups)) {
976             // Post to each of my groups.
977             require_capability('mod/forum:canposttomygroups', $modcontext);
979             // Fetch all of this user's groups.
980             // Note: all groups are returned when in visible groups mode so we must manually filter.
981             $allowedgroups = groups_get_activity_allowed_groups($cm);
982             foreach ($allowedgroups as $groupid => $group) {
983                 if ($capabilitymanager->can_create_discussions($USER, $groupid)) {
984                     $groupstopostto[] = $groupid;
985                 }
986             }
987         } else if (isset($fromform->groupinfo)) {
988             // Use the value provided in the dropdown group selection.
989             $groupstopostto[] = $fromform->groupinfo;
990             $redirectto->param('group', $fromform->groupinfo);
991         } else if (isset($fromform->groupid) && !empty($fromform->groupid)) {
992             // Use the value provided in the hidden form element instead.
993             $groupstopostto[] = $fromform->groupid;
994             $redirectto->param('group', $fromform->groupid);
995         } else {
996             // Use the value for all participants instead.
997             $groupstopostto[] = -1;
998         }
1000         // Before we post this we must check that the user will not exceed the blocking threshold.
1001         forum_check_blocking_threshold($thresholdwarning);
1003         foreach ($groupstopostto as $group) {
1004             if (!$capabilitymanager->can_create_discussions($USER, $groupid)) {
1005                 print_error('cannotcreatediscussion', 'forum');
1006             }
1008             $discussion->groupid = $group;
1009             $message = '';
1010             if ($discussion->id = forum_add_discussion($discussion, $mformpost)) {
1012                 $params = array(
1013                     'context' => $modcontext,
1014                     'objectid' => $discussion->id,
1015                     'other' => array(
1016                         'forumid' => $forum->id,
1017                     )
1018                 );
1019                 $event = \mod_forum\event\discussion_created::create($params);
1020                 $event->add_record_snapshot('forum_discussions', $discussion);
1021                 $event->trigger();
1023                 if ($fromform->mailnow) {
1024                     $message .= get_string("postmailnow", "forum");
1025                 } else {
1026                     $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
1027                     $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
1028                 }
1030                 $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
1031             } else {
1032                 print_error("couldnotadd", "forum", $errordestination);
1033             }
1034         }
1036         // Update completion status.
1037         $completion = new completion_info($course);
1038         if ($completion->is_enabled($cm) &&
1039             ($forum->completiondiscussions || $forum->completionposts)) {
1040             $completion->update_state($cm, COMPLETION_COMPLETE);
1041         }
1043         // Redirect back to the discussion.
1044         redirect(
1045             forum_go_back_to($redirectto->out()),
1046             $message . $subscribemessage,
1047             null,
1048             \core\output\notification::NOTIFY_SUCCESS
1049         );
1050     }
1054 // This section is only shown after all checks are in place, and the forumentity and any relevant discussion and post
1055 // entity are available.
1057 if (!empty($discussionentity)) {
1058     $titlesubject = format_string($discussionentity->get_name(), true);
1059 } else if ('news' == $forumentity->get_type()) {
1060     $titlesubject = get_string("addanewtopic", "forum");
1061 } else {
1062     $titlesubject = get_string("addanewdiscussion", "forum");
1065 if (empty($post->edit)) {
1066     $post->edit = '';
1069 if (empty($discussion->name)) {
1070     if (empty($discussion)) {
1071         $discussion = new stdClass();
1072     }
1073     $discussion->name = $forum->name;
1076 $strdiscussionname = '';
1077 if ('single' == $forumentity->get_type()) {
1078     // There is only one discussion thread for this forum type. We should
1079     // not show the discussion name (same as forum name in this case) in
1080     // the breadcrumbs.
1081     $strdiscussionname = '';
1082 } else if (!empty($discussionentity)) {
1083     // Show the discussion name in the breadcrumbs.
1084     $strdiscussionname = format_string($discussionentity->get_name()) . ': ';
1087 $forcefocus = empty($reply) ? null : 'message';
1089 if (!empty($discussion->id)) {
1090     $PAGE->navbar->add($titlesubject, $urlfactory->get_discussion_view_url_from_discussion($discussionentity));
1093 if ($post->parent) {
1094     $PAGE->navbar->add(get_string('reply', 'forum'));
1097 if ($edit) {
1098     $PAGE->navbar->add(get_string('edit', 'forum'));
1101 $PAGE->set_title("{$course->shortname}: {$strdiscussionname}{$titlesubject}");
1102 $PAGE->set_heading($course->fullname);
1104 echo $OUTPUT->header();
1105 echo $OUTPUT->heading(format_string($forum->name), 2);
1107 // Checkup.
1108 if (!empty($parententity) && !$capabilitymanager->can_view_post($USER, $discussionentity, $parententity)) {
1109     print_error('cannotreply', 'forum');
1112 if (empty($parententity) && empty($edit) && !$capabilitymanager->can_create_discussions($USER, $groupid)) {
1113     print_error('cannotcreatediscussion', 'forum');
1116 if (!empty($discussionentity) && 'qanda' == $forumentity->get_type()) {
1117     $displaywarning = $capabilitymanager->must_post_before_viewing_discussion($USER, $discussionentity);
1118     $displaywarning = $displaywarning && !forum_user_has_posted($forumentity->get_id(), $discussionentity->get_id(), $USER->id);
1119     if ($displaywarning) {
1120         echo $OUTPUT->notification(get_string('qandanotify', 'forum'));
1121     }
1124 // If there is a warning message and we are not editing a post we need to handle the warning.
1125 if (!empty($thresholdwarning) && !$edit) {
1126     // Here we want to throw an exception if they are no longer allowed to post.
1127     forum_check_blocking_threshold($thresholdwarning);
1130 if (!empty($parententity)) {
1131     $postentities = [$parententity];
1133     if (empty($post->edit)) {
1134         if ('qanda' != $forumentity->get_type() || forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
1135             $replies = $postvault->get_replies_to_post(
1136                     $USER,
1137                     $parententity,
1138                     $capabilitymanager->can_view_any_private_reply($USER),
1139                     'created ASC'
1140                 );
1141             $postentities = array_merge($postentities, $replies);
1142         }
1143     }
1145     $rendererfactory = mod_forum\local\container::get_renderer_factory();
1146     $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(FORUM_MODE_THREADED, true);
1147     echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], $postentities);
1148 } else {
1149     if (!empty($forum->intro)) {
1150         echo $OUTPUT->box(format_module_intro('forum', $forum, $cm->id), 'generalbox', 'intro');
1151     }
1154 // Call print disclosure for enabled plagiarism plugins.
1155 if (!empty($CFG->enableplagiarism)) {
1156     require_once($CFG->libdir.'/plagiarismlib.php');
1157     echo plagiarism_print_disclosure($cm->id);
1160 if (!empty($formheading)) {
1161     echo $OUTPUT->heading($formheading, 2, array('class' => 'accesshide'));
1164 if (!empty($postentity)) {
1165     $data = (object) [
1166         'tags' => core_tag_tag::get_item_tags_array('mod_forum', 'forum_posts', $postentity->get_id())
1167     ];
1168     $mformpost->set_data($data);
1171 $mformpost->display();
1173 echo $OUTPUT->footer();