public function run() { $faker = Faker::create(); $log = new Stream('php://stdout'); $log->info('Start ' . __CLASS__); /** @var Phalcon\Db\AdapterInterface $database */ $database = $this->getDI()->get('db'); $userIds = Users::find(['columns' => 'id'])->toArray(); $database->begin(); for ($i = 0; $i <= self::POSTS_TOTAL; $i++) { $title = $faker->company; $userRandId = array_rand($userIds); $posts = new Posts(); $posts->usersId = $userIds[$userRandId]['id']; $posts->type = rand(0, 1) ? 'questions' : 'tips'; $posts->title = $title; $posts->slug = \Phalcon\Tag::friendlyTitle($title); $posts->numberViews = rand(5, 100); $posts->numberReply = rand(0, 20); $posts->content = $faker->text; $posts->sticked = 'N'; $posts->status = 'A'; $posts->locked = 'N'; $posts->deleted = 0; $posts->acceptedAnswer = 'N'; if (!$posts->save()) { var_dump($posts->getMessages()); $database->rollback(); die; } $log->info('posts: ' . $posts->getTitle()); } }
public function getPostBySlug($slug) { $post = Posts::findFirstBySlug($slug); if (!$post) { return null; } return $post; }
public function indexAction($user) { d($user); if (!($user = Users::findFirstByUsername($user))) { $this->flashSession->error(t('The User dosen\'t exits')); return $this->indexRedirect(); } $tab = $this->request->getQuery('tab', 'string'); if ($tab == "answers") { $join = ['type' => 'join', 'model' => 'Phanbook\\Models\\PostsReply', 'on' => 'r.postsId = p.id', 'alias' => 'r']; list($itemBuilder, $totalBuilder) = $this->prepareQueries($join, false, self::POSTS_IN_PAGE); $itemBuilder->groupBy(array('p.id')); } else { list($itemBuilder, $totalBuilder) = $this->prepareQueries('', false, self::POSTS_IN_PAGE); } $params = []; switch ($tab) { case 'questions': $this->tag->setTitle('Questions'); $questionConditions = 'p.type = "questions"'; $itemBuilder->where($questionConditions); break; case 'tips': $this->tag->setTitle('Tips'); $questionConditions = 'p.type = "tips"'; $itemBuilder->where($questionConditions); break; case 'hackernews': $this->tag->setTitle('Hackernews'); $questionConditions = 'p.type = "hackernews"'; $itemBuilder->where($questionConditions); break; case 'answers': $this->tag->setTitle('My Answers'); $answersConditions = 'r.usersId = ?0'; $itemBuilder->where($answersConditions); //$totalBuilder->where($answersConditions); break; default: $this->tag->setTitle('All Questions and Tips'); break; } $conditions = 'p.deleted = 0 and p.usersId = ?0'; if ($tab == 'answers') { $conditions = 'p.deleted = 0'; } $itemBuilder->andWhere($conditions); $totalBuilder->andWhere($conditions); $params = array($user->getId()); //get all reply $parametersNumberReply = ['group' => 'postsId', 'usersId = ?0', 'bind' => [$user->getId()]]; $paramTips = ['usersId = ?0 and type = "tips" and deleted = 0', 'bind' => [$user->getId()]]; $paramQuestions = ['usersId = ?0 and type = "questions" and deleted = 0', 'bind' => [$user->getId()]]; $paramHackernews = ['usersId = ?0 and type = "hackernews" and deleted = 0', 'bind' => [$user->getId()]]; $this->view->setVars(['user' => $user, 'posts' => $itemBuilder->getQuery()->execute($params), 'totalTips' => Posts::count($paramTips), 'totalQuestions' => Posts::count($paramQuestions), 'totalHackernews' => Posts::count($paramHackernews), 'totalReply' => PostsReply::find($parametersNumberReply)->count(), 'currentOrder' => $tab]); }
/** * Subscribe to a post to receive e-mail notifications * * @return mixed */ public function indexAction() { $this->view->disable(); $this->setJsonResponse(); if (!$this->request->isPost()) { return false; } //Find the post by Id $post = Posts::findFirstById($this->request->getPost('objectId')); if (!$post) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => 'The Post does not exist']; return $this->jsonMessages; } /** * Sometime We need to get object User login, so I do check user like below * By the way, you can checking session * * {code} Users::findFirstById($this->auth->getAuth()['id'] {/code} */ $userId = $this->auth->getAuth()['id']; if (!$userId) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => 'You must log in first to subscribe post']; return $this->jsonMessages; } $subscription = PostsSubscribers::findFirst(['postsId = ?0 AND usersId = ?1', 'bind' => [$post->getId(), $userId]]); if (!$subscription) { $subscription = new PostsSubscribers(); $subscription->setPostsId($post->getId()); $subscription->setUsersId($userId); if (!$subscription->save()) { foreach ($subscription->getMessages() as $message) { $this->logger->error('Subscribe save false ' . $message . __LINE__ . 'and' . __CLASS__); } return false; } $this->jsonMessages['messages'][] = ['type' => 'info', 'content' => 'You have just subscribe post', 'flag' => 1]; return $this->jsonMessages; } else { //unsubsribe posts if (!$subscription->delete()) { foreach ($subscription->getMessages() as $message) { $this->logger->error('Unsubscribe delete false ' . $message . __LINE__ . 'and' . __CLASS__); } return false; } $this->jsonMessages['messages'][] = ['type' => 'info', 'content' => 'You have just unsubscribe post']; return $this->jsonMessages; } }
/** * Displays a post and its comments * * @param $id * @param $slug * * @return \Phalcon\Http\ResponseInterface */ public function viewAction($id, $slug) { $id = (int) $id; $userId = $this->auth->getAuth()['id']; if (!($object = Posts::findFirstById($id))) { $this->flashSession->error(t('Posts doesn\'t exist.')); return $this->indexRedirect(); } if ($object->getDeleted()) { $this->flashSession->error('The Post is deleted'); return $this->indexRedirect(); } $ipAddress = $this->request->getClientAddress(); $parameters = ['postsId = ?0 AND ipaddress = ?1', 'bind' => [$id, $ipAddress]]; $viewed = PostsViews::count($parameters); //A view is stored by ipaddress if (!$viewed) { //Increase the number of views in the post $object->setNumberViews($object->getNumberViews() + 1); if ($object->getUsersId() != $userId) { $object->user->increaseKarma(Karma::VISIT_ON_MY_POST); if ($userId > 0) { $user = Users::findFirstById($userId); if ($user) { if ($user->getModerator() == 'Y') { $user->increaseKarma(Karma::MODERATE_VISIT_POST); } else { $user->increaseKarma(Karma::VISIT_POST); } //send log to server if (!$user->save()) { $this->saveLoger($user->getMessages()); } } } } $postView = new PostsViews(); $postView->setPostsId($id); $postView->setIpaddress($ipAddress); if (!$postView->save()) { $this->saveLoger($postView->getMessages()); } } $this->view->setVars(['post' => $object, 'form' => new ReplyForm(), 'votes' => $object->getVotes($id, Vote::OBJECT_POSTS), 'postsReply' => $object->getPostsWithVotes($id), 'commentForm' => new CommentForm(), 'userPosts' => $object->user]); $this->tag->setTitle($this->escaper->escapeHtml($object->getTitle())); return $this->view->pickCustom('single'); }
/** * Finds related posts */ public function showRelatedAction() { $this->view->disable(); if ($this->request->isAjax()) { //$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW); $post = Posts::findFirstById($this->request->getPost('id')); if ($post) { $posts = Posts::postRelated($post); if (count($posts) > 0) { $params = ['posts' => $posts]; echo $this->view->getRender('partials', 'list-posts', $params, function ($view) { $view->setRenderLevel(View::LEVEL_ACTION_VIEW); }); } } } }
/** * Retrieve a list of Posts for a specific tags id. * * @param int $id The Tags ID * @param string $slugTags * * @return array list of posts */ public function postByTagAction($id, $slugName) { $join = ['type' => 'join', 'model' => 'Phanbook\\Models\\PostsTags', 'on' => 'pt.postsId = p.id', 'alias' => 'pt']; /**@Todo later for security*/ $Where = 'p.deleted = 0 AND pt.tagsId = ' . $id; list($itemBuilder, $totalBuilder) = $this->prepareQueries($join, $Where, self::ITEM_IN_PAGE); //$itemBuilder->andWhere($conditions); $page = isset($_GET['page']) ? (int) $_GET['page'] : 1; $totalPosts = $totalBuilder->getQuery()->setUniqueRow(true)->execute(); $totalPages = ceil($totalPosts->count / self::ITEM_IN_PAGE); if ($page > 1) { $itemBuilder->offset((int) $page); } $this->view->setVars(['tab' => 'tags', 'object' => $itemBuilder->getQuery()->execute(), 'totalPages' => $totalPages, 'currentPage' => $page, 'slugName' => $slugName, 'hotPosts' => Posts::getHotPosts()]); $this->tag->setTitle(t('These posts fillter by tags')); return $this->view->pick('post'); }
/** * Finds related posts */ public function showRelatedAction() { if ($this->request->isAjax()) { $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW); $post = Posts::findFirstById($this->request->getPost('id')); if ($post) { $indexer = new Indexer(); $posts = $indexer->search(['title' => $post->getTitle(), 'content' => $post->getContent()], 5, true); if (count($posts) == 0) { $posts = $indexer->search(['title' => $post->title], 5, true); } $this->view->object = $posts; } else { $this->view->object = array(); } return 1; } }
public function saveAction() { if (!$this->request->isPost()) { $this->flashSession->error(t('Hack attempt!!!')); return $this->currentRedirect(); } $id = $this->request->getPost('id'); if (!($object = Posts::findFirstById($id))) { $this->flashSession->error(t('The post not exist')); return $this->currentRedirect(); } $object->setSticked($this->request->getPost('sticked')); if (!$object->save()) { error_log('Save false ' . __LINE__ . ' and ' . __CLASS__); return false; } $this->flashSession->success(t('Data was successfully saved')); return $this->response->redirect($this->router->getControllerName()); }
public function getData() { $lastWeek = new \DateTime(); $lastWeek->modify('-1 week'); $parameters = ['createdAt >= ?0 AND deleted != 1', 'bind' => [$lastWeek->getTimestamp()], 'order' => 'numberViews', 'limit' => 10]; $url = $this->config->application->publicUrl; $posts = []; foreach (Posts::find($parameters) as $post) { $user = $post->user; if ($user == false) { continue; } $title = $post->getTitle(); $content = substr($this->markdown->text($post->getContent()), 0, 200); $link = $url . '/posts/' . $post->getId() . '/' . $post->getSlug(); $posts[] = ['link' => $link, 'title' => $title, 'content' => strip_tags($content)]; } return $posts; }
/** * Finds related posts */ public function showRelatedAction() { $this->view->disable(); if ($this->request->isAjax()) { #$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW); $post = Posts::findFirstById($this->request->getPost('id')); if ($post) { $indexer = new Indexer(); $posts = $indexer->search(['title' => $post->getTitle(), 'content' => $post->getContent()], 5, true); if (count($posts) == 0) { $posts = $indexer->search(['title' => $post->title], 5, true); } if (count($posts) > 0) { $params = ['posts' => $posts]; echo $this->view->getRender('partials', 'list-posts', $params, function ($view) { $view->setRenderLevel(View::LEVEL_ACTION_VIEW); }); } } } }
public function run() { $faker = Faker::create(); $log = new Stream('php://stdout'); $log->info('Start ' . __CLASS__); /** @var Phalcon\Db\AdapterInterface $database */ $database = $this->getDI()->get('db'); $database->begin(); $postsId = Posts::find(['columns' => 'id'])->toArray(); $tagsId = Tags::find(['columns' => 'id'])->toArray(); for ($i = 0; $i <= self::POSTS_TAGS_TOTAL; $i++) { $postRandId = array_rand($postsId); $tagsRandId = array_rand($tagsId); $postTag = new PostsTags(); $postTag->postsId = $postsId[$postRandId]['id']; $postTag->tagsId = $tagsId[$tagsRandId]['id']; if (!$postTag->save()) { var_dump($tags->getMessages()); $database->rollback(); die; } $log->info('Posts<->Tags ' . $postTag->getPostsId() . '<->' . $postTag->getTagsId()); } }
public static function getHotArticle() { $posts = Posts::query()->where('deleted = 0 AND type = "blog"')->orderBy('numberReply DESC, modifiedAt DESC')->limit(7)->execute(); if ($posts->valid()) { return $posts; } return false; }
/** * Method for voting a task * * @return mixed */ public function voteAction() { $this->view->disable(); if (!$this->request->isPost()) { return $this->response->redirect($this->router->getControllerName()); } $way = 'positive'; if ($this->request->getPost('way') == 'negative') { $way = 'negative'; } $objectId = $this->request->getPost('objectId'); $object = $this->request->getPost('object'); $vote = Vote::vote($objectId, $object, $way); $user = Users::findFirstById($this->auth->getAuth()['id']); $this->setJsonResponse(); if (!$user) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => 'You need to login first']; return $this->jsonMessages; } if ($object == Vote::OBJECT_POSTS) { if (!($post = Posts::findFirstById($objectId))) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => 'Post does not exist']; return $this->jsonMessages; } $this->setPointPost($way, $user, $post); //Adding notification when you have receive vote on the post, and not for now for post replies if ($user->getId() != $post->getUsersId()) { $this->setActivityNotifications($user, $post); } } if ($object == Vote::OBJECT_POSTS_REPLY) { if (!($postReply = PostsReply::findFirstById($objectId))) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => 'Post reply does not exist']; return $this->jsonMessages; } //Set karam Voting someone else's post (positive or negative) on posts reply $this->setPointReply($way, $user, $postReply); } if (!$vote) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => 'Vote have a problem :)']; return $this->jsonMessages; } if ($user->getVote() <= 0) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => t('You don\'t have enough votes available :)')]; return $this->jsonMessages; } //checking the user have already voted this post yet if (is_array($vote)) { $this->jsonMessages['messages'][] = $vote; return $this->jsonMessages; } if ($this->request->isAjax()) { $vote = (new Vote())->getVotes($objectId, $object); return ['data' => $vote['positive'] - $vote['negative']]; } echo 0; return 0; }
public static function totalPost() { return Posts::count(); }
/** * Indexes all posts in the forum in ES */ public function indexAll() { $client = new Client(); try { $deleteParams['index'] = $this->index; $client->indices()->delete($deleteParams); } catch (\Exception $e) { // the index does not exist yet } foreach (Posts::find('deleted != 1') as $post) { $this->_doIndex($client, $post); } }
public function editAnswerAction($id) { $auth = $this->auth->getAuth(); $postReply = PostsReply::findFirstById($id); if (!$auth) { $this->flashSession->error(t('You must be logged in first to post answer')); return $this->currentRedirect(); } if (!$this->auth->isTrustModeration() && $auth['id'] != $postReply->getUsersId()) { $this->flashSession->error(t('You don\'t have permission')); return $this->currentRedirect(); } if (!$postReply) { $this->flashSession->error(t('The posts replies not exist!')); return $this->currentRedirect(); } if ($this->request->isPost()) { //save history postreplies table, it just for admin or moderator if ($this->auth->isTrustModeration() && $auth['id'] != $postReply->getUsersId()) { $postReplyHistory = new PostsReplyHistory(); $postReplyHistory->setContent($this->request->getPost('content')); $postReplyHistory->setPostsReplyId($id); $postReplyHistory->setUsersId($auth['id']); if (!$postReplyHistory->save()) { $this->saveLoger($postReplyHistory->getMessages()); } } //Update replies post $postReply->setContent($this->request->getPost('content')); if (!$postReply->save()) { $this->saveLoger($postReply->getMessages()); } $this->flashSession->success(t('Data was successfully saved')); return $this->response->redirect('/posts/' . $postReply->getPostsId() . '/editpost'); } $this->view->hotPosts = Posts::getHotPosts(); $this->view->form = new ReplyForm($postReply); $this->tag->setTitle(t('Edit answer')); return $this->view->pickCustom('replies/editAnswer'); }
/** * Retrieve a page give its title * * @param string $title Page title * * @return object on success or null on failure */ public function getPageByTitle($title) { $param = ['type = "pages" AND title =?0', 'bind' => [$title]]; if (Posts::findFirst($param)) { return Posts::findFirst($param); } return null; }
public function detailAction($user) { if (!($user = Users::findFirstByUsername($user))) { $this->flashSession->error(t('The User dosen\'t exits')); return $this->indexRedirect(); } $tab = $this->request->getQuery('tab'); $page = isset($_GET['page']) ? (int) $_GET['page'] : $this->numberPage; $perPage = isset($_GET['perPage']) ? (int) $_GET['perPage'] : $this->perPage; $where = ''; if ($tab == "answers") { $join = ['type' => 'join', 'model' => 'PostsReply', 'on' => 'r.postsId = p.id', 'alias' => 'r']; list($itemBuilder, $totalBuilder) = ModelBase::prepareQueriesPosts($join, $where, $this->perPage); $itemBuilder->groupBy(array('p.id')); } else { list($itemBuilder, $totalBuilder) = ModelBase::prepareQueriesPosts('', $where, $this->perPage); } $params = []; switch ($tab) { case 'questions': $this->tag->setTitle('Questions'); $questionConditions = 'p.type = "questions"'; $itemBuilder->where($questionConditions); break; case 'answers': $this->tag->setTitle('My Answers'); $answersConditions = 'r.usersId = ?0'; $itemBuilder->where($answersConditions); //$totalBuilder->where($answersConditions); break; default: $this->tag->setTitle('All Questions'); break; } $conditions = 'p.deleted = 0 and p.usersId = ?0'; if ($tab == 'answers') { $conditions = 'p.deleted = 0'; } $itemBuilder->andWhere($conditions); $totalBuilder->andWhere($conditions); $params = array($user->getId()); //get all reply $parametersNumberReply = ['group' => 'postsId', 'usersId = ?0', 'bind' => [$user->getId()]]; $paramQuestions = ['usersId = ?0 and type = "questions" and deleted = 0', 'bind' => [$user->getId()]]; $totalPosts = $totalBuilder->getQuery()->setUniqueRow(true)->execute($params); $totalPages = ceil($totalPosts->count / $perPage); $offset = ($page - 1) * $perPage + 1; if ($page > 1) { $itemBuilder->offset($offset); } $this->view->setVars(['user' => $user, 'posts' => $itemBuilder->getQuery()->execute($params), 'totalQuestions' => Posts::count($paramQuestions), 'totalReply' => PostsReply::find($parametersNumberReply)->count(), 'tab' => $tab, 'totalPages' => $totalPages, 'currentPage' => $page]); }
/** * @return \Phalcon\Http\ResponseInterface */ public function saveAction() { $this->view->disable(); // Is not $_POST if (!$this->request->isPost()) { return $this->indexRedirect(); } $id = $this->request->getPost('id'); if (!empty($id)) { $object = Posts::findFirstById($id); $object->setSlug(Slug::generate($this->request->getPost('title'))); } else { $object = new Posts(); //@todo } $form = new PostsForm($object); $form->bind($_POST, $object); // Form isn't valid if (!$form->isValid($this->request->getPost())) { $this->saveLoger($form->getMessages()); // Redirect to edit form if we have an ID in page, otherwise redirect to add a new item page return $this->response->redirect($this->getPathController() . (!is_null($id) ? '/edit/' . $id : '/new')); } else { if (!$object->save()) { $this->saveLoger($object->getMessages()); return $this->dispatcher->forward(['controller' => $this->getPathController(), 'action' => 'new']); } else { $this->flashSession->success(t('Data was successfully saved')); return $this->currentRedirect(); } } }
/** * @return \Phalcon\Http\ResponseInterface */ public function saveAction() { $this->view->disable(); // Is not $_POST if (!$this->request->isPost()) { return $this->indexRedirect(); } $id = $this->request->getPost('id'); $auth = $this->auth->getAuth(); $tags = $this->request->getPost('tags', 'string', null); if (!empty($id)) { $object = Posts::findFirstById($id); } else { $object = new Posts(); //@todo } $object->setSlug(Slug::generate($this->request->getPost('title'))); $object->setUsersId($auth['id']); $form = new PostsForm($object); $form->bind($_POST, $object); // Form isn't valid if (!$form->isValid($this->request->getPost())) { $this->saveLoger($form->getMessages()); // Redirect to edit form if we have an ID in page, otherwise redirect to add a new item page return $this->response->redirect($this->getPathController() . (!is_null($id) ? '/edit/' . $id : '/new')); } else { $object->setStatus(Posts::PUBLISH_STATUS); //Save post to draft if ($this->request->getPost('saveDraft')) { $object->setStatus(Posts::DRAFT_STATUS); } if (!$object->save()) { $this->saveLoger($object->getMessages()); return $this->dispatcher->forward(['controller' => $this->getPathController(), 'action' => 'new']); } else { $this->phanbook->tag()->saveTagsInPosts($tags, $object); $this->flashSession->success(t('Data was successfully saved')); return $this->indexRedirect(); } } }