/** save a new comment from submit * * @global record $USER * @global object $DB * @return array, result array. */ public function save_likes_from_submit() { global $USER, $DB; if (empty($this->course->enablelikes)) { print_error('likesaredisabled', 'format_socialwall'); } // Ensure that post exists and get the right courseid. $postid = required_param('postid', PARAM_INT); if (!($post = $DB->get_record('format_socialwall_posts', array('id' => $postid)))) { print_error('invalidpostid', 'format_socialwall'); } $userlike = optional_param('userlike', '0', PARAM_INT); // ... check capability. $coursecontext = \context_course::instance($post->courseid); if (!has_capability('format/socialwall:like', $coursecontext)) { print_error('missingcaplikepost', 'format_socialwall'); } $refresh = false; if (empty($userlike)) { if ($like = $DB->get_records('format_socialwall_likes', array('postid' => $postid, 'fromuserid' => $USER->id))) { $DB->delete_records_select('format_socialwall_likes', 'fromuserid = ? AND postid = ?', array($USER->id, $postid)); $refresh = true; // We use a instant enqueueing, if needed you might use events here. notification::enqueue_like_deleted($post); } } else { if (!($like = $DB->get_records('format_socialwall_likes', array('postid' => $postid, 'fromuserid' => $USER->id)))) { $newlike = new \stdClass(); $newlike->courseid = $this->course->id; $newlike->postid = $postid; $newlike->fromuserid = $USER->id; $newlike->timecreated = time(); $DB->insert_record('format_socialwall_likes', $newlike); $refresh = true; notification::enqueue_like_created($post); } } $result = array('error' => '0', 'message' => 'likesaved', 'postid' => $postid, 'userlike' => $userlike, 'countcomments' => $post->countcomments, 'countlikes' => $post->countlikes); if ($refresh) { $posts = posts::instance($this->course->id); $result['countlikes'] = $posts->refresh_likes_count($postid); } return $result; }