MDL-65069 mod_forum: Stripped out inpage form and advanced redirect
[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);
724 $manageactivities = has_capability('moodle/course:manageactivities', $coursecontext);
725 if (\mod_forum\subscriptions::subscription_disabled($forum) && !$manageactivities) {
726     // User does not have permission to subscribe to this discussion at all.
727     $discussionsubscribe = false;
728 } else if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
729     // User does not have permission to unsubscribe from this discussion at all.
730     $discussionsubscribe = true;
731 } else {
732     if (isset($discussion) && \mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussion->id, $cm)) {
733         // User is subscribed to the discussion - continue the subscription.
734         $discussionsubscribe = true;
735     } else if (!isset($discussion) && \mod_forum\subscriptions::is_subscribed($USER->id, $forum, null, $cm)) {
736         // Starting a new discussion, and the user is subscribed to the forum - subscribe to the discussion.
737         $discussionsubscribe = true;
738     } else {
739         // User is not subscribed to either forum or discussion. Follow user preference.
740         $discussionsubscribe = $USER->autosubscribe;
741     }
744 $mformpost->set_data(
745     array(
746         'attachments' => $draftitemid,
747         'general' => $heading,
748         'subject' => $post->subject,
749         'message' => array(
750             'text' => $currenttext,
751             'format' => empty($post->messageformat) ? editors_get_preferred_format() : $post->messageformat,
752             'itemid' => $draftideditor
753         ),
754         'discussionsubscribe' => $discussionsubscribe,
755         'mailnow' => !empty($post->mailnow),
756         'userid' => $post->userid,
757         'parent' => $post->parent,
758         'discussion' => $post->discussion,
759         'course' => $course->id
760     ) +
762     $pageparams +
764     (isset($post->format) ? array('format' => $post->format) : array()) +
766     (isset($discussion->timestart) ? array('timestart' => $discussion->timestart) : array()) +
768     (isset($discussion->timeend) ? array('timeend' => $discussion->timeend) : array()) +
770     (isset($discussion->pinned) ? array('pinned' => $discussion->pinned) : array()) +
772     (isset($post->groupid) ? array('groupid' => $post->groupid) : array()) +
774     (isset($discussion->id) ? array('discussion' => $discussion->id) : array())
775 );
777 if ($mformpost->is_cancelled()) {
778     if (!isset($discussion->id) || $forum->type === 'single') {
779         // Single forums don't have a discussion page.
780         redirect($urlfactory->get_forum_view_url_from_forum($forumentity));
781     } else {
782         redirect($urlfactory->get_discussion_view_url_from_discussion($discussionentity));
783     }
784 } else if ($mformpost->is_submitted() && !$mformpost->no_submit_button_pressed()) {
786     if (empty($SESSION->fromurl)) {
787         $errordestination = $urlfactory->get_forum_view_url_from_forum($forumentity);
788     } else {
789         $errordestination = $SESSION->fromurl;
790     }
791     $fromform = $mformpost->get_data();
792     $fromform->itemid        = $fromform->message['itemid'];
793     $fromform->messageformat = $fromform->message['format'];
794     $fromform->message       = $fromform->message['text'];
795     // WARNING: the $fromform->message array has been overwritten, do not use it anymore!
796     $fromform->messagetrust  = trusttext_trusted($modcontext);
798     // Clean message text.
799     $fromform = trusttext_pre_edit($fromform, 'message', $modcontext);
801     if ($fromform->edit) {
802         // Updating a post.
803         unset($fromform->groupid);
804         $fromform->id = $fromform->edit;
805         $message = '';
807         if (!$capabilitymanager->can_edit_post($USER, $discussionentity, $postentity)) {
808             redirect(
809                     $urlfactory->get_view_post_url_from_post($postentity),
810                     get_string('cannotupdatepost', 'forum'),
811                     null,
812                     \core\output\notification::ERROR
813                 );
814         }
816         if (isset($fromform->groupinfo) && $capabilitymanager->can_move_discussions($USER)) {
817             // If the user has access to all groups and they are changing the group, then update the post.
818             if (empty($fromform->groupinfo)) {
819                 $fromform->groupinfo = -1;
820             }
822             if (!$capabilitymanager->can_create_discussions($USER, $fromform->groupinfo)) {
823                 redirect(
824                         $urlfactory->get_view_post_url_from_post($postentity),
825                         get_string('cannotupdatepost', 'forum'),
826                         null,
827                         \core\output\notification::ERROR
828                     );
829             }
831             if ($discussionentity->get_group_id() != $fromform->groupinfo) {
832                 $DB->set_field('forum_discussions', 'groupid', $fromform->groupinfo, array('firstpost' => $fromform->id));
833             }
834         }
836         // When editing first post/discussion.
837         if ($postentity->has_parent()) {
838             if ($capabilitymanager->can_pin_discussions($USER)) {
839                 // Can change pinned if we have capability.
840                 $fromform->pinned = !empty($fromform->pinned) ? FORUM_DISCUSSION_PINNED : FORUM_DISCUSSION_UNPINNED;
841             } else {
842                 // We don't have the capability to change so keep to previous value.
843                 unset($fromform->pinned);
844             }
845         }
846         $updatepost = $fromform;
847         $updatepost->forum = $forum->id;
848         if (!forum_update_post($updatepost, $mformpost)) {
849             print_error("couldnotupdate", "forum", $errordestination);
850         }
852         if ('single' == $forumentity->get_type() && !$postentity->has_parent()) {
853             // Updating first post of single discussion type -> updating forum intro.
854             $forum->intro = $updatepost->message;
855             $forum->timemodified = time();
856             $DB->update_record("forum", $forum);
857         }
859         if ($USER->id === $postentity->get_author_id()) {
860             $message .= get_string("postupdated", "forum");
861         } else {
862             $realuser = \core_user::get_user($postentity->get_author_id());
863             $message .= get_string("editedpostupdated", "forum", fullname($realuser));
864         }
866         $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
867         if ('single' == $forumentity->get_type()) {
868             // Single discussion forums are an exception.
869             // We show the forum itself since it only has one discussion thread.
870             $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
871         } else {
872             $discussionurl = $urlfactory->get_view_post_url_from_post($postentity);
873         }
875         $params = array(
876             'context' => $modcontext,
877             'objectid' => $fromform->id,
878             'other' => array(
879                 'discussionid' => $discussion->id,
880                 'forumid' => $forum->id,
881                 'forumtype' => $forum->type,
882             )
883         );
885         if ($USER->id !== $postentity->get_author_id()) {
886             $params['relateduserid'] = $postentity->get_author_id();
887         }
889         $event = \mod_forum\event\post_updated::create($params);
890         $event->add_record_snapshot('forum_discussions', $discussion);
891         $event->trigger();
893         redirect(
894             forum_go_back_to($discussionurl),
895             $message . $subscribemessage,
896             null,
897             \core\output\notification::NOTIFY_SUCCESS
898         );
900     } else if ($fromform->discussion) {
901         // Adding a new post to an existing discussion
902         // Before we add this we must check that the user will not exceed the blocking threshold.
903         forum_check_blocking_threshold($thresholdwarning);
905         unset($fromform->groupid);
906         $message = '';
907         $addpost = $fromform;
908         $addpost->forum = $forum->id;
909         if ($fromform->id = forum_add_new_post($addpost, $mformpost)) {
910             $postentity = $postvault->get_from_id($fromform->id);
911             $fromform->deleted = 0;
912             $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
914             if (!empty($fromform->mailnow)) {
915                 $message .= get_string("postmailnow", "forum");
916             } else {
917                 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
918                 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
919             }
921             if ($forum->type == 'single') {
922                 // Single discussion forums are an exception.
923                 // We show the forum itself since it only has one discussion thread.
924                 $discussionurl = $urlfactory->get_forum_view_url_from_forum($forumentity);
925             } else {
926                 $discussionurl = $urlfactory->get_view_post_url_from_post($postentity);
927             }
929             $params = array(
930                 'context' => $modcontext,
931                 'objectid' => $fromform->id,
932                 'other' => array(
933                     'discussionid' => $discussion->id,
934                     'forumid' => $forum->id,
935                     'forumtype' => $forum->type,
936                 )
937             );
938             $event = \mod_forum\event\post_created::create($params);
939             $event->add_record_snapshot('forum_posts', $fromform);
940             $event->add_record_snapshot('forum_discussions', $discussion);
941             $event->trigger();
943             // Update completion state.
944             $completion = new completion_info($course);
945             if ($completion->is_enabled($cm) &&
946                 ($forum->completionreplies || $forum->completionposts)) {
947                 $completion->update_state($cm, COMPLETION_COMPLETE);
948             }
950             redirect(
951                 forum_go_back_to($discussionurl),
952                 $message . $subscribemessage,
953                 null,
954                 \core\output\notification::NOTIFY_SUCCESS
955             );
957         } else {
958             print_error("couldnotadd", "forum", $errordestination);
959         }
960         exit;
962     } else {
963         // Adding a new discussion.
964         // The location to redirect to after successfully posting.
965         $redirectto = new moodle_url('/mod/forum/view.php', array('f' => $fromform->forum));
967         $fromform->mailnow = empty($fromform->mailnow) ? 0 : 1;
969         $discussion = $fromform;
970         $discussion->name = $fromform->subject;
972         $newstopic = false;
973         if ($forum->type == 'news' && !$fromform->parent) {
974             $newstopic = true;
975         }
976         $discussion->timestart = $fromform->timestart;
977         $discussion->timeend = $fromform->timeend;
978         $discussion->pinned = FORUM_DISCUSSION_UNPINNED;
980         if (!empty($fromform->pinned) && $capabilitymanager->can_pin_discussions($USER)) {
981             $discussion->pinned = FORUM_DISCUSSION_PINNED;
982         }
984         $allowedgroups = array();
985         $groupstopostto = array();
987         // If we are posting a copy to all groups the user has access to.
988         if (isset($fromform->posttomygroups)) {
989             // Post to each of my groups.
990             require_capability('mod/forum:canposttomygroups', $modcontext);
992             // Fetch all of this user's groups.
993             // Note: all groups are returned when in visible groups mode so we must manually filter.
994             $allowedgroups = groups_get_activity_allowed_groups($cm);
995             foreach ($allowedgroups as $groupid => $group) {
996                 if ($capabilitymanager->can_create_discussions($USER, $groupid)) {
997                     $groupstopostto[] = $groupid;
998                 }
999             }
1000         } else if (isset($fromform->groupinfo)) {
1001             // Use the value provided in the dropdown group selection.
1002             $groupstopostto[] = $fromform->groupinfo;
1003             $redirectto->param('group', $fromform->groupinfo);
1004         } else if (isset($fromform->groupid) && !empty($fromform->groupid)) {
1005             // Use the value provided in the hidden form element instead.
1006             $groupstopostto[] = $fromform->groupid;
1007             $redirectto->param('group', $fromform->groupid);
1008         } else {
1009             // Use the value for all participants instead.
1010             $groupstopostto[] = -1;
1011         }
1013         // Before we post this we must check that the user will not exceed the blocking threshold.
1014         forum_check_blocking_threshold($thresholdwarning);
1016         foreach ($groupstopostto as $group) {
1017             if (!$capabilitymanager->can_create_discussions($USER, $groupid)) {
1018                 print_error('cannotcreatediscussion', 'forum');
1019             }
1021             $discussion->groupid = $group;
1022             $message = '';
1023             if ($discussion->id = forum_add_discussion($discussion, $mformpost)) {
1025                 $params = array(
1026                     'context' => $modcontext,
1027                     'objectid' => $discussion->id,
1028                     'other' => array(
1029                         'forumid' => $forum->id,
1030                     )
1031                 );
1032                 $event = \mod_forum\event\discussion_created::create($params);
1033                 $event->add_record_snapshot('forum_discussions', $discussion);
1034                 $event->trigger();
1036                 if ($fromform->mailnow) {
1037                     $message .= get_string("postmailnow", "forum");
1038                 } else {
1039                     $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
1040                     $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
1041                 }
1043                 $subscribemessage = forum_post_subscription($fromform, $forum, $discussion);
1044             } else {
1045                 print_error("couldnotadd", "forum", $errordestination);
1046             }
1047         }
1049         // Update completion status.
1050         $completion = new completion_info($course);
1051         if ($completion->is_enabled($cm) &&
1052             ($forum->completiondiscussions || $forum->completionposts)) {
1053             $completion->update_state($cm, COMPLETION_COMPLETE);
1054         }
1056         // Redirect back to the discussion.
1057         redirect(
1058             forum_go_back_to($redirectto->out()),
1059             $message . $subscribemessage,
1060             null,
1061             \core\output\notification::NOTIFY_SUCCESS
1062         );
1063     }
1067 // This section is only shown after all checks are in place, and the forumentity and any relevant discussion and post
1068 // entity are available.
1070 if (!empty($discussionentity)) {
1071     $titlesubject = format_string($discussionentity->get_name(), true);
1072 } else if ('news' == $forumentity->get_type()) {
1073     $titlesubject = get_string("addanewtopic", "forum");
1074 } else {
1075     $titlesubject = get_string("addanewdiscussion", "forum");
1078 if (empty($post->edit)) {
1079     $post->edit = '';
1082 if (empty($discussion->name)) {
1083     if (empty($discussion)) {
1084         $discussion = new stdClass();
1085     }
1086     $discussion->name = $forum->name;
1089 $strdiscussionname = '';
1090 if ('single' == $forumentity->get_type()) {
1091     // There is only one discussion thread for this forum type. We should
1092     // not show the discussion name (same as forum name in this case) in
1093     // the breadcrumbs.
1094     $strdiscussionname = '';
1095 } else if (!empty($discussionentity)) {
1096     // Show the discussion name in the breadcrumbs.
1097     $strdiscussionname = format_string($discussionentity->get_name()) . ': ';
1100 $forcefocus = empty($reply) ? null : 'message';
1102 if (!empty($discussion->id)) {
1103     $PAGE->navbar->add($titlesubject, $urlfactory->get_discussion_view_url_from_discussion($discussionentity));
1106 if ($post->parent) {
1107     $PAGE->navbar->add(get_string('reply', 'forum'));
1110 if ($edit) {
1111     $PAGE->navbar->add(get_string('edit', 'forum'));
1114 $PAGE->set_title("{$course->shortname}: {$strdiscussionname}{$titlesubject}");
1115 $PAGE->set_heading($course->fullname);
1117 echo $OUTPUT->header();
1118 echo $OUTPUT->heading(format_string($forum->name), 2);
1120 // Checkup.
1121 if (!empty($parententity) && !$capabilitymanager->can_view_post($USER, $discussionentity, $parententity)) {
1122     print_error('cannotreply', 'forum');
1125 if (empty($parententity) && empty($edit) && !$capabilitymanager->can_create_discussions($USER, $groupid)) {
1126     print_error('cannotcreatediscussion', 'forum');
1129 if (!empty($discussionentity) && 'qanda' == $forumentity->get_type()) {
1130     $displaywarning = $capabilitymanager->must_post_before_viewing_discussion($USER, $discussionentity);
1131     $displaywarning = $displaywarning && !forum_user_has_posted($forumentity->get_id(), $discussionentity->get_id(), $USER->id);
1132     if ($displaywarning) {
1133         echo $OUTPUT->notification(get_string('qandanotify', 'forum'));
1134     }
1137 // If there is a warning message and we are not editing a post we need to handle the warning.
1138 if (!empty($thresholdwarning) && !$edit) {
1139     // Here we want to throw an exception if they are no longer allowed to post.
1140     forum_check_blocking_threshold($thresholdwarning);
1143 if (!empty($parententity)) {
1144     $postentities = [$parententity];
1146     if (empty($post->edit)) {
1147         if ('qanda' != $forumentity->get_type() || forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
1148             $replies = $postvault->get_replies_to_post(
1149                     $USER,
1150                     $parententity,
1151                     $capabilitymanager->can_view_any_private_reply($USER),
1152                     'created ASC'
1153                 );
1154             $postentities = array_merge($postentities, $replies);
1155         }
1156     }
1158     $rendererfactory = mod_forum\local\container::get_renderer_factory();
1159     $postsrenderer = $rendererfactory->get_single_discussion_posts_renderer(FORUM_MODE_THREADED, true);
1160     echo $postsrenderer->render($USER, [$forumentity], [$discussionentity], $postentities);
1161 } else {
1162     if (!empty($forum->intro)) {
1163         echo $OUTPUT->box(format_module_intro('forum', $forum, $cm->id), 'generalbox', 'intro');
1164     }
1167 // Call print disclosure for enabled plagiarism plugins.
1168 if (!empty($CFG->enableplagiarism)) {
1169     require_once($CFG->libdir.'/plagiarismlib.php');
1170     echo plagiarism_print_disclosure($cm->id);
1173 if (!empty($formheading)) {
1174     echo $OUTPUT->heading($formheading, 2, array('class' => 'accesshide'));
1177 if (!empty($postentity)) {
1178     $data = (object) [
1179         'tags' => core_tag_tag::get_item_tags_array('mod_forum', 'forum_posts', $postentity->get_id())
1180     ];
1181     $mformpost->set_data($data);
1184 $mformpost->display();
1186 echo $OUTPUT->footer();