/** * Vote action (Vote a post action) * * @throws \Modules\Core\Exceptions\HTTPException * @return int Votes after the vote */ public function vote() { //Check if user is authorized \Modules\Core\Library\Authorize::isAuthorized(); $post = new Posts(); $vote = new Votes(); $filter = new Filter(); $filter->add('vote', function ($value) { if ($value > 0) { return 1; } if ($value < 0) { return -1; } return 0; }); $params = array('id' => $this->getDI()->get('requestBody')->id, 'uid' => \Modules\Core\Library\Authorize::getUid(), 'vote' => $filter->sanitize((int) $this->getDI()->get('requestBody')->vote, 'vote')); $userVote = Votes::find("id = 0x" . $params['id'] . " AND uid = 0x" . $params['uid']); $oldVote = 0; if (isset($userVote->getFirst()->vote)) { $oldVote = $userVote->getFirst()->vote; } if ((int) $oldVote == (int) $params['vote']) { $params['vote'] = 0; } $vote->save($params); return $post->getVotes($this->getDI()->get('requestBody')->id); }
/** * Fetch posts by page (Each page is 20 records) * * @param int $page Number of page to get records * @return array(array(posts), array(votes by user)) */ public function fetch($page) { $offset = $page * self::LIMIT - self::LIMIT; $sql = 'SELECT @count := ifnull(@count, 0) + 1 as rank, ' . ' HEX(id) as id, username, title, url, unix_timestamp(creation) as creation, votes, score' . ' FROM' . ' vv_posts p, (select @count := ' . $offset . ') c' . ' LIMIT ' . $offset . ', ' . self::LIMIT; $rs = DI::getDefault()->get('db')->query($sql); $rs->setFetchMode(\Phalcon\Db::FETCH_ASSOC); $posts = $rs->fetchAll(); $ids = array(); foreach ($posts as $post) { $ids[] = '0x' . $post['id']; } $userVotes = array(); try { $uid = \Modules\Core\Library\Authorize::getUid(); } catch (\Modules\Core\Exceptions\HTTPException $e) { $uid = false; } if ($uid) { $sql = 'SELECT HEX(id) as id, vote FROM votes ' . ' WHERE ' . ' uid = 0x' . $uid . ' AND' . ' id IN (' . implode(',', $ids) . ')'; $rs = DI::getDefault()->get('db')->query($sql); $rs->setFetchMode(\Phalcon\Db::FETCH_ASSOC); $votes = $rs->fetchAll(); foreach ($votes as $vote) { $userVotes[$vote['id']] = $vote['vote']; } } return array('posts' => $posts, 'votes' => $userVotes); }
/** * Check login status * * @throws \Modules\Core\Exceptions\HTTPException * @return string */ public function loginStatus() { //Check if user is authorized \Modules\Core\Library\Authorize::isAuthorized(); return md5(uniqid()); }