Inheritance: extends Phalcon\Mvc\Model
Esempio n. 1
0
 /**
  * Sends the digest
  */
 public function send()
 {
     $lastMonths = new \DateTime();
     $lastMonths->modify('-6 month');
     $parameters = array('modified_at >= ?0 AND digest = "Y" AND notifications <> "N"', 'bind' => array($lastMonths->getTimestamp()));
     $users = array();
     foreach (Users::find($parameters) as $user) {
         if ($user->email && strpos($user->email, '@') !== false && strpos($user->email, '@users.noreply.github.com') === false) {
             $users[trim($user->email)] = $user->name;
         }
     }
     $fromName = $this->config->mail->fromName;
     $fromEmail = $this->config->mail->fromEmail;
     $url = $this->config->site->url;
     $subject = 'Top Stories from Phosphorum ' . date('d/m/y');
     $lastWeek = new \DateTime();
     $lastWeek->modify('-1 week');
     $order = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - ' . 'IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies + IF(accepted_answer = "Y", 10, 0) DESC';
     $parameters = array('created_at >= ?0 AND deleted != 1 AND categories_id <> 4', 'bind' => array($lastWeek->getTimestamp()), 'order' => $order, 'limit' => 10);
     $e = $this->escaper;
     $content = '<html><head></head><body><p><h1 style="font-size:22px;color:#333;letter-spacing:-0.5px;line-height:1.25;font-weight:normal;padding:16px 0;border-bottom:1px solid #e2e2e2">Top Stories from Phosphorum</h1></p>';
     foreach (Posts::find($parameters) as $post) {
         $user = $post->user;
         if ($user == false) {
             continue;
         }
         $content .= '<p><a style="text-decoration:none;display:block;font-size:20px;color:#333;letter-spacing:-0.5px;line-height:1.25;font-weight:normal;color:#155fad" href="' . $url . '/discussion/' . $post->id . '/' . $post->slug . '">' . $e->escapeHtml($post->title) . '</a></p>';
         $content .= '<p><table width="100%"><td><table><tr><td>' . '<img src="https://secure.gravatar.com/avatar/' . $user->gravatar_id . '?s=32&amp;r=pg&amp;d=identicon" width="32" height="32" alt="' . $user->name . ' icon">' . '</td><td><a style="text-decoration:none;color:#155fad" href="' . $url . '/user/' . $user->id . '/' . $user->login . '">' . $user->name . '<br><span style="text-decoration:none;color:#999;text-decoration:none">' . $user->getHumanKarma() . '</span></a></td></tr></table></td><td align="right"><table style="border: 1px solid #dadada;" cellspacing=5>' . '<td align="center"><label style="color:#999;margin:0px;font-weight:normal;">Created</label><br>' . $post->getHumanCreatedAt() . '</td>' . '<td align="center"><label style="color:#999;margin:0px;font-weight:normal;">Replies</label><br>' . $post->number_replies . '</td>' . '<td align="center"><label style="color:#999;margin:0px;font-weight:normal;">Views</label><br>' . $post->number_views . '</td>' . '<td align="center"><label style="color:#999;margin:0px;font-weight:normal;">Votes</label><br>' . ($post->votes_up - $post->votes_down) . '</td>' . '</tr></table></td></tr></table></p>';
         $content .= $this->markdown->render($e->escapeHtml($post->content));
         $content .= '<p><a style="color:#155fad" href="' . $url . '/discussion/' . $post->id . '/' . $post->slug . '">Read more</a></p>';
         $content .= '<hr style="border: 1px solid #dadada">';
     }
     $textContent = strip_tags($content);
     $htmlContent = $content . '<p style="font-size:small;-webkit-text-size-adjust:none;color:#717171;">';
     $htmlContent .= PHP_EOL . 'This email was sent by Phalcon Framework. Change your e-mail preferences <a href="' . $url . '/settings">here</a></p>';
     foreach ($users as $email => $name) {
         try {
             $message = new \Swift_Message('[Phalcon Forum] ' . $subject);
             $message->setTo(array($email => $name));
             $message->setFrom(array($fromEmail => $fromName));
             $bodyMessage = new \Swift_MimePart($htmlContent, 'text/html');
             $bodyMessage->setCharset('UTF-8');
             $message->attach($bodyMessage);
             $bodyMessage = new \Swift_MimePart($textContent, 'text/plain');
             $bodyMessage->setCharset('UTF-8');
             $message->attach($bodyMessage);
             if (!$this->transport) {
                 $this->transport = \Swift_SmtpTransport::newInstance($this->config->smtp->host, $this->config->smtp->port, $this->config->smtp->security);
                 $this->transport->setUsername($this->config->smtp->username);
                 $this->transport->setPassword($this->config->smtp->password);
             }
             if (!$this->mailer) {
                 $this->mailer = \Swift_Mailer::newInstance($this->transport);
             }
             $this->mailer->send($message);
         } catch (\Exception $e) {
             echo $e->getMessage(), PHP_EOL;
         }
     }
 }
Esempio n. 2
0
 /**
  * @return \Phalcon\Http\ResponseInterface
  */
 public function indexAction()
 {
     $this->tag->setTitle('Forum');
     $userId = $this->session->get('identity');
     $categories = Categories::find();
     $lastAuthor = [];
     $notRead = [];
     $postsPerCategory = [];
     foreach ($categories as $category) {
         /** @var \Phalcon\Mvc\Model\Resultset\Simple $posts */
         $posts = Posts::find("categories_id=" . $category->id);
         $postsPerCategory[$category->id] = $posts->count();
         if ($posts->count()) {
             $lastAuthor[$category->id] = $this->modelsManager->createBuilder()->from(['p' => 'Phosphorum\\Models\\Posts'])->where('p.categories_id = "' . $category->id . '"')->join('Phosphorum\\Models\\Users', "u.id = p.users_id", 'u')->columns(['p.users_id as users_id', 'u.name as name_user', 'p.title as post1_title', 'p.slug as post1_slug', 'p.id as post1_id'])->orderBy('p.id DESC')->limit(1)->getQuery()->execute();
         } else {
             $postsPerCategory[$category->id] = 0;
             $lastAuthor[$category->id] = 0;
         }
         // SQL
         $sql[$category->id] = "\n                SELECT *\n                FROM `posts` `p`\n                JOIN `topic_tracking` `tt` ON `tt`.`topic_id`\n                WHERE CONCAT(`p`.`id`)\n                  AND NOT(FIND_IN_SET(`p`.`id`, `tt`.`topic_id`))\n                  AND `p`.`categories_id` = '{$category->id}' AND `tt`.`user_id` = '{$userId}';\n            ";
         $notRead[$category->id] = $this->db->query($sql[$category->id]);
     }
     if ($userId) {
         $check_topic = new TopicTracking();
         $check_topic->user_id = '' . $userId . '';
         $check_topic->topic_id = '9999999';
         $check_topic->create();
     }
     $this->view->setVars(['last_author' => $lastAuthor, 'not_read' => $notRead, 'logged' => $userId, 'categories' => $categories, 'posts_per_category' => $postsPerCategory]);
 }
Esempio n. 3
0
 public function onConstruct()
 {
     $lastThreads = $this->modelsManager->createBuilder()->from(['p' => 'Phosphorum\\Models\\Posts'])->groupBy("p.id")->join('Phosphorum\\Models\\Categories', "r.id = p.categories_id", 'r')->join('Phosphorum\\Models\\Users', "u.id = p.users_id", 'u')->columns(['p.title as title_post', 'p.id as id_post', 'p.slug as slug_post', 'r.name as name_category', 'u.name as name_user'])->where('p.deleted = 0')->orderBy('p.created_at DESC')->limit(3)->getQuery()->execute();
     /** @var Simple $lastMember */
     $lastMember = Users::find(['order' => 'created_at DESC', 'limit' => 1, 'columns' => 'login']);
     $login = null;
     if ($lastMember->valid()) {
         $login = $lastMember->getFirst()->login;
     }
     $this->view->setVars(['app_name' => $this->config->get('site')->name, 'app_version' => VERSION, 'threads' => Posts::count(), 'last_threads' => $lastThreads, 'users' => Users::count(), 'users_latest' => $login, 'actionName' => $this->dispatcher->getActionName(), 'controllerName' => $this->dispatcher->getControllerName()]);
 }
Esempio n. 4
0
 public function statsAction()
 {
     $this->view->threads = Posts::count();
     $this->view->replies = Posts::sum(array('column' => 'number_replies'));
     $this->view->votes = Posts::sum(array('column' => 'votes_up + votes_down'));
     $this->view->users = Users::count();
     $this->view->karma = Users::sum(array('column' => 'karma'));
     $this->view->notifications = Notifications::count();
     $this->view->unotifications = ActivityNotifications::count();
     $this->view->views = Posts::sum(array('column' => 'number_views'));
     $this->view->irc = IrcLog::count();
 }
Esempio n. 5
0
 /**
  * Votes for a poll option
  *
  * @param int $id     Post ID
  * @param int $option Option ID
  * @return Response
  */
 public function voteAction($id = 0, $option = 0)
 {
     $response = new Response();
     if (!$this->checkTokenGetJson('post-' . $id)) {
         $csrfTokenError = ['status' => 'error', 'message' => 'This post is outdated. Please try to vote again.'];
         return $response->setJsonContent($csrfTokenError);
     }
     if (!($post = Posts::findFirstById($id))) {
         $contentNotExist = ['status' => 'error', 'message' => 'Poll does not exist'];
         return $response->setJsonContent($contentNotExist);
     }
     if (!($user = Users::findFirstById($this->session->get('identity')))) {
         $contentlogIn = ['status' => 'error', 'message' => 'You must log in first to vote'];
         return $response->setJsonContent($contentlogIn);
     }
     if (!($option = PostsPollOptions::findFirstById($option))) {
         $optionNotFound = ['status' => 'error', 'message' => 'Please select one option from the list below'];
         return $response->setJsonContent($optionNotFound);
     }
     if ($post->isParticipatedInPoll($user->id)) {
         $contentAlreadyVote = ['status' => 'error', 'message' => 'You have already voted this post'];
         return $response->setJsonContent($contentAlreadyVote);
     }
     $pollVote = new PostsPollVotes();
     $pollVote->posts_id = $post->id;
     $pollVote->users_id = $user->id;
     $pollVote->options_id = $option->id;
     if (!$pollVote->save()) {
         foreach ($pollVote->getMessages() as $message) {
             /** @var \Phalcon\Mvc\Model\Message $message */
             $contentError = ['status' => 'error', 'message' => $message->getMessage()];
             return $response->setJsonContent($contentError);
         }
     }
     if ($post->users_id != $user->id) {
         $post->user->increaseKarma(Karma::SOMEONE_DID_VOTE_MY_POLL);
         $user->increaseKarma(Karma::VOTE_ON_SOMEONE_ELSE_POLL);
     }
     if (!$post->save()) {
         foreach ($post->getMessages() as $message) {
             /** @var \Phalcon\Mvc\Model\Message $message */
             $contentErrorSave = ['status' => 'error', 'message' => $message->getMessage()];
             return $response->setJsonContent($contentErrorSave);
         }
     }
     $viewCache = $this->getDI()->getShared('viewCache');
     $viewCache->delete('post-' . $post->id);
     $viewCache->delete('poll-votes-' . $post->id);
     $viewCache->delete('poll-options-' . $post->id);
     $contentOk = ['status' => 'OK'];
     return $response->setJsonContent($contentOk);
 }
Esempio n. 6
0
 public function karmaAction()
 {
     foreach (Users::find() as $user) {
         if ($user->karma === null) {
             $parametersNumbersPost = array('users_id = ?0', 'bind' => array($user->id));
             $numberPosts = Posts::count($parametersNumbersPost);
             $parametersNumberReplies = array('users_id = ?0', 'bind' => array($user->id));
             $numberReplies = PostsReplies::count($parametersNumberReplies);
             $user->karma = $numberReplies * 10 + $numberPosts * 5;
             $user->votes = intval($user->karma / 50);
             $user->save();
         }
     }
 }
Esempio n. 7
0
 public function run()
 {
     $log = new Stream('php://stdout');
     /** @var Config $config */
     $config = Di::getDefault()->getShared('config');
     $expireDate = new DateTime('now', new DateTimeZone('UTC'));
     $expireDate->modify('+1 day');
     $sitemap = new DOMDocument("1.0", "UTF-8");
     $sitemap->formatOutput = true;
     $urlset = $sitemap->createElement('urlset');
     $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
     $urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
     $baseUrl = $config->get('site')->url;
     $url = $sitemap->createElement('url');
     $url->appendChild($sitemap->createElement('loc', $baseUrl));
     $url->appendChild($sitemap->createElement('changefreq', 'daily'));
     $url->appendChild($sitemap->createElement('priority', '1.0'));
     $urlset->appendChild($url);
     $karmaSql = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies';
     $parametersPosts = ['conditions' => 'deleted != 1', 'columns' => "id, slug, modified_at, {$karmaSql} AS karma", 'order' => 'karma DESC'];
     $posts = Posts::find($parametersPosts);
     $parametersKarma = ['column' => $karmaSql, 'conditions' => 'deleted != 1'];
     $karma = Posts::maximum($parametersKarma);
     $modifiedAt = new DateTime('now', new DateTimeZone('UTC'));
     foreach ($posts as $post) {
         $modifiedAt->setTimestamp($post->modified_at);
         $postKarma = $post->karma / ($karma + 100);
         $url = $sitemap->createElement('url');
         $href = trim($baseUrl, '/') . '/discussion/' . $post->id . '/' . $post->slug;
         $url->appendChild($sitemap->createElement('loc', $href));
         $valuePriority = $postKarma > 0.7 ? sprintf("%0.1f", $postKarma) : sprintf("%0.1f", $postKarma + 0.25);
         $url->appendChild($sitemap->createElement('priority', $valuePriority));
         $url->appendChild($sitemap->createElement('lastmod', $modifiedAt->format('Y-m-d\\TH:i:s\\Z')));
         $urlset->appendChild($url);
     }
     $sitemap->appendChild($urlset);
     $adapter = new Local(dirname(dirname(__FILE__)) . '/public');
     $filesystem = new Filesystem($adapter);
     if ($filesystem->has('sitemap.xml')) {
         $result = $filesystem->update('sitemap.xml', $sitemap->saveXML() . PHP_EOL);
     } else {
         $result = $filesystem->write('sitemap.xml', $sitemap->saveXML() . PHP_EOL);
     }
     if ($result) {
         $log->info('The sitemap.xml was successfully updated');
     } else {
         $log->error('Failed to update the sitemap.xml file');
     }
 }
Esempio n. 8
0
 /**
  * Generate the website sitemap
  */
 public function indexAction()
 {
     $response = new Response();
     $expireDate = new \DateTime();
     $expireDate->modify('+1 day');
     $response->setExpires($expireDate);
     $response->setHeader('Content-Type', "application/xml; charset=UTF-8");
     $sitemap = new \DOMDocument("1.0", "UTF-8");
     $urlset = $sitemap->createElement('urlset');
     $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
     $urlset->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
     $baseUrl = $this->config->site->url;
     $url = $sitemap->createElement('url');
     $url->appendChild($sitemap->createElement('loc', $baseUrl));
     $url->appendChild($sitemap->createElement('changefreq', 'daily'));
     $url->appendChild($sitemap->createElement('priority', '1.0'));
     $urlset->appendChild($url);
     $karmaSql = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies';
     $parametersPosts = ['conditions' => 'deleted != 1', 'columns' => "id, slug, modified_at, {$karmaSql} AS karma", 'order' => 'karma DESC'];
     $posts = Posts::find($parametersPosts);
     $parametersKarma = ['column' => $karmaSql, 'conditions' => 'deleted != 1'];
     $karma = Posts::maximum($parametersKarma);
     $modifiedAt = new \DateTime();
     $modifiedAt->setTimezone(new \DateTimeZone('UTC'));
     foreach ($posts as $post) {
         $modifiedAt->setTimestamp($post->modified_at);
         $postKarma = $post->karma / ($karma + 100);
         $url = $sitemap->createElement('url');
         $href = trim($baseUrl, '/') . '/discussion/' . $post->id . '/' . $post->slug;
         $url->appendChild($sitemap->createElement('loc', $href));
         $valuePriority = $postKarma > 0.7 ? sprintf("%0.1f", $postKarma) : sprintf("%0.1f", $postKarma + 0.25);
         $url->appendChild($sitemap->createElement('priority', $valuePriority));
         $url->appendChild($sitemap->createElement('lastmod', $modifiedAt->format('Y-m-d\\TH:i:s\\Z')));
         $urlset->appendChild($url);
     }
     $sitemap->appendChild($urlset);
     $response->setContent($sitemap->saveXML());
     return $response;
 }
Esempio n. 9
0
 public function statsAction()
 {
     $this->breadcrumbs->add('Help', '/help')->add('Statistics', '/help/stats', ['linked' => false]);
     $this->tag->setTitle("Statistics");
     $this->view->setVars(['threads' => Posts::count(), 'replies' => Posts::sum(['column' => 'number_replies']), 'votes' => Posts::sum(['column' => 'votes_up + votes_down']), 'users' => Users::count(), 'karma' => Users::sum(['column' => 'karma']), 'notifications' => Notifications::count(), 'unotifications' => ActivityNotifications::count(), 'views' => Posts::sum(['column' => 'number_views']), 'irc' => IrcLog::count()]);
 }
Esempio n. 10
0
 /**
  * Finds related posts
  */
 public function showRelatedAction()
 {
     $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
     $post = Posts::findFirstById($this->request->getPost('id'));
     if ($post) {
         $indexer = new Indexer();
         $posts = $indexer->search(['title' => $post->title, 'category' => $post->categories_id], 5, true);
         if (count($posts) == 0) {
             $posts = $indexer->search(['title' => $post->title], 5, true);
         }
         $this->view->setVar('posts', $posts);
     } else {
         $this->view->setVar('posts', []);
     }
 }
Esempio n. 11
0
 public function onConstruct()
 {
     $last_threads = $this->modelsManager->createBuilder()->from(array('p' => 'Phosphorum\\Models\\Posts'))->groupBy("p.id")->join('Phosphorum\\Models\\Categories', "r.id = p.categories_id", 'r')->join('Phosphorum\\Models\\Users', "u.id = p.users_id", 'u')->columns(array('p.title as title_post', 'p.id as id_post', 'p.slug as slug_post', 'r.name as name_category', 'u.name as name_user'))->orderBy('p.created_at DESC')->limit(3)->getQuery()->execute();
     $users = Users::find()->getLast();
     $this->view->setVars(['threads' => Posts::count(), 'last_threads' => $last_threads, 'users' => Users::count(), 'users_latest' => $users->login, 'actionName' => $this->dispatcher->getActionName()]);
 }
Esempio n. 12
0
 /**
  * Sends the digest
  */
 public function send()
 {
     $lastMonths = new \DateTime();
     $lastMonths->modify('-6 month');
     $parameters = ['modified_at >= ?0 AND digest = "Y" AND notifications <> "N"', 'bind' => [$lastMonths->getTimestamp()]];
     $users = [];
     foreach (Users::find($parameters) as $user) {
         if ($user->email && strpos($user->email, '@') !== false && strpos($user->email, '@users.noreply.github.com') === false) {
             $users[trim($user->email)] = $user->name;
         }
     }
     $view = new View();
     $view->setViewsDir($this->config->application->viewsDir);
     $fromName = $this->config->mail->fromName;
     $fromEmail = $this->config->mail->fromEmail;
     $url = rtrim($this->config->site->url, '/');
     $subject = sprintf('Top Stories from Phosphorum %s', date('d/m/y'));
     $view->setVar('title', $subject);
     $lastWeek = new \DateTime();
     $lastWeek->modify('-1 week');
     $order = 'number_views + ' . '((IF(votes_up IS NOT NULL, votes_up, 0) - ' . 'IF(votes_down IS NOT NULL, votes_down, 0)) * 4) + ' . 'number_replies + IF(accepted_answer = "Y", 10, 0) DESC';
     $parameters = ['created_at >= ?0 AND deleted != 1 AND categories_id <> 4', 'bind' => [$lastWeek->getTimestamp()], 'order' => $order, 'limit' => 10];
     $e = $this->escaper;
     /** @var \Phalcon\Logger\AdapterInterface $logger */
     $logger = $this->getDI()->get('logger', ['mail']);
     $stories = [];
     foreach (Posts::find($parameters) as $i => $post) {
         $user = $post->user;
         if ($user == false) {
             continue;
         }
         $this->gravatar->setSize(32);
         $stories[$i]['user_name'] = $user->name;
         $stories[$i]['user_avatar'] = $this->gravatar->getAvatar($user->email);
         $stories[$i]['user_url'] = "{$url}/user/{$user->id}/{$user->login}";
         $stories[$i]['user_karma'] = $user->getHumanKarma();
         $stories[$i]['post_title'] = $e->escapeHtml($post->title);
         $stories[$i]['post_created'] = $post->getHumanCreatedAt();
         $stories[$i]['post_replies'] = (int) $post->number_replies;
         $stories[$i]['post_views'] = (int) $post->number_views;
         $stories[$i]['post_votes'] = $post->votes_up - $post->votes_down;
         $stories[$i]['post_content'] = $this->markdown->render($e->escapeHtml($post->content));
         $stories[$i]['post_url'] = "{$url}/discussion/{$post->id}/{$post->slug}";
     }
     if (empty($stories)) {
         return;
     }
     $view->setVar('stories', $stories);
     $view->setVar('notice', sprintf('This email was sent by %s mail sender. Change your e-mail preferences <a href="%s/settings">here</a>', $this->config->site->name, $url));
     $content = $view->render('mail/digest.phtml');
     $textContent = preg_replace('#<a[^>]+href="([^"]+)"[^>]*>([^<]+)<\\/a>#', '$2:' . "\n" . '$1', $content);
     $textContent = str_replace('<span class="foot-line"></span>', "--\n", $textContent);
     $textContent = trim(strip_tags($textContent));
     $textContent = str_replace('&nbsp;', ' ', $textContent);
     $textContent = preg_replace('#\\t+#', '', $textContent);
     $textContent = preg_replace('# {2,}#', ' ', $textContent);
     $textContent = preg_split('#(\\r|\\n)#', $textContent);
     $textContent = join("\n\n", array_filter($textContent, function ($line) {
         return '' !== trim($line);
     }));
     $textContent = preg_replace('#^[ \\t]+#m', '', $textContent);
     foreach ($users as $email => $name) {
         try {
             $message = new \Swift_Message("[{$this->config->site->name} Forum] " . $subject);
             $message->setTo([$email => $name]);
             $message->setFrom([$fromEmail => $fromName]);
             $bodyMessage = new \Swift_MimePart($content, 'text/html');
             $bodyMessage->setCharset('UTF-8');
             $message->attach($bodyMessage);
             $bodyMessage = new \Swift_MimePart($textContent, 'text/plain');
             $bodyMessage->setCharset('UTF-8');
             $message->attach($bodyMessage);
             if (!$this->transport) {
                 $this->transport = \Swift_SmtpTransport::newInstance($this->config->smtp->host, $this->config->smtp->port, $this->config->smtp->security);
                 $this->transport->setUsername($this->config->smtp->username);
                 $this->transport->setPassword($this->config->smtp->password);
             }
             if (!$this->mailer) {
                 $this->mailer = \Swift_Mailer::newInstance($this->transport);
             }
             $failedRecipients = [];
             $this->mailer->send($message, $failedRecipients);
             if (empty($failedRecipients)) {
                 $logger->info("Sent an email to {$email}");
             } else {
                 $logger->error("Unable to sent an email to " . join(', ', $failedRecipients));
             }
         } catch (\Exception $e) {
             $logger->error($e->getMessage());
             throw new \Exception($e->getMessage(), $e->getCode(), $e);
         }
     }
 }
Esempio n. 13
0
    $user->login = $faker->userName;
    $user->email = $faker->email;
    $user->timezone = $faker->timezone;
    if (!$user->save()) {
        $database->rollback();
        die(join(PHP_EOL, $user->getMessages()));
    }
    $log->info('User: '******'columns' => 'id'])->toArray();
$userIds = Users::find(['columns' => 'id'])->toArray();
$database->begin();
for ($i = 0; $i <= 500; $i++) {
    $title = $faker->company;
    $post = new Posts();
    $post->title = $title;
    $post->slug = Tag::friendlyTitle($title);
    $post->content = $faker->text();
    $userRandId = array_rand($userIds);
    $post->users_id = $userIds[$userRandId]['id'];
    $categoryRandId = array_rand($categoryIds);
    $post->categories_id = $categoryIds[$categoryRandId]['id'];
    if (!$post->save()) {
        $database->rollback();
        die(join(PHP_EOL, $post->getMessages()));
    }
    if (!mt_rand(0, 10)) {
        $size = mt_rand(2, 10);
        $options = [];
        for ($j = 0; $j < $size; $j++) {
Esempio n. 14
0
 /**
  * This implements an inbound webhook from MandrillApp to reply to posts using emails
  *
  */
 public function mailReplyAction()
 {
     $response = new Response();
     if ($this->request->isPost()) {
         if (!isset($this->config->mandrillapp->secret)) {
             return $response;
         }
         if ($this->config->mandrillapp->secret != $this->request->getQuery('secret')) {
             return $response;
         }
         $events = @json_decode($this->request->getPost('mandrill_events'), true);
         if (!is_array($events)) {
             return $response;
         }
         foreach ($events as $event) {
             if (!isset($event['event'])) {
                 continue;
             }
             $type = $event['event'];
             if ($type != 'inbound') {
                 continue;
             }
             if (!isset($event['msg'])) {
                 continue;
             }
             $msg = $event['msg'];
             if (!isset($msg['dkim'])) {
                 continue;
             }
             if (!isset($msg['from_email'])) {
                 continue;
             }
             if (!isset($msg['email'])) {
                 continue;
             }
             if (!isset($msg['text'])) {
                 continue;
             }
             $content = $msg['text'];
             if (!trim($content)) {
                 continue;
             }
             $user = Users::findFirstByEmail($msg['from_email']);
             if (!$user) {
                 continue;
             }
             $email = $msg['email'];
             if (!preg_match('#^reply-i([0-9]+)-([0-9]+)@phosphorum.com$#', $email, $matches)) {
                 continue;
             }
             $post = Posts::findFirst($matches[1]);
             if (!$post) {
                 continue;
             }
             if ($post->deleted) {
                 continue;
             }
             /**
              * Process replies to remove the base message
              */
             $str = array();
             $firstNoBaseReplyLine = false;
             foreach (array_reverse(preg_split('/\\r\\n|\\n/', trim($content))) as $line) {
                 if (!$firstNoBaseReplyLine) {
                     if (substr($line, 0, 1) == '>') {
                         continue;
                     } else {
                         $firstNoBaseReplyLine = true;
                     }
                 }
                 if (preg_match('/^[0-9]{4}\\-[0-9]{2}\\-[0-9]{2} [0-9]{2}:[0-9]{2} GMT([\\-\\+][0-9]{2}:[0-9]{2})? ([^:]*):$/u', $line)) {
                     continue;
                 }
                 if (preg_match('/^On [A-Za-z]{3} [0-9]{1,2}, [0-9]{4} [0-9]{1,2}:[0-9]{2} [AP]M, ([^:]*):$/u', $line)) {
                     continue;
                 }
                 $str[] = $line;
             }
             $content = join("\r\n", array_reverse($str));
             /**
              * Check if the question can have a bounty before add the reply
              */
             $canHaveBounty = $post->canHaveBounty();
             /**
              * Only update the number of replies if the user that commented isn't the same that posted
              */
             if ($post->users_id != $user->id) {
                 $post->number_replies++;
                 $post->modified_at = time();
                 $post->user->increaseKarma(Karma::SOMEONE_REPLIED_TO_MY_POST);
                 $user->increaseKarma(Karma::REPLY_ON_SOMEONE_ELSE_POST);
                 $user->save();
             }
             $postReply = new PostsReplies();
             $postReply->post = $post;
             $postReply->users_id = $user->id;
             $postReply->content = $content;
             if ($postReply->save()) {
                 if ($post->users_id != $user->id && $canHaveBounty) {
                     $bounty = $post->getBounty();
                     $postBounty = new PostsBounties();
                     $postBounty->posts_id = $post->id;
                     $postBounty->users_id = $users->id;
                     $postBounty->posts_replies_id = $postReply->id;
                     $postBounty->points = $bounty['value'];
                     if (!$postBounty->save()) {
                         foreach ($postBounty->getMessages() as $message) {
                             $this->flash->error($message);
                         }
                     }
                 }
             }
         }
     }
     return $response;
 }
Esempio n. 15
0
 protected function createPostArray(Posts $post)
 {
     return ['slug' => "discussion/{$post->id}/{$post->slug}", 'title' => $post->title, 'created' => $post->getHumanCreatedAt()];
 }
Esempio n. 16
0
 /**
  * Indexes all posts in the forum in ES
  */
 public function indexAll()
 {
     $client = new Client();
     try {
         $deleteParams['index'] = 'phosphorum';
         $client->indices()->delete($deleteParams);
     } catch (\Exception $e) {
         // the index does not exist yet
     }
     foreach (Posts::find('deleted != 1') as $post) {
         $this->doIndex($client, $post);
     }
 }
Esempio n. 17
0
 /**
  * Allow to change your user settings
  */
 public function settingsAction()
 {
     $usersId = $this->session->get('identity');
     if (!$usersId) {
         $this->flashSession->error('You must be logged first');
         $this->response->redirect();
         return;
     }
     $user = Users::findFirstById($usersId);
     if (!$user) {
         $this->flashSession->error('The user does not exist');
         $this->response->redirect();
         return;
     }
     if ($this->request->isPost()) {
         if (!$this->checkTokenPost()) {
             $this->response->redirect();
             return;
         }
         $user->timezone = $this->request->getPost('timezone');
         $user->notifications = $this->request->getPost('notifications');
         $user->theme = $this->request->getPost('theme');
         $user->digest = $this->request->getPost('digest');
         if ($user->save()) {
             $this->session->set('identity-theme', $user->theme);
             $this->session->get('identity-timezone', $user->timezone);
             $this->flashSession->success('Settings were successfully updated');
             $this->response->redirect();
             return;
         }
     } else {
         $this->tag->displayTo('timezone', $user->timezone);
         $this->tag->displayTo('notifications', $user->notifications);
         $this->tag->displayTo('theme', $user->theme);
         $this->tag->displayTo('digest', $user->digest);
     }
     $this->tag->setTitle('My Settings');
     $this->tag->setAutoEscape(false);
     $this->gravatar->setSize(64);
     $this->view->setVars(['user' => $user, 'timezones' => $this->di->getShared('timezones'), 'numberPosts' => Posts::count(['users_id = ?0 AND deleted = 0', 'bind' => [$user->id]]), 'numberReplies' => PostsReplies::count(['users_id = ?0', 'bind' => [$user->id]])]);
 }