sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function actionThumb() { if (!Yii::$app->request->isAjax) { return $this->redirect(['forum/index']); } $data = [ 'error' => 1, 'msg' => Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Error while voting on this post!'), ['class' => 'text-danger'] ), ]; if ($this->module->user->isGuest) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Please sign in to vote on this post'), ['class' => 'text-info'] ); return Json::encode($data); } $postId = Yii::$app->request->post('post'); $thumb = Yii::$app->request->post('thumb'); if (is_numeric($postId) && $postId > 0 && in_array($thumb, ['up', 'down'])) { $post = Post::find()->where(['id' => $postId])->limit(1)->one(); if ($post) { if ($post->thread->locked) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'This thread is locked.'), ['class' => 'text-info'] ); return Json::encode($data); } if ($post->author_id == User::loggedId()) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'You can not vote on your own post!'), ['class' => 'text-info'] ); return Json::encode($data); } $count = 0; $votes = $this->module->podiumCache->get('user.votes.' . User::loggedId()); if ($votes !== false) { if ($votes['expire'] < time()) { $votes = false; } elseif ($votes['count'] >= 10) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', '{max} votes per hour limit reached!', ['max' => 10]), ['class' => 'text-danger'] ); return Json::encode($data); } else { $count = $votes['count']; } } if ($post->podiumThumb($thumb == 'up', $count)) { $data = [ 'error' => 0, 'likes' => '+' . $post->likes, 'dislikes' => '-' . $post->dislikes, 'summ' => $post->likes - $post->dislikes, 'msg' => Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-ok-circle']) . ' ' . Yii::t('podium/view', 'Your vote has been saved!'), ['class' => 'text-success'] ), ]; } } } return Json::encode($data); }
Voting on the post. @return string|Response
entailment
public function actionMarkSeen() { if (Thread::podiumMarkAllSeen()) { $this->success(Yii::t('podium/flash', 'All unread threads have been marked as seen.')); return $this->redirect(['forum/index']); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while marking threads as seen. Contact administrator about this problem.')); return $this->redirect(['forum/unread-posts']); }
Marking all unread posts as seen. @return Response
entailment
public function run($id = null) { $model = User::find()->where(['id' => $id])->limit(1)->one(); if (empty($model)) { $this->controller->error(Yii::t('podium/flash', 'Sorry! We can not find User with this ID.')); return $this->controller->redirect(['admin/members']); } if ($model->role != $this->fromRole) { $this->controller->error($this->restrictMessage); return $this->controller->redirect(['admin/members']); } if (call_user_func([$model, $this->method], $this->toRole)) { $this->controller->success($this->successMessage); if ($this->method == 'promoteTo') { return $this->controller->redirect(['admin/mods', 'id' => $model->id]); } return $this->controller->redirect(['admin/members']); } $this->controller->error($this->errorMessage); return $this->controller->redirect(['admin/members']); }
Runs action. @param int $id user ID @return Response
entailment
public function createCommand($db = null) { if ($db === null) { $db = Podium::getInstance()->db; } return parent::createCommand($db); }
Creates a DB command that can be used to execute this query. @param Connection $db the database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used. @return Command the created DB command instance.
entailment
public function run() { $user = $this->user; if (empty($user)) { return [ true, Yii::t('podium/flash', 'Sorry! We can not find the account with that user name or e-mail address.'), false ]; } $user->scenario = 'token'; $user->generatePasswordResetToken(); if (!$user->save()) { return [true, null, false]; } if (empty($user->email)) { return [ true, Yii::t('podium/flash', 'Sorry! There is no e-mail address saved with your account. Contact administrator about resetting password.'), true ]; } if (!$this->sendResetEmail($user)) { return [ true, Yii::t('podium/flash', 'Sorry! There was some error while sending you the password reset link. Contact administrator about this problem.'), true ]; } return [ false, Yii::t('podium/flash', 'The password reset link has been sent to your e-mail address.'), true ]; }
Generates new password reset token. @return int
entailment
public function actionCategory($id = null, $slug = null) { if (!is_numeric($id) || $id < 1 || empty($slug)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the category you are looking for.')); return $this->redirect(['forum/index']); } $conditions = ['id' => $id, 'slug' => $slug]; if ($this->module->user->isGuest) { $conditions['visible'] = 1; } $model = Category::find()->where($conditions)->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the category you are looking for.')); return $this->redirect(['forum/index']); } $this->setMetaTags($model->keywords, $model->description); return $this->render('category', ['model' => $model]); }
Displaying the category of given ID and slug. @param int $id @param string $slug @return string|Response
entailment
public function actionForum($cid = null, $id = null, $slug = null, $toggle = null) { $filters = Yii::$app->session->get('forum-filters'); if (in_array(strtolower($toggle), ['new', 'edit', 'hot', 'pin', 'lock', 'all'])) { if (strtolower($toggle) == 'all') { $filters = null; } else { $filters[strtolower($toggle)] = empty($filters[strtolower($toggle)]) || $filters[strtolower($toggle)] == 0 ? 1 : 0; } Yii::$app->session->set('forum-filters', $filters); return $this->redirect([ 'forum/forum', 'cid' => $cid, 'id' => $id, 'slug' => $slug ]); } $forum = Forum::verify($cid, $id, $slug, $this->module->user->isGuest); if (empty($forum)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the forum you are looking for.')); return $this->redirect(['forum/index']); } $this->setMetaTags( $forum->keywords ?: $forum->category->keywords, $forum->description ?: $forum->category->description ); return $this->render('forum', [ 'model' => $forum, 'filters' => $filters ]); }
Displaying the forum of given category ID, own ID and slug. @param int $cid category ID @param int $id forum ID @param string $slug forum slug @return string|Response
entailment
public function actionLast($id = null) { if (!is_numeric($id) || $id < 1) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the thread you are looking for.')); return $this->redirect(['forum/index']); } $thread = Thread::find()->where(['id' => $id])->limit(1)->one(); if (empty($thread)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the thread you are looking for.')); return $this->redirect(['forum/index']); } $url = [ 'forum/thread', 'cid' => $thread->category_id, 'fid' => $thread->forum_id, 'id' => $thread->id, 'slug' => $thread->slug ]; $count = $thread->postsCount; $page = floor($count / 10) + 1; if ($page > 1) { $url['page'] = $page; } return $this->redirect($url); }
Direct link for the last post in thread of given ID. @param int $id @return Response
entailment
public function actionShow($id = null) { if (!is_numeric($id) || $id < 1) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the post you are looking for.')); return $this->redirect(['forum/index']); } $post = Post::find()->where(['id' => $id])->limit(1)->one(); if (empty($post)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the post you are looking for.')); return $this->redirect(['forum/index']); } $url = [ 'forum/thread', 'cid' => $post->thread->category_id, 'fid' => $post->forum_id, 'id' => $post->thread_id, 'slug' => $post->thread->slug ]; try { $count = (new Query)->from(Post::tableName())->where([ 'and', ['thread_id' => $post->thread_id], ['<', 'id', $post->id] ])->count(); $page = floor($count / 10) + 1; if ($page > 1) { $url['page'] = $page; } $url['#'] = 'post' . $post->id; return $this->redirect($url); } catch (Exception $e) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the post you are looking for.')); return $this->redirect(['forum/index']); } }
Direct link for the post of given ID. @param int $id @return Response
entailment
public function actionThread($cid = null, $fid = null, $id = null, $slug = null) { $thread = (new ThreadVerifier([ 'categoryId' => $cid, 'forumId' => $fid, 'threadId' => $id, 'threadSlug' => $slug ]))->verify(); if (empty($thread)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the thread you are looking for.')); return $this->redirect(['forum/index']); } $this->setMetaTags( $thread->forum->keywords ?: $thread->forum->category->keywords, $thread->forum->description ?: $thread->forum->category->description ); $model = new Post; $model->subscribe = 1; $dataProvider = $model->search($thread->forum->id, $thread->id); return $this->render('thread', [ 'model' => $model, 'dataProvider' => $dataProvider, 'thread' => $thread, ]); }
Displaying the thread of given category ID, forum ID, own ID and slug. @param int $cid category ID @param int $fid forum ID @param int $id thread ID @param string $slug thread slug @return string|Response
entailment
public function setMetaTags($keywords = null, $description = null) { if (empty($keywords)) { $keywords = $this->module->podiumConfig->get('meta_keywords'); } if ($keywords) { $this->getView()->registerMetaTag([ 'name' => 'keywords', 'content' => $keywords ]); } if (empty($description)) { $description = $this->module->podiumConfig->get('meta_description'); } if ($description) { $this->getView()->registerMetaTag([ 'name' => 'description', 'content' => $description ]); } }
Setting meta tags. @param string $keywords @param string $description
entailment
public function actionDeletepoll($cid = null, $fid = null, $tid = null, $pid = null) { $poll = Poll::find()->joinWith('thread')->where([ Poll::tableName() . '.id' => $pid, Poll::tableName() . '.thread_id' => $tid, Thread::tableName() . '.category_id' => $cid, Thread::tableName() . '.forum_id' => $fid, ])->limit(1)->one(); if (empty($poll)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the poll you are looking for.')); return $this->redirect(['forum/index']); } if ($poll->thread->locked == 1 && !User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $poll->thread])) { $this->info(Yii::t('podium/flash', 'This thread is locked.')); return $this->redirect([ 'forum/thread', 'cid' => $poll->thread->category_id, 'fid' => $poll->thread->forum_id, 'id' => $poll->thread->id, 'slug' => $poll->thread->slug ]); } if ($poll->author_id != User::loggedId() && !User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $poll->thread])) { $this->error(Yii::t('podium/flash', 'Sorry! You do not have the required permission to perform this action.')); return $this->redirect(['forum/index']); } $postData = Yii::$app->request->post('poll'); if ($postData) { if ($postData != $poll->id) { $this->error(Yii::t('podium/flash', 'Sorry! There was an error while deleting the poll.')); } else { if ($poll->podiumDelete()) { $this->success(Yii::t('podium/flash', 'Poll has been deleted.')); return $this->redirect([ 'forum/thread', 'cid' => $poll->thread->category_id, 'fid' => $poll->thread->forum_id, 'id' => $poll->thread->id, 'slug' => $poll->thread->slug ]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while deleting the poll.')); } } return $this->render('deletepoll', ['model' => $poll]); }
Deleting the poll of given category ID, forum ID, thread ID and ID. @param int $cid category ID @param int $fid forum ID @param int $tid thread ID @param int $pid poll ID @return string|Response @since 0.5
entailment
public function actionSearch() { $searchModel = new Vocabulary; if (!$searchModel->load(Yii::$app->request->get(), '')) { return $this->redirect(['forum/advanced-search']); } return $this->render('search', [ 'dataProvider' => $searchModel->search(), 'query' => $searchModel->query, ]); }
Searching through the forum. @return string
entailment
public function actionAdvancedSearch() { $dataProvider = null; $list = []; $model = new SearchForm; $model->setParams(); if ($model->nextPage) { $dataProvider = $model->searchAdvanced(); } else { $categories = Category::find()->orderBy(['name' => SORT_ASC]); $forums = Forum::find()->orderBy(['name' => SORT_ASC]); foreach ($categories->each() as $cat) { $catlist = []; foreach ($forums->each() as $for) { if ($for->category_id == $cat->id) { $catlist[$for->id] = '|-- ' . Html::encode($for->name); } } $list[Html::encode($cat->name)] = $catlist; } if ($model->load(Yii::$app->request->post()) && $model->validate()) { if (empty($model->query) && empty($model->author)) { $this->error(Yii::t('podium/flash', "You have to enter words or author's name first.")); } else { $stop = false; if (!empty($model->query)) { $words = explode(' ', preg_replace('/\s+/', ' ', $model->query)); $checkedWords = []; foreach ($words as $word) { if (mb_strlen($word, 'UTF-8') > 2) { $checkedWords[] = $word; } } $model->query = implode(' ', $checkedWords); if (mb_strlen($model->query, 'UTF-8') < 3) { $this->error(Yii::t('podium/flash', 'You have to enter word at least 3 characters long.')); $stop = true; } } if (!$stop) { $dataProvider = $model->searchAdvanced(); } } } } return $this->render('search', [ 'model' => $model, 'list' => $list, 'dataProvider' => $dataProvider, 'query' => $model->query, 'author' => $model->author, ]); }
Advanced searching through the forum. @return string @since 0.8
entailment
public function actionPoll() { if (!Yii::$app->request->isAjax) { return $this->redirect(['forum/index']); } $data = [ 'error' => 1, 'msg' => Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Error while voting in this poll!'), ['class' => 'text-danger'] ), ]; if ($this->module->user->isGuest) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Please sign in to vote in this poll'), ['class' => 'text-info'] ); return Json::encode($data); } $pollId = Yii::$app->request->post('poll_id'); $votes = Yii::$app->request->post('poll_vote'); if (is_numeric($pollId) && $pollId > 0 && !empty($votes)) { /* @var $poll Poll */ $poll = Poll::find()->where([ 'and', ['id' => $pollId], [ 'or', ['>', 'end_at', time()], ['end_at' => null] ] ])->limit(1)->one(); if (empty($poll)) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'This poll is not active.'), ['class' => 'text-danger'] ); return Json::encode($data); } $loggedId = User::loggedId(); if ($poll->getUserVoted($loggedId)) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-info-sign']) . ' ' . Yii::t('podium/view', 'You have already voted in this poll.'), ['class' => 'text-info'] ); return Json::encode($data); } $checkedAnswers = []; foreach ($votes as $vote) { if (!$poll->hasAnswer((int)$vote)) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Invalid poll answer given.'), ['class' => 'text-danger'] ); return Json::encode($data); } $checkedAnswers[] = (int)$vote; } if (empty($checkedAnswers)) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'You need to select at least one answer.'), ['class' => 'text-warning'] ); return Json::encode($data); } if (count($checkedAnswers) > $poll->votes) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'This poll allows maximum {n, plural, =1{# answer} other{# answers}}.', ['n' => $poll->votes]), ['class' => 'text-danger'] ); return Json::encode($data); } if ($poll->vote($loggedId, $checkedAnswers)) { $data = [ 'error' => 0, 'votes' => $poll->currentVotes, 'count' => $poll->votesCount, 'msg' => Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-ok-circle']) . ' ' . Yii::t('podium/view', 'Your vote has been saved!'), ['class' => 'text-success'] ), ]; } } return Json::encode($data); }
Voting in poll. @return array @since 0.5
entailment
public function actionEditpoll($cid = null, $fid = null, $tid = null, $pid = null) { $poll = Poll::find()->joinWith('thread')->where([ Poll::tableName() . '.id' => $pid, Poll::tableName() . '.thread_id' => $tid, Thread::tableName() . '.category_id' => $cid, Thread::tableName() . '.forum_id' => $fid, ])->limit(1)->one(); if (empty($poll)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the poll you are looking for.')); return $this->redirect(['forum/index']); } if ($poll->thread->locked == 1 && !User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $poll->thread])) { $this->info(Yii::t('podium/flash', 'This thread is locked.')); return $this->redirect(['forum/thread', 'cid' => $poll->thread->forum->category->id, 'fid' => $poll->thread->forum->id, 'id' => $poll->thread->id, 'slug' => $poll->thread->slug ]); } if ($poll->author_id != User::loggedId() && !User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $poll->thread])) { $this->error(Yii::t('podium/flash', 'Sorry! You do not have the required permission to perform this action.')); return $this->redirect(['forum/thread', 'cid' => $poll->thread->forum->category->id, 'fid' => $poll->thread->forum->id, 'id' => $poll->thread->id, 'slug' => $poll->thread->slug ]); } if ($poll->votesCount) { $this->error(Yii::t('podium/flash', 'Sorry! Someone has already voted and this poll can no longer be edited.')); return $this->redirect(['forum/thread', 'cid' => $poll->thread->forum->category->id, 'fid' => $poll->thread->forum->id, 'id' => $poll->thread->id, 'slug' => $poll->thread->slug ]); } foreach ($poll->answers as $answer) { $poll->editAnswers[] = $answer->answer; } $postData = Yii::$app->request->post(); if ($poll->load($postData)) { if ($poll->validate()) { if ($poll->podiumEdit()) { $this->success(Yii::t('podium/flash', 'Poll has been updated.')); return $this->redirect(['forum/thread', 'cid' => $poll->thread->forum->category->id, 'fid' => $poll->thread->forum->id, 'id' => $poll->thread->id, 'slug' => $poll->thread->slug ]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while updating the post. Contact administrator about this problem.')); } } return $this->render('editpoll', ['model' => $poll]); }
Editing the poll of given category ID, forum ID, thread ID and own ID. @param int $cid category ID @param int $fid forum ID @param int $tid thread ID @param int $pid poll ID @return string|Response @since 0.5
entailment
public function activate() { if ($this->status == self::STATUS_REGISTERED) { $transaction = static::getDb()->beginTransaction(); try { $this->removeActivationToken(); $this->status = self::STATUS_ACTIVE; if (!$this->save()) { throw new Exception('User saving error!'); } if (!Podium::getInstance()->rbac->assign(Podium::getInstance()->rbac->getRole(Rbac::ROLE_USER), $this->id)) { throw new Exception('User role assigning error!'); } $transaction->commit(); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } } return false; }
Activates account. @return bool
entailment
public function changeEmail() { $this->email = $this->new_email; $this->new_email = null; $this->removeEmailToken(); return $this->save(); }
Changes email address. @return bool
entailment
public function changePassword() { $this->setPassword($this->password); $this->generateAuthKey(); $this->removePasswordResetToken(); return $this->save(); }
Changes password. @return bool
entailment
public function getNewMessagesCount() { $cache = Podium::getInstance()->podiumCache->getElement('user.newmessages', $this->id); if ($cache === false) { $cache = (new Query())->from(MessageReceiver::tableName())->where([ 'receiver_id' => $this->id, 'receiver_status' => Message::STATUS_NEW ])->count(); Podium::getInstance()->podiumCache->setElement('user.newmessages', $this->id, $cache); } return $cache; }
Returns number of new user messages. @return int
entailment
public function getPodiumTag($simple = false) { return Helper::podiumUserTag($this->podiumName, $this->role, $this->id, $this->podiumSlug, $simple); }
Returns Podium name tag. @param bool $simple @return string
entailment
public static function findPostsCount($id) { $cache = Podium::getInstance()->podiumCache->getElement('user.postscount', $id); if ($cache === false) { $cache = (new Query)->from(Post::tableName())->where(['author_id' => $id])->count(); Podium::getInstance()->podiumCache->setElement('user.postscount', $id, $cache); } return $cache; }
Returns number of active posts added by user of given ID. @param int $id @return int
entailment
public static function findThreadsCount($id) { $cache = Podium::getInstance()->podiumCache->getElement('user.threadscount', $id); if ($cache === false) { $cache = (new Query)->from(Thread::tableName())->where(['author_id' => $id])->count(); Podium::getInstance()->podiumCache->setElement('user.threadscount', $id, $cache); } return $cache; }
Returns number of active threads added by user of given ID. @param int $id @return int
entailment
public static function getRoles() { return [ self::ROLE_MEMBER => Yii::t('podium/view', 'Member'), self::ROLE_MODERATOR => Yii::t('podium/view', 'Moderator'), self::ROLE_ADMIN => Yii::t('podium/view', 'Admin'), ]; }
Returns list of roles. @return array
entailment
public static function getStatuses() { return [ self::STATUS_ACTIVE => Yii::t('podium/view', 'Active'), self::STATUS_BANNED => Yii::t('podium/view', 'Banned'), self::STATUS_REGISTERED => Yii::t('podium/view', 'Registered'), ]; }
Returns list of statuses. @return array
entailment
public function getSubscriptionsCount() { $cache = Podium::getInstance()->podiumCache->getElement('user.subscriptions', $this->id); if ($cache === false) { $cache = (new Query)->from(Subscription::tableName())->where([ 'user_id' => $this->id, 'post_seen' => Subscription::POST_NEW ])->count(); Podium::getInstance()->podiumCache->setElement('user.subscriptions', $this->id, $cache); } return $cache; }
Returns number of user subscribed threads with new posts. @return int
entailment
public function isIgnoredBy($userId) { if ((new Query)->select('id')->from('{{%podium_user_ignore}}')->where([ 'user_id' => $userId, 'ignored_id' => $this->id ])->exists()) { return true; } return false; }
Finds out if user is ignored by another. @param int $userId user ID @return bool
entailment
public function isIgnoring($user_id) { if ((new Query)->select('id')->from('{{%podium_user_ignore}}')->where([ 'user_id' => $this->id, 'ignored_id' => $user_id ])->exists()) { return true; } return false; }
Finds out if user is ignoring another. @param int $user_id user ID @return bool
entailment
public static function loggedId() { if (Podium::getInstance()->user->isGuest) { return null; } if (Podium::getInstance()->userComponent !== true) { $user = static::findMe(); if (empty($user)) { return null; } return $user->id; } return Podium::getInstance()->user->id; }
Returns ID of current logged user. @return int
entailment
public function demoteTo($role) { $transaction = static::getDb()->beginTransaction(); try { $this->scenario = 'role'; $this->role = $role; if (!$this->save()) { throw new Exception('User saving error!'); } if (Podium::getInstance()->rbac->getRolesByUser($this->id) && !Podium::getInstance()->rbac->revoke(Podium::getInstance()->rbac->getRole(Rbac::ROLE_MODERATOR), $this->id)) { throw new Exception('User role revoking error!'); } if (!Podium::getInstance()->rbac->assign(Podium::getInstance()->rbac->getRole(Rbac::ROLE_USER), $this->id)) { throw new Exception('User role assigning error!'); } if ((new Query())->from(Mod::tableName())->where(['user_id' => $this->id])->exists() && !Podium::getInstance()->db->createCommand()->delete(Mod::tableName(), ['user_id' => $this->id])->execute()) { throw new Exception('Moderator deleting error!'); } Activity::updateRole($this->id, User::ROLE_MEMBER); $transaction->commit(); Log::info('User demoted', $this->id, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Demotes user to given role. @param int $role @return bool
entailment
public function promoteTo($role) { $transaction = static::getDb()->beginTransaction(); try { $this->scenario = 'role'; $this->role = $role; if (!$this->save()) { throw new Exception('User saving error!'); } if (Podium::getInstance()->rbac->getRolesByUser($this->id) && !Podium::getInstance()->rbac->revoke(Podium::getInstance()->rbac->getRole(Rbac::ROLE_USER), $this->id)) { throw new Exception('User role revoking error!'); } if (!Podium::getInstance()->rbac->assign(Podium::getInstance()->rbac->getRole(Rbac::ROLE_MODERATOR), $this->id)) { throw new Exception('User role assigning error!'); } Activity::updateRole($this->id, User::ROLE_MODERATOR); $transaction->commit(); Log::info('User promoted', $this->id, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Promotes user to given role. Only moderator supported now. @param int $role @return bool
entailment
public function register() { $this->setPassword($this->password); $this->generateActivationToken(); $this->generateAuthKey(); $this->status = self::STATUS_REGISTERED; if (!$this->save()) { return self::RESP_ERR; } if (empty($this->email)) { return self::RESP_NO_EMAIL_ERR; } if (!$this->sendActivationEmail()) { return self::RESP_EMAIL_SEND_ERR; } return self::RESP_OK; }
Registers new account. @return int
entailment
public function saveChanges() { if (!empty($this->newPassword)) { $this->setPassword($this->newPassword); } if (!empty($this->new_email)) { $this->generateEmailToken(); } $updateActivityName = $this->isAttributeChanged('username'); if (!$this->save(false)) { return false; } if ($updateActivityName) { Activity::updateName($this->id, $this->podiumName, $this->podiumSlug); } return true; }
Saves user account details changes. @return bool
entailment
public static function can($permissionName, $params = [], $allowCaching = true) { if (Podium::getInstance()->userComponent === true) { return Podium::getInstance()->user->can($permissionName, $params, $allowCaching); } if (!Podium::getInstance()->user->isGuest) { $user = static::findMe(); if (empty($user)) { return false; } if ($allowCaching && empty($params) && isset($user->_access[$permissionName])) { return $user->_access[$permissionName]; } $access = Podium::getInstance()->rbac->checkAccess($user->id, $permissionName, $params); if ($allowCaching && empty($params)) { $user->_access[$permissionName] = $access; } return $access; } return false; }
Implementation of \yii\web\User::can(). @param string $permissionName the name of the permission. @param array $params name-value pairs that would be passed to the rules. @param bool $allowCaching whether to allow caching the result. @return bool
entailment
public static function friendsList() { if (Podium::getInstance()->user->isGuest) { return null; } $logged = static::loggedId(); $cache = Podium::getInstance()->podiumCache->getElement('user.friends', $logged); if ($cache === false) { $cache = []; $friends = static::findMe()->friends; if ($friends) { /* @var $friend User */ foreach ($friends as $friend) { $cache[$friend->id] = $friend->getPodiumTag(true); } } Podium::getInstance()->podiumCache->setElement('user.friends', $logged, $cache); } return $cache; }
Returns list of friends for dropdown. @return array @since 0.2
entailment
public function updateModeratorForOne($forumId = null) { try { if ((new Query())->from(Mod::tableName())->where([ 'forum_id' => $forumId, 'user_id' => $this->id ])->exists()) { Podium::getInstance()->db->createCommand()->delete(Mod::tableName(), [ 'forum_id' => $forumId, 'user_id' => $this->id ])->execute(); } else { Podium::getInstance()->db->createCommand()->insert(Mod::tableName(), [ 'forum_id' => $forumId, 'user_id' => $this->id ])->execute(); } Podium::getInstance()->podiumCache->deleteElement('forum.moderators', $forumId); Log::info('Moderator updated', $this->id, __METHOD__); return true; } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Updates moderator assignment for given forum. @param int $forumId forum ID @return bool @since 0.2
entailment
public function updateModeratorForMany($newForums = [], $oldForums = []) { $transaction = static::getDb()->beginTransaction(); try { $add = []; foreach ($newForums as $forum) { if (!in_array($forum, $oldForums, true) && (new Query)->from(Forum::tableName())->where(['id' => $forum])->exists() && (new Query)->from(Mod::tableName())->where(['forum_id' => $forum, 'user_id' => $this->id])->exists() === false) { $add[] = [$forum, $this->id]; } } $remove = []; foreach ($oldForums as $forum) { if (!in_array($forum, $newForums, true) && (new Query)->from(Mod::tableName())->where(['forum_id' => $forum, 'user_id' => $this->id])->exists()) { $remove[] = $forum; } } if (!empty($add) && !Podium::getInstance()->db->createCommand()->batchInsert(Mod::tableName(), ['forum_id', 'user_id'], $add)->execute()) { throw new Exception('Moderators adding error!'); } if (!empty($remove) && !Podium::getInstance()->db->createCommand()->delete(Mod::tableName(), ['forum_id' => $remove, 'user_id' => $this->id])->execute()) { throw new Exception('Moderators deleting error!'); } Podium::getInstance()->podiumCache->delete('forum.moderators'); Log::info('Moderators updated', null, __METHOD__); $transaction->commit(); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Updates moderator assignment for given forums. @param array $newForums new assigned forum IDs @param array $oldForums old assigned forum IDs @return bool @since 0.2
entailment
protected function generateUsername() { $userNameField = Podium::getInstance()->userNameField; if ($userNameField !== null) { if (empty(Podium::getInstance()->user->identity->$userNameField)) { throw new InvalidConfigException("Non-existing or empty '$userNameField' field!"); } $username = Podium::getInstance()->user->identity->$userNameField; } else { $try = 0; do { $username = 'user_' . time() . mt_rand(1000, 9999); if ($try++ > 10) { throw new Exception('Failed to generate unique username!'); } } while ((new Query)->from(static::tableName())->where(['username' => $username])->exists()); } $this->username = $username; }
Generates username for inherited account. @throws Exception @since 0.7
entailment
public static function createInheritedAccount() { if (!Podium::getInstance()->user->isGuest) { $transaction = static::getDb()->beginTransaction(); try { $newUser = new static; $newUser->setScenario('installation'); $newUser->inherited_id = Podium::getInstance()->user->id; $newUser->status = self::STATUS_ACTIVE; $newUser->role = self::ROLE_MEMBER; $newUser->generateUsername(); if (!$newUser->save()) { throw new Exception('Account creating error'); } if (!Podium::getInstance()->rbac->assign(Podium::getInstance()->rbac->getRole(Rbac::ROLE_USER), $newUser->id)) { throw new Exception('User role assigning error'); } PodiumCache::clearAfter('activate'); Log::info('Inherited account created', $newUser->id, __METHOD__); $transaction->commit(); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } } return false; }
Creates inherited account. @return bool @since 0.2
entailment
public static function updateInheritedAccount() { if (!Podium::getInstance()->user->isGuest) { $userNameField = Podium::getInstance()->userNameField; if ($userNameField === null) { return true; } if (empty(Podium::getInstance()->user->identity->$userNameField)) { throw new InvalidConfigException("Non-existing or empty '$userNameField' field!"); } $savedUser = static::find()->where(['inherited_id' => Podium::getInstance()->user->id])->limit(1)->one(); if (empty($savedUser)) { throw new InvalidConfigException('Can not find inherited account in database!'); } if ($savedUser->username === Podium::getInstance()->user->identity->$userNameField) { return true; } $savedUser->scenario = 'installation'; $savedUser->username = Podium::getInstance()->user->identity->$userNameField; if ($savedUser->save()) { Log::info('Inherited account updated', $savedUser->id, __METHOD__); return true; } throw new Exception('Inherited account updating error'); } return true; }
Updates inherited account's username. @return bool @throws Exception @throws InvalidConfigException @since 0.8
entailment
public static function getMembersList($query = null) { if (null === $query || !is_string($query)) { return Json::encode(['results' => []]); } $cache = Podium::getInstance()->podiumCache->getElement('members.fieldlist', $query); if ($cache === false) { $users = static::find()->where(['and', ['status' => self::STATUS_ACTIVE], ['!=', 'id', static::loggedId()], ['like', 'username', $query] ]); $users->orderBy(['username' => SORT_ASC, 'id' => SORT_ASC]); $results = ['results' => []]; foreach ($users->each() as $user) { $results['results'][] = ['id' => $user->id, 'text' => $user->getPodiumTag(true)]; } if (empty($results['results'])) { return Json::encode(['results' => []]); } $cache = Json::encode($results); Podium::getInstance()->podiumCache->setElement('members.fieldlist', $query, $cache); } return $cache; }
Returns JSON list of members matching query. @param string $query @return string @since 0.2
entailment
public function updateIgnore($member) { try { if ($this->isIgnoredBy($member)) { if (!Podium::getInstance()->db->createCommand()->delete('{{%podium_user_ignore}}', [ 'user_id' => $member, 'ignored_id' => $this->id ])->execute()) { return false; } Log::info('User unignored', $this->id, __METHOD__); } else { if (!Podium::getInstance()->db->createCommand()->insert('{{%podium_user_ignore}}', ['user_id' => $member, 'ignored_id' => $this->id])->execute()) { return false; } Log::info('User ignored', $this->id, __METHOD__); } return true; } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Updates ignore status for the user. @param int $member @return bool @since 0.2
entailment
public function updateFriend($friend) { try { if ($this->isBefriendedBy($friend)) { if (!Podium::getInstance()->db->createCommand()->delete('{{%podium_user_friend}}', [ 'user_id' => $friend, 'friend_id' => $this->id ])->execute()) { return false; } Log::info('User unfriended', $this->id, __METHOD__); } else { if (!Podium::getInstance()->db->createCommand()->insert('{{%podium_user_friend}}', ['user_id' => $friend, 'friend_id' => $this->id])->execute()) { return false; } Log::info('User befriended', $this->id, __METHOD__); } Podium::getInstance()->podiumCache->deleteElement('user.friends', $friend); return true; } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Updates friend status for the user. @param int $friend @return bool @since 0.2
entailment
protected function sendActivationEmail() { $forum = Podium::getInstance()->podiumConfig->get('name'); $email = Content::fill(Content::EMAIL_REGISTRATION); if ($email !== false) { $link = Url::to(['account/activate', 'token' => $this->activation_token], true); return Email::queue( $this->email, str_replace('{forum}', $forum, $email->topic), str_replace('{forum}', $forum, str_replace('{link}', Html::a($link, $link), $email->content)), !empty($this->id) ? $this->id : null ); } return false; }
Sends activation email. @return bool @since 0.2
entailment
public static function findMe() { if (Podium::getInstance()->userComponent === true) { return Podium::getInstance()->user->identity; } if (static::$_identity === null) { static::$_identity = static::find()->where(['inherited_id' => Podium::getInstance()->user->id])->limit(1)->one(); } return static::$_identity; }
Returns current user based on module configuration. @return static
entailment
public function run() { if (!$this->model) { return null; } $hidden = $this->model->hidden; if ($hidden && !empty($this->model->end_at) && $this->model->end_at < time()) { $hidden = 0; } return $this->render('view', [ 'model' => $this->model, 'hidden' => $hidden, 'voted' => $this->display ? true : $this->model->getUserVoted(User::loggedId()), 'display' => $this->display ]); }
Rendering the poll. @return string
entailment
public function firstToSee() { if ($this->firstNewNotSeen) { return $this->firstNewNotSeen; } if ($this->firstEditedNotSeen) { return $this->firstEditedNotSeen; } return $this->latest; }
Returns first post to see. @return Post
entailment
public function search($forumId = null, $filters = null) { $query = static::find(); if ($forumId) { $query->where(['forum_id' => (int)$forumId]); } if (!empty($filters)) { $loggedId = User::loggedId(); if (!empty($filters['pin']) && $filters['pin'] == 1) { $query->andWhere(['pinned' => 1]); } if (!empty($filters['lock']) && $filters['lock'] == 1) { $query->andWhere(['locked' => 1]); } if (!empty($filters['hot']) && $filters['hot'] == 1) { $query->andWhere(['>=', 'posts', Podium::getInstance()->podiumConfig->get('hot_minimum')]); } if (!empty($filters['new']) && $filters['new'] == 1 && !Podium::getInstance()->user->isGuest) { $query->joinWith(['threadView tvn' => function ($q) use ($loggedId) { $q->onCondition(['tvn.user_id' => $loggedId]); $q->andWhere(['or', new Expression('tvn.new_last_seen < new_post_at'), ['tvn.new_last_seen' => null] ]); }], false); } if (!empty($filters['edit']) && $filters['edit'] == 1 && !Podium::getInstance()->user->isGuest) { $query->joinWith(['threadView tve' => function ($q) use ($loggedId) { $q->onCondition(['tve.user_id' => $loggedId]); $q->andWhere(['or', new Expression('tve.edited_last_seen < edited_post_at'), ['tve.edited_last_seen' => null] ]); }], false); } } $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => false, ]); $dataProvider->sort->defaultOrder = [ 'pinned' => SORT_DESC, 'updated_at' => SORT_DESC, 'id' => SORT_ASC ]; return $dataProvider; }
Searches for thread. @param int $forumId @return ActiveDataProvider
entailment
public function searchByUser($userId) { $query = static::find(); $query->where(['author_id' => $userId]); if (Podium::getInstance()->user->isGuest) { $query->joinWith(['forum' => function ($q) { $q->where([Forum::tableName() . '.visible' => 1]); }]); } $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => false, ]); $dataProvider->sort->defaultOrder = [ 'updated_at' => SORT_DESC, 'id' => SORT_ASC ]; return $dataProvider; }
Searches for threads created by user of given ID. @param int $userId @return ActiveDataProvider
entailment
public function getIcon() { $icon = self::ICON_NO_NEW; $append = false; if ($this->locked) { $icon = self::ICON_LOCKED; $append = true; } elseif ($this->pinned) { $icon = self::ICON_PINNED; $append = true; } elseif ($this->posts >= Podium::getInstance()->podiumConfig->get('hot_minimum')) { $icon = self::ICON_HOT; $append = true; } if ($this->userView) { if ($this->new_post_at > $this->userView->new_last_seen) { if (!$append) { $icon = self::ICON_NEW; } } elseif ($this->edited_post_at > $this->userView->edited_last_seen) { if (!$append) { $icon = self::ICON_NEW; } } } else { if (!$append) { $icon = self::ICON_NEW; } } return $icon; }
Returns proper icon for thread. @return string
entailment
public function getDescription() { $description = Yii::t('podium/view', 'No New Posts'); $append = false; if ($this->locked) { $description = Yii::t('podium/view', 'Locked Thread'); $append = true; } elseif ($this->pinned) { $description = Yii::t('podium/view', 'Pinned Thread'); $append = true; } elseif ($this->posts >= Podium::getInstance()->podiumConfig->get('hot_minimum')) { $description = Yii::t('podium/view', 'Hot Thread'); $append = true; } if ($this->userView) { if ($this->new_post_at > $this->userView->new_last_seen) { if (!$append) { $description = Yii::t('podium/view', 'New Posts'); } else { $description .= ' (' . Yii::t('podium/view', 'New Posts') . ')'; } } elseif ($this->edited_post_at > $this->userView->edited_last_seen) { if (!$append) { $description = Yii::t('podium/view', 'Edited Posts'); } else { $description = ' (' . Yii::t('podium/view', 'Edited Posts') . ')'; } } } else { if (!$append) { $description = Yii::t('podium/view', 'New Posts'); } else { $description .= ' (' . Yii::t('podium/view', 'New Posts') . ')'; } } return $description; }
Returns proper description for thread. @return string
entailment
public function getCssClass() { $class = self::CLASS_DEFAULT; if ($this->userView) { if ($this->new_post_at > $this->userView->new_last_seen) { $class = self::CLASS_NEW; } elseif ($this->edited_post_at > $this->userView->edited_last_seen) { $class = self::CLASS_EDITED; } } else { $class = self::CLASS_NEW; } return $class; }
Returns proper CSS class for thread. @return string
entailment
public function isMod($userId = null) { if (User::can(Rbac::ROLE_ADMIN)) { return true; } if (in_array($userId, $this->forum->getMods())) { return true; } return false; }
Checks if user is this thread moderator. @param int $userId @return bool
entailment
public function podiumDelete() { $transaction = Thread::getDb()->beginTransaction(); try { if (!$this->delete()) { throw new Exception('Thread deleting error!'); } $this->forum->updateCounters([ 'threads' => -1, 'posts' => -$this->postsCount ]); $transaction->commit(); PodiumCache::clearAfter('threadDelete'); Log::info('Thread deleted', $this->id, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs thread delete with parent forum counters update. @return bool @since 0.2
entailment
public function podiumDeletePosts($posts) { $transaction = static::getDb()->beginTransaction(); try { foreach ($posts as $post) { if (!is_numeric($post) || $post < 1) { throw new Exception('Incorrect post ID'); } $nPost = Post::find() ->where([ 'id' => $post, 'thread_id' => $this->id, 'forum_id' => $this->forum->id ]) ->limit(1) ->one(); if (!$nPost) { throw new Exception('No post of given ID found'); } if (!$nPost->delete()) { throw new Exception('Post deleting error!'); } } $wholeThread = false; if ($this->postsCount) { $this->updateCounters(['posts' => -count($posts)]); $this->forum->updateCounters(['posts' => -count($posts)]); } else { $wholeThread = true; if (!$this->delete()) { throw new Exception('Thread deleting error!'); } $this->forum->updateCounters(['posts' => -count($posts), 'threads' => -1]); } $transaction->commit(); PodiumCache::clearAfter('postDelete'); Log::info('Posts deleted', null, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs thread posts delete with parent forum counters update. @param array $posts posts IDs @return bool @throws Exception @since 0.2
entailment
public function podiumLock() { $this->locked = !$this->locked; if ($this->save()) { Log::info($this->locked ? 'Thread locked' : 'Thread unlocked', $this->id, __METHOD__); return true; } return false; }
Performs thread lock / unlock. @return bool @since 0.2
entailment
public function podiumMoveTo($target = null) { $newParent = Forum::find()->where(['id' => $target])->limit(1)->one(); if (empty($newParent)) { Log::error('No parent forum of given ID found', $this->id, __METHOD__); return false; } $postsCount = $this->postsCount; $transaction = Forum::getDb()->beginTransaction(); try { $this->forum->updateCounters(['threads' => -1, 'posts' => -$postsCount]); $newParent->updateCounters(['threads' => 1, 'posts' => $postsCount]); $this->forum_id = $newParent->id; $this->category_id = $newParent->category_id; if (!$this->save()) { throw new Exception('Thread saving error!'); } Post::updateAll(['forum_id' => $newParent->id], ['thread_id' => $this->id]); $transaction->commit(); PodiumCache::clearAfter('threadMove'); Log::info('Thread moved', $this->id, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs thread move with counters update. @param int $target new parent forum's ID @return bool @since 0.2
entailment
public function podiumMovePostsTo($target = null, $posts = [], $name = null, $forum = null) { $transaction = static::getDb()->beginTransaction(); try { if ($target == 0) { $parent = Forum::find()->where(['id' => $forum])->limit(1)->one(); if (empty($parent)) { throw new Exception('No parent forum of given ID found'); } $newThread = new Thread(); $newThread->name = $name; $newThread->posts = 0; $newThread->views = 0; $newThread->category_id = $parent->category_id; $newThread->forum_id = $parent->id; $newThread->author_id = User::loggedId(); if (!$newThread->save()) { throw new Exception('Thread saving error!'); } } else { $newThread = Thread::find()->where(['id' => $target])->limit(1)->one(); if (empty($newThread)) { throw new Exception('No thread of given ID found'); } } if (empty($newThread)) { throw new Exception('No target thread selected!'); } foreach ($posts as $post) { if (!is_numeric($post) || $post < 1) { throw new Exception('Incorrect post ID'); } $newPost = Post::find() ->where([ 'id' => $post, 'thread_id' => $this->id, 'forum_id' => $this->forum->id ]) ->limit(1) ->one(); if (empty($newPost)) { throw new Exception('No post of given ID found'); } $newPost->thread_id = $newThread->id; $newPost->forum_id = $newThread->forum_id; if (!$newPost->save()) { throw new Exception('Post saving error!'); } } $wholeThread = false; if ($this->postCount) { $this->updateCounters(['posts' => -count($posts)]); $this->forum->updateCounters(['posts' => -count($posts)]); } else { $wholeThread = true; if (!$this->delete()) { throw new Exception('Thread deleting error!'); } $this->forum->updateCounters(['posts' => -count($posts), 'threads' => -1]); } $newThread->updateCounters(['posts' => count($posts)]); $newThread->forum->updateCounters(['posts' => count($posts)]); $transaction->commit(); PodiumCache::clearAfter('postMove'); Log::info('Posts moved', null, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs thread posts move with counters update. @param int $target new parent thread ID @param array $posts IDs of posts to move @param string $name new thread name if $target = 0 @param type $forum new thread parent forum if $target = 0 @return bool @throws Exception @since 0.2
entailment
public function podiumNew() { $transaction = static::getDb()->beginTransaction(); try { if (!$this->save()) { throw new Exception('Thread saving error!'); } $loggedIn = User::loggedId(); if ($this->pollAdded && Podium::getInstance()->podiumConfig->get('allow_polls')) { $poll = new Poll(); $poll->thread_id = $this->id; $poll->question = $this->pollQuestion; $poll->votes = $this->pollVotes; $poll->hidden = $this->pollHidden; $poll->end_at = !empty($this->pollEnd) ? Podium::getInstance()->formatter->asTimestamp($this->pollEnd . ' 23:59:59') : null; $poll->author_id = $loggedIn; if (!$poll->save()) { throw new Exception('Poll saving error!'); } foreach ($this->pollAnswers as $answer) { $pollAnswer = new PollAnswer(); $pollAnswer->poll_id = $poll->id; $pollAnswer->answer = $answer; if (!$pollAnswer->save()) { throw new Exception('Poll Answer saving error!'); } } Log::info('Poll added', $poll->id, __METHOD__); } $this->forum->updateCounters(['threads' => 1]); $post = new Post(); $post->content = $this->post; $post->thread_id = $this->id; $post->forum_id = $this->forum_id; $post->author_id = $loggedIn; $post->likes = 0; $post->dislikes = 0; if (!$post->save()) { throw new Exception('Post saving error!'); } $post->markSeen(); $this->forum->updateCounters(['posts' => 1]); $this->updateCounters(['posts' => 1]); $this->touch('new_post_at'); $this->touch('edited_post_at'); if ($this->subscribe) { $subscription = new Subscription(); $subscription->user_id = $loggedIn; $subscription->thread_id = $this->id; $subscription->post_seen = Subscription::POST_SEEN; if (!$subscription->save()) { throw new Exception('Subscription saving error!'); } } $transaction->commit(); PodiumCache::clearAfter('newThread'); Log::info('Thread added', $this->id, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs new thread with first post creation and subscription. Saves thread poll. @return bool @since 0.2
entailment
public function podiumPin() { $this->pinned = !$this->pinned; if ($this->save()) { Log::info($this->pinned ? 'Thread pinned' : 'Thread unpinned', $this->id, __METHOD__); return true; } return false; }
Performs thread pin / unpin. @return bool @since 0.2
entailment
public static function podiumMarkAllSeen() { try { $loggedId = User::loggedId(); if (empty($loggedId)) { throw new Exception('User ID missing'); } $updateBatch = []; $threadsPrevMarked = Thread::find()->joinWith(['threadView' => function ($q) use ($loggedId) { $q->onCondition(['user_id' => $loggedId]); $q->andWhere(['or', new Expression('new_last_seen < new_post_at'), new Expression('edited_last_seen < edited_post_at'), ]); }], false); $time = time(); foreach ($threadsPrevMarked->each() as $thread) { $updateBatch[] = $thread->id; } if (!empty($updateBatch)) { Podium::getInstance()->db->createCommand()->update(ThreadView::tableName(), [ 'new_last_seen' => $time, 'edited_last_seen' => $time ], ['thread_id' => $updateBatch, 'user_id' => $loggedId])->execute(); } $insertBatch = []; $threadsNew = Thread::find()->joinWith(['threadView' => function ($q) use ($loggedId) { $q->onCondition(['user_id' => $loggedId]); $q->andWhere(['new_last_seen' => null]); }], false); foreach ($threadsNew->each() as $thread) { $insertBatch[] = [$loggedId, $thread->id, $time, $time]; } if (!empty($insertBatch)) { Podium::getInstance()->db->createCommand()->batchInsert(ThreadView::tableName(), [ 'user_id', 'thread_id', 'new_last_seen', 'edited_last_seen' ], $insertBatch)->execute(); } return true; } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs marking all unread threads as seen for user. @return bool @throws Exception @since 0.2
entailment
public function getParsedPost() { if (Podium::getInstance()->podiumConfig->get('use_wysiwyg') == '0') { $parser = new GithubMarkdown(); $parser->html5 = true; return $parser->parse($this->post); } return $this->post; }
Returns post Markdown-parsed if WYSIWYG editor is switched off. @return string @since 0.6
entailment
public function actionFieldlist($q = null) { if (!Yii::$app->request->isAjax) { return $this->redirect(['forum/index']); } return User::getMembersList($q); }
Listing the active users for ajax. @param string $q Username query @return string|Response
entailment
public function actionIgnore($id = null) { if (Podium::getInstance()->user->isGuest) { return $this->redirect(['forum/index']); } $model = User::find()->where([ 'and', ['id' => (int)$id], ['!=', 'status', User::STATUS_REGISTERED] ])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Member with this ID.')); return $this->redirect(['members/index']); } $logged = User::loggedId(); if ($model->id == $logged) { $this->error(Yii::t('podium/flash', 'Sorry! You can not ignore your own account.')); return $this->redirect(['members/view', 'id' => $model->id, 'slug' => $model->podiumSlug]); } if ($model->id == User::ROLE_ADMIN) { $this->error(Yii::t('podium/flash', 'Sorry! You can not ignore Administrator.')); return $this->redirect(['members/view', 'id' => $model->id, 'slug' => $model->podiumSlug]); } if ($model->updateIgnore($logged)) { if ($model->isIgnoredBy($logged)) { $this->success(Yii::t('podium/flash', 'User is now ignored.')); } else { $this->success(Yii::t('podium/flash', 'User is not ignored anymore.')); } } else { $this->error(Yii::t('podium/flash', 'Sorry! There was some error while performing this action.')); } return $this->redirect(['members/view', 'id' => $model->id, 'slug' => $model->podiumSlug]); }
Ignoring the user of given ID. @param int $id @return Response
entailment
public function actionIndex() { $searchModel = new UserSearch(); return $this->render('index', [ 'dataProvider' => $searchModel->search(Yii::$app->request->get(), true), 'searchModel' => $searchModel ]); }
Listing the users. @return string
entailment
public function actionView($id = null, $slug = null) { $model = User::find()->where(['and', ['id' => $id], ['!=', 'status', User::STATUS_REGISTERED], ['or', ['slug' => $slug], ['slug' => ''], ['slug' => null], ] ])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Member with this ID.')); return $this->redirect(['members/index']); } return $this->render('view', ['model' => $model]); }
Viewing profile of user of given ID and slug. @param int $id @param string $slug @return string|Response
entailment
public function actionFriend($id = null) { if (Podium::getInstance()->user->isGuest) { return $this->redirect(['forum/index']); } $model = User::find()->where(['and', ['id' => $id], ['!=', 'status', User::STATUS_REGISTERED] ])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Member with this ID.')); return $this->redirect(['members/index']); } $logged = User::loggedId(); if ($model->id == $logged) { $this->error(Yii::t('podium/flash', 'Sorry! You can not befriend your own account.')); return $this->redirect(['members/view', 'id' => $model->id, 'slug' => $model->podiumSlug]); } if ($model->updateFriend($logged)) { if ($model->isBefriendedBy($logged)) { $this->success(Yii::t('podium/flash', 'User is your friend now.')); } else { $this->success(Yii::t('podium/flash', 'User is not your friend anymore.')); } } else { $this->error(Yii::t('podium/flash', 'Sorry! There was some error while performing this action.')); } return $this->redirect(['members/view', 'id' => $model->id, 'slug' => $model->podiumSlug]); }
Adding or removing user as a friend. @param int $id user ID @return Response @since 0.2
entailment
public function getThread($cid, $fid, $id, $slug) { if ($this->_thread === null) { $this->_thread = (new ThreadVerifier([ 'categoryId' => $cid, 'forumId' => $fid, 'threadId' => $id, 'threadSlug' => $slug ]))->verify(); } return $this->_thread; }
Returns thread. @param int $cid @param int $fid @param int $id @param string $slug @return Thread
entailment
public function run($cid = null, $fid = null, $id = null, $slug = null) { $thread = $this->getThread($cid, $fid, $id, $slug); if (empty($thread)) { $this->controller->error(Yii::t('podium/flash', 'Sorry! We can not find the thread you are looking for.')); return $this->controller->redirect(['forum/index']); } if (!User::can($this->permission, ['item' => $thread])) { $this->controller->error(Yii::t('podium/flash', 'Sorry! You do not have the required permission to perform this action.')); return $this->controller->redirect(['forum/index']); } if (call_user_func([$thread, $this->switcher])) { $this->controller->success($thread->{$this->boolAttribute} ? $this->onMessage : $this->offMessage); } else { $this->controller->error(Yii::t('podium/flash', 'Sorry! There was an error while updating the thread.')); } return $this->controller->redirect([ 'forum/thread', 'cid' => $thread->forum->category->id, 'fid' => $thread->forum->id, 'id' => $thread->id, 'slug' => $thread->slug ]); }
Runs action. @param int $cid @param int $fid @param int $id @param string $slug @return Response
entailment
public function search($params) { $query = static::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); $dataProvider->sort->defaultOrder = ['id' => SORT_DESC]; $dataProvider->pagination->pageSize = Yii::$app->session->get('per-page', 20); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query ->andFilterWhere(['id' => $this->id]) ->andFilterWhere(['level' => $this->level]) ->andFilterWhere(['model' => $this->model]) ->andFilterWhere(['user' => $this->user]) ->andFilterWhere(['like', 'category', $this->category]) ->andFilterWhere(['like', 'ip', $this->ip]) ->andFilterWhere(['like', 'message', $this->message]); return $dataProvider; }
Searches for logs. @param array $params Attributes @return ActiveDataProvider
entailment
public function countPercent($currentStep, $maxStep) { $percent = $maxStep ? round(100 * $currentStep / $maxStep) : 0; if ($percent > 100) { $percent = 100; } if ($percent == 100 && $currentStep != $maxStep) { $percent = 99; } if ($percent == 100) { $this->clearCache(); } return $percent; }
Returns percent. Clears cache at 100. @param int $currentStep @param int $maxStep @return int @since 0.2
entailment
public function afterSave($insert, $changedAttributes) { try { if ($insert) { $this->insertWords(); } else { $this->updateWords(); } } catch (Exception $e) { throw $e; } parent::afterSave($insert, $changedAttributes); }
Updates post tag words. @param bool $insert @param array $changedAttributes @throws Exception
entailment
protected function prepareWords() { $cleanHtml = HtmlPurifier::process(trim($this->content)); $purged = preg_replace('/<[^>]+>/', ' ', $cleanHtml); $wordsRaw = array_unique(preg_split('/[\s,\.\n]+/', $purged)); $allWords = []; foreach ($wordsRaw as $word) { if (mb_strlen($word, 'UTF-8') > 2 && mb_strlen($word, 'UTF-8') <= 255) { $allWords[] = $word; } } return $allWords; }
Prepares tag words. @return string[]
entailment
protected function addNewWords($allWords) { try { $newWords = $allWords; $query = (new Query())->from(Vocabulary::tableName())->where(['word' => $allWords]); foreach ($query->each() as $vocabularyFound) { if (($key = array_search($vocabularyFound['word'], $allWords)) !== false) { unset($newWords[$key]); } } $formatWords = []; foreach ($newWords as $word) { $formatWords[] = [$word]; } if (!empty($formatWords)) { if (!Podium::getInstance()->db->createCommand()->batchInsert( Vocabulary::tableName(), ['word'], $formatWords )->execute()) { throw new Exception('Words saving error!'); } } } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); throw $e; } }
Adds new tag words. @param string[] $allWords All words extracted from post @throws Exception
entailment
protected function insertWords() { try { $vocabulary = []; $allWords = $this->prepareWords(); $this->addNewWords($allWords); $query = (new Query())->from(Vocabulary::tableName())->where(['word' => $allWords]); foreach ($query->each() as $vocabularyNew) { $vocabulary[] = [$vocabularyNew['id'], $this->id]; } if (!empty($vocabulary)) { if (!Podium::getInstance()->db->createCommand()->batchInsert( '{{%podium_vocabulary_junction}}', ['word_id', 'post_id'], $vocabulary )->execute()) { throw new Exception('Words connections saving error!'); } } } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); throw $e; } }
Inserts tag words. @throws Exception
entailment
protected function updateWords() { try { $vocabulary = []; $allWords = $this->prepareWords(); $this->addNewWords($allWords); $queryVocabulary = (new Query())->from(Vocabulary::tableName())->where(['word' => $allWords]); foreach ($queryVocabulary->each() as $vocabularyNew) { $vocabulary[$vocabularyNew['id']] = [$vocabularyNew['id'], $this->id]; } if (!empty($vocabulary)) { if (!Podium::getInstance()->db->createCommand()->batchInsert( '{{%podium_vocabulary_junction}}', ['word_id', 'post_id'], array_values($vocabulary) )->execute()) { throw new Exception('Words connections saving error!'); } } $queryJunction = (new Query())->from('{{%podium_vocabulary_junction}}')->where(['post_id' => $this->id]); foreach ($queryJunction->each() as $junk) { if (!array_key_exists($junk['word_id'], $vocabulary)) { if (!Podium::getInstance()->db->createCommand()->delete( '{{%podium_vocabulary_junction}}', ['id' => $junk['id']] )->execute()) { throw new Exception('Words connections deleting error!'); } } } } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); throw $e; } }
Updates tag words. @throws Exception
entailment
public function search($forumId, $threadId) { $dataProvider = new ActiveDataProvider([ 'query' => static::find()->where(['forum_id' => $forumId, 'thread_id' => $threadId]), 'pagination' => [ 'defaultPageSize' => 10, 'pageSizeLimit' => false, 'forcePageParam' => false ], ]); $dataProvider->sort->defaultOrder = ['id' => SORT_ASC]; return $dataProvider; }
Searches for posts. @param int $forumId @param int $threadId @return ActiveDataProvider
entailment
public function markSeen($updateCounters = true) { if (!Podium::getInstance()->user->isGuest) { $transaction = static::getDb()->beginTransaction(); try { $loggedId = User::loggedId(); $threadView = ThreadView::find()->where([ 'user_id' => $loggedId, 'thread_id' => $this->thread_id ])->limit(1)->one(); if (empty($threadView)) { $threadView = new ThreadView(); $threadView->user_id = $loggedId; $threadView->thread_id = $this->thread_id; $threadView->new_last_seen = $this->created_at; $threadView->edited_last_seen = !empty($this->edited_at) ? $this->edited_at : $this->created_at; if (!$threadView->save()) { throw new Exception('Thread View saving error!'); } if ($updateCounters) { if (!$this->thread->updateCounters(['views' => 1])) { throw new Exception('Thread views adding error!'); } } } else { if ($this->edited) { if ($threadView->edited_last_seen < $this->edited_at) { $threadView->edited_last_seen = $this->edited_at; if (!$threadView->save()) { throw new Exception('Thread View saving error!'); } if ($updateCounters) { if (!$this->thread->updateCounters(['views' => 1])) { throw new Exception('Thread views adding error!'); } } } } else { $save = false; if ($threadView->new_last_seen < $this->created_at) { $threadView->new_last_seen = $this->created_at; $save = true; } if ($threadView->edited_last_seen < max($this->created_at, $this->edited_at)) { $threadView->edited_last_seen = max($this->created_at, $this->edited_at); $save = true; } if ($save) { if (!$threadView->save()) { throw new Exception('Thread View saving error!'); } if ($updateCounters) { if (!$this->thread->updateCounters(['views' => 1])) { throw new Exception('Thread views adding error!'); } } } } } if ($this->thread->subscription) { if ($this->thread->subscription->post_seen == Subscription::POST_NEW) { $this->thread->subscription->post_seen = Subscription::POST_SEEN; if (!$this->thread->subscription->save()) { throw new Exception('Thread Subscription saving error!'); } } } $transaction->commit(); } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } } }
Marks post as seen by current user. @param bool $updateCounters Whether to update view counter
entailment
public static function verify($categoryId = null, $forumId = null, $threadId = null, $id = null) { if (!is_numeric($categoryId) || $categoryId < 1 || !is_numeric($forumId) || $forumId < 1 || !is_numeric($threadId) || $threadId < 1 || !is_numeric($id) || $id < 1) { return null; } return static::find()->joinWith(['thread', 'forum' => function ($query) use ($categoryId) { $query->joinWith(['category'])->andWhere([Category::tableName() . '.id' => $categoryId]); }])->where([ static::tableName() . '.id' => $id, static::tableName() . '.thread_id' => $threadId, static::tableName() . '.forum_id' => $forumId, ])->limit(1)->one(); }
Returns the verified post. @param int $categoryId post category ID @param int $forumId post forum ID @param int $threadId post thread ID @param int $id post ID @return Post @since 0.2
entailment
public function podiumDelete() { $transaction = static::getDb()->beginTransaction(); try { if (!$this->delete()) { throw new Exception('Post deleting error!'); } $wholeThread = false; if ($this->thread->postsCount) { if (!$this->thread->updateCounters(['posts' => -1])) { throw new Exception('Thread Post counter subtracting error!'); } if (!$this->forum->updateCounters(['posts' => -1])) { throw new Exception('Forum Post counter subtracting error!'); } } else { $wholeThread = true; if (!$this->thread->delete()) { throw new Exception('Thread deleting error!'); } if (!$this->forum->updateCounters(['posts' => -1, 'threads' => -1])) { throw new Exception('Forum Post and Thread counter subtracting error!'); } } $transaction->commit(); PodiumCache::clearAfter('postDelete'); Log::info('Post deleted', !empty($this->id) ? $this->id : '', __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs post delete with parent forum and thread counters update. @return bool @since 0.2
entailment
public function podiumEdit($isFirstPost = false) { $transaction = static::getDb()->beginTransaction(); try { $this->edited = 1; $this->touch('edited_at'); if (!$this->save()) { throw new Exception('Post saving error!'); } if ($isFirstPost) { $this->thread->name = $this->topic; if (!$this->thread->save()) { throw new Exception('Thread saving error!'); } } $this->markSeen(); $this->thread->touch('edited_post_at'); $transaction->commit(); Log::info('Post updated', $this->id, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs post update with parent thread topic update in case of first post in thread. @param bool $isFirstPost whether post is first in thread @return bool @since 0.2
entailment
public function podiumNew($previous = null) { $transaction = static::getDb()->beginTransaction(); try { $id = null; $loggedId = User::loggedId(); $sameAuthor = !empty($previous->author_id) && $previous->author_id == $loggedId; if ($sameAuthor && Podium::getInstance()->podiumConfig->get('merge_posts')) { $separator = '<hr>'; if (Podium::getInstance()->podiumConfig->get('use_wysiwyg') == '0') { $separator = "\n\n---\n"; } $previous->content .= $separator . $this->content; $previous->edited = 1; $previous->touch('edited_at'); if (!$previous->save()) { throw new Exception('Previous Post saving error!'); } $previous->markSeen(false); $previous->thread->touch('edited_post_at'); $id = $previous->id; $thread = $previous->thread; } else { if (!$this->save()) { throw new Exception('Post saving error!'); } $this->markSeen(!$sameAuthor); if (!$this->forum->updateCounters(['posts' => 1])) { throw new Exception('Forum Post counter adding error!'); } if (!$this->thread->updateCounters(['posts' => 1])) { throw new Exception('Thread Post counter adding error!'); } $this->thread->touch('new_post_at'); $this->thread->touch('edited_post_at'); $id = $this->id; $thread = $this->thread; } if (empty($id)) { throw new Exception('Saved Post ID missing'); } Subscription::notify($thread->id); if ($this->subscribe && !$thread->subscription) { $subscription = new Subscription(); $subscription->user_id = $loggedId; $subscription->thread_id = $thread->id; $subscription->post_seen = Subscription::POST_SEEN; if (!$subscription->save()) { throw new Exception('Subscription saving error!'); } } $transaction->commit(); PodiumCache::clearAfter('newPost'); Log::info('Post added', $id, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs new post creation and subscription. Depending on the settings previous post can be merged. @param Post $previous previous post @return bool @since 0.2
entailment
public function podiumThumb($up = true, $count = 0) { $transaction = static::getDb()->beginTransaction(); try { $loggedId = User::loggedId(); if ($this->thumb) { if ($this->thumb->thumb == 1 && !$up) { $this->thumb->thumb = -1; if (!$this->thumb->save()) { throw new Exception('Thumb saving error!'); } if (!$this->updateCounters(['likes' => -1, 'dislikes' => 1])) { throw new Exception('Thumb counters saving error!'); } } elseif ($this->thumb->thumb == -1 && $up) { $this->thumb->thumb = 1; if (!$this->thumb->save()) { throw new Exception('Thumb saving error!'); } if (!$this->updateCounters(['likes' => 1, 'dislikes' => -1])) { throw new Exception('Thumb counters saving error!'); } } } else { $postThumb = new PostThumb(); $postThumb->post_id = $this->id; $postThumb->user_id = $loggedId; $postThumb->thumb = $up ? 1 : -1; if (!$postThumb->save()) { throw new Exception('PostThumb saving error!'); } if ($postThumb->thumb) { if (!$this->updateCounters(['likes' => 1])) { throw new Exception('Thumb counters saving error!'); } } else { if (!$this->updateCounters(['dislikes' => 1])) { throw new Exception('Thumb counters saving error!'); } } } if ($count == 0) { Podium::getInstance()->podiumCache->set('user.votes.' . $loggedId, ['count' => 1, 'expire' => time() + 3600]); } else { Podium::getInstance()->podiumCache->setElement('user.votes.' . $loggedId, 'count', $count + 1); } $transaction->commit(); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs vote processing. @param bool $up whether this is upvote @param int $count number of user cached votes @return bool @since 0.2
entailment
public static function adminCategoriesPrepareContent($category) { $actions = []; $actions[] = Html::button(Html::tag('span', '', ['class' => 'glyphicon glyphicon-eye-' . ($category->visible ? 'open' : 'close')]), ['class' => 'btn btn-xs text-muted', 'data-toggle' => 'tooltip', 'data-placement' => 'top', 'title' => $category->visible ? Yii::t('podium/view', 'Category visible for guests') : Yii::t('podium/view', 'Category hidden for guests')]); $actions[] = Html::a(Html::tag('span', '', ['class' => 'glyphicon glyphicon-list']) . ' ' . Yii::t('podium/view', 'List Forums'), ['admin/forums', 'cid' => $category->id], ['class' => 'btn btn-default btn-xs']); $actions[] = Html::a(Html::tag('span', '', ['class' => 'glyphicon glyphicon-plus-sign']) . ' ' . Yii::t('podium/view', 'Create new forum'), ['admin/new-forum', 'cid' => $category->id], ['class' => 'btn btn-success btn-xs']); $actions[] = Html::a(Html::tag('span', '', ['class' => 'glyphicon glyphicon-cog']), ['admin/edit-category', 'id' => $category->id], ['class' => 'btn btn-default btn-xs', 'data-toggle' => 'tooltip', 'data-placement' => 'top', 'title' => Yii::t('podium/view', 'Edit Category')]); $actions[] = Html::tag('span', Html::button(Html::tag('span', '', ['class' => 'glyphicon glyphicon-trash']), ['class' => 'btn btn-danger btn-xs', 'data-url' => Url::to(['admin/delete-category', 'id' => $category->id]), 'data-toggle' => 'modal', 'data-target' => '#podiumModalDelete']), ['data-toggle' => 'tooltip', 'data-placement' => 'top', 'title' => Yii::t('podium/view', 'Delete Category')]); return Html::tag('p', implode(' ', $actions), ['class' => 'pull-right']) . Html::tag('span', Html::encode($category->name), ['class' => 'podium-forum', 'data-id' => $category->id]); }
Prepares content for categories administration. @param mixed $category @return string
entailment
public static function adminForumsPrepareContent($forum) { $actions = []; $actions[] = Html::button(Html::tag('span', '', ['class' => 'glyphicon glyphicon-eye-' . ($forum->visible ? 'open' : 'close')]), ['class' => 'btn btn-xs text-muted', 'data-toggle' => 'tooltip', 'data-placement' => 'top', 'title' => $forum->visible ? Yii::t('podium/view', 'Forum visible for guests (if category is visible)') : Yii::t('podium/view', 'Forum hidden for guests')]); $actions[] = Html::a(Html::tag('span', '', ['class' => 'glyphicon glyphicon-cog']), ['admin/edit-forum', 'id' => $forum->id, 'cid' => $forum->category_id], ['class' => 'btn btn-default btn-xs', 'data-toggle' => 'tooltip', 'data-placement' => 'top', 'title' => Yii::t('podium/view', 'Edit Forum')]); $actions[] = Html::tag('span', Html::button(Html::tag('span', '', ['class' => 'glyphicon glyphicon-trash']), ['class' => 'btn btn-danger btn-xs', 'data-url' => Url::to(['admin/delete-forum', 'id' => $forum->id, 'cid' => $forum->category_id]), 'data-toggle' => 'modal', 'data-target' => '#podiumModalDelete']), ['data-toggle' => 'tooltip', 'data-placement' => 'top', 'title' => Yii::t('podium/view', 'Delete Forum')]); return Html::tag('p', implode(' ', $actions), ['class' => 'pull-right']) . Html::tag('span', Html::encode($forum->name), ['class' => 'podium-forum', 'data-id' => $forum->id, 'data-category' => $forum->category_id]); }
Prepares content for forums administration. @param mixed $forum @return string
entailment
public static function podiumUserTag($name, $role, $id = null, $slug = null, $simple = false) { $icon = Html::tag('span', '', ['class' => $id ? 'glyphicon glyphicon-user' : 'glyphicon glyphicon-ban-circle']); $url = $id ? ['members/view', 'id' => $id, 'slug' => $slug] : '#'; switch ($role) { case 0: $colourClass = 'text-muted'; break; case User::ROLE_MODERATOR: $colourClass = 'text-info'; break; case User::ROLE_ADMIN: $colourClass = 'text-danger'; break; case User::ROLE_MEMBER: default: $colourClass = 'text-warning'; } $encodedName = Html::tag('span', $icon . ' ' . ($id ? Html::encode($name) : Yii::t('podium/view', 'user deleted')), ['class' => $colourClass]); if ($simple) { return $encodedName; } return Html::a($encodedName, $url, ['class' => 'btn btn-xs btn-default', 'data-pjax' => '0']); }
Returns user tag. @param string $name user name @param int $role user role @param int|null $id user ID @param bool $simple whether to return simple tag instead of full @return string tag
entailment
public static function prepareQuote($post, $quote = '') { if (Podium::getInstance()->podiumConfig->get('use_wysiwyg') == '0') { $content = !empty($quote) ? '[...] ' . HtmlPurifier::process($quote) . ' [...]' : $post->content; return '> ' . $post->author->podiumTag . ' @ ' . Podium::getInstance()->formatter->asDatetime($post->created_at) . "\n> " . $content . "\n"; } $content = !empty($quote) ? '[...] ' . nl2br(HtmlPurifier::process($quote)) . ' [...]' : $post->content; return Html::tag('blockquote', $post->author->podiumTag . ' @ ' . Podium::getInstance()->formatter->asDatetime($post->created_at) . '<br>' . $content) . '<br>'; }
Returns quote HTML. @param Post $post post model to be quoted @param string $quote partial text to be quoted @return string
entailment
public static function roleLabel($role = null) { switch ($role) { case User::ROLE_ADMIN: $label = 'danger'; $name = ArrayHelper::getValue(User::getRoles(), $role); break; case User::ROLE_MODERATOR: $label = 'info'; $name = ArrayHelper::getValue(User::getRoles(), $role); break; default: $label = 'warning'; $name = ArrayHelper::getValue(User::getRoles(), User::ROLE_MEMBER); } return Html::tag('span', $name, ['class' => 'label label-' . $label]); }
Returns role label HTML. @param int|null $role role ID @return string
entailment
public static function sortOrder($attribute = null) { if (!empty($attribute)) { $sort = Yii::$app->request->get('sort'); if ($sort == $attribute) { return ' ' . Html::tag('span', '', ['class' => 'glyphicon glyphicon-sort-by-alphabet']); } if ($sort == '-' . $attribute) { return ' ' . Html::tag('span', '', ['class' => 'glyphicon glyphicon-sort-by-alphabet-alt']); } } return null; }
Returns sorting icon. @param string|null $attribute sorting attribute name @return string|null icon HTML or null if empty attribute
entailment
public static function statusLabel($status = null) { switch ($status) { case User::STATUS_ACTIVE: $label = 'info'; $name = ArrayHelper::getValue(User::getStatuses(), $status); break; case User::STATUS_BANNED: $label = 'warning'; $name = ArrayHelper::getValue(User::getStatuses(), $status); break; default: $label = 'default'; $name = ArrayHelper::getValue(User::getStatuses(), User::STATUS_REGISTERED); } return Html::tag('span', $name, ['class' => 'label label-' . $label]); }
Returns User status label. @param int|null $status status ID @return string label HTML
entailment
public static function timeZones() { $timeZones = []; $timezone_identifiers = DateTimeZone::listIdentifiers(); sort($timezone_identifiers); $timeZones['UTC'] = Yii::t('podium/view', 'default (UTC)'); foreach ($timezone_identifiers as $zone) { if ($zone != 'UTC') { $zoneName = $zone; $timeForZone = new DateTime(null, new DateTimeZone($zone)); $offset = $timeForZone->getOffset(); if (is_numeric($offset)) { $zoneName .= ' (UTC'; if ($offset != 0) { $offset = $offset / 60 / 60; $offsetDisplay = floor($offset) . ':' . str_pad(60 * ($offset - floor($offset)), 2, '0', STR_PAD_LEFT); $zoneName .= ' ' . ($offset < 0 ? '' : '+') . $offsetDisplay; } $zoneName .= ')'; } $timeZones[$zone] = $zoneName; } } return $timeZones; }
Returns time zones with current offset array. @return array
entailment
public static function compareVersions($a, $b) { $versionPos = max(count($a), count($b)); while (count($a) < $versionPos) { $a[] = 0; } while (count($b) < $versionPos) { $b[] = 0; } for ($v = 0; $v < count($a); $v++) { if ((int)$a[$v] < (int)$b[$v]) { return '<'; } if ((int)$a[$v] > (int)$b[$v]) { return '>'; } } return '='; }
Comparing versions. @param array $a @param array $b @return string @since 0.2
entailment
public static function defaultContent($name = null) { $defaults = [ self::EMAIL_REACTIVATION => [ 'topic' => Yii::t('podium/view', '{forum} account reactivation'), 'content' => Yii::t('podium/view', '<p>{forum} Account Activation</p><p>You are receiving this e-mail because someone has started the process of activating the account at {forum}.<br>If this person is you open the following link in your Internet browser and follow the instructions on screen.</p><p>{link}</p><p>If it was not you just ignore this e-mail.</p><p>Thank you!<br>{forum}</p>'), ], self::EMAIL_REGISTRATION => [ 'topic' => Yii::t('podium/view', 'Welcome to {forum}! This is your activation link'), 'content' => Yii::t('podium/view', '<p>Thank you for registering at {forum}!</p><p>To activate your account open the following link in your Internet browser:<br>{link}<br></p><p>See you soon!<br>{forum}</p>'), ], self::EMAIL_PASSWORD => [ 'topic' => Yii::t('podium/view', '{forum} password reset link'), 'content' => Yii::t('podium/view', '<p>{forum} Password Reset</p><p>You are receiving this e-mail because someone has started the process of changing the account password at {forum}.<br>If this person is you open the following link in your Internet browser and follow the instructions on screen.</p><p>{link}</p><p>If it was not you just ignore this e-mail.</p><p>Thank you!<br>{forum}</p>'), ], self::EMAIL_NEW => [ 'topic' => Yii::t('podium/view', 'New e-mail activation link at {forum}'), 'content' => Yii::t('podium/view', '<p>{forum} New E-mail Address Activation</p><p>To activate your new e-mail address open the following link in your Internet browser and follow the instructions on screen.</p><p>{link}</p><p>Thank you<br>{forum}</p>'), ], self::EMAIL_SUBSCRIPTION => [ 'topic' => Yii::t('podium/view', 'New post in subscribed thread at {forum}'), 'content' => Yii::t('podium/view', '<p>There has been new post added in the thread you are subscribing. Click the following link to read the thread.</p><p>{link}</p><p>See you soon!<br>{forum}</p>'), ], self::TERMS_AND_CONDS => [ 'topic' => Yii::t('podium/view', 'Forum Terms and Conditions'), 'content' => Yii::t('podium/view', "Please remember that we are not responsible for any messages posted. We do not vouch for or warrant the accuracy, completeness or usefulness of any post, and are not responsible for the contents of any post.<br><br>The posts express the views of the author of the post, not necessarily the views of this forum. Any user who feels that a posted message is objectionable is encouraged to contact us immediately by email. We have the ability to remove objectionable posts and we will make every effort to do so, within a reasonable time frame, if we determine that removal is necessary.<br><br>You agree, through your use of this service, that you will not use this forum to post any material which is knowingly false and/or defamatory, inaccurate, abusive, vulgar, hateful, harassing, obscene, profane, sexually oriented, threatening, invasive of a person's privacy, or otherwise violative of any law.<br><br>You agree not to post any copyrighted material unless the copyright is owned by you or by this forum."), ], ]; if (empty($name)) { return $defaults; } if (!empty($defaults[$name])) { return $defaults[$name]; } return null; }
Returns default content array or its element. @param string $name content's name @return array @since 0.2
entailment
public static function prepareDefault($name) { $default = static::defaultContent($name); if (empty($default)) { return false; } $content = new static; $content->topic = $default['topic']; $content->content = $default['content']; return $content; }
Returns default content object. @param string $name content name @return bool|Content @since 0.2
entailment
public static function fill($name) { $email = Content::find()->where(['name' => $name])->limit(1)->one(); if (empty($email)) { $email = Content::prepareDefault($name); } return $email; }
Returns email content. @param string $name content name @return Content @since 0.2
entailment
public function search() { $dataProvider = new ActiveDataProvider([ 'query' => static::find()->where(['user_id' => User::loggedId()]), 'pagination' => [ 'defaultPageSize' => 10, 'forcePageParam' => false ], ]); $dataProvider->sort->defaultOrder = ['post_seen' => SORT_ASC, 'id' => SORT_DESC]; $dataProvider->pagination->pageSize = Yii::$app->session->get('per-page', 20); return $dataProvider; }
Searches for subscription @return ActiveDataProvider
entailment
public function seen() { $this->post_seen = self::POST_SEEN; if (!$this->save()) { return false; } Podium::getInstance()->podiumCache->deleteElement('user.subscriptions', User::loggedId()); return true; }
Marks post as seen. @return bool
entailment
public function unseen() { $this->post_seen = self::POST_NEW; if (!$this->save()) { return false; } Podium::getInstance()->podiumCache->deleteElement('user.subscriptions', User::loggedId()); return true; }
Marks post as unseen. @return bool
entailment
public static function notify($thread) { if (is_numeric($thread) && $thread > 0) { $forum = Podium::getInstance()->podiumConfig->get('name'); $email = Content::fill(Content::EMAIL_SUBSCRIPTION); $subs = static::find()->where(['thread_id' => $thread, 'post_seen' => self::POST_SEEN]); foreach ($subs->each() as $sub) { $sub->post_seen = self::POST_NEW; if ($sub->save()) { if ($email !== false && !empty($sub->user->email)) { if (Email::queue( $sub->user->email, str_replace('{forum}', $forum, $email->topic), str_replace('{forum}', $forum, str_replace('{link}', Html::a( Url::to(['forum/last', 'id' => $sub->thread_id], true), Url::to(['forum/last', 'id' => $sub->thread_id], true) ), $email->content)), $sub->user_id )) { Log::info('Subscription notice link queued', $sub->user_id, __METHOD__); } else { Log::error('Error while queuing subscription notice link', $sub->user_id, __METHOD__); } } else { Log::warning('Error while queuing subscription notice link - no email set', $sub->user_id, __METHOD__); } } } } }
Prepares notification email. @param int $thread
entailment
public static function remove($threads = []) { try { if (!empty($threads)) { return Podium::getInstance()->db->createCommand()->delete( Subscription::tableName(), ['id' => $threads, 'user_id' => User::loggedId()] )->execute(); } } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Removes threads subscriptions of given IDs. @param array $threads thread IDs @return bool @since 0.2
entailment