MDL-10092:
[moodle-linuxchix.git] / mod / forum / rate.php
blob97ba2dfd1b4f87805fd6e508869a9946c9a5558c
1 <?php // $Id$
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);
25 if (isguestuser()) {
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)) {
42 continue;
45 // following query validates the submitted postid too
46 $sql = "SELECT fp.*
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
59 continue;
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);
77 } else {
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'));
93 } else {
94 redirect("$CFG->wwwroot/mod/forum/discuss.php?d=$discussionid", get_string('ratingssaved', 'forum'));
97 } else {
98 error("This page was not accessed correctly");