MDL-25176 forum Redirects for new discussions shouldn't use SESSION
[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                 add_to_log($discussion->course, "forum", "delete discussion",
339                            "view.php?id=$cm->id", "$forum->id", $cm->id);
341                 redirect("view.php?f=$discussion->forum");
343             } else if (forum_delete_post($post, has_capability('mod/forum:deleteanypost', $modcontext),
344                 $course, $cm, $forum)) {
346                 if ($forum->type == 'single') {
347                     // Single discussion forums are an exception. We show
348                     // the forum itself since it only has one discussion
349                     // thread.
350                     $discussionurl = "view.php?f=$forum->id";
351                 } else {
352                     $discussionurl = "discuss.php?d=$post->discussion";
353                 }
355                 add_to_log($discussion->course, "forum", "delete post", $discussionurl, "$post->id", $cm->id);
357                 redirect(forum_go_back_to($discussionurl));
358             } else {
359                 print_error('errorwhiledelete', 'forum');
360             }
361         }
364     } else { // User just asked to delete something
366         forum_set_return();
367         $PAGE->navbar->add(get_string('delete', 'forum'));
368         $PAGE->set_title($course->shortname);
369         $PAGE->set_heading($course->fullname);
371         if ($replycount) {
372             if (!has_capability('mod/forum:deleteanypost', $modcontext)) {
373                 print_error("couldnotdeletereplies", "forum",
374                       forum_go_back_to("discuss.php?d=$post->discussion"));
375             }
376             echo $OUTPUT->header();
377             echo $OUTPUT->heading(format_string($forum->name), 2);
378             echo $OUTPUT->confirm(get_string("deletesureplural", "forum", $replycount+1),
379                          "post.php?delete=$delete&confirm=$delete",
380                          $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
382             forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
384             if (empty($post->edit)) {
385                 $forumtracked = forum_tp_is_tracked($forum);
386                 $posts = forum_get_all_discussion_posts($discussion->id, "created ASC", $forumtracked);
387                 forum_print_posts_nested($course, $cm, $forum, $discussion, $post, false, false, $forumtracked, $posts);
388             }
389         } else {
390             echo $OUTPUT->header();
391             echo $OUTPUT->heading(format_string($forum->name), 2);
392             echo $OUTPUT->confirm(get_string("deletesure", "forum", $replycount),
393                          "post.php?delete=$delete&confirm=$delete",
394                          $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
395             forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
396         }
398     }
399     echo $OUTPUT->footer();
400     die;
403 } else if (!empty($prune)) {  // Pruning
405     if (!$post = forum_get_post_full($prune)) {
406         print_error('invalidpostid', 'forum');
407     }
408     if (!$discussion = $DB->get_record("forum_discussions", array("id" => $post->discussion))) {
409         print_error('notpartofdiscussion', 'forum');
410     }
411     if (!$forum = $DB->get_record("forum", array("id" => $discussion->forum))) {
412         print_error('invalidforumid', 'forum');
413     }
414     if ($forum->type == 'single') {
415         print_error('cannotsplit', 'forum');
416     }
417     if (!$post->parent) {
418         print_error('alreadyfirstpost', 'forum');
419     }
420     if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $forum->course)) { // For the logs
421         print_error('invalidcoursemodule');
422     } else {
423         $modcontext = context_module::instance($cm->id);
424     }
425     if (!has_capability('mod/forum:splitdiscussions', $modcontext)) {
426         print_error('cannotsplit', 'forum');
427     }
429     if (!empty($name) && confirm_sesskey()) {    // User has confirmed the prune
431         $newdiscussion = new stdClass();
432         $newdiscussion->course       = $discussion->course;
433         $newdiscussion->forum        = $discussion->forum;
434         $newdiscussion->name         = $name;
435         $newdiscussion->firstpost    = $post->id;
436         $newdiscussion->userid       = $discussion->userid;
437         $newdiscussion->groupid      = $discussion->groupid;
438         $newdiscussion->assessed     = $discussion->assessed;
439         $newdiscussion->usermodified = $post->userid;
440         $newdiscussion->timestart    = $discussion->timestart;
441         $newdiscussion->timeend      = $discussion->timeend;
443         $newid = $DB->insert_record('forum_discussions', $newdiscussion);
445         $newpost = new stdClass();
446         $newpost->id      = $post->id;
447         $newpost->parent  = 0;
448         $newpost->subject = $name;
450         $DB->update_record("forum_posts", $newpost);
452         forum_change_discussionid($post->id, $newid);
454         // update last post in each discussion
455         forum_discussion_update_last_post($discussion->id);
456         forum_discussion_update_last_post($newid);
458         add_to_log($discussion->course, "forum", "prune post",
459                        "discuss.php?d=$newid", "$post->id", $cm->id);
461         redirect(forum_go_back_to("discuss.php?d=$newid"));
463     } else { // User just asked to prune something
465         $course = $DB->get_record('course', array('id' => $forum->course));
467         $PAGE->set_cm($cm);
468         $PAGE->set_context($modcontext);
469         $PAGE->navbar->add(format_string($post->subject, true), new moodle_url('/mod/forum/discuss.php', array('d'=>$discussion->id)));
470         $PAGE->navbar->add(get_string("prune", "forum"));
471         $PAGE->set_title(format_string($discussion->name).": ".format_string($post->subject));
472         $PAGE->set_heading($course->fullname);
473         echo $OUTPUT->header();
474         echo $OUTPUT->heading(format_string($forum->name), 2);
475         echo $OUTPUT->heading(get_string('pruneheading', 'forum'), 3);
476         echo '<center>';
478         include('prune.html');
480         forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
481         echo '</center>';
482     }
483     echo $OUTPUT->footer();
484     die;
485 } else {
486     print_error('unknowaction');
490 if (!isset($coursecontext)) {
491     // Has not yet been set by post.php.
492     $coursecontext = context_course::instance($forum->course);
496 // from now on user must be logged on properly
498 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) { // For the logs
499     print_error('invalidcoursemodule');
501 $modcontext = context_module::instance($cm->id);
502 require_login($course, false, $cm);
504 if (isguestuser()) {
505     // just in case
506     print_error('noguest');
509 if (!isset($forum->maxattachments)) {  // TODO - delete this once we add a field to the forum table
510     $forum->maxattachments = 3;
513 $thresholdwarning = forum_check_throttling($forum, $cm);
514 $mform_post = new mod_forum_post_form('post.php', array('course' => $course,
515                                                         'cm' => $cm,
516                                                         'coursecontext' => $coursecontext,
517                                                         'modcontext' => $modcontext,
518                                                         'forum' => $forum,
519                                                         'post' => $post,
520                                                         'thresholdwarning' => $thresholdwarning,
521                                                         'edit' => $edit), 'post', '', array('id' => 'mformforum'));
523 $draftitemid = file_get_submitted_draft_itemid('attachments');
524 file_prepare_draft_area($draftitemid, $modcontext->id, 'mod_forum', 'attachment', empty($post->id)?null:$post->id, mod_forum_post_form::attachment_options($forum));
526 //load data into form NOW!
528 if ($USER->id != $post->userid) {   // Not the original author, so add a message to the end
529     $data = new stdClass();
530     $data->date = userdate($post->modified);
531     if ($post->messageformat == FORMAT_HTML) {
532         $data->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'&course='.$post->course.'">'.
533                        fullname($USER).'</a>';
534         $post->message .= '<p><span class="edited">('.get_string('editedby', 'forum', $data).')</span></p>';
535     } else {
536         $data->name = fullname($USER);
537         $post->message .= "\n\n(".get_string('editedby', 'forum', $data).')';
538     }
539     unset($data);
542 $formheading = '';
543 if (!empty($parent)) {
544     $heading = get_string("yourreply", "forum");
545     $formheading = get_string('reply', 'forum');
546 } else {
547     if ($forum->type == 'qanda') {
548         $heading = get_string('yournewquestion', 'forum');
549     } else {
550         $heading = get_string('yournewtopic', 'forum');
551     }
554 if (forum_is_subscribed($USER->id, $forum->id)) {
555     $subscribe = true;
557 } else if (forum_user_has_posted($forum->id, 0, $USER->id)) {
558     $subscribe = false;
560 } else {
561     // user not posted yet - use subscription default specified in profile
562     $subscribe = !empty($USER->autosubscribe);
565 $postid = empty($post->id) ? null : $post->id;
566 $draftid_editor = file_get_submitted_draft_itemid('message');
567 $currenttext = file_prepare_draft_area($draftid_editor, $modcontext->id, 'mod_forum', 'post', $postid, mod_forum_post_form::editor_options($modcontext, $postid), $post->message);
568 $mform_post->set_data(array(        'attachments'=>$draftitemid,
569                                     'general'=>$heading,
570                                     'subject'=>$post->subject,
571                                     'message'=>array(
572                                         'text'=>$currenttext,
573                                         'format'=>empty($post->messageformat) ? editors_get_preferred_format() : $post->messageformat,
574                                         'itemid'=>$draftid_editor
575                                     ),
576                                     'subscribe'=>$subscribe?1:0,
577                                     'mailnow'=>!empty($post->mailnow),
578                                     'userid'=>$post->userid,
579                                     'parent'=>$post->parent,
580                                     'discussion'=>$post->discussion,
581                                     'course'=>$course->id) +
582                                     $page_params +
584                             (isset($post->format)?array(
585                                     'format'=>$post->format):
586                                 array())+
588                             (isset($discussion->timestart)?array(
589                                     'timestart'=>$discussion->timestart):
590                                 array())+
592                             (isset($discussion->timeend)?array(
593                                     'timeend'=>$discussion->timeend):
594                                 array())+
596                             (isset($post->groupid)?array(
597                                     'groupid'=>$post->groupid):
598                                 array())+
600                             (isset($discussion->id)?
601                                     array('discussion'=>$discussion->id):
602                                     array()));
604 if ($fromform = $mform_post->get_data()) {
606     if (empty($SESSION->fromurl)) {
607         $errordestination = "$CFG->wwwroot/mod/forum/view.php?f=$forum->id";
608     } else {
609         $errordestination = $SESSION->fromurl;
610     }
612     $fromform->itemid        = $fromform->message['itemid'];
613     $fromform->messageformat = $fromform->message['format'];
614     $fromform->message       = $fromform->message['text'];
615     // WARNING: the $fromform->message array has been overwritten, do not use it anymore!
616     $fromform->messagetrust  = trusttext_trusted($modcontext);
618     $contextcheck = isset($fromform->groupinfo) && has_capability('mod/forum:movediscussions', $modcontext);
620     if ($fromform->edit) {           // Updating a post
621         unset($fromform->groupid);
622         $fromform->id = $fromform->edit;
623         $message = '';
625         //fix for bug #4314
626         if (!$realpost = $DB->get_record('forum_posts', array('id' => $fromform->id))) {
627             $realpost = new stdClass();
628             $realpost->userid = -1;
629         }
632         // if user has edit any post capability
633         // or has either startnewdiscussion or reply capability and is editting own post
634         // then he can proceed
635         // MDL-7066
636         if ( !(($realpost->userid == $USER->id && (has_capability('mod/forum:replypost', $modcontext)
637                             || has_capability('mod/forum:startdiscussion', $modcontext))) ||
638                             has_capability('mod/forum:editanypost', $modcontext)) ) {
639             print_error('cannotupdatepost', 'forum');
640         }
642         // If the user has access to all groups and they are changing the group, then update the post.
643         if ($contextcheck) {
644             if (empty($fromform->groupinfo)) {
645                 $fromform->groupinfo = -1;
646             }
647             $DB->set_field('forum_discussions' ,'groupid' , $fromform->groupinfo, array('firstpost' => $fromform->id));
648         }
650         $updatepost = $fromform; //realpost
651         $updatepost->forum = $forum->id;
652         if (!forum_update_post($updatepost, $mform_post, $message)) {
653             print_error("couldnotupdate", "forum", $errordestination);
654         }
656         // MDL-11818
657         if (($forum->type == 'single') && ($updatepost->parent == '0')){ // updating first post of single discussion type -> updating forum intro
658             $forum->intro = $updatepost->message;
659             $forum->timemodified = time();
660             $DB->update_record("forum", $forum);
661         }
663         $timemessage = 2;
664         if (!empty($message)) { // if we're printing stuff about the file upload
665             $timemessage = 4;
666         }
668         if ($realpost->userid == $USER->id) {
669             $message .= '<br />'.get_string("postupdated", "forum");
670         } else {
671             $realuser = $DB->get_record('user', array('id' => $realpost->userid));
672             $message .= '<br />'.get_string("editedpostupdated", "forum", fullname($realuser));
673         }
675         if ($subscribemessage = forum_post_subscription($fromform, $forum)) {
676             $timemessage = 4;
677         }
678         if ($forum->type == 'single') {
679             // Single discussion forums are an exception. We show
680             // the forum itself since it only has one discussion
681             // thread.
682             $discussionurl = "view.php?f=$forum->id";
683         } else {
684             $discussionurl = "discuss.php?d=$discussion->id#p$fromform->id";
685         }
686         add_to_log($course->id, "forum", "update post",
687                 "$discussionurl&amp;parent=$fromform->id", "$fromform->id", $cm->id);
689         redirect(forum_go_back_to("$discussionurl"), $message.$subscribemessage, $timemessage);
691         exit;
694     } else if ($fromform->discussion) { // Adding a new post to an existing discussion
695         // Before we add this we must check that the user will not exceed the blocking threshold.
696         forum_check_blocking_threshold($thresholdwarning);
698         unset($fromform->groupid);
699         $message = '';
700         $addpost = $fromform;
701         $addpost->forum=$forum->id;
702         if ($fromform->id = forum_add_new_post($addpost, $mform_post, $message)) {
704             $timemessage = 2;
705             if (!empty($message)) { // if we're printing stuff about the file upload
706                 $timemessage = 4;
707             }
709             if ($subscribemessage = forum_post_subscription($fromform, $forum)) {
710                 $timemessage = 4;
711             }
713             if (!empty($fromform->mailnow)) {
714                 $message .= get_string("postmailnow", "forum");
715                 $timemessage = 4;
716             } else {
717                 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
718                 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
719             }
721             if ($forum->type == 'single') {
722                 // Single discussion forums are an exception. We show
723                 // the forum itself since it only has one discussion
724                 // thread.
725                 $discussionurl = "view.php?f=$forum->id";
726             } else {
727                 $discussionurl = "discuss.php?d=$discussion->id";
728             }
729             add_to_log($course->id, "forum", "add post",
730                       "$discussionurl&amp;parent=$fromform->id", "$fromform->id", $cm->id);
732             // Update completion state
733             $completion=new completion_info($course);
734             if($completion->is_enabled($cm) &&
735                 ($forum->completionreplies || $forum->completionposts)) {
736                 $completion->update_state($cm,COMPLETION_COMPLETE);
737             }
739             redirect(forum_go_back_to("$discussionurl#p$fromform->id"), $message.$subscribemessage, $timemessage);
741         } else {
742             print_error("couldnotadd", "forum", $errordestination);
743         }
744         exit;
746     } else { // Adding a new discussion.
747         // Before we add this we must check that the user will not exceed the blocking threshold.
748         forum_check_blocking_threshold($thresholdwarning);
750         if (!forum_user_can_post_discussion($forum, $fromform->groupid, -1, $cm, $modcontext)) {
751             print_error('cannotcreatediscussion', 'forum');
752         }
753         // If the user has access all groups capability let them choose the group.
754         if ($contextcheck) {
755             $fromform->groupid = $fromform->groupinfo;
756         }
757         if (empty($fromform->groupid)) {
758             $fromform->groupid = -1;
759         }
761         $fromform->mailnow = empty($fromform->mailnow) ? 0 : 1;
763         $discussion = $fromform;
764         $discussion->name    = $fromform->subject;
766         $newstopic = false;
767         if ($forum->type == 'news' && !$fromform->parent) {
768             $newstopic = true;
769         }
770         $discussion->timestart = $fromform->timestart;
771         $discussion->timeend = $fromform->timeend;
773         $message = '';
774         if ($discussion->id = forum_add_discussion($discussion, $mform_post, $message)) {
776             add_to_log($course->id, "forum", "add discussion",
777                     "discuss.php?d=$discussion->id", "$discussion->id", $cm->id);
779             $timemessage = 2;
780             if (!empty($message)) { // if we're printing stuff about the file upload
781                 $timemessage = 4;
782             }
784             if ($fromform->mailnow) {
785                 $message .= get_string("postmailnow", "forum");
786                 $timemessage = 4;
787             } else {
788                 $message .= '<p>'.get_string("postaddedsuccess", "forum") . '</p>';
789                 $message .= '<p>'.get_string("postaddedtimeleft", "forum", format_time($CFG->maxeditingtime)) . '</p>';
790             }
792             if ($subscribemessage = forum_post_subscription($discussion, $forum)) {
793                 $timemessage = 4;
794             }
796             // Update completion status
797             $completion=new completion_info($course);
798             if($completion->is_enabled($cm) &&
799                 ($forum->completiondiscussions || $forum->completionposts)) {
800                 $completion->update_state($cm,COMPLETION_COMPLETE);
801             }
803             redirect(forum_go_back_to("view.php?f=$fromform->forum"), $message.$subscribemessage, $timemessage);
805         } else {
806             print_error("couldnotadd", "forum", $errordestination);
807         }
809         exit;
810     }
815 // To get here they need to edit a post, and the $post
816 // variable will be loaded with all the particulars,
817 // so bring up the form.
819 // $course, $forum are defined.  $discussion is for edit and reply only.
821 if ($post->discussion) {
822     if (! $toppost = $DB->get_record("forum_posts", array("discussion" => $post->discussion, "parent" => 0))) {
823         print_error('cannotfindparentpost', 'forum', '', $post->id);
824     }
825 } else {
826     $toppost = new stdClass();
827     $toppost->subject = ($forum->type == "news") ? get_string("addanewtopic", "forum") :
828                                                    get_string("addanewdiscussion", "forum");
831 if (empty($post->edit)) {
832     $post->edit = '';
835 if (empty($discussion->name)) {
836     if (empty($discussion)) {
837         $discussion = new stdClass();
838     }
839     $discussion->name = $forum->name;
841 if ($forum->type == 'single') {
842     // There is only one discussion thread for this forum type. We should
843     // not show the discussion name (same as forum name in this case) in
844     // the breadcrumbs.
845     $strdiscussionname = '';
846 } else {
847     // Show the discussion name in the breadcrumbs.
848     $strdiscussionname = format_string($discussion->name).':';
851 $forcefocus = empty($reply) ? NULL : 'message';
853 if (!empty($discussion->id)) {
854     $PAGE->navbar->add(format_string($toppost->subject, true), "discuss.php?d=$discussion->id");
857 if ($post->parent) {
858     $PAGE->navbar->add(get_string('reply', 'forum'));
861 if ($edit) {
862     $PAGE->navbar->add(get_string('edit', 'forum'));
865 $PAGE->set_title("$course->shortname: $strdiscussionname ".format_string($toppost->subject));
866 $PAGE->set_heading($course->fullname);
868 echo $OUTPUT->header();
869 echo $OUTPUT->heading(format_string($forum->name), 2);
871 // checkup
872 if (!empty($parent) && !forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
873     print_error('cannotreply', 'forum');
875 if (empty($parent) && empty($edit) && !forum_user_can_post_discussion($forum, $groupid, -1, $cm, $modcontext)) {
876     print_error('cannotcreatediscussion', 'forum');
879 if ($forum->type == 'qanda'
880             && !has_capability('mod/forum:viewqandawithoutposting', $modcontext)
881             && !empty($discussion->id)
882             && !forum_user_has_posted($forum->id, $discussion->id, $USER->id)) {
883     echo $OUTPUT->notification(get_string('qandanotify','forum'));
886 // If there is a warning message and we are not editing a post we need to handle the warning.
887 if (!empty($thresholdwarning) && !$edit) {
888     // Here we want to throw an exception if they are no longer allowed to post.
889     forum_check_blocking_threshold($thresholdwarning);
892 if (!empty($parent)) {
893     if (!$discussion = $DB->get_record('forum_discussions', array('id' => $parent->discussion))) {
894         print_error('notpartofdiscussion', 'forum');
895     }
897     forum_print_post($parent, $discussion, $forum, $cm, $course, false, false, false);
898     if (empty($post->edit)) {
899         if ($forum->type != 'qanda' || forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
900             $forumtracked = forum_tp_is_tracked($forum);
901             $posts = forum_get_all_discussion_posts($discussion->id, "created ASC", $forumtracked);
902             forum_print_posts_threaded($course, $cm, $forum, $discussion, $parent, 0, false, $forumtracked, $posts);
903         }
904     }
905 } else {
906     if (!empty($forum->intro)) {
907         echo $OUTPUT->box(format_module_intro('forum', $forum, $cm->id), 'generalbox', 'intro');
909         if (!empty($CFG->enableplagiarism)) {
910             require_once($CFG->libdir.'/plagiarismlib.php');
911             echo plagiarism_print_disclosure($cm->id);
912         }
913     }
916 if (!empty($formheading)) {
917     echo $OUTPUT->heading($formheading, 2, array('class' => 'accesshide'));
919 $mform_post->display();
921 echo $OUTPUT->footer();