3 // Collect ratings, store them, then return to where we came from
6 require_once('../../config.php');
7 require_once('lib.php');
9 $forumid = required_param('forumid', PARAM_INT
); // The forum the rated posts are from
11 if (!$forum = get_record('forum', 'id', $forumid)) {
12 error("Course ID was incorrect");
15 if (!$course = get_record('course', 'id', $forum->course
)) {
16 error("Course ID was incorrect");
19 if (!$cm = get_coursemodule_from_instance('forum', $forum->id
)) {
20 error("Course Module ID was incorrect");
23 require_login($course, false, $cm);
26 error("Guests are not allowed to rate entries.");
29 if (!$forum->assessed
) {
30 error("Rating of items not allowed!");
33 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
34 require_capability('mod/forum:rate', $context);
36 if ($data = data_submitted()) {
38 $discussionid = false;
40 foreach ((array)$data as $postid => $rating) {
41 if (!is_numeric($postid)) {
45 // following query validates the submitted postid too
47 FROM {$CFG->prefix}forum_posts fp, {$CFG->prefix}forum_discussions fd
48 WHERE fp.id = '$postid' AND fp.discussion = fd.id AND fd.forum = $forum->id";
50 if (!$post = get_record_sql($sql)) {
51 error("Incorrect postid - $postid");
54 $discussionid = $post->discussion
;
56 if ($forum->assesstimestart
and $forum->assesstimefinish
) {
57 if ($post->created
< $forum->assesstimestart
or $post->created
> $forum->assesstimefinish
) {
58 // we can not rate this, ignore it - this should not happen anyway unless teacher changes setting
63 if ($rating == FORUM_UNSET_POST_RATING
) {
64 delete_records('forum_ratings', 'post', $postid, 'userid', $USER->id
);
65 forum_update_grades($forum, $post->userid
);
67 } else if ($oldrating = get_record('forum_ratings', 'userid', $USER->id
, 'post', $post->id
)) {
68 if ($rating != $oldrating->rating
) {
69 $oldrating->rating
= $rating;
70 $oldrating->time
= time();
71 if (! update_record('forum_ratings', $oldrating)) {
72 error("Could not update an old rating ($post->id = $rating)");
74 forum_update_grades($forum, $post->userid
);
78 $newrating = new object();
79 $newrating->userid
= $USER->id
;
80 $newrating->time
= time();
81 $newrating->post
= $post->id
;
82 $newrating->rating
= $rating;
84 if (! insert_record('forum_ratings', $newrating)) {
85 error("Could not insert a new rating ($postid = $rating)");
87 forum_update_grades($forum, $post->userid
);
91 if ($forum->type
== 'single' or !$discussionid) {
92 redirect("$CFG->wwwroot/mod/forum/view.php?id=$cm->id", get_string('ratingssaved', 'forum'));
94 redirect("$CFG->wwwroot/mod/forum/discuss.php?d=$discussionid", get_string('ratingssaved', 'forum'));
98 error("This page was not accessed correctly");