public function editAction($id)
{
if (!($usersId = $this->session->get('identity'))) {
$this->flashSession->error('You must be logged first');
$this->response->redirect();
return;
}
$parameters = ["id = ?0 AND (users_id = ?1 OR 'Y' = ?2)", 'bind' => [$id, $usersId, $this->session->get('identity-moderator')]];
if (!($post = Posts::findFirst($parameters))) {
$this->flashSession->error('The discussion does not exist');
$this->response->redirect();
return;
}
if ($this->request->isPost()) {
if (!$this->checkTokenPost('edit-post-' . $id)) {
$this->response->redirect();
return;
}
$title = $this->request->getPost('title', 'trim');
$content = $this->request->getPost('content');
/** @var \Phalcon\Db\Adapter\Pdo\Mysql $connection */
$connection = $this->getDI()->getShared('db');
$connection->begin();
$post->categories_id = $this->request->getPost('categoryId');
$post->title = $title;
$post->slug = $this->slug->generate($title);
$post->content = $content;
$post->edited_at = time();
if (!$post->hasPoll() || !$post->isStartVoting()) {
foreach ($post->getPollOptions() as $option) {
$option->delete();
}
if ($pollOptions = $this->request->getPost('pollOptions', ['trim'], [])) {
foreach ($pollOptions as $opt) {
$option = new PostsPollOptions();
$option->posts_id = $post->id;
$option->title = htmlspecialchars($opt, ENT_QUOTES);
$option->save();
}
}
}
if ($post->isStartVoting()) {
$connection->rollback();
$this->flashSession->error("The voting for the poll was started. You can't change the Poll.");
} elseif ($post->save()) {
if ($post->users_id != $usersId && ($user = Users::findFirstById($usersId))) {
$user->increaseKarma(Karma::MODERATE_POST);
$user->save();
}
$connection->commit();
$this->response->redirect("discussion/{$post->id}/{$post->slug}");
return;
} else {
$connection->rollback();
$this->flashSession->error(join('<br>', $post->getMessages()));
}
} else {
$this->tag->displayTo('id', $post->id);
$this->tag->displayTo('title', $post->title);
$this->tag->displayTo('content', $post->content);
$this->tag->displayTo('categoryId', $post->categories_id);
}
$this->tag->setTitle('Edit Discussion: ' . $this->escaper->escapeHtml($post->title));
$this->gravatar->setSize(48);
$this->view->setVars(['categories' => Categories::find(['order' => 'name']), 'post' => $post, 'optionsCount' => $post->pollOptions->count()]);
}