Example #1
0
 /**
  * TODO: In future models will have more relations which might not delete automatically. It should be tested properly
  * TODO: Files should be deleted too
  * Deletes all boards, threads and posts with 'is_deleted = 1', handles relation between them.
  * @return array with deleted rows
  */
 public static function clean()
 {
     $itemsToDelete = ['boardsIds' => [], 'threadsIds' => [], 'postsIds' => [], 'postDataIds' => [], 'postMessageIds' => []];
     Post::getDeletedRows($itemsToDelete);
     Thread::getDeletedRows($itemsToDelete);
     Board::getDeletedRows($itemsToDelete);
     self::getPostDataIds($itemsToDelete);
     self::getPostMessageIds($itemsToDelete);
     /**
      * Deletes post_message's related to threads and posts
      */
     $deleted['post_messages'] = PostMessage::deleteAll(['in', 'id', array_unique($itemsToDelete['postMessageIds'])]);
     /**
      * Deletes threads and posts because of FK
      */
     $deleted['threads'] = Thread::deleteAll(['in', 'id', array_unique($itemsToDelete['threadsIds'])]);
     /**
      * Deleted posts and threads related to post_data
      */
     $deleted['post_data'] = PostData::deleteAll(['in', 'id', array_unique($itemsToDelete['postDataIds'])]);
     /**
      * Deleted boards
      */
     $deleted['boards'] = Board::deleteAll(['in', 'id', array_unique($itemsToDelete['boardsIds'])]);
     $deleted['posts'] = $deleted['post_data'] - $deleted['threads'];
     $deleted['total'] = $deleted['boards'] + $deleted['threads'] + $deleted['posts'] + $deleted['post_data'] + $deleted['post_messages'];
     return $deleted;
 }
 public function beforeAction($action)
 {
     $request = \Yii::$app->urlManager->parseRequest(\Yii::$app->request);
     $board = Board::findOne(['name' => $request[1]['name']]);
     $thread = isset($request[1]['threadNum']) ? Thread::findOne($request[1]['threadNum']) : null;
     $ban = new Ban($board, $thread);
     return $ban->check();
 }
 public function create(string $boardName, array $data)
 {
     /** @var Board $board */
     if (!($board = Board::findOne(['name' => $boardName]))) {
         throw new UserException('Board was not found', 404);
     }
     $validationParams = $board->postsSettings->getValidationParams();
     $thread = new Thread(['boardId' => $board->id]);
     $postData = new PostData(['validationParams' => $validationParams]);
     $uploadForm = new UploadForm(['files' => PostedFile::getPostedFiles($validationParams['maxFiles']), 'validationParams' => $validationParams]);
     $toLoad = [$thread, $postData];
     $toValidate = [$thread, $postData, $uploadForm];
     if (!ARExtended::loadMultiple($toLoad, $data) || !Model::validateMultiple($toValidate)) {
         throw new UserException('Failed to load/validate data', 400);
     }
     if (strlen($postData->messageText) == 0 && count($uploadForm->files)) {
         throw new UserException('Must be attached atleast 1 file or non-empty message', 400);
     }
     $toSave = [$postData, $thread, $uploadForm];
     $postData->on(PostData::EVENT_AFTER_INSERT, function ($event) use($thread) {
         $thread->postDataId = $event->sender->id;
     });
     $saved = true;
     foreach ($toSave as $model) {
         if (method_exists($model, 'save')) {
             $saved = $saved && $model->save();
             if (!$saved) {
                 break;
             }
         }
     }
     if (!$saved) {
         for ($i = count($toSave) - 1; $i >= 0; $i--) {
             method_exists($toSave[$i], 'delete') && $toSave[$i]->delete();
         }
         throw new UserException('Failed to create thread', 500);
     }
     foreach ($uploadForm->getFileInfos() as $fileInfo) {
         $postData->link('fileInfos', $fileInfo);
     }
     $thread->link('board', $board);
     return $thread;
 }
 function search()
 {
     if (!isset($_GET['q'])) {
         $q = "";
     } else {
         $q = $_GET['q'];
     }
     $threads = Thread::search($q);
     $view = new SearchResultsView(compact('threads'));
     $view->render();
 }
 public static function notification($template, $recipient, $variables)
 {
     $variables['recipient'] = $recipient;
     if ($recipient instanceof User) {
         $recipient = array($recipient);
     }
     foreach ($recipient as $user) {
         $messageParts = View::make('messenger.templates.' . $template, $variables)->renderSections();
         $thread = Thread::create(['subject' => $messageParts['subject']]);
         // Message
         Message::create(['thread_id' => $thread->id, 'user_id' => $user->id, 'body' => $messageParts['body'] . $messageParts['footer'], 'type' => 'notification']);
         // Sender
         Participant::create(['thread_id' => $thread->id, 'user_id' => $user->id]);
         // Recipients
         $thread->addParticipants(array($user->id));
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $users = User::where(['frequency' => 'new-challenge', 'confirmed' => true, 'unsubscribed' => false])->get();
     $latestChallenge = Thread::all()->sortByDesc('published_at')->first();
     $isNewChallenge = $this->verifyNewChallenge($latestChallenge);
     if (!$isNewChallenge) {
         return;
     }
     Cache::forget('last_challenge_sent');
     Cache::forever('last_challenge_sent', $latestChallenge);
     $latestChallenge->markdown_content = (new CommonMarkConverter())->convertToHtml($latestChallenge->content);
     $latestChallenge->markdown_content = str_replace('<pre>', '<pre style="white-space: pre-wrap;"', $latestChallenge->markdown_content);
     $latestChallengeDifficulty = $latestChallenge->difficulty;
     $users = $users->filter(function ($user) use($latestChallengeDifficulty) {
         return $user->hasDifficulty($latestChallengeDifficulty) || $user->hasDifficulty('all') || collect($user->difficulties)->count() == 0;
     });
     $users->each(function ($user) use($latestChallenge) {
         $this->dispatch(new SendChallengesEmail($user, collect([$latestChallenge]), 'new-challenge'));
     });
 }
Example #7
0
 public function getNewNotifications()
 {
     $threadsWithNewMessages = [];
     $participants = Participant::where('user_id', $this->id)->lists('last_read', 'thread_id');
     /**
      * @todo: see if we can fix this more in the future.
      * Illuminate\Foundation is not available through composer, only in laravel/framework which
      * I don't want to include as a dependency for this package...it's overkill. So let's
      * exclude this check in the testing environment.
      */
     if (getenv('APP_ENV') == 'testing' || !str_contains(\Illuminate\Foundation\Application::VERSION, '5.0')) {
         $participants = $participants->all();
     }
     if ($participants) {
         $threads = Thread::whereIn('id', array_keys($participants))->get();
         foreach ($threads as $thread) {
             if ($thread->updated_at > $participants[$thread->id] && $thread->getLatestMessageAttribute()->type == 'notification') {
                 $threadsWithNewMessages[] = $thread->id;
             }
         }
     }
     return $threadsWithNewMessages;
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $users = User::where(['frequency' => 'weekly', 'confirmed' => true, 'unsubscribed' => false])->get();
     $threads = Thread::all();
     $currentWeekIndex = Carbon::now()->weekOfYear;
     $currentYear = Carbon::now()->year;
     $currentWeekChallenges = $threads->filter(function ($thread) use($currentWeekIndex, $currentYear) {
         return $thread->published_at->weekOfYear == $currentWeekIndex && $thread->published_at->year == $currentYear;
     });
     if ($currentWeekChallenges->count() == 0) {
         return;
     }
     $markdownConverter = new CommonMarkConverter();
     $currentWeekChallenges->map(function ($challenge) use($markdownConverter) {
         $challenge->markdown_content = $markdownConverter->convertToHtml($challenge->content);
         $challenge->markdown_content = str_replace('<pre>', '<pre style="white-space: pre-wrap;"', $challenge->markdown_content);
     });
     $users->each(function ($user) use($currentWeekChallenges) {
         $challengesForUser = $this->getChallengesForCurrentUser($user, $currentWeekChallenges);
         if ($challengesForUser->count() > 0) {
             $this->dispatch(new SendChallengesEmail($user, $challengesForUser, 'weekly'));
         }
     });
 }
 public function createThread($data)
 {
     $res = preg_match('#^\\[(?P<date>.*)\\]\\s(?P<challenge_index>\\w+\\s.*)\\s*\\[(?P<difficulty>\\w+)\\]\\s*(?P<title>.*)\\z#', $data['title'], $matches);
     if ($res) {
         $this->info($data['title'] . ' matches pattern');
         $title = trim($matches['challenge_index']) . ' - ' . trim($matches['title']);
         $difficulty = strtolower($matches['difficulty']);
         $url = $data['url'];
         $thread_already_stored = Thread::where(['title' => $title, 'difficulty' => $difficulty, 'url' => $url])->count() > 0;
         if (!$thread_already_stored) {
             Thread::create(['title' => $title, 'difficulty' => $difficulty, 'url' => $data['url'], 'published_at' => $data['published_at'], 'content' => $data['content'], 'html_content' => $data['html_content']]);
         }
     } else {
         $this->warn($data['title'] . ' failed to match pattern');
     }
 }
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function destroy($id)
 {
     $thread = Thread::find($id);
     $thread->delete();
     return redirect(route('intern.discuss.index'));
 }
 /**
  * Delete a thread
  *
  * @param $threadId
  * @return mixed
  */
 public function delete($threadId)
 {
     try {
         $thread = Thread::findOrFail($threadId);
     } catch (ModelNotFoundException $e) {
         Session::flash('error_message', 'The thread with ID: ' . $threadId . ' was not found.');
         return Redirect::to('messages');
     }
     $thread->delete();
     return Redirect::to('messages/');
 }
Example #12
0
 public function getThreads()
 {
     return $this->hasMany(Thread::className(), ['board_id' => 'id'])->orderBy(['updated_at' => SORT_DESC]);
 }
 public function destroy()
 {
     static::$auth->mustBeAdmin();
     Thread::destroy($_POST['id']);
     header("Location: ./?page=threads");
 }