2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Subscribe to or unsubscribe from a forum discussion.
21 * @copyright 2014 Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 define('AJAX_SCRIPT', true);
26 require_once(dirname(dirname(__DIR__)) . '/config.php');
27 require_once($CFG->dirroot . '/mod/forum/lib.php');
29 $forumid = required_param('forumid', PARAM_INT); // The forum to subscribe or unsubscribe.
30 $discussionid = optional_param('discussionid', null, PARAM_INT); // The discussionid to subscribe.
31 $sesskey = optional_param('sesskey', null, PARAM_RAW);
32 $includetext = optional_param('includetext', false, PARAM_BOOL);
34 $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
35 $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
36 $discussion = $DB->get_record('forum_discussions', array('id' => $discussionid), '*', MUST_EXIST);
37 $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
38 $context = context_module::instance($cm->id);
40 require_login($course, false, $cm);
41 require_capability('mod/forum:viewdiscussion', $context);
43 $return = new stdClass();
45 if (!\mod_forum\subscriptions::is_subscribable($forum)) {
46 // Nothing to do. We won't actually output any content here though.
47 echo json_encode($return);
51 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum, $discussion->id, $cm)) {
52 // The user is subscribed, unsubscribe them.
53 \mod_forum\subscriptions::unsubscribe_user_from_discussion($USER->id, $discussion, $context);
55 // The user is unsubscribed, subscribe them.
56 \mod_forum\subscriptions::subscribe_user_to_discussion($USER->id, $discussion, $context);
59 // Now return the updated subscription icon.
60 $return->icon = forum_get_discussion_subscription_icon($forum, $discussion->id, null, $includetext);
61 echo json_encode($return);