MDL-65069 mod_forum: Remove unused code and additional dev docs.
[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             }
220         }
221         print_error('nopostforum', 'forum');
222     }
224     // Make sure user can post here.
225     if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
226         $groupmode = $cm->groupmode;
227     } else {
228         $groupmode = $course->groupmode;
229     }
230     if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
231         if ($discussion->groupid == -1) {
232             print_error('nopostforum', 'forum');
233         } else {
234             if (!groups_is_member($discussion->groupid)) {
235                 print_error('nopostforum', 'forum');
236             }
237         }
238     }
240     if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $modcontext)) {
241         print_error("activityiscurrentlyhidden");
242     }
244     if ($parententity->is_private_reply()) {
245         print_error('cannotreplytoprivatereply', 'forum');
246     }
248     // Load up the $post variable.
249     $post = new stdClass();
250     $post->course      = $course->id;
251     $post->forum       = $forum->id;
252     $post->discussion  = $parent->discussion;
253     $post->parent      = $parent->id;
254     $post->subject     = $subject ? $subject : $parent->subject;
255     $post->userid      = $USER->id;
256     $post->parentpostauthor = $parent->userid;
257     $post->message     = $prefilledpost;
258     $canreplyprivately = $capabilitymanager->can_reply_privately_to_post($USER, $parententity);
260     $post->groupid = ($discussion->groupid == -1) ? 0 : $discussion->groupid;
262     $strre = get_string('re', 'forum');
263     if (!(substr($post->subject, 0, strlen($strre)) == $strre)) {
264         $post->subject = $strre.' '.$post->subject;
265     }
267     // Unsetting this will allow the correct return URL to be calculated later.
268     unset($SESSION->fromdiscussion);
270 } else if (!empty($edit)) {
271     // User is editing their own post.
273     $postentity = $postvault->get_from_id($edit);
274     if (empty($postentity)) {
275         print_error('invalidpostid', 'forum');
276     }
277     if ($postentity->has_parent()) {
278         $parententity = $postvault->get_from_id($postentity->get_parent_id());
279         $parent = $postdatamapper->to_legacy_object($parententity);
280     }
282     $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
283     if (empty($discussionentity)) {
284         print_error('notpartofdiscussion', 'forum');
285     }
287     $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
288     if (empty($forumentity)) {
289         print_error('invalidforumid', 'forum');
290     }
292     $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
293     $post = $postdatamapper->to_legacy_object($postentity);
294     $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
295     $forum = $forumdatamapper->to_legacy_object($forumentity);
296     $course = $forumentity->get_course_record();
297     $modcontext = $forumentity->get_context();
298     $coursecontext = context_course::instance($course->id);
300     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
301         print_error('invalidcoursemodule');
302     }
304     $PAGE->set_cm($cm, $course, $forum);
306     if (!($forum->type == 'news' && !$post->parent && $discussion->timestart > time())) {
307         if (((time() - $post->created) > $CFG->maxeditingtime) and
308             !has_capability('mod/forum:editanypost', $modcontext)) {
309             print_error('maxtimehaspassed', 'forum', '', format_time($CFG->maxeditingtime));
310         }
311     }
312     if (($post->userid <> $USER->id) and
313         !has_capability('mod/forum:editanypost', $modcontext)) {
314         print_error('cannoteditposts', 'forum');
315     }
317     // Load up the $post variable.
318     $post->edit   = $edit;
319     $post->course = $course->id;
320     $post->forum  = $forum->id;
321     $post->groupid = ($discussion->groupid == -1) ? 0 : $discussion->groupid;
322     if ($postentity->has_parent()) {
323         $canreplyprivately = forum_user_can_reply_privately($modcontext, $parent);
324     }
326     $post = trusttext_pre_edit($post, 'message', $modcontext);
328     // Unsetting this will allow the correct return URL to be calculated later.
329     unset($SESSION->fromdiscussion);
331 } else if (!empty($delete)) {
332     // User is deleting a post.
334     $postentity = $postvault->get_from_id($delete);
335     if (empty($postentity)) {
336         print_error('invalidpostid', 'forum');
337     }
339     $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
340     if (empty($discussionentity)) {
341         print_error('notpartofdiscussion', 'forum');
342     }
344     $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
345     if (empty($forumentity)) {
346         print_error('invalidforumid', 'forum');
347     }
349     $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
350     $post = $postdatamapper->to_legacy_object($postentity);
351     $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
352     $forum = $forumdatamapper->to_legacy_object($forumentity);
353     $course = $forumentity->get_course_record();
354     $modcontext = $forumentity->get_context();
355     $coursecontext = context_course::instance($course->id);
357     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
358         print_error('invalidcoursemodule');
359     }
361     require_login($course, false, $cm);
363     if (!$capabilitymanager->can_delete_post($USER, $discussionentity, $postentity)) {
364         redirect(
365                 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
366                 get_string('cannotdeletepost', 'forum'),
367                 null,
368                 \core\output\notice::NOTIFY_ERROR
369             );
370     }
372     $replycount = $postvault->get_reply_count_for_post_id_in_discussion_id(
373         $USER, $postentity->get_id(), $discussionentity->get_id(), true);
375     if (!empty($confirm) && confirm_sesskey()) {
376         // User has confirmed the delete.
377         // Check user capability to delete post.
378         $timepassed = time() - $post->created;
379         if ($post->totalscore) {
380             redirect(
381                     $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
382                     get_string('couldnotdeleteratings', 'rating'),
383                     null,
384                     \core\output\notice::NOTIFY_ERROR
385                 );
386         } else if ($replycount && !has_capability('mod/forum:deleteanypost', $modcontext)) {
387             redirect(
388                     $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
389                     get_string('couldnotdeletereplies', 'rating'),
390                     null,
391                     \core\output\notice::NOTIFY_ERROR
392                 );
393         } else {
394             if (!$postentity->has_parent()) {
395                 // Post is a discussion topic as well, so delete discussion.
396                 if ($forum->type == 'single') {
397                     redirect(
398                             $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
399                             get_string('cannotdeletediscussioninsinglediscussion', 'rating'),
400                             null,
401                             \core\output\notice::NOTIFY_ERROR
402                         );
403                 }
404                 forum_delete_discussion($discussion, false, $course, $cm, $forum);
406                 $params = array(
407                     'objectid' => $discussion->id,
408                     'context' => $modcontext,
409                     'other' => array(
410                         'forumid' => $forum->id,
411                     )
412                 );
414                 $event = \mod_forum\event\discussion_deleted::create($params);
415                 $event->add_record_snapshot('forum_discussions', $discussion);
416                 $event->trigger();
418                 redirect(
419                     $urlfactory->get_forum_view_url_from_forum($forumentity),
420                     get_string('eventdiscussiondeleted', 'forum'),
421                     null,
422                     \core\output\notification::NOTIFY_SUCCESS
423                 );
425             } else {
426                 $deleted = forum_delete_post($post, has_capability('mod/forum:deleteanypost', $modcontext), $course, $cm, $forum);
428                 if (!$deleted) {
429                     redirect(
430                             $urlfactory->get_discussion_view_url_from_post($postentity),
431                             get_string('errorwhiledelete', 'forum'),
432                             null,
433                             \core\output\notice::NOTIFY_ERROR
434                         );
435                 }
437                 if ($forum->type == 'single') {
438                     // Single discussion forums are an exception.
439                     // We show the forum itself since it only has one discussion thread.
440                     $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
441                 } else {
442                     $discussionurl = $urlfactory->get_discussion_view_url_from_discussion($discussionentity);
443                 }
445                 redirect(
446                     forum_go_back_to($discussionurl),
447                     get_string('eventpostdeleted', 'forum'),
448                     null,
449                     \core\output\notification::NOTIFY_SUCCESS
450                 );
451             }
452         }
455     } else {
456         // User just asked to delete something.
457         forum_set_return();
458         $PAGE->navbar->add(get_string('delete', 'forum'));
459         $PAGE->set_title($course->shortname);
460         $PAGE->set_heading($course->fullname);
462         if ($replycount) {
463             if (!has_capability('mod/forum:deleteanypost', $modcontext)) {
464                 redirect(
465                         forum_go_back_to($urlfactory->get_view_post_url_from_post($postentity)),
466                         get_string('couldnotdeletereplies', 'rating'),
467                         null,
468                         \core\output\notice::NOTIFY_ERROR
469                     );
470             }
472             echo $OUTPUT->header();
473             echo $OUTPUT->heading(format_string($forum->name), 2);
474             echo $OUTPUT->confirm(get_string("deletesureplural", "forum", $replycount + 1),
475                 "post.php?delete=$delete&confirm=$delete",
476                 $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
478             $postentities = [$postentity];
479             if (empty($post->edit)) {
480                 $postvault = $vaultfactory->get_post_vault();
481                 $replies = $postvault->get_replies_to_post(
482                         $USER,
483                         $postentity,
484                         // Note: All replies are fetched here as the user has deleteanypost.
485                         true,
486                         'created ASC'
487                     );
488                 $postentities = array_merge($postentities, $replies);
489             }
491             $rendererfactory = mod_forum\local\container::get_renderer_factory();
492             $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(FORUM_MODE_NESTED, true);
493             echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], $postentities);
494         } else {
495             echo $OUTPUT->header();
496             echo $OUTPUT->heading(format_string($forum->name), 2);
497             echo $OUTPUT->confirm(get_string("deletesure", "forum", $replycount),
498                 "post.php?delete=$delete&confirm=$delete",
499                 $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
501             $rendererfactory = mod_forum\local\container::get_renderer_factory();
502             $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(null, true);
503             echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], [$postentity]);
504         }
506     }
507     echo $OUTPUT->footer();
508     die;
510 } else if (!empty($prune)) {
511     // Pruning.
513     $postentity = $postvault->get_from_id($prune);
514     if (empty($postentity)) {
515         print_error('invalidpostid', 'forum');
516     }
518     $discussionentity = $discussionvault->get_from_id($postentity->get_discussion_id());
519     if (empty($discussionentity)) {
520         print_error('notpartofdiscussion', 'forum');
521     }
523     $forumentity = $forumvault->get_from_id($discussionentity->get_forum_id());
524     if (empty($forumentity)) {
525         print_error('invalidforumid', 'forum');
526     }
528     $capabilitymanager = $managerfactory->get_capability_manager($forumentity);
529     $post = $postdatamapper->to_legacy_object($postentity);
530     $discussion = $discussiondatamapper->to_legacy_object($discussionentity);
531     $forum = $forumdatamapper->to_legacy_object($forumentity);
532     $course = $forumentity->get_course_record();
533     $modcontext = $forumentity->get_context();
534     $coursecontext = context_course::instance($course->id);
536     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
537         print_error('invalidcoursemodule');
538     }
540     if (!$postentity->has_parent()) {
541         redirect(
542                 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
543                 get_string('alreadyfirstpost', 'forum'),
544                 null,
545                 \core\output\notification::NOTIFY_ERROR
546             );
547     }
548     if (!$capabilitymanager->can_split_post($USER, $discussionentity, $postentity)) {
549         redirect(
550                 $urlfactory->get_discussion_view_url_from_discussion($discussionentity),
551                 get_string('cannotsplit', 'forum'),
552                 null,
553                 \core\output\notification::NOTIFY_ERROR
554             );
555     }
557     $PAGE->set_cm($cm);
558     $PAGE->set_context($modcontext);
560     $prunemform = new mod_forum_prune_form(null, array('prune' => $prune, 'confirm' => $prune));
562     if ($prunemform->is_cancelled()) {
563         redirect(forum_go_back_to($urlfactory->get_discussion_view_url_from_discussion($discussionentity)));
564     } else if ($fromform = $prunemform->get_data()) {
565         // User submits the data.
566         $newdiscussion = new stdClass();
567         $newdiscussion->course       = $discussion->course;
568         $newdiscussion->forum        = $discussion->forum;
569         $newdiscussion->name         = $name;
570         $newdiscussion->firstpost    = $post->id;
571         $newdiscussion->userid       = $discussion->userid;
572         $newdiscussion->groupid      = $discussion->groupid;
573         $newdiscussion->assessed     = $discussion->assessed;
574         $newdiscussion->usermodified = $post->userid;
575         $newdiscussion->timestart    = $discussion->timestart;
576         $newdiscussion->timeend      = $discussion->timeend;
578         $newid = $DB->insert_record('forum_discussions', $newdiscussion);
580         $newpost = new stdClass();
581         $newpost->id      = $post->id;
582         $newpost->parent  = 0;
583         $newpost->subject = $name;
585         $DB->update_record("forum_posts", $newpost);
586         $postentity = $postvault->get_from_id($postentity->get_id());
588         forum_change_discussionid($post->id, $newid);
590         // Update last post in each discussion.
591         forum_discussion_update_last_post($discussion->id);
592         forum_discussion_update_last_post($newid);
594         // Fire events to reflect the split..
595         $params = array(
596             'context' => $modcontext,
597             'objectid' => $discussion->id,
598             'other' => array(
599                 'forumid' => $forum->id,
600             )
601         );
602         $event = \mod_forum\event\discussion_updated::create($params);
603         $event->trigger();
605         $params = array(
606             'context' => $modcontext,
607             'objectid' => $newid,
608             'other' => array(
609                 'forumid' => $forum->id,
610             )
611         );
612         $event = \mod_forum\event\discussion_created::create($params);
613         $event->trigger();
615         $params = array(
616             'context' => $modcontext,
617             'objectid' => $post->id,
618             'other' => array(
619                 'discussionid' => $newid,
620                 'forumid' => $forum->id,
621                 'forumtype' => $forum->type,
622             )
623         );
624         $event = \mod_forum\event\post_updated::create($params);
625         $event->add_record_snapshot('forum_discussions', $discussion);
626         $event->trigger();
628         redirect(
629             forum_go_back_to($urlfactory->get_discussion_view_url_from_post($postentity)),
630             get_string('discussionsplit', 'forum'),
631             null,
632             \core\output\notification::NOTIFY_SUCCESS
633         );
634     } else {
635         // Display the prune form.
636         $course = $DB->get_record('course', array('id' => $forum->course));
637         $subjectstr = format_string($post->subject, true);
638         $PAGE->navbar->add($subjectstr, new moodle_url('/mod/forum/discuss.php', array('d' => $discussion->id)));
639         $PAGE->navbar->add(get_string("prune", "forum"));
640         $PAGE->set_title(format_string($discussion->name).": ".format_string($post->subject));
641         $PAGE->set_heading($course->fullname);
642         echo $OUTPUT->header();
643         echo $OUTPUT->heading(format_string($forum->name), 2);
644         echo $OUTPUT->heading(get_string('pruneheading', 'forum'), 3);
646         $prunemform->display();
648         $postentity = $entityfactory->get_post_from_stdclass($post);
649         $discussionentity = $entityfactory->get_discussion_from_stdclass($discussion);
650         $forumentity = $entityfactory->get_forum_from_stdclass($forum, $modcontext, $cm, $course);
651         $rendererfactory = mod_forum\local\container::get_renderer_factory();
652         $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(null, true);
653         echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], [$postentity]);
654     }
656     echo $OUTPUT->footer();
657     die;
658 } else {
659     print_error('unknowaction');
663 // From now on user must be logged on properly.
665 require_login($course, false, $cm);
667 if (isguestuser()) {
668     // Just in case.
669     print_error('noguest');
672 $thresholdwarning = forum_check_throttling($forum, $cm);
673 $mformpost = new mod_forum_post_form('post.php', [
674         'course' => $course,
675         'cm' => $cm,
676         'coursecontext' => $coursecontext,
677         'modcontext' => $modcontext,
678         'forum' => $forum,
679         'post' => $post,
680         'subscribe' => \mod_forum\subscriptions::is_subscribed($USER->id, $forum, null, $cm),
681         'thresholdwarning' => $thresholdwarning,
682         'edit' => $edit,
683         'canreplyprivately' => $canreplyprivately,
684     ], 'post', '', array('id' => 'mformforum'));
686 $draftitemid = file_get_submitted_draft_itemid('attachments');
687 $postid = empty($post->id) ? null : $post->id;
688 $attachoptions = mod_forum_post_form::attachment_options($forum);
689 file_prepare_draft_area($draftitemid, $modcontext->id, 'mod_forum', 'attachment', $postid, $attachoptions);
691 // Load data into form NOW!
693 if ($USER->id != $post->userid) {   // Not the original author, so add a message to the end.
694     $data = new stdClass();
695     $data->date = userdate($post->created);
696     if ($post->messageformat == FORMAT_HTML) {
697         $data->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'&course='.$post->course.'">'.
698             fullname($USER).'</a>';
699         $post->message .= '<p><span class="edited">('.get_string('editedby', 'forum', $data).')</span></p>';
700     } else {
701         $data->name = fullname($USER);
702         $post->message .= "\n\n(".get_string('editedby', 'forum', $data).')';
703     }
704     unset($data);
707 $formheading = '';
708 if (!empty($parent)) {
709     $heading = get_string("yourreply", "forum");
710     $formheading = get_string('reply', 'forum');
711 } else {
712     if ($forum->type == 'qanda') {
713         $heading = get_string('yournewquestion', 'forum');
714     } else {
715         $heading = get_string('yournewtopic', 'forum');
716     }
719 $postid = empty($post->id) ? null : $post->id;
720 $draftideditor = file_get_submitted_draft_itemid('message');
721 $editoropts = mod_forum_post_form::editor_options($modcontext, $postid);
722 $currenttext = file_prepare_draft_area($draftideditor, $modcontext->id, 'mod_forum', 'post', $postid, $editoropts, $post->message);
723 $discussionid = isset($discussion) ? $discussion->id : null;
724 $discussionsubscribe = \mod_forum\subscriptions::get_user_default_subscription($forum, $coursecontext, $cm, $discussionid);
726 $mformpost->set_data(
727     array(
728         'attachments' => $draftitemid,
729         'general' => $heading,
730         'subject' => $post->subject,
731         'message' => array(
732             'text' => $currenttext,
733             'format' => empty($post->messageformat) ? editors_get_preferred_format() : $post->messageformat,
734             'itemid' => $draftideditor
735         ),
736         'discussionsubscribe' => $discussionsubscribe,
737         'mailnow' => !empty($post->mailnow),
738         'userid' => $post->userid,
739         'parent' => $post->parent,
740         'discussion' => $post->discussion,
741         'course' => $course->id
742     ) +
744     $pageparams +
746     (isset($post->format) ? array('format' => $post->format) : array()) +
748     (isset($discussion->timestart) ? array('timestart' => $discussion->timestart) : array()) +
750     (isset($discussion->timeend) ? array('timeend' => $discussion->timeend) : array()) +
752     (isset($discussion->pinned) ? array('pinned' => $discussion->pinned) : array()) +
754     (isset($post->groupid) ? array('groupid' => $post->groupid) : array()) +
756     (isset($discussion->id) ? array('discussion' => $discussion->id) : array())
757 );
759 if ($mformpost->is_cancelled()) {
760     if (!isset($discussion->id) || $forum->type === 'single') {
761         // Single forums don't have a discussion page.
762         redirect($urlfactory->get_forum_view_url_from_forum($forumentity));
763     } else {
764         redirect($urlfactory->get_discussion_view_url_from_discussion($discussionentity));
765     }
766 } else if ($mformpost->is_submitted() && !$mformpost->no_submit_button_pressed()) {
768     if (empty($SESSION->fromurl)) {
769         $errordestination = $urlfactory->get_forum_view_url_from_forum($forumentity);
770     } else {
771         $errordestination = $SESSION->fromurl;
772     }
773     $fromform = $mformpost->get_data();
774     $fromform->itemid        = $fromform->message['itemid'];
775     $fromform->messageformat = $fromform->message['format'];
776     $fromform->message       = $fromform->message['text'];
777     // WARNING: the $fromform->message array has been overwritten, do not use it anymore!
778     $fromform->messagetrust  = trusttext_trusted($modcontext);
780     // Clean message text.
781     $fromform = trusttext_pre_edit($fromform, 'message', $modcontext);
783     if ($fromform->edit) {
784         // Updating a post.
785         unset($fromform->groupid);
786         $fromform->id = $fromform->edit;
787         $message = '';
789         if (!$capabilitymanager->can_edit_post($USER, $discussionentity, $postentity)) {
790             redirect(
791                     $urlfactory->get_view_post_url_from_post($postentity),
792                     get_string('cannotupdatepost', 'forum'),
793                     null,
794                     \core\output\notification::ERROR
795                 );
796         }
798         if (isset($fromform->groupinfo) && $capabilitymanager->can_move_discussions($USER)) {
799             // If the user has access to all groups and they are changing the group, then update the post.
800             if (empty($fromform->groupinfo)) {
801                 $fromform->groupinfo = -1;
802             }
804             if (!$capabilitymanager->can_create_discussions($USER, $fromform->groupinfo)) {
805                 redirect(
806                         $urlfactory->get_view_post_url_from_post($postentity),
807                         get_string('cannotupdatepost', 'forum'),
808                         null,
809                         \core\output\notification::ERROR
810                     );
811             }
813             if ($discussionentity->get_group_id() != $fromform->groupinfo) {
814                 $DB->set_field('forum_discussions', 'groupid', $fromform->groupinfo, array('firstpost' => $fromform->id));
815             }
816         }
818         // When editing first post/discussion.
819         if ($postentity->has_parent()) {
820             if ($capabilitymanager->can_pin_discussions($USER)) {
821                 // Can change pinned if we have capability.
822                 $fromform->pinned = !empty($fromform->pinned) ? FORUM_DISCUSSION_PINNED : FORUM_DISCUSSION_UNPINNED;
823             } else {
824                 // We don't have the capability to change so keep to previous value.
825                 unset($fromform->pinned);
826             }
827         }
828         $updatepost = $fromform;
829         $updatepost->forum = $forum->id;
830         if (!forum_update_post($updatepost, $mformpost)) {
831             print_error("couldnotupdate", "forum", $errordestination);
832         }
834         if ('single' == $forumentity->get_type() && !$postentity->has_parent()) {
835             // Updating first post of single discussion type -> updating forum intro.
836             $forum->intro = $updatepost->message;
837             $forum->timemodified = time();
838             $DB->update_record("forum", $forum);
839         }
841         if ($USER->id === $postentity->get_author_id()) {
842             $message .= get_string("postupdated", "forum");
843         } else {
844             $realuser = \core_user::get_user($postentity->get_author_id());
845             $message .= get_string("editedpostupdated", "forum", fullname($realuser));
846         }
848         $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
849         if ('single' == $forumentity->get_type()) {
850             // Single discussion forums are an exception.
851             // We show the forum itself since it only has one discussion thread.
852             $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
853         } else {
854             $discussionurl = $urlfactory->get_view_post_url_from_post($postentity);
855         }
857         $params = array(
858             'context' => $modcontext,
859             'objectid' => $fromform->id,
860             'other' => array(
861                 'discussionid' => $discussion->id,
862                 'forumid' => $forum->id,
863                 'forumtype' => $forum->type,
864             )
865         );
867         if ($USER->id !== $postentity->get_author_id()) {
868             $params['relateduserid'] = $postentity->get_author_id();
869         }
871         $event = \mod_forum\event\post_updated::create($params);
872         $event->add_record_snapshot('forum_discussions', $discussion);
873         $event->trigger();
875         redirect(
876             forum_go_back_to($discussionurl),
877             $message . $subscribemessage,
878             null,
879             \core\output\notification::NOTIFY_SUCCESS
880         );
882     } else if ($fromform->discussion) {
883         // Adding a new post to an existing discussion
884         // Before we add this we must check that the user will not exceed the blocking threshold.
885         forum_check_blocking_threshold($thresholdwarning);
887         unset($fromform->groupid);
888         $message = '';
889         $addpost = $fromform;
890         $addpost->forum = $forum->id;
891         if ($fromform->id = forum_add_new_post($addpost, $mformpost)) {
892             $postentity = $postvault->get_from_id($fromform->id);
893             $fromform->deleted = 0;
894             $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
896             if (!empty($fromform->mailnow)) {
897                 $message .= get_string("postmailnow", "forum");
898             } else {
899                 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
900                 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
901             }
903             if ($forum->type == 'single') {
904                 // Single discussion forums are an exception.
905                 // We show the forum itself since it only has one discussion thread.
906                 $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
907             } else {
908                 $discussionurl = $urlfactory->get_view_post_url_from_post($postentity);
909             }
911             $params = array(
912                 'context' => $modcontext,
913                 'objectid' => $fromform->id,
914                 'other' => array(
915                     'discussionid' => $discussion->id,
916                     'forumid' => $forum->id,
917                     'forumtype' => $forum->type,
918                 )
919             );
920             $event = \mod_forum\event\post_created::create($params);
921             $event->add_record_snapshot('forum_posts', $fromform);
922             $event->add_record_snapshot('forum_discussions', $discussion);
923             $event->trigger();
925             // Update completion state.
926             $completion = new completion_info($course);
927             if ($completion->is_enabled($cm) &&
928                 ($forum->completionreplies || $forum->completionposts)) {
929                 $completion->update_state($cm, COMPLETION_COMPLETE);
930             }
932             redirect(
933                 forum_go_back_to($discussionurl),
934                 $message . $subscribemessage,
935                 null,
936                 \core\output\notification::NOTIFY_SUCCESS
937             );
939         } else {
940             print_error("couldnotadd", "forum", $errordestination);
941         }
942         exit;
944     } else {
945         // Adding a new discussion.
946         // The location to redirect to after successfully posting.
947         $redirectto = new moodle_url('/mod/forum/view.php', array('f' => $fromform->forum));
949         $fromform->mailnow = empty($fromform->mailnow) ? 0 : 1;
951         $discussion = $fromform;
952         $discussion->name = $fromform->subject;
954         $newstopic = false;
955         if ($forum->type == 'news' && !$fromform->parent) {
956             $newstopic = true;
957         }
958         $discussion->timestart = $fromform->timestart;
959         $discussion->timeend = $fromform->timeend;
960         $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
962         if (!empty($fromform->pinned) && $capabilitymanager->can_pin_discussions($USER)) {
963             $discussion->pinned = FORUM_DISCUSSION_PINNED;
964         }
966         $allowedgroups = array();
967         $groupstopostto = array();
969         // If we are posting a copy to all groups the user has access to.
970         if (isset($fromform->posttomygroups)) {
971             // Post to each of my groups.
972             require_capability('mod/forum:canposttomygroups', $modcontext);
974             // Fetch all of this user's groups.
975             // Note: all groups are returned when in visible groups mode so we must manually filter.
976             $allowedgroups = groups_get_activity_allowed_groups($cm);
977             foreach ($allowedgroups as $groupid => $group) {
978                 if ($capabilitymanager->can_create_discussions($USER, $groupid)) {
979                     $groupstopostto[] = $groupid;
980                 }
981             }
982         } else if (isset($fromform->groupinfo)) {
983             // Use the value provided in the dropdown group selection.
984             $groupstopostto[] = $fromform->groupinfo;
985             $redirectto->param('group', $fromform->groupinfo);
986         } else if (isset($fromform->groupid) && !empty($fromform->groupid)) {
987             // Use the value provided in the hidden form element instead.
988             $groupstopostto[] = $fromform->groupid;
989             $redirectto->param('group', $fromform->groupid);
990         } else {
991             // Use the value for all participants instead.
992             $groupstopostto[] = -1;
993         }
995         // Before we post this we must check that the user will not exceed the blocking threshold.
996         forum_check_blocking_threshold($thresholdwarning);
998         foreach ($groupstopostto as $group) {
999             if (!$capabilitymanager->can_create_discussions($USER, $groupid)) {
1000                 print_error('cannotcreatediscussion', 'forum');
1001             }
1003             $discussion->groupid = $group;
1004             $message = '';
1005             if ($discussion->id = forum_add_discussion($discussion, $mformpost)) {
1007                 $params = array(
1008                     'context' => $modcontext,
1009                     'objectid' => $discussion->id,
1010                     'other' => array(
1011                         'forumid' => $forum->id,
1012                     )
1013                 );
1014                 $event = \mod_forum\event\discussion_created::create($params);
1015                 $event->add_record_snapshot('forum_discussions', $discussion);
1016                 $event->trigger();
1018                 if ($fromform->mailnow) {
1019                     $message .= get_string("postmailnow", "forum");
1020                 } else {
1021                     $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
1022                     $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
1023                 }
1025                 $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
1026             } else {
1027                 print_error("couldnotadd", "forum", $errordestination);
1028             }
1029         }
1031         // Update completion status.
1032         $completion = new completion_info($course);
1033         if ($completion->is_enabled($cm) &&
1034             ($forum->completiondiscussions || $forum->completionposts)) {
1035             $completion->update_state($cm, COMPLETION_COMPLETE);
1036         }
1038         // Redirect back to the discussion.
1039         redirect(
1040             forum_go_back_to($redirectto->out()),
1041             $message . $subscribemessage,
1042             null,
1043             \core\output\notification::NOTIFY_SUCCESS
1044         );
1045     }
1049 // This section is only shown after all checks are in place, and the forumentity and any relevant discussion and post
1050 // entity are available.
1052 if (!empty($discussionentity)) {
1053     $titlesubject = format_string($discussionentity->get_name(), true);
1054 } else if ('news' == $forumentity->get_type()) {
1055     $titlesubject = get_string("addanewtopic", "forum");
1056 } else {
1057     $titlesubject = get_string("addanewdiscussion", "forum");
1060 if (empty($post->edit)) {
1061     $post->edit = '';
1064 if (empty($discussion->name)) {
1065     if (empty($discussion)) {
1066         $discussion = new stdClass();
1067     }
1068     $discussion->name = $forum->name;
1071 $strdiscussionname = '';
1072 if ('single' == $forumentity->get_type()) {
1073     // There is only one discussion thread for this forum type. We should
1074     // not show the discussion name (same as forum name in this case) in
1075     // the breadcrumbs.
1076     $strdiscussionname = '';
1077 } else if (!empty($discussionentity)) {
1078     // Show the discussion name in the breadcrumbs.
1079     $strdiscussionname = format_string($discussionentity->get_name()) . ': ';
1082 $forcefocus = empty($reply) ? null : 'message';
1084 if (!empty($discussion->id)) {
1085     $PAGE->navbar->add($titlesubject, $urlfactory->get_discussion_view_url_from_discussion($discussionentity));
1088 if ($post->parent) {
1089     $PAGE->navbar->add(get_string('reply', 'forum'));
1092 if ($edit) {
1093     $PAGE->navbar->add(get_string('edit', 'forum'));
1096 $PAGE->set_title("{$course->shortname}: {$strdiscussionname}{$titlesubject}");
1097 $PAGE->set_heading($course->fullname);
1099 echo $OUTPUT->header();
1100 echo $OUTPUT->heading(format_string($forum->name), 2);
1102 // Checkup.
1103 if (!empty($parententity) && !$capabilitymanager->can_view_post($USER, $discussionentity, $parententity)) {
1104     print_error('cannotreply', 'forum');
1107 if (empty($parententity) && empty($edit) && !$capabilitymanager->can_create_discussions($USER, $groupid)) {
1108     print_error('cannotcreatediscussion', 'forum');
1111 if (!empty($discussionentity) && 'qanda' == $forumentity->get_type()) {
1112     $displaywarning = $capabilitymanager->must_post_before_viewing_discussion($USER, $discussionentity);
1113     $displaywarning = $displaywarning && !forum_user_has_posted($forumentity->get_id(), $discussionentity->get_id(), $USER->id);
1114     if ($displaywarning) {
1115         echo $OUTPUT->notification(get_string('qandanotify', 'forum'));
1116     }
1119 // If there is a warning message and we are not editing a post we need to handle the warning.
1120 if (!empty($thresholdwarning) && !$edit) {
1121     // Here we want to throw an exception if they are no longer allowed to post.
1122     forum_check_blocking_threshold($thresholdwarning);
1125 if (!empty($parententity)) {
1126     $postentities = [$parententity];
1128     if (empty($post->edit)) {
1129         if ('qanda' != $forumentity->get_type() || forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
1130             $replies = $postvault->get_replies_to_post(
1131                     $USER,
1132                     $parententity,
1133                     $capabilitymanager->can_view_any_private_reply($USER),
1134                     'created ASC'
1135                 );
1136             $postentities = array_merge($postentities, $replies);
1137         }
1138     }
1140     $rendererfactory = mod_forum\local\container::get_renderer_factory();
1141     $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(FORUM_MODE_THREADED, true);
1142     echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], $postentities);
1143 } else {
1144     if (!empty($forum->intro)) {
1145         echo $OUTPUT->box(format_module_intro('forum', $forum, $cm->id), 'generalbox', 'intro');
1146     }
1149 // Call print disclosure for enabled plagiarism plugins.
1150 if (!empty($CFG->enableplagiarism)) {
1151     require_once($CFG->libdir.'/plagiarismlib.php');
1152     echo plagiarism_print_disclosure($cm->id);
1155 if (!empty($formheading)) {
1156     echo $OUTPUT->heading($formheading, 2, array('class' => 'accesshide'));
1159 if (!empty($postentity)) {
1160     $data = (object) [
1161         'tags' => core_tag_tag::get_item_tags_array('mod_forum', 'forum_posts', $postentity->get_id())
1162     ];
1163     $mformpost->set_data($data);
1166 $mformpost->display();
1168 echo $OUTPUT->footer();