/** * 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&r=pg&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; } } }
/** * @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]); }
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'); } }
/** * 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; }
/** * 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(' ', ' ', $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); } } }
/** * Indexes all posts in the forum in ES */ public function indexAll() { $deleteParams = ['index' => $this->config->get('index', 'phosphorum')]; try { $this->client->indices()->delete($deleteParams); } catch (Missing404Exception $e) { $this->logger->info('The index does not exist yet. Skip deleting...'); } catch (\Exception $e) { $this->logger->error("Indexer: {$e->getMessage()}. {$e->getFile()}:{$e->getLine()}"); } foreach (Posts::find('deleted != ' . Posts::IS_DELETED) as $post) { $this->doIndex($post); } }
/** * 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); } }
foreach ($options as $opt) { $option = new PostsPollOptions(); $option->posts_id = $post->id; $option->title = htmlspecialchars($opt, ENT_QUOTES); if (!$option->save()) { echo join(PHP_EOL, $option->getMessages()), PHP_EOL; $database->rollback(); die; } $log->info('Option: ' . $option->title); } } $log->info('Post: ' . $post->title); } $database->commit(); $postIds = Posts::find(['columns' => 'id'])->toArray(); $database->begin(); for ($i = 0; $i <= 1000; $i++) { $reply = new PostsReplies(); $reply->content = $faker->paragraph(); $postRandId = array_rand($postIds); $reply->posts_id = $postIds[$postRandId]['id']; $userRandId = array_rand($userIds); $reply->users_id = $userIds[$userRandId]['id']; if (!$reply->save()) { $database->rollback(); die(join(PHP_EOL, $reply->getMessages())); } $reply->post->number_replies++; $reply->post->modified_at = time(); $reply->save();