MDL-40062 mod_forum: discussion events
[moodle.git] / mod / forum / post.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Edit and save a new post to a discussion
20  *
21  * @package mod-forum
22  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
23  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 require_once('../../config.php');
27 require_once('lib.php');
28 require_once($CFG->libdir.'/completionlib.php');
30 $reply   = optional_param('reply', 0, PARAM_INT);
31 $forum   = optional_param('forum', 0, PARAM_INT);
32 $edit    = optional_param('edit', 0, PARAM_INT);
33 $delete  = optional_param('delete', 0, PARAM_INT);
34 $prune   = optional_param('prune', 0, PARAM_INT);
35 $name    = optional_param('name', '', PARAM_CLEAN);
36 $confirm = optional_param('confirm', 0, PARAM_INT);
37 $groupid = optional_param('groupid', null, PARAM_INT);
39 $PAGE->set_url('/mod/forum/post.php', array(
40         'reply' => $reply,
41         'forum' => $forum,
42         'edit'  => $edit,
43         'delete'=> $delete,
44         'prune' => $prune,
45         'name'  => $name,
46         'confirm'=>$confirm,
47         'groupid'=>$groupid,
48         ));
49 //these page_params will be passed as hidden variables later in the form.
50 $page_params = array('reply'=>$reply, 'forum'=>$forum, 'edit'=>$edit);
52 $sitecontext = context_system::instance();
54 if (!isloggedin() or isguestuser()) {
56     if (!isloggedin() and !get_referer()) {
57         // No referer+not logged in - probably coming in via email  See MDL-9052
58         require_login();
59     }
61     if (!empty($forum)) {      // User is starting a new discussion in a forum
62         if (! $forum = $DB->get_record('forum', array('id' => $forum))) {
63             print_error('invalidforumid', 'forum');
64         }
65     } else if (!empty($reply)) {      // User is writing a new reply
66         if (! $parent = forum_get_post_full($reply)) {
67             print_error('invalidparentpostid', 'forum');
68         }
69         if (! $discussion = $DB->get_record('forum_discussions', array('id' => $parent->discussion))) {
70             print_error('notpartofdiscussion', 'forum');
71         }
72         if (! $forum = $DB->get_record('forum', array('id' => $discussion->forum))) {
73             print_error('invalidforumid');
74         }
75     }
76     if (! $course = $DB->get_record('course', array('id' => $forum->course))) {
77         print_error('invalidcourseid');
78     }
80     if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) { // For the logs
81         print_error('invalidcoursemodule');
82     } else {
83         $modcontext = context_module::instance($cm->id);
84     }
86     $PAGE->set_cm($cm, $course, $forum);
87     $PAGE->set_context($modcontext);
88     $PAGE->set_title($course->shortname);
89     $PAGE->set_heading($course->fullname);
91     echo $OUTPUT->header();
92     echo $OUTPUT->confirm(get_string('noguestpost', 'forum').'<br /><br />'.get_string('liketologin'), get_login_url(), get_referer(false));
93     echo $OUTPUT->footer();
94     exit;
95 }
97 require_login(0, false);   // Script is useless unless they're logged in
99 if (!empty($forum)) {      // User is starting a new discussion in a forum
100     if (! $forum = $DB->get_record("forum", array("id" => $forum))) {
101         print_error('invalidforumid', 'forum');
102     }
103     if (! $course = $DB->get_record("course", array("id" => $forum->course))) {
104         print_error('invalidcourseid');
105     }
106     if (! $cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
107         print_error("invalidcoursemodule");
108     }
110     $coursecontext = context_course::instance($course->id);
112     if (! forum_user_can_post_discussion($forum, $groupid, -1, $cm)) {
113         if (!isguestuser()) {
114             if (!is_enrolled($coursecontext)) {
115                 if (enrol_selfenrol_available($course->id)) {
116                     $SESSION->wantsurl = qualified_me();
117                     $SESSION->enrolcancel = $_SERVER['HTTP_REFERER'];
118                     redirect($CFG->wwwroot.'/enrol/index.php?id='.$course->id, get_string('youneedtoenrol'));
119                 }
120             }
121         }
122         print_error('nopostforum', 'forum');
123     }
125     if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $coursecontext)) {
126         print_error("activityiscurrentlyhidden");
127     }
129     if (isset($_SERVER["HTTP_REFERER"])) {
130         $SESSION->fromurl = $_SERVER["HTTP_REFERER"];
131     } else {
132         $SESSION->fromurl = '';
133     }
136     // Load up the $post variable.
138     $post = new stdClass();
139     $post->course        = $course->id;
140     $post->forum         = $forum->id;
141     $post->discussion    = 0;           // ie discussion # not defined yet
142     $post->parent        = 0;
143     $post->subject       = '';
144     $post->userid        = $USER->id;
145     $post->message       = '';
146     $post->messageformat = editors_get_preferred_format();
147     $post->messagetrust  = 0;
149     if (isset($groupid)) {
150         $post->groupid = $groupid;
151     } else {
152         $post->groupid = groups_get_activity_group($cm);
153     }
155     // Unsetting this will allow the correct return URL to be calculated later.
156     unset($SESSION->fromdiscussion);
158 } else if (!empty($reply)) {      // User is writing a new reply
160     if (! $parent = forum_get_post_full($reply)) {
161         print_error('invalidparentpostid', 'forum');
162     }
163     if (! $discussion = $DB->get_record("forum_discussions", array("id" => $parent->discussion))) {
164         print_error('notpartofdiscussion', 'forum');
165     }
166     if (! $forum = $DB->get_record("forum", array("id" => $discussion->forum))) {
167         print_error('invalidforumid', 'forum');
168     }
169     if (! $course = $DB->get_record("course", array("id" => $discussion->course))) {
170         print_error('invalidcourseid');
171     }
172     if (! $cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
173         print_error('invalidcoursemodule');
174     }
176     // Ensure lang, theme, etc. is set up properly. MDL-6926
177     $PAGE->set_cm($cm, $course, $forum);
179     $coursecontext = context_course::instance($course->id);
180     $modcontext    = context_module::instance($cm->id);
182     if (! forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
183         if (!isguestuser()) {
184             if (!is_enrolled($coursecontext)) {  // User is a guest here!
185                 $SESSION->wantsurl = qualified_me();
186                 $SESSION->enrolcancel = $_SERVER['HTTP_REFERER'];
187                 redirect($CFG->wwwroot.'/enrol/index.php?id='.$course->id, get_string('youneedtoenrol'));
188             }
189         }
190         print_error('nopostforum', 'forum');
191     }
193     // Make sure user can post here
194     if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
195         $groupmode =  $cm->groupmode;
196     } else {
197         $groupmode = $course->groupmode;
198     }
199     if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
200         if ($discussion->groupid == -1) {
201             print_error('nopostforum', 'forum');
202         } else {
203             if (!groups_is_member($discussion->groupid)) {
204                 print_error('nopostforum', 'forum');
205             }
206         }
207     }
209     if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $coursecontext)) {
210         print_error("activityiscurrentlyhidden");
211     }
213     // Load up the $post variable.
215     $post = new stdClass();
216     $post->course      = $course->id;
217     $post->forum       = $forum->id;
218     $post->discussion  = $parent->discussion;
219     $post->parent      = $parent->id;
220     $post->subject     = $parent->subject;
221     $post->userid      = $USER->id;
222     $post->message     = '';
224     $post->groupid = ($discussion->groupid == -1) ? 0 : $discussion->groupid;
226     $strre = get_string('re', 'forum');
227     if (!(substr($post->subject, 0, strlen($strre)) == $strre)) {
228         $post->subject = $strre.' '.$post->subject;
229     }
231     // Unsetting this will allow the correct return URL to be calculated later.
232     unset($SESSION->fromdiscussion);
234 } else if (!empty($edit)) {  // User is editing their own post
236     if (! $post = forum_get_post_full($edit)) {
237         print_error('invalidpostid', 'forum');
238     }
239     if ($post->parent) {
240         if (! $parent = forum_get_post_full($post->parent)) {
241             print_error('invalidparentpostid', 'forum');
242         }
243     }
245     if (! $discussion = $DB->get_record("forum_discussions", array("id" => $post->discussion))) {
246         print_error('notpartofdiscussion', 'forum');
247     }
248     if (! $forum = $DB->get_record("forum", array("id" => $discussion->forum))) {
249         print_error('invalidforumid', 'forum');
250     }
251     if (! $course = $DB->get_record("course", array("id" => $discussion->course))) {
252         print_error('invalidcourseid');
253     }
254     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
255         print_error('invalidcoursemodule');
256     } else {
257         $modcontext = context_module::instance($cm->id);
258     }
260     $PAGE->set_cm($cm, $course, $forum);
262     if (!($forum->type == 'news' && !$post->parent && $discussion->timestart > time())) {
263         if (((time() - $post->created) > $CFG->maxeditingtime) and
264                     !has_capability('mod/forum:editanypost', $modcontext)) {
265             print_error('maxtimehaspassed', 'forum', '', format_time($CFG->maxeditingtime));
266         }
267     }
268     if (($post->userid <> $USER->id) and
269                 !has_capability('mod/forum:editanypost', $modcontext)) {
270         print_error('cannoteditposts', 'forum');
271     }
274     // Load up the $post variable.
275     $post->edit   = $edit;
276     $post->course = $course->id;
277     $post->forum  = $forum->id;
278     $post->groupid = ($discussion->groupid == -1) ? 0 : $discussion->groupid;
280     $post = trusttext_pre_edit($post, 'message', $modcontext);
282     // Unsetting this will allow the correct return URL to be calculated later.
283     unset($SESSION->fromdiscussion);
285 }else if (!empty($delete)) {  // User is deleting a post
287     if (! $post = forum_get_post_full($delete)) {
288         print_error('invalidpostid', 'forum');
289     }
290     if (! $discussion = $DB->get_record("forum_discussions", array("id" => $post->discussion))) {
291         print_error('notpartofdiscussion', 'forum');
292     }
293     if (! $forum = $DB->get_record("forum", array("id" => $discussion->forum))) {
294         print_error('invalidforumid', 'forum');
295     }
296     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $forum->course)) {
297         print_error('invalidcoursemodule');
298     }
299     if (!$course = $DB->get_record('course', array('id' => $forum->course))) {
300         print_error('invalidcourseid');
301     }
303     require_login($course, false, $cm);
304     $modcontext = context_module::instance($cm->id);
306     if ( !(($post->userid == $USER->id && has_capability('mod/forum:deleteownpost', $modcontext))
307                 || has_capability('mod/forum:deleteanypost', $modcontext)) ) {
308         print_error('cannotdeletepost', 'forum');
309     }
312     $replycount = forum_count_replies($post);
314     if (!empty($confirm) && confirm_sesskey()) {    // User has confirmed the delete
315         //check user capability to delete post.
316         $timepassed = time() - $post->created;
317         if (($timepassed > $CFG->maxeditingtime) && !has_capability('mod/forum:deleteanypost', $modcontext)) {
318             print_error("cannotdeletepost", "forum",
319                       forum_go_back_to("discuss.php?d=$post->discussion"));
320         }
322         if ($post->totalscore) {
323             notice(get_string('couldnotdeleteratings', 'rating'),
324                     forum_go_back_to("discuss.php?d=$post->discussion"));
326         } else if ($replycount && !has_capability('mod/forum:deleteanypost', $modcontext)) {
327             print_error("couldnotdeletereplies", "forum",
328                     forum_go_back_to("discuss.php?d=$post->discussion"));
330         } else {
331             if (! $post->parent) {  // post is a discussion topic as well, so delete discussion
332                 if ($forum->type == 'single') {
333                     notice("Sorry, but you are not allowed to delete that discussion!",
334                             forum_go_back_to("discuss.php?d=$post->discussion"));
335                 }
336                 forum_delete_discussion($discussion, false, $course, $cm, $forum);
338                 $params = array(
339                     'objectid' => $discussion->id,
340                     'context' => $modcontext,
341                     'other' => array(
342                         'forumid' => $forum->id,
343                     )
344                 );
346                 $event = \mod_forum\event\discussion_deleted::create($params);
347                 $event->add_record_snapshot('forum_discussions', $discussion);
348                 $event->trigger();
350                 redirect("view.php?f=$discussion->forum");
352             } else if (forum_delete_post($post, has_capability('mod/forum:deleteanypost', $modcontext),
353                 $course, $cm, $forum)) {
355                 if ($forum->type == 'single') {
356                     // Single discussion forums are an exception. We show
357                     // the forum itself since it only has one discussion
358                     // thread.
359                     $discussionurl = "view.php?f=$forum->id";
360                 } else {
361                     $discussionurl = "discuss.php?d=$post->discussion";
362                 }
364                 add_to_log($discussion->course, "forum", "delete post", $discussionurl, "$post->id", $cm->id);
366                 redirect(forum_go_back_to($discussionurl));
367             } else {
368                 print_error('errorwhiledelete', 'forum');
369             }
370         }
373     } else { // User just asked to delete something
375         forum_set_return();
376         $PAGE->navbar->add(get_string('delete', 'forum'));
377         $PAGE->set_title($course->shortname);
378         $PAGE->set_heading($course->fullname);
380         if ($replycount) {
381             if (!has_capability('mod/forum:deleteanypost', $modcontext)) {
382                 print_error("couldnotdeletereplies", "forum",
383                       forum_go_back_to("discuss.php?d=$post->discussion"));
384             }
385             echo $OUTPUT->header();
386             echo $OUTPUT->heading(format_string($forum->name), 2);
387             echo $OUTPUT->confirm(get_string("deletesureplural", "forum", $replycount+1),
388                          "post.php?delete=$delete&confirm=$delete",
389                          $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
391             forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
393             if (empty($post->edit)) {
394                 $forumtracked = forum_tp_is_tracked($forum);
395                 $posts = forum_get_all_discussion_posts($discussion->id, "created ASC", $forumtracked);
396                 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, false, false, $forumtracked, $posts);
397             }
398         } else {
399             echo $OUTPUT->header();
400             echo $OUTPUT->heading(format_string($forum->name), 2);
401             echo $OUTPUT->confirm(get_string("deletesure", "forum", $replycount),
402                          "post.php?delete=$delete&confirm=$delete",
403                          $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
404             forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
405         }
407     }
408     echo $OUTPUT->footer();
409     die;
412 } else if (!empty($prune)) {  // Pruning
414     if (!$post = forum_get_post_full($prune)) {
415         print_error('invalidpostid', 'forum');
416     }
417     if (!$discussion = $DB->get_record("forum_discussions", array("id" => $post->discussion))) {
418         print_error('notpartofdiscussion', 'forum');
419     }
420     if (!$forum = $DB->get_record("forum", array("id" => $discussion->forum))) {
421         print_error('invalidforumid', 'forum');
422     }
423     if ($forum->type == 'single') {
424         print_error('cannotsplit', 'forum');
425     }
426     if (!$post->parent) {
427         print_error('alreadyfirstpost', 'forum');
428     }
429     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $forum->course)) { // For the logs
430         print_error('invalidcoursemodule');
431     } else {
432         $modcontext = context_module::instance($cm->id);
433     }
434     if (!has_capability('mod/forum:splitdiscussions', $modcontext)) {
435         print_error('cannotsplit', 'forum');
436     }
438     if (!empty($name) && confirm_sesskey()) {    // User has confirmed the prune
440         $newdiscussion = new stdClass();
441         $newdiscussion->course       = $discussion->course;
442         $newdiscussion->forum        = $discussion->forum;
443         $newdiscussion->name         = $name;
444         $newdiscussion->firstpost    = $post->id;
445         $newdiscussion->userid       = $discussion->userid;
446         $newdiscussion->groupid      = $discussion->groupid;
447         $newdiscussion->assessed     = $discussion->assessed;
448         $newdiscussion->usermodified = $post->userid;
449         $newdiscussion->timestart    = $discussion->timestart;
450         $newdiscussion->timeend      = $discussion->timeend;
452         $newid = $DB->insert_record('forum_discussions', $newdiscussion);
454         $newpost = new stdClass();
455         $newpost->id      = $post->id;
456         $newpost->parent  = 0;
457         $newpost->subject = $name;
459         $DB->update_record("forum_posts", $newpost);
461         forum_change_discussionid($post->id, $newid);
463         // update last post in each discussion
464         forum_discussion_update_last_post($discussion->id);
465         forum_discussion_update_last_post($newid);
467         add_to_log($discussion->course, "forum", "prune post",
468                        "discuss.php?d=$newid", "$post->id", $cm->id);
470         redirect(forum_go_back_to("discuss.php?d=$newid"));
472     } else { // User just asked to prune something
474         $course = $DB->get_record('course', array('id' => $forum->course));
476         $PAGE->set_cm($cm);
477         $PAGE->set_context($modcontext);
478         $PAGE->navbar->add(format_string($post->subject, true), new moodle_url('/mod/forum/discuss.php', array('d'=>$discussion->id)));
479         $PAGE->navbar->add(get_string("prune", "forum"));
480         $PAGE->set_title(format_string($discussion->name).": ".format_string($post->subject));
481         $PAGE->set_heading($course->fullname);
482         echo $OUTPUT->header();
483         echo $OUTPUT->heading(format_string($forum->name), 2);
484         echo $OUTPUT->heading(get_string('pruneheading', 'forum'), 3);
485         echo '<center>';
487         include('prune.html');
489         forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
490         echo '</center>';
491     }
492     echo $OUTPUT->footer();
493     die;
494 } else {
495     print_error('unknowaction');
499 if (!isset($coursecontext)) {
500     // Has not yet been set by post.php.
501     $coursecontext = context_course::instance($forum->course);
505 // from now on user must be logged on properly
507 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) { // For the logs
508     print_error('invalidcoursemodule');
510 $modcontext = context_module::instance($cm->id);
511 require_login($course, false, $cm);
513 if (isguestuser()) {
514     // just in case
515     print_error('noguest');
518 if (!isset($forum->maxattachments)) {  // TODO - delete this once we add a field to the forum table
519     $forum->maxattachments = 3;
522 $thresholdwarning = forum_check_throttling($forum, $cm);
523 $mform_post = new mod_forum_post_form('post.php', array('course' => $course,
524                                                         'cm' => $cm,
525                                                         'coursecontext' => $coursecontext,
526                                                         'modcontext' => $modcontext,
527                                                         'forum' => $forum,
528                                                         'post' => $post,
529                                                         'thresholdwarning' => $thresholdwarning,
530                                                         'edit' => $edit), 'post', '', array('id' => 'mformforum'));
532 $draftitemid = file_get_submitted_draft_itemid('attachments');
533 file_prepare_draft_area($draftitemid, $modcontext->id, 'mod_forum', 'attachment', empty($post->id)?null:$post->id, mod_forum_post_form::attachment_options($forum));
535 //load data into form NOW!
537 if ($USER->id != $post->userid) {   // Not the original author, so add a message to the end
538     $data = new stdClass();
539     $data->date = userdate($post->modified);
540     if ($post->messageformat == FORMAT_HTML) {
541         $data->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'&course='.$post->course.'">'.
542                        fullname($USER).'</a>';
543         $post->message .= '<p><span class="edited">('.get_string('editedby', 'forum', $data).')</span></p>';
544     } else {
545         $data->name = fullname($USER);
546         $post->message .= "\n\n(".get_string('editedby', 'forum', $data).')';
547     }
548     unset($data);
551 $formheading = '';
552 if (!empty($parent)) {
553     $heading = get_string("yourreply", "forum");
554     $formheading = get_string('reply', 'forum');
555 } else {
556     if ($forum->type == 'qanda') {
557         $heading = get_string('yournewquestion', 'forum');
558     } else {
559         $heading = get_string('yournewtopic', 'forum');
560     }
563 if (forum_is_subscribed($USER->id, $forum->id)) {
564     $subscribe = true;
566 } else if (forum_user_has_posted($forum->id, 0, $USER->id)) {
567     $subscribe = false;
569 } else {
570     // user not posted yet - use subscription default specified in profile
571     $subscribe = !empty($USER->autosubscribe);
574 $postid = empty($post->id) ? null : $post->id;
575 $draftid_editor = file_get_submitted_draft_itemid('message');
576 $currenttext = file_prepare_draft_area($draftid_editor, $modcontext->id, 'mod_forum', 'post', $postid, mod_forum_post_form::editor_options($modcontext, $postid), $post->message);
577 $mform_post->set_data(array(        'attachments'=>$draftitemid,
578                                     'general'=>$heading,
579                                     'subject'=>$post->subject,
580                                     'message'=>array(
581                                         'text'=>$currenttext,
582                                         'format'=>empty($post->messageformat) ? editors_get_preferred_format() : $post->messageformat,
583                                         'itemid'=>$draftid_editor
584                                     ),
585                                     'subscribe'=>$subscribe?1:0,
586                                     'mailnow'=>!empty($post->mailnow),
587                                     'userid'=>$post->userid,
588                                     'parent'=>$post->parent,
589                                     'discussion'=>$post->discussion,
590                                     'course'=>$course->id) +
591                                     $page_params +
593                             (isset($post->format)?array(
594                                     'format'=>$post->format):
595                                 array())+
597                             (isset($discussion->timestart)?array(
598                                     'timestart'=>$discussion->timestart):
599                                 array())+
601                             (isset($discussion->timeend)?array(
602                                     'timeend'=>$discussion->timeend):
603                                 array())+
605                             (isset($post->groupid)?array(
606                                     'groupid'=>$post->groupid):
607                                 array())+
609                             (isset($discussion->id)?
610                                     array('discussion'=>$discussion->id):
611                                     array()));
613 if ($fromform = $mform_post->get_data()) {
615     if (empty($SESSION->fromurl)) {
616         $errordestination = "$CFG->wwwroot/mod/forum/view.php?f=$forum->id";
617     } else {
618         $errordestination = $SESSION->fromurl;
619     }
621     $fromform->itemid        = $fromform->message['itemid'];
622     $fromform->messageformat = $fromform->message['format'];
623     $fromform->message       = $fromform->message['text'];
624     // WARNING: the $fromform->message array has been overwritten, do not use it anymore!
625     $fromform->messagetrust  = trusttext_trusted($modcontext);
627     $contextcheck = isset($fromform->groupinfo) && has_capability('mod/forum:movediscussions', $modcontext);
629     if ($fromform->edit) {           // Updating a post
630         unset($fromform->groupid);
631         $fromform->id = $fromform->edit;
632         $message = '';
634         //fix for bug #4314
635         if (!$realpost = $DB->get_record('forum_posts', array('id' => $fromform->id))) {
636             $realpost = new stdClass();
637             $realpost->userid = -1;
638         }
641         // if user has edit any post capability
642         // or has either startnewdiscussion or reply capability and is editting own post
643         // then he can proceed
644         // MDL-7066
645         if ( !(($realpost->userid == $USER->id && (has_capability('mod/forum:replypost', $modcontext)
646                             || has_capability('mod/forum:startdiscussion', $modcontext))) ||
647                             has_capability('mod/forum:editanypost', $modcontext)) ) {
648             print_error('cannotupdatepost', 'forum');
649         }
651         // If the user has access to all groups and they are changing the group, then update the post.
652         if ($contextcheck) {
653             if (empty($fromform->groupinfo)) {
654                 $fromform->groupinfo = -1;
655             }
656             $DB->set_field('forum_discussions' ,'groupid' , $fromform->groupinfo, array('firstpost' => $fromform->id));
657         }
659         $updatepost = $fromform; //realpost
660         $updatepost->forum = $forum->id;
661         if (!forum_update_post($updatepost, $mform_post, $message)) {
662             print_error("couldnotupdate", "forum", $errordestination);
663         }
665         // MDL-11818
666         if (($forum->type == 'single') && ($updatepost->parent == '0')){ // updating first post of single discussion type -> updating forum intro
667             $forum->intro = $updatepost->message;
668             $forum->timemodified = time();
669             $DB->update_record("forum", $forum);
670         }
672         $timemessage = 2;
673         if (!empty($message)) { // if we're printing stuff about the file upload
674             $timemessage = 4;
675         }
677         if ($realpost->userid == $USER->id) {
678             $message .= '<br />'.get_string("postupdated", "forum");
679         } else {
680             $realuser = $DB->get_record('user', array('id' => $realpost->userid));
681             $message .= '<br />'.get_string("editedpostupdated", "forum", fullname($realuser));
682         }
684         if ($subscribemessage = forum_post_subscription($fromform, $forum)) {
685             $timemessage = 4;
686         }
687         if ($forum->type == 'single') {
688             // Single discussion forums are an exception. We show
689             // the forum itself since it only has one discussion
690             // thread.
691             $discussionurl = "view.php?f=$forum->id";
692         } else {
693             $discussionurl = "discuss.php?d=$discussion->id#p$fromform->id";
694         }
695         add_to_log($course->id, "forum", "update post",
696                 "$discussionurl&amp;parent=$fromform->id", "$fromform->id", $cm->id);
698         redirect(forum_go_back_to("$discussionurl"), $message.$subscribemessage, $timemessage);
700         exit;
703     } else if ($fromform->discussion) { // Adding a new post to an existing discussion
704         // Before we add this we must check that the user will not exceed the blocking threshold.
705         forum_check_blocking_threshold($thresholdwarning);
707         unset($fromform->groupid);
708         $message = '';
709         $addpost = $fromform;
710         $addpost->forum=$forum->id;
711         if ($fromform->id = forum_add_new_post($addpost, $mform_post, $message)) {
713             $timemessage = 2;
714             if (!empty($message)) { // if we're printing stuff about the file upload
715                 $timemessage = 4;
716             }
718             if ($subscribemessage = forum_post_subscription($fromform, $forum)) {
719                 $timemessage = 4;
720             }
722             if (!empty($fromform->mailnow)) {
723                 $message .= get_string("postmailnow", "forum");
724                 $timemessage = 4;
725             } else {
726                 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
727                 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
728             }
730             if ($forum->type == 'single') {
731                 // Single discussion forums are an exception. We show
732                 // the forum itself since it only has one discussion
733                 // thread.
734                 $discussionurl = "view.php?f=$forum->id";
735             } else {
736                 $discussionurl = "discuss.php?d=$discussion->id";
737             }
738             add_to_log($course->id, "forum", "add post",
739                       "$discussionurl&amp;parent=$fromform->id", "$fromform->id", $cm->id);
741             // Update completion state
742             $completion=new completion_info($course);
743             if($completion->is_enabled($cm) &&
744                 ($forum->completionreplies || $forum->completionposts)) {
745                 $completion->update_state($cm,COMPLETION_COMPLETE);
746             }
748             redirect(forum_go_back_to("$discussionurl#p$fromform->id"), $message.$subscribemessage, $timemessage);
750         } else {
751             print_error("couldnotadd", "forum", $errordestination);
752         }
753         exit;
755     } else { // Adding a new discussion.
756         // Before we add this we must check that the user will not exceed the blocking threshold.
757         forum_check_blocking_threshold($thresholdwarning);
759         if (!forum_user_can_post_discussion($forum, $fromform->groupid, -1, $cm, $modcontext)) {
760             print_error('cannotcreatediscussion', 'forum');
761         }
762         // If the user has access all groups capability let them choose the group.
763         if ($contextcheck) {
764             $fromform->groupid = $fromform->groupinfo;
765         }
766         if (empty($fromform->groupid)) {
767             $fromform->groupid = -1;
768         }
770         $fromform->mailnow = empty($fromform->mailnow) ? 0 : 1;
772         $discussion = $fromform;
773         $discussion->name    = $fromform->subject;
775         $newstopic = false;
776         if ($forum->type == 'news' && !$fromform->parent) {
777             $newstopic = true;
778         }
779         $discussion->timestart = $fromform->timestart;
780         $discussion->timeend = $fromform->timeend;
782         $message = '';
783         if ($discussion->id = forum_add_discussion($discussion, $mform_post, $message)) {
785             $params = array(
786                 'context' => $modcontext,
787                 'objectid' => $discussion->id,
788                 'other' => array(
789                     'forumid' => $forum->id,
790                 )
791             );
792             $event = \mod_forum\event\discussion_created::create($params);
793             $event->add_record_snapshot('forum_discussions', $discussion);
794             $event->trigger();
796             $timemessage = 2;
797             if (!empty($message)) { // if we're printing stuff about the file upload
798                 $timemessage = 4;
799             }
801             if ($fromform->mailnow) {
802                 $message .= get_string("postmailnow", "forum");
803                 $timemessage = 4;
804             } else {
805                 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
806                 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
807             }
809             if ($subscribemessage = forum_post_subscription($discussion, $forum)) {
810                 $timemessage = 6;
811             }
813             // Update completion status
814             $completion=new completion_info($course);
815             if($completion->is_enabled($cm) &&
816                 ($forum->completiondiscussions || $forum->completionposts)) {
817                 $completion->update_state($cm,COMPLETION_COMPLETE);
818             }
820             redirect(forum_go_back_to("view.php?f=$fromform->forum"), $message.$subscribemessage, $timemessage);
822         } else {
823             print_error("couldnotadd", "forum", $errordestination);
824         }
826         exit;
827     }
832 // To get here they need to edit a post, and the $post
833 // variable will be loaded with all the particulars,
834 // so bring up the form.
836 // $course, $forum are defined.  $discussion is for edit and reply only.
838 if ($post->discussion) {
839     if (! $toppost = $DB->get_record("forum_posts", array("discussion" => $post->discussion, "parent" => 0))) {
840         print_error('cannotfindparentpost', 'forum', '', $post->id);
841     }
842 } else {
843     $toppost = new stdClass();
844     $toppost->subject = ($forum->type == "news") ? get_string("addanewtopic", "forum") :
845                                                    get_string("addanewdiscussion", "forum");
848 if (empty($post->edit)) {
849     $post->edit = '';
852 if (empty($discussion->name)) {
853     if (empty($discussion)) {
854         $discussion = new stdClass();
855     }
856     $discussion->name = $forum->name;
858 if ($forum->type == 'single') {
859     // There is only one discussion thread for this forum type. We should
860     // not show the discussion name (same as forum name in this case) in
861     // the breadcrumbs.
862     $strdiscussionname = '';
863 } else {
864     // Show the discussion name in the breadcrumbs.
865     $strdiscussionname = format_string($discussion->name).':';
868 $forcefocus = empty($reply) ? NULL : 'message';
870 if (!empty($discussion->id)) {
871     $PAGE->navbar->add(format_string($toppost->subject, true), "discuss.php?d=$discussion->id");
874 if ($post->parent) {
875     $PAGE->navbar->add(get_string('reply', 'forum'));
878 if ($edit) {
879     $PAGE->navbar->add(get_string('edit', 'forum'));
882 $PAGE->set_title("$course->shortname: $strdiscussionname ".format_string($toppost->subject));
883 $PAGE->set_heading($course->fullname);
885 echo $OUTPUT->header();
886 echo $OUTPUT->heading(format_string($forum->name), 2);
888 // checkup
889 if (!empty($parent) && !forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
890     print_error('cannotreply', 'forum');
892 if (empty($parent) && empty($edit) && !forum_user_can_post_discussion($forum, $groupid, -1, $cm, $modcontext)) {
893     print_error('cannotcreatediscussion', 'forum');
896 if ($forum->type == 'qanda'
897             && !has_capability('mod/forum:viewqandawithoutposting', $modcontext)
898             && !empty($discussion->id)
899             && !forum_user_has_posted($forum->id, $discussion->id, $USER->id)) {
900     echo $OUTPUT->notification(get_string('qandanotify','forum'));
903 // If there is a warning message and we are not editing a post we need to handle the warning.
904 if (!empty($thresholdwarning) && !$edit) {
905     // Here we want to throw an exception if they are no longer allowed to post.
906     forum_check_blocking_threshold($thresholdwarning);
909 if (!empty($parent)) {
910     if (!$discussion = $DB->get_record('forum_discussions', array('id' => $parent->discussion))) {
911         print_error('notpartofdiscussion', 'forum');
912     }
914     forum_print_post($parent, $discussion, $forum, $cm, $course, false, false, false);
915     if (empty($post->edit)) {
916         if ($forum->type != 'qanda' || forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
917             $forumtracked = forum_tp_is_tracked($forum);
918             $posts = forum_get_all_discussion_posts($discussion->id, "created ASC", $forumtracked);
919             forum_print_posts_threaded($course, $cm, $forum, $discussion, $parent, 0, false, $forumtracked, $posts);
920         }
921     }
922 } else {
923     if (!empty($forum->intro)) {
924         echo $OUTPUT->box(format_module_intro('forum', $forum, $cm->id), 'generalbox', 'intro');
926         if (!empty($CFG->enableplagiarism)) {
927             require_once($CFG->libdir.'/plagiarismlib.php');
928             echo plagiarism_print_disclosure($cm->id);
929         }
930     }
933 if (!empty($formheading)) {
934     echo $OUTPUT->heading($formheading, 2, array('class' => 'accesshide'));
936 $mform_post->display();
938 echo $OUTPUT->footer();