sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function actionLevelUp() { Yii::$app->session->set(Update::SESSION_KEY, 0); $error = ''; $info = ''; $dbVersion = 0; $mdVersion = $this->module->version; $dbQuery = (new Query())->from('{{%podium_config}}')->select('value')->where(['name' => 'version'])->limit(1)->one(); if (!isset($dbQuery['value'])) { $error = Yii::t('podium/flash', 'Error while checking current database version! Please verify your database.'); } else { $dbVersion = $dbQuery['value']; $result = Helper::compareVersions(explode('.', $mdVersion), explode('.', $dbVersion)); if ($result == '=') { $info = Yii::t('podium/flash', 'Module and database versions are the same!'); } elseif ($result == '<') { $error = Yii::t('podium/flash', 'Module version appears to be older than database! Please verify your database.'); } } Yii::$app->session->set(Update::SESSION_VERSION, $dbVersion); return $this->render('level-up', [ 'currentVersion' => $mdVersion, 'dbVersion' => $dbVersion, 'error' => $error, 'info' => $info ]); }
Running the upgrade. @return string @since 0.2
entailment
public function init() { $this->header = Html::tag('h4', $this->header, ['class' => 'modal-title', 'id' => $this->id . 'Label']); $this->options['aria-labelledby'] = $this->id . 'Label'; $this->footer = Html::button(Yii::t('podium/view', 'Cancel'), ['class' => 'btn btn-default', 'data-dismiss' => 'modal']) . "\n" . Html::a($this->footer, $this->footerConfirmUrl, $this->footerConfirmOptions); parent::init(); }
Initializes the widget.
entailment
public function search() { $query = static::find(); if (Podium::getInstance()->user->isGuest) { $query->andWhere(['visible' => 1]); } $dataProvider = new ActiveDataProvider(['query' => $query]); $dataProvider->sort->defaultOrder = ['sort' => SORT_ASC, 'id' => SORT_ASC]; return $dataProvider; }
Searches users. @return ActiveDataProvider
entailment
public function show() { $dataProvider = new ActiveDataProvider(['query' => static::find()]); $dataProvider->sort->defaultOrder = ['sort' => SORT_ASC, 'id' => SORT_ASC]; return $dataProvider->getModels(); }
Returns categories. @return Category[]
entailment
public function update($data) { $validator = new StringValidator(); $validator->max = 255; foreach ($data as $key => $value) { if (!in_array($key, $this->readonly) && array_key_exists($key, $this->settings)) { if (!$validator->validate($value)) { return false; } if (!$this->config->set($key, $value)) { return false; } } } return true; }
Updates the value of setting. @param string[] $data @return bool
entailment
public function validate() { if (is_numeric($this->categoryId) && $this->categoryId >= 1 && is_numeric($this->forumId) && $this->forumId >= 1 && is_numeric($this->threadId) && $this->threadId >= 1 && !empty($this->threadSlug)) { return true; } return false; }
Validates parameters. @return bool
entailment
public function verify() { if (!$this->validate()) { return null; } $this->_query = Thread::find()->where([ Thread::tableName() . '.id' => $this->threadId, Thread::tableName() . '.slug' => $this->threadSlug, Thread::tableName() . '.forum_id' => $this->forumId, Thread::tableName() . '.category_id' => $this->categoryId, ]); if (Podium::getInstance()->user->isGuest) { return $this->getThreadForGuests(); } return $this->getThreadForMembers(); }
Returns verified thread. @return Thread
entailment
protected function getThreadForGuests() { return $this->_query->joinWith([ 'forum' => function ($query) { $query->andWhere([ Forum::tableName() . '.visible' => 1 ])->joinWith(['category' => function ($query) { $query->andWhere([Category::tableName() . '.visible' => 1]); }]); } ])->limit(1)->one(); }
Returns thread for guests. @return Thread
entailment
public function actionClear() { if ($this->module->podiumCache->flush()) { $this->success(Yii::t('podium/flash', 'Cache has been cleared.')); } else { $this->error(Yii::t('podium/flash', 'Sorry! There was some error while clearing the cache.')); } return $this->redirect(['admin/settings']); }
Clearing all cache. @return string
entailment
public function actionContents($name = '') { if (empty($name)) { $name = Content::TERMS_AND_CONDS; } $model = Content::fill($name); if ($model->load(Yii::$app->request->post())) { if (User::can(Rbac::PERM_CHANGE_SETTINGS)) { if ($model->save()) { $this->success(Yii::t('podium/flash', 'Content has been saved.')); } else { $this->error(Yii::t('podium/flash', 'Sorry! There was some error while saving the content.')); } } else { $this->error(Yii::t('podium/flash', 'You are not allowed to perform this action.')); } return $this->refresh(); } return $this->render('contents', ['model' => $model]); }
Listing the contents. @param string $name content name @return string|Response
entailment
public function actionDeleteCategory($id = null) { $model = Category::find()->where(['id' => $id])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Category with this ID.')); return $this->redirect(['admin/categories']); } if ($model->delete()) { PodiumCache::clearAfter('categoryDelete'); Log::info('Category deleted', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'Category has been deleted.')); } else { Log::error('Error while deleting category', $model->id, __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There was some error while deleting the category.')); } return $this->redirect(['admin/categories']); }
Deleting the category of given ID. @param int $id @return Response
entailment
public function actionEditForum($cid = null, $id = null) { $model = Forum::find()->where(['id' => $id, 'category_id' => $cid])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Forum with this ID.')); return $this->redirect(['admin/forums', 'cid' => $cid]); } if ($model->load(Yii::$app->request->post())) { if ($model->save()) { Log::info('Forum updated', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'Forum has been updated.')); return $this->refresh(); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while updating the forum.')); } return $this->render('forum', [ 'model' => $model, 'forums' => Forum::find()->where(['category_id' => $cid])->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all(), 'categories' => Category::find()->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all() ]); }
Editing the forum of given ID. @param int $cid parent category ID @param int $id forum ID @return string|Response
entailment
public function actionForums($cid = null) { $model = Category::find()->where(['id' => $cid])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Category with this ID.')); return $this->redirect(['admin/categories']); } return $this->render('forums', [ 'model' => $model, 'categories' => Category::find()->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all(), 'forums' => Forum::find()->where(['category_id' => $model->id])->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all() ]); }
Listing the forums of given category ID. @param int $cid parent category ID @return string|Response
entailment
public function actionIndex() { return $this->render('index', [ 'members' => User::find()->orderBy(['id' => SORT_DESC])->limit(10)->all(), 'posts' => Post::find()->orderBy(['id' => SORT_DESC])->limit(10)->all() ]); }
Dashboard. @return string
entailment
public function actionLogs() { $searchModel = new LogSearch(); return $this->render('logs', [ 'dataProvider' => $searchModel->search(Yii::$app->request->get()), 'searchModel' => $searchModel, ]); }
Listing the logs. @return string
entailment
public function actionNewCategory() { $model = new Category(); $model->visible = 1; $model->sort = 0; if ($model->load(Yii::$app->request->post()) && $model->save()) { Log::info('Category added', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'New category has been created.')); return $this->redirect(['admin/categories']); } return $this->render('category', [ 'model' => $model, 'categories' => Category::find()->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all() ]); }
Adding new category. @return string|Response
entailment
public function actionNewForum($cid = null) { $category = Category::find()->where(['id' => $cid])->limit(1)->one(); if (empty($category)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Category with this ID.')); return $this->redirect(['admin/categories']); } $model = new Forum(); $model->category_id = $category->id; $model->visible = 1; $model->sort = 0; if ($model->load(Yii::$app->request->post()) && $model->save()) { Log::info('Forum added', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'New forum has been created.')); return $this->redirect(['admin/forums', 'cid' => $category->id]); } return $this->render('forum', [ 'model' => $model, 'forums' => Forum::find()->where(['category_id' => $category->id])->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all(), 'categories' => Category::find()->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])->all() ]); }
Adding new forum. @param int $cid parent category ID @return string|Response
entailment
public function actionSettings() { $model = new ConfigForm(); $data = Yii::$app->request->post('ConfigForm'); if ($data) { if (User::can(Rbac::PERM_CHANGE_SETTINGS)) { if ($model->update($data)) { Log::info('Settings updated', null, __METHOD__); $this->success(Yii::t('podium/flash', 'Settings have been updated.')); return $this->refresh(); } $this->error(Yii::t('podium/flash', "One of the setting's values is too long (255 characters max).")); } else { $this->error(Yii::t('podium/flash', 'You are not allowed to perform this action.')); } } return $this->render('settings', ['model' => $model]); }
Updating the module configuration. @return string|Response
entailment
public function actionSortCategory() { if (!Yii::$app->request->isAjax) { return $this->redirect(['admin/categories']); } if (!User::can(Rbac::PERM_UPDATE_CATEGORY)) { return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'You are not allowed to perform this action.'), ['class' => 'text-danger'] ); } $modelId = Yii::$app->request->post('id'); $new = Yii::$app->request->post('new'); if (!is_numeric($modelId) || !is_numeric($new)) { return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Sorry! Sorting parameters are wrong.'), ['class' => 'text-danger'] ); } $moved = Category::find()->where(['id' => $modelId])->limit(1)->one(); if (empty($moved)) { return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Sorry! We can not find Category with this ID.'), ['class' => 'text-danger'] ); } if ($moved->newOrder((int)$new)) { return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-ok-circle']) . ' ' . Yii::t('podium/view', "New categories' order has been saved."), ['class' => 'text-success'] ); } return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', "Sorry! We can not save new categories' order."), ['class' => 'text-danger'] ); }
Updating the categories order. @return string|Response
entailment
public function actionSortForum() { if (!Yii::$app->request->isAjax) { return $this->redirect(['admin/forums']); } if (!User::can(Rbac::PERM_UPDATE_FORUM)) { return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'You are not allowed to perform this action.'), ['class' => 'text-danger'] ); } $modelId = Yii::$app->request->post('id'); $modelCategory = Yii::$app->request->post('category'); $new = Yii::$app->request->post('new'); if (!is_numeric($modelId) || !is_numeric($modelCategory) || !is_numeric($new)) { return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Sorry! Sorting parameters are wrong.'), ['class' => 'text-danger'] ); } $moved = Forum::find()->where(['id' => $modelId])->limit(1)->one(); $movedCategory = Category::find()->where(['id' => $modelCategory])->limit(1)->one(); if (empty($moved) || empty($modelCategory) || $moved->category_id != $movedCategory->id) { return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Sorry! We can not find Forum with this ID.'), ['class' => 'text-danger'] ); } if ($moved->newOrder((int)$new)) { return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-ok-circle']) . ' ' . Yii::t('podium/view', "New forums' order has been saved."), ['class' => 'text-success'] ); } return Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', "Sorry! We can not save new forums' order."), ['class' => 'text-danger'] ); }
Updating the forums order. @return string|Response
entailment
public function actionInbox() { $searchModel = new MessageReceiver(); return $this->render('inbox', [ 'dataProvider' => $searchModel->search(Yii::$app->request->get()), 'searchModel' => $searchModel ]); }
Listing the messages inbox. @return string
entailment
public function actionNew($user = null) { $podiumUser = User::findMe(); if (Message::tooMany($podiumUser->id)) { $this->warning(Yii::t('podium/flash', 'You have reached maximum {max_messages, plural, =1{ message} other{ messages}} per {max_minutes, plural, =1{ minute} other{ minutes}} limit. Wait few minutes before sending a new message.', [ 'max_messages' => Message::SPAM_MESSAGES, 'max_minutes' => Message::SPAM_WAIT ])); return $this->redirect(['messages/inbox']); } $model = new Message(); $to = null; if (!empty($user) && (int)$user > 0 && (int)$user != $podiumUser->id) { $member = User::find()->where(['id' => (int)$user, 'status' => User::STATUS_ACTIVE])->limit(1)->one(); if ($member) { $model->receiversId = [$member->id]; $to = $member; } } if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { $validated = []; $errors = false; if (!empty($model->friendsId)) { $model->receiversId = array_merge( is_array($model->receiversId) ? $model->receiversId : [], is_array($model->friendsId) ? $model->friendsId : [] ); } if (empty($model->receiversId)) { $model->addError('receiversId', Yii::t('podium/view', 'You have to select at least one message receiver.')); $errors = true; } else { foreach ($model->receiversId as $r) { if ($r == $podiumUser->id) { $model->addError('receiversId', Yii::t('podium/view', 'You can not send message to yourself.')); $errors = true; } elseif ($podiumUser->isIgnoredBy($r)) { $model->addError('receiversId', Yii::t('podium/view', 'One of the selected members ignores you and has been removed from message receivers.')); $errors = true; } else { $member = User::find()->where(['id' => (int)$r, 'status' => User::STATUS_ACTIVE])->limit(1)->one(); if ($member) { $validated[] = $member->id; if (count($validated) > Message::MAX_RECEIVERS) { $model->addError('receiversId', Yii::t('podium/view', 'You can send message up to a maximum of 10 receivers at once.')); $errors = true; break; } } } } $model->receiversId = $validated; } if (!$errors) { if ($model->send()) { $this->success(Yii::t('podium/flash', 'Message has been sent.')); return $this->redirect(['messages/inbox']); } $this->error(Yii::t('podium/flash', 'Sorry! There was some error while sending your message.')); } } } return $this->render('new', ['model' => $model, 'to' => $to, 'friends' => User::friendsList()]); }
Adding a new message. @param int $user message receiver's ID @return string|Response
entailment
public function actionReply($id = null) { $podiumUser = User::findMe(); if (Message::tooMany($podiumUser->id)) { $this->warning(Yii::t('podium/flash', 'You have reached maximum {max_messages, plural, =1{ message} other{ messages}} per {max_minutes, plural, =1{ minute} other{ minutes}} limit. Wait few minutes before sending a new message.', [ 'max_messages' => Message::SPAM_MESSAGES, 'max_minutes' => Message::SPAM_WAIT ])); return $this->redirect(['messages/inbox']); } $reply = Message::find()->where([Message::tableName() . '.id' => $id])->joinWith([ 'messageReceivers' => function ($q) use ($podiumUser) { $q->where(['receiver_id' => $podiumUser->id]); }])->limit(1)->one(); if (empty($reply)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the message with the given ID.')); return $this->redirect(['messages/inbox']); } $model = new Message(); $model->topic = Message::re() . ' ' . $reply->topic; if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { if (!$podiumUser->isIgnoredBy($model->receiversId[0])) { $model->replyto = $reply->id; if ($model->send()) { $this->success(Yii::t('podium/flash', 'Message has been sent.')); return $this->redirect(['messages/inbox']); } $this->error(Yii::t('podium/flash', 'Sorry! There was some error while sending your message.')); } else { $this->error(Yii::t('podium/flash', 'Sorry! This member ignores you so you can not send the message.')); } } } $model->receiversId = [$reply->sender_id]; return $this->render('reply', ['model' => $model, 'reply' => $reply]); }
Replying to the message of given ID. @param int $id @return string|Response
entailment
public function actionSent() { $searchModel = new MessageSearch(); return $this->render('sent', [ 'dataProvider' => $searchModel->search(Yii::$app->request->get()), 'searchModel' => $searchModel ]); }
Listing the sent messages. @return string
entailment
public function actionViewSent($id = null) { $model = Message::find()->where([ 'and', ['id' => $id, 'sender_id' => User::loggedId()], ['!=', 'sender_status', Message::STATUS_DELETED] ])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the message with the given ID.')); return $this->redirect(['messages/inbox']); } $model->markRead(); return $this->render('view', [ 'model' => $model, 'type' => 'sent', 'id' => $model->id ]); }
Viewing the sent message of given ID. @param int $id @return string|Response
entailment
public function actionViewReceived($id = null) { $model = MessageReceiver::find()->where([ 'and', ['id' => $id, 'receiver_id' => User::loggedId()], ['!=', 'receiver_status', MessageReceiver::STATUS_DELETED] ])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find the message with the given ID.')); return $this->redirect(['messages/inbox']); } $model->markRead(); return $this->render('view', [ 'model' => $model->message, 'type' => 'received', 'id' => $model->id ]); }
Viewing the received message of given ID. @param int $id @return string|Response
entailment
public function actionLoad() { if (!Yii::$app->request->isAjax) { return $this->redirect(['forum/index']); } $result = ['messages' => '', 'more' => 0]; if (!Podium::getInstance()->user->isGuest) { $loggedId = User::loggedId(); $id = Yii::$app->request->post('message'); $message = Message::find()->where(['id' => $id])->limit(1)->one(); if ($message && ($message->sender_id == $loggedId || $message->isMessageReceiver($loggedId))) { $stack = 0; $reply = clone $message; while ($reply->reply && $stack < 5) { $result['more'] = 0; if ($reply->reply->sender_id == $loggedId && $reply->reply->sender_status == Message::STATUS_DELETED) { $reply = $reply->reply; continue; } $result['messages'] .= $this->renderPartial('load', ['reply' => $reply]); $reply = $reply->reply; if ($reply) { $result['more'] = $reply->id; } $stack++; } } } return Json::encode($result); }
Loads older messages in thread. @return string
entailment
protected function encodePath($path) { $a = explode('/', $path); for ($i=0; $i<count($a); $i++) { $a[$i] = rawurlencode($a[$i]); } return implode('/', $a); }
url encode a path @param string $path @return string
entailment
public function getMetadata($path) { $location = $this->applyPathPrefix($this->encodePath($path)); try { $result = $this->client->propFind($location, self::$metadataFields); if (empty($result)) { return false; } return $this->normalizeObject($result, $path); } catch (Exception $e) { return false; } catch (HttpException $e) { return false; } }
{@inheritdoc}
entailment
public function read($path) { $location = $this->applyPathPrefix($this->encodePath($path)); try { $response = $this->client->request('GET', $location); if ($response['statusCode'] !== 200) { return false; } return array_merge([ 'contents' => $response['body'], 'timestamp' => strtotime(is_array($response['headers']['last-modified']) ? current($response['headers']['last-modified']) : $response['headers']['last-modified']), 'path' => $path, ], Util::map($response['headers'], static::$resultMap)); } catch (Exception $e) { return false; } }
{@inheritdoc}
entailment
public function write($path, $contents, Config $config) { if (!$this->createDir(Util::dirname($path), $config)) { return false; } $location = $this->applyPathPrefix($this->encodePath($path)); $response = $this->client->request('PUT', $location, $contents); if ($response['statusCode'] >= 400) { return false; } $result = compact('path', 'contents'); if ($config->get('visibility')) { throw new LogicException(__CLASS__.' does not support visibility settings.'); } return $result; }
{@inheritdoc}
entailment
public function copy($path, $newpath) { if ($this->useStreamedCopy === true) { return $this->streamedCopy($path, $newpath); } else { return $this->nativeCopy($path, $newpath); } }
{@inheritdoc}
entailment
public function delete($path) { $location = $this->applyPathPrefix($this->encodePath($path)); try { $response = $this->client->request('DELETE', $location)['statusCode']; return $response >= 200 && $response < 300; } catch (NotFound $e) { return false; } }
{@inheritdoc}
entailment
public function createDir($path, Config $config) { $encodedPath = $this->encodePath($path); $path = trim($path, '/'); $result = compact('path') + ['type' => 'dir']; if (Util::normalizeDirname($path) === '' || $this->has($path)) { return $result; } $directories = explode('/', $path); if (count($directories) > 1) { $parentDirectories = array_splice($directories, 0, count($directories) - 1); if (!$this->createDir(implode('/', $parentDirectories), $config)) { return false; } } $location = $this->applyPathPrefix($encodedPath); $response = $this->client->request('MKCOL', $location . $this->pathSeparator); if ($response['statusCode'] !== 201) { return false; } return $result; }
{@inheritdoc}
entailment
public function listContents($directory = '', $recursive = false) { $location = $this->applyPathPrefix($this->encodePath($directory)); $response = $this->client->propFind($location . '/', self::$metadataFields, 1); array_shift($response); $result = []; foreach ($response as $path => $object) { $path = rawurldecode($this->removePathPrefix($path)); $object = $this->normalizeObject($object, $path); $result[] = $object; if ($recursive && $object['type'] === 'dir') { $result = array_merge($result, $this->listContents($object['path'], true)); } } return $result; }
{@inheritdoc}
entailment
public function actionAssignRole($idOrEmail, $role) { if (!$user = $this->findUser($idOrEmail)) { return self::EXIT_CODE_ERROR; } $rbac = Podium::getInstance()->getRbac(); if (!$role = $rbac->getRole($role)) { $this->stderr('No such role.' . PHP_EOL); return self::EXIT_CODE_ERROR; } if (strpos($role->name, 'podium') === 0) { $this->setPodiumUserRole($user, $role); } else { $rbac->assign($role, $user->id); } $this->stdout("user#{$user->id} has role '{$role->name}'" . PHP_EOL); }
Changes forum user role. @param int|string $idOrEmail internal podium user id or email @param string $role one of 'podiumUser', 'podiumModerator', 'podiumAdmin' or other application defined role
entailment
public function actionRevokeRole($idOrEmail, $role) { if (!$user = $this->findUser($idOrEmail)) { return self::EXIT_CODE_ERROR; } $rbac = Podium::getInstance()->getRbac(); if (!$role = $rbac->getRole($role)) { $this->stderr('No such role.' . PHP_EOL); return self::EXIT_CODE_ERROR; } if (strpos($role->name, 'podium') === 0) { $defaultPodiumRole = $rbac->getRole(Rbac::ROLE_USER); $this->setPodiumUserRole($user, $defaultPodiumRole); $this->stdout("user#{$user->id} has role '{$defaultPodiumRole->name}'" . PHP_EOL); } else { $rbac->revoke($role, $user->id); $this->stdout("user#{$user->id} role '{$role->name}' revoked" . PHP_EOL); } }
Revokes specified forum user role, and sets default forum user role @param int|string $idOrEmail internal podium user id or email @param string $role one of 'podiumUser', 'podiumModerator', 'podiumAdmin' or other application defined role
entailment
public function actionShowRoles($idOrEmail) { if (!$user = $this->findUser($idOrEmail)) { return self::EXIT_CODE_ERROR; } $roles = Podium::getInstance()->getRbac()->getRolesByUser($user->id); print_r($roles); }
Shows user roles @param int|string $idOrEmail internal podium user id or email
entailment
protected function setPodiumUserRole($user, $role) { $rbac = Podium::getInstance()->getRbac(); $userRoles = $rbac->getRolesByUser($user->id); $podiumRoles = array_filter($userRoles, function ($role) { return strpos($role->name, 'podium') === 0; }); foreach ($podiumRoles as $podiumRole) { $rbac->revoke($podiumRole, $user->id); } $rbac->assign($role, $user->id); }
Assigns specified role to user, after removing all forum roles (with 'podium' prefix) @param User $user @param Role $role
entailment
protected function findUser($idOrEmail) { if (!$user = User::find()->andWhere(is_numeric($idOrEmail) ? ['id' => $idOrEmail] : ['email' => $idOrEmail])->limit(1)->one()) { $this->stderr('User not found.' . PHP_EOL); } return $user; }
Finds user by id or email @param int|string $idOrEmail internal podium user id or email @return User
entailment
public function getUserVoted($userId) { return (new Query())->from('{{%podium_poll_vote}}')->where([ 'poll_id' => $this->id, 'caster_id' => $userId ])->count('id') ? true : false; }
Checks if user has already voted in poll. @param int $userId @return bool
entailment
public function vote($userId, $answers) { $votes = []; $time = time(); foreach ($answers as $answer) { $votes[] = [$this->id, $answer, $userId, $time]; } if (!empty($votes)) { $transaction = static::getDb()->beginTransaction(); try { if (!Podium::getInstance()->db->createCommand()->batchInsert( '{{%podium_poll_vote}}', ['poll_id', 'answer_id', 'caster_id', 'created_at'], $votes )->execute()) { throw new Exception('Votes saving error!'); } if (!PollAnswer::updateAllCounters(['votes' => 1], ['id' => $answers])) { throw new Exception('Votes adding error!'); } $transaction->commit(); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), $this->id, __METHOD__); } } return false; }
Votes in poll. @param int $userId @param array $answers @return bool
entailment
public function hasAnswer($answerId) { foreach ($this->answers as $answer) { if ($answer->id == $answerId) { return true; } } return false; }
Checks if poll has given answer. @param int $answerId @return bool
entailment
public function getVotesCount() { $votes = 0; foreach ($this->answers as $answer) { $votes += $answer->votes; } return $votes; }
Returns number of casted votes. @return int
entailment
public function podiumDelete() { $transaction = static::getDb()->beginTransaction(); try { if (!Podium::getInstance()->db->createCommand()->delete('{{%podium_poll_vote}}', ['poll_id' => $this->id])->execute()) { throw new Exception('Poll Votes deleting error!'); } if (!PollAnswer::deleteAll(['poll_id' => $this->id])) { throw new Exception('Poll Answers deleting error!'); } if (!$this->delete()) { throw new Exception('Poll deleting error!'); } $transaction->commit(); Log::info('Poll deleted', !empty($this->id) ? $this->id : '', __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs poll delete with answers and votes. @return bool
entailment
public function podiumEdit() { $transaction = static::getDb()->beginTransaction(); try { if (!$this->save()) { throw new Exception('Poll saving error!'); } foreach ($this->editAnswers as $answer) { foreach ($this->answers as $oldAnswer) { if ($answer == $oldAnswer->answer) { continue(2); } } $pollAnswer = new PollAnswer(); $pollAnswer->poll_id = $this->id; $pollAnswer->answer = $answer; if (!$pollAnswer->save()) { throw new Exception('Poll Answer saving error!'); } } foreach ($this->answers as $oldAnswer) { foreach ($this->editAnswers as $answer) { if ($answer == $oldAnswer->answer) { continue(2); } } if (!$oldAnswer->delete()) { throw new Exception('Poll Answer deleting error!'); } } $transaction->commit(); Log::info('Poll updated', $this->id, __METHOD__); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs poll update. @return bool
entailment
public function validatePassword($attribute) { if (!$this->hasErrors()) { $user = $this->user; if (empty($user) || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Incorrect username or password.'); } } }
Validates password. @param string $attribute
entailment
public function login() { if ($this->validate()) { return Podium::getInstance()->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); } return false; }
Logs user in. @return bool
entailment
public function getUser() { if ($this->_user === false) { $this->_user = User::findByKeyfield($this->username); } return $this->_user; }
Returns user. @return User
entailment
public function run($id = null) { if (!is_numeric($id) || $id < 1) { $this->controller->error(Yii::t('podium/flash', 'Sorry! We can not find the message you are looking for.')); return $this->controller->redirect($this->redirectRoute); } $model = $this->modelQuery->where([ 'and', ['id' => $id, $this->type . '_id' => User::loggedId()], ['!=', $this->type . '_status', $this->deletedStatus] ])->limit(1)->one(); if (empty($model)) { $this->controller->error(Yii::t('podium/flash', 'Sorry! We can not find the message with the given ID.')); return $this->controller->redirect($this->redirectRoute); } if ($model->remove()) { $this->controller->success(Yii::t('podium/flash', 'Message has been deleted.')); } else { Log::error('Error while deleting message', $model->id, __METHOD__); $this->controller->error(Yii::t('podium/flash', 'Sorry! We can not delete this message. Contact administrator about this problem.')); } return $this->controller->redirect($this->redirectRoute); }
Runs action. @param int $id @return Response
entailment
public function actionDetails() { $model = User::findMe(); if (empty($model)) { return $this->redirect(['account/login']); } $model->scenario = Podium::getInstance()->userComponent !== true ? 'accountInherit' : 'account'; $model->currentPassword = null; $previous_new_email = $model->new_email; if (empty($model->username)) { $model->username = 'user_' . $model->id; } if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { if ($model->saveChanges()) { if ($previous_new_email != $model->new_email) { $forum = $this->module->podiumConfig->get('name'); $email = Content::fill(Content::EMAIL_NEW); if ($email !== false && Email::queue( $model->new_email, str_replace('{forum}', $forum, $email->topic), str_replace('{forum}', $forum, str_replace('{link}', Html::a( Url::to(['account/new-email', 'token' => $model->email_token], true), Url::to(['account/new-email', 'token' => $model->email_token], true) ), $email->content)), !empty($model->id) ? $model->id : null )) { Log::info('New email activation link queued', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'Your account has been updated but your new e-mail address is not active yet. Click the activation link that will be sent to your new e-mail address in few minutes.')); } else { Log::error('Error while queuing new email activation link', $model->id, __METHOD__); $this->warning(Yii::t('podium/flash', 'Your account has been updated but your new e-mail address is not active yet. Unfortunately there was some error while sending you the activation link. Contact administrator about this problem.')); } } else { Log::info('Details updated', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'Your account has been updated.')); } return $this->refresh(); } } } $model->currentPassword = null; return $this->render('details', ['model' => $model]); }
Updating the profile details. @return string|Response
entailment
public function actionForum() { $user = User::findMe(); $model = Meta::find()->where(['user_id' => $user->id])->limit(1)->one(); if (empty($model)) { $model = new Meta(); } if ($model->load(Yii::$app->request->post())) { $model->user_id = $user->id; $uploadAvatar = false; $path = Yii::getAlias('@webroot/avatars'); $model->image = UploadedFile::getInstance($model, 'image'); if ($model->validate()) { if ($model->gravatar && empty($user->email)) { $model->addError('gravatar', Yii::t('podium/view', 'You need email address set to use Gravatar.')); } else { if ($model->image) { $folderExists = true; if (!file_exists($path)) { if (!FileHelper::createDirectory($path)) { $folderExists = false; Log::error('Error while creating avatars folder', null, __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There was an error while creating the avatars folder. Contact administrator about this problem.')); } } if ($folderExists) { $oldAvatarPath = $path . DIRECTORY_SEPARATOR . $model->avatar; if (!empty($model->avatar) && file_exists($oldAvatarPath)) { if (!unlink($oldAvatarPath)) { Log::error('Error while deleting old avatar image', null, __METHOD__); } } $model->avatar = Yii::$app->security->generateRandomString() . '.' . $model->image->getExtension(); $uploadAvatar = true; } } if ($model->save(false)) { if ($uploadAvatar) { if (!$model->image->saveAs($path . DIRECTORY_SEPARATOR . $model->avatar)) { Log::error('Error while saving avatar image', null, __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There was an error while uploading the avatar image. Contact administrator about this problem.')); } } Log::info('Profile updated', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'Your profile details have been updated.')); return $this->refresh(); } } } } return $this->render('forum', ['model' => $model, 'user' => $user]); }
Updating the forum details. @return string|Response
entailment
public function actionIndex() { $model = User::findMe(); if (empty($model)) { if ($this->module->userComponent === true) { return $this->redirect(['account/login']); } return $this->module->goPodium(); } return $this->render('profile', ['model' => $model]); }
Showing the profile card. @return string|Response
entailment
public function actionSubscriptions() { $postData = Yii::$app->request->post(); if ($postData) { if (Subscription::remove(!empty($postData['selection']) ? $postData['selection'] : [])) { $this->success(Yii::t('podium/flash', 'Subscription list has been updated.')); } else { $this->error(Yii::t('podium/flash', 'Sorry! There was an error while unsubscribing the thread list.')); } return $this->refresh(); } return $this->render('subscriptions', [ 'dataProvider' => (new Subscription())->search(Yii::$app->request->get()) ]); }
Showing the subscriptions. @return string|Response
entailment
public function actionMark($id = null) { $model = Subscription::find()->where(['id' => $id, 'user_id' => User::loggedId()])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Subscription with this ID.')); return $this->redirect(['profile/subscriptions']); } if ($model->post_seen == Subscription::POST_SEEN) { if ($model->unseen()) { $this->success(Yii::t('podium/flash', 'Thread has been marked unseen.')); } else { Log::error('Error while marking thread', $model->id, __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There was some error while marking the thread.')); } return $this->redirect(['profile/subscriptions']); } if ($model->post_seen == Subscription::POST_NEW) { if ($model->seen()) { $this->success(Yii::t('podium/flash', 'Thread has been marked seen.')); } else { Log::error('Error while marking thread', $model->id, __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There was some error while marking the thread.')); } return $this->redirect(['profile/subscriptions']); } $this->error(Yii::t('podium/flash', 'Sorry! Subscription has got the wrong status.')); return $this->redirect(['profile/subscriptions']); }
Marking the subscription of given ID. @param int $id @return Response
entailment
public function actionDelete($id = null) { $model = Subscription::find()->where(['id' => (int)$id, 'user_id' => User::loggedId()])->limit(1)->one(); if (empty($model)) { $this->error(Yii::t('podium/flash', 'Sorry! We can not find Subscription with this ID.')); return $this->redirect(['profile/subscriptions']); } if ($model->delete()) { $this->module->podiumCache->deleteElement('user.subscriptions', User::loggedId()); $this->success(Yii::t('podium/flash', 'Thread has been unsubscribed.')); } else { Log::error('Error while deleting subscription', $model->id, __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There was some error while deleting the subscription.')); } return $this->redirect(['profile/subscriptions']); }
Deleting the subscription of given ID. @param int $id @return Response
entailment
public function actionAdd($id = null) { 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 adding this subscription!'), ['class' => 'text-danger'] ), ]; if (Podium::getInstance()->user->isGuest) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'Please sign in to subscribe to this thread'), ['class' => 'text-info'] ); } if (is_numeric($id) && $id > 0) { $subscription = Subscription::find()->where(['thread_id' => $id, 'user_id' => User::loggedId()])->limit(1)->one(); if (!empty($subscription)) { $data['msg'] = Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-warning-sign']) . ' ' . Yii::t('podium/view', 'You are already subscribed to this thread.'), ['class' => 'text-info'] ); } else { if (Subscription::add((int)$id)) { $data = [ 'error' => 0, 'msg' => Html::tag('span', Html::tag('span', '', ['class' => 'glyphicon glyphicon-ok-circle']) . ' ' . Yii::t('podium/view', 'You have subscribed to this thread!'), ['class' => 'text-success'] ), ]; } } } return Json::encode($data); }
Subscribing the thread of given ID. @param int $id @return Response
entailment
public function beforeAction($action) { if (!parent::beforeAction($action)) { return false; } if ($this->accessType === 0) { return $this->module->goPodium(); } return true; }
Redirect in case of guest access type. @param Action $action the action to be executed @return bool @since 0.6
entailment
public function actionActivate($token) { if ($this->module->userComponent !== true) { $this->info(Yii::t('podium/flash', 'Please contact the administrator to activate your account.')); return $this->module->goPodium(); } $model = User::findByActivationToken($token); if (!$model) { $this->error(Yii::t('podium/flash', 'The provided activation token is invalid or expired.')); return $this->module->goPodium(); } $model->scenario = 'token'; if ($model->activate()) { PodiumCache::clearAfter('activate'); Log::info('Account activated', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'Your account has been activated. You can sign in now.')); } else { Log::error('Error while activating account', $model->id, __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There was some error while activating your account. Contact administrator about this problem.')); } return $this->module->goPodium(); }
Activating the account based on the provided activation token. @param string $token @return Response
entailment
public function actionLogin() { if ($this->module->userComponent !== true) { $this->info(Yii::t('podium/flash', 'Please use application Login form to sign in.')); return $this->module->goPodium(); } $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->module->goPodium(); } return $this->render('login', ['model' => $model]); }
Signing in. @return string|Response
entailment
public function actionNewEmail($token) { $model = User::findByEmailToken($token); if (!$model) { $this->error(Yii::t('podium/flash', 'The provided activation token is invalid or expired.')); return $this->module->goPodium(); } $model->scenario = 'token'; if ($model->changeEmail()) { Log::info('Email address changed', $model->id, __METHOD__); Yii::$app->session->removeFlash('warning'); // removes warning about not having the email $this->success(Yii::t('podium/flash', 'Your new e-mail address has been activated.')); } else { Log::error('Error while activating email', $model->id, __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There was some error while activating your new e-mail address. Contact administrator about this problem.')); } return $this->module->goPodium(); }
Activating new email address based on the provided token. @param string $token @return Response
entailment
public function actionPassword($token) { if ($this->module->userComponent !== true) { $this->info(Yii::t('podium/flash', 'Please contact the administrator to change your account password.')); return $this->module->goPodium(); } $model = User::findByPasswordResetToken($token); if (!$model) { $this->error(Yii::t('podium/flash', 'The provided password reset token is invalid or expired.')); return $this->module->goPodium(); } $model->scenario = 'passwordChange'; if ($model->load(Yii::$app->request->post()) && $model->changePassword()) { Log::info('Password changed', $model->id, __METHOD__); $this->success(Yii::t('podium/flash', 'Your account password has been changed.')); return $this->module->goPodium(); } return $this->render('password', ['model' => $model]); }
Changing the account password with provided token. @param string $token @return string|Response
entailment
public function actionRegister() { if ($this->module->userComponent !== true) { $this->info(Yii::t('podium/flash', "Please use application's Register form to sign up.")); return $this->module->goPodium(); } if ($this->module->podiumConfig->get('registration_off') == '1') { $this->info(Yii::t('podium/flash', 'User registration is currently not allowed.')); return $this->module->goPodium(); } $model = new User(); $model->scenario = 'register'; if ($model->load(Yii::$app->request->post())) { $result = $model->register(); if ($result == User::RESP_OK) { Log::info('Activation link queued', !empty($model->id) ? $model->id : '', __METHOD__); $this->success(Yii::t('podium/flash', 'Your account has been created but it is not active yet. Click the activation link that will be sent to your e-mail address in few minutes.')); return $this->module->goPodium(); } if ($result == User::RESP_EMAIL_SEND_ERR) { Log::warning('Error while queuing activation link', !empty($model->id) ? $model->id : '', __METHOD__); $this->warning(Yii::t('podium/flash', 'Your account has been created but it is not active yet. Unfortunately there was some error while sending you the activation link. Contact administrator about this or try to {resend the link}.', [ 'resend the link' => Html::a(Yii::t('podium/flash', 'resend the link'), ['account/reactivate']) ])); return $this->module->goPodium(); } if ($result == User::RESP_NO_EMAIL_ERR) { Log::error('Error while queuing activation link - no email set', !empty($model->id) ? $model->id : '', __METHOD__); $this->error(Yii::t('podium/flash', 'Sorry! There is no e-mail address saved with your account. Contact administrator about activating.')); return $this->module->goPodium(); } } $model->captcha = null; return $this->render('register', [ 'model' => $model, 'terms' => Content::fill(Content::TERMS_AND_CONDS)] ); }
Registering the new account and sending the activation link. @return string|Response
entailment
protected function reformRun($componentInfo, $model, $log, $view) { if ($this->module->userComponent !== true) { $this->info($componentInfo); return $this->module->goPodium(); } if ($model->load(Yii::$app->request->post())) { list($error, $message, $back) = $model->run(); if ($error) { Log::error($log['error'], !empty($model->user->id) ? $model->user->id : null, $log['method']); if (!empty($message)) { $this->error($message); } } else { Log::info($log['info'], $model->user->id, $log['method']); if (!empty($message)) { $this->success($message); } } if ($back) { return $this->module->goPodium(); } } return $this->render($view, ['model' => $model]); }
Runs actions processed with email. @param string $componentInfo @param ReactivateForm|ResetForm $model @param array $log @return string|Response @since 0.6
entailment
public function beforeAction($action) { try { if (parent::beforeAction($action)) { $this->db = !$this->db ? Podium::getInstance()->getDb() : Instance::ensure($this->db, Connection::className()); $this->mailer = Instance::ensure($this->mailer, BaseMailer::className()); return true; } } catch (Exception $e) { $this->stderr("ERROR: " . $e->getMessage() . "\n"); } return false; }
Checks the existence of the db and mailer components. @param Action $action the action to be executed. @return bool whether the action should continue to be executed.
entailment
public function getNewBatch($limit = 0) { try { if (!is_numeric($limit) || $limit <= 0) { $limit = $this->limit; } return (new Query) ->from($this->queueTable) ->where(['status' => Email::STATUS_PENDING]) ->orderBy(['id' => SORT_ASC]) ->limit((int)$limit) ->all($this->db); } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } }
Returns new batch of emails. @param int $limit maximum number of rows in batch @return array
entailment
public function send($email, $fromName, $fromEmail) { try { $mailer = Yii::$app->mailer->compose(); $mailer->setFrom([$fromEmail => $fromName]); $mailer->setTo($email['email']); $mailer->setSubject($email['subject']); $mailer->setHtmlBody($email['content']); $mailer->setTextBody(strip_tags(str_replace( ['<br>', '<br/>', '<br />', '</p>'], "\n", $email['content'] ))); return $mailer->send(); } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } }
Sends email using mailer component. @param string $email @param string $fromName @param string $fromEmail @return bool
entailment
public function process($email, $fromName, $fromEmail, $maxAttempts) { try { if ($this->send($email, $fromName, $fromEmail)) { $this ->db ->createCommand() ->update( $this->queueTable, ['status' => Email::STATUS_SENT], ['id' => $email['id']] ) ->execute(); return true; } $attempt = $email['attempt'] + 1; if ($attempt <= $maxAttempts) { $this ->db ->createCommand() ->update( $this->queueTable, ['attempt' => $attempt], ['id' => $email['id']] ) ->execute(); } else { $this ->db ->createCommand() ->update( $this->queueTable, ['status' => Email::STATUS_GAVEUP], ['id' => $email['id']] ) ->execute(); } } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Tries to send email from queue and updates its status. @param string $email @param string $fromName @param string $fromEmail @param int $maxAttempts @return bool
entailment
public function actionRun($limit = 0) { $version = $this->module->version; $this->stdout("\nPodium mail queue v{$version}\n"); $this->stdout("------------------------------\n"); $emails = $this->getNewBatch($limit); if (empty($emails)) { $this->stdout("No pending emails in the queue found.\n\n", Console::FG_GREEN); return self::EXIT_CODE_NORMAL; } $total = count($emails); $this->stdout( "\n$total pending " . ($total === 1 ? 'email' : 'emails') . " to be sent now:\n", Console::FG_YELLOW ); $errors = false; foreach ($emails as $email) { if (!$this->process( $email, $this->module->podiumConfig->get('from_name'), $this->module->podiumConfig->get('from_email'), $this->module->podiumConfig->get('max_attempts') )) { $errors = true; } } if ($errors) { $this->stdout("\nBatch sent with errors.\n\n", Console::FG_RED); } else { $this->stdout("\nBatch sent successfully.\n\n", Console::FG_GREEN); } return self::EXIT_CODE_NORMAL; }
Runs the queue. @param int $limit @return int|void
entailment
public function actionCheck() { $version = $this->module->version; $this->stdout("\nPodium mail queue check v{$version}\n"); $this->stdout("------------------------------\n"); $this->stdout(" EMAILS | COUNT\n"); $this->stdout("------------------------------\n"); $pending = (new Query) ->from($this->queueTable) ->where(['status' => Email::STATUS_PENDING]) ->count('id', $this->db); $sent = (new Query) ->from($this->queueTable) ->where(['status' => Email::STATUS_SENT]) ->count('id', $this->db); $gaveup = (new Query) ->from($this->queueTable) ->where(['status' => Email::STATUS_GAVEUP]) ->count('id', $this->db); $showPending = $this->ansiFormat($pending, Console::FG_YELLOW); $showSent = $this->ansiFormat($sent, Console::FG_GREEN); $showGaveup = $this->ansiFormat($gaveup, Console::FG_RED); $this->stdout(" pending | $showPending\n"); $this->stdout(" sent | $showSent\n"); $this->stdout(" stucked | $showGaveup\n"); $this->stdout("------------------------------\n\n"); return self::EXIT_CODE_NORMAL; }
Checks the current status for the mail queue.
entailment
public function init() { parent::init(); $this->matchCallback = function () { return !User::can($this->perm); }; $this->denyCallback = function () { Yii::$app->session->addFlash('danger', Yii::t('podium/flash', 'You are not allowed to perform this action.'), true); return Yii::$app->response->redirect([Podium::getInstance()->prepareRoute($this->redirect)]); }; }
Sets match and deny callbacks.
entailment
public function getDefaults() { return [ 'activation_token_expire' => self::SECONDS_ACTIVATION_TOKEN_EXPIRE, 'allow_polls' => self::FLAG_ALLOW_POLLS, 'email_token_expire' => self::SECONDS_EMAIL_TOKEN_EXPIRE, 'from_email' => self::DEFAULT_FROM_EMAIL, 'from_name' => self::DEFAULT_FROM_NAME, 'hot_minimum' => self::HOT_MINIMUM, 'maintenance_mode' => self::MAINTENANCE_MODE, 'max_attempts' => self::MAX_SEND_ATTEMPTS, 'members_visible' => self::FLAG_MEMBERS_VISIBLE, 'merge_posts' => self::FLAG_MERGE_POSTS, 'meta_description' => self::META_DESCRIPTION, 'meta_keywords' => self::META_KEYWORDS, 'name' => self::PODIUM_NAME, 'password_reset_token_expire' => self::SECONDS_PASSWORD_RESET_TOKEN_EXPIRE, 'recaptcha_secretkey' => '', 'recaptcha_sitekey' => '', 'registration_off' => self::REGISTRATION_OFF, 'use_captcha' => self::FLAG_USE_CAPTCHA, 'use_wysiwyg' => self::FLAG_USE_WYSIWYG, 'version' => Podium::getInstance()->version, ]; }
Returns list of default configuration values. These values are stored in cached configuration but saved only when administrator saves Podium settings. @return array @since 0.2
entailment
public function getAll() { if ($this->_config !== null) { return $this->_config; } try { $this->_config = $this->cached; } catch (Exception $exc) { Log::warning($exc->getMessage(), null, __METHOD__); $this->_config = $this->stored; } return $this->_config; }
Returns configuration values. @return array @since 0.6
entailment
public function getCached() { $cache = $this->cache->get('config'); if ($cache === false) { $cache = $this->notCached; $this->cache->set('config', $cache); } return $cache; }
Returns cached configuration values. @return array @throws Exception @since 0.6
entailment
public function getStored() { $stored = []; try { $query = (new Query)->from(static::tableName())->all(); if (!empty($query)) { foreach ($query as $setting) { $stored[$setting['name']] = $setting['value']; } } } catch (Exception $e) { if (Podium::getInstance()->getInstalled()) { Log::error($e->getMessage(), null, __METHOD__); } } return $stored; }
Returns stored configuration values. These can be empty if configuration has not been modified. @return array @since 0.6
entailment
public function get($name) { $config = $this->all; return isset($config[$name]) ? $config[$name] : null; }
Returns configuration value of the given name. @param string $name configuration key @return string|null
entailment
public function set($name, $value) { try { if (is_string($name) && (is_string($value) || $value === null)) { if ($value === null) { if (!array_key_exists($name, $this->defaults)) { return false; } $value = $this->defaults[$name]; } if ((new Query)->from(static::tableName())->where(['name' => $name])->exists()) { Podium::getInstance()->db->createCommand()->update( static::tableName(), ['value' => $value], ['name' => $name] )->execute(); } else { Podium::getInstance()->db->createCommand()->insert( static::tableName(), ['name' => $name, 'value' => $value] )->execute(); } $this->cache->set('config', $this->notCached); $this->_config = null; return true; } } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Sets configuration value of the given name. Every change automatically updates the cache. Set value to null to restore default one. @param string $name configuration key @param string $value configuration value @return bool
entailment
public function loggedUser($id) { if (Podium::getInstance()->userComponent !== true) { return $this->andWhere(['inherited_id' => $id]); } return $this->andWhere(['id' => $id]); }
Adds proper user ID for query. @param int $id
entailment
public function getNamedUsersList($url) { $out = ''; $conditions = ['and', [Activity::tableName() . '.anonymous' => 0], ['is not', 'user_id', null], ['like', 'url', $url . '%', false], ['>=', Activity::tableName() . '.updated_at', time() - 5 * 60] ]; if (!Podium::getInstance()->user->isGuest) { $this->_guest = false; $me = User::findMe(); $conditions[] = ['!=', 'user_id', $me->id]; if (!empty($me->meta) && $me->meta->anonymous == 0) { $out .= $me->podiumTag . ' '; } else { $this->_anon = true; } } $users = Activity::find() ->joinWith(['user']) ->where($conditions); foreach ($users->each() as $user) { $out .= $user->user->podiumTag . ' '; } return $out; }
Returns formatted list of named users browsing given url group. @param string $url @return string @since 0.2
entailment
public function getAnonymousUsers($url) { $anons = Activity::find() ->where(['and', ['anonymous' => 1], ['like', 'url', $url . '%', false], ['>=', 'updated_at', time() - 5 * 60] ]) ->count('id'); if ($this->_anon) { $anons += 1; } return $anons; }
Returns number of anonymous users browsing given url group. @param string $url @return int @since 0.2
entailment
public function getGuestUsers($url) { $guests = Activity::find() ->where(['and', ['user_id' => null], ['like', 'url', $url . '%', false], ['>=', 'updated_at', time() - 5 * 60] ]) ->count('id'); if ($this->_guest) { $guests += 1; } return $guests; }
Returns number of guest users browsing given url group. @param string $url @return int @since 0.2
entailment
public function run() { $url = Yii::$app->request->getUrl(); $out = ''; switch ($this->what) { case 'forum': $out .= Yii::t('podium/view', 'Browsing this forum') . ': '; break; case 'topic': $out .= Yii::t('podium/view', 'Reading this thread') . ': '; break; case 'unread': $out .= Yii::t('podium/view', 'Browsing unread threads') . ': '; break; case 'members': $out .= Yii::t('podium/view', 'Browsing the members') . ': '; break; } $out .= $this->getNamedUsersList($url); $anonymous = $this->getAnonymousUsers($url); if ($anonymous) { $out .= Html::button( Yii::t('podium/view', '{n, plural, =1{# anonymous user} other{# anonymous users}}', [ 'n' => $anonymous ]), ['class' => 'btn btn-xs btn-default disabled'] ) . ' '; } $guests = $this->getGuestUsers($url); if ($guests) { $out .= Html::button( Yii::t('podium/view', '{n, plural, =1{# guest} other{# guests}}', [ 'n' => $guests ]), ['class' => 'btn btn-xs btn-default disabled'] ); } return $out; }
Renders the list of users reading current section. @return string
entailment
public function run() { $avatar = Html::img(Helper::defaultAvatar(), [ 'class' => 'podium-avatar img-circle img-responsive center-block', 'alt' => Yii::t('podium/view', 'user deleted') ]); $name = Helper::deletedUserTag(true); if ($this->author instanceof User) { $avatar = Html::img(Helper::defaultAvatar(), [ 'class' => 'podium-avatar img-circle img-responsive center-block', 'alt' => Html::encode($this->author->podiumName) ]); $name = $this->author->podiumTag; $meta = $this->author->meta; if (!empty($meta)) { if (!empty($meta->gravatar)) { $avatar = Gravatar::widget([ 'email' => $this->author->email, 'defaultImage' => 'identicon', 'rating' => 'r', 'options' => [ 'alt' => Html::encode($this->author->podiumName), 'class' => 'podium-avatar img-circle img-responsive center-block', ] ]); } elseif (!empty($meta->avatar)) { $avatar = Html::img('@web/avatars/' . $meta->avatar, [ 'class' => 'podium-avatar img-circle img-responsive center-block', 'alt' => Html::encode($this->author->podiumName) ]); } } } return $avatar . ($this->showName ? Html::tag('p', $name, ['class' => 'avatar-name']) : ''); }
Renders the image. Based on user settings the avatar can be uploaded image, Gravatar image or default one. @return string
entailment
public function remove() { $transaction = static::getDb()->beginTransaction(); try { $clearCache = false; if ($this->receiver_status == self::STATUS_NEW) { $clearCache = true; } $deleteParent = null; $this->scenario = 'remove'; if ($this->message->sender_status != Message::STATUS_DELETED) { $this->receiver_status = self::STATUS_DELETED; if (!$this->save()) { throw new Exception('Message status changing error!'); } if ($clearCache) { Podium::getInstance()->podiumCache->deleteElement('user.newmessages', $this->receiver_id); } $transaction->commit(); return true; } if ($this->message->sender_status == Message::STATUS_DELETED && count($this->message->messageReceivers) == 1) { $deleteParent = $this->message; } if (!$this->delete()) { throw new Exception('Message removing error!'); } if ($clearCache) { Podium::getInstance()->podiumCache->deleteElement('user.newmessages', $this->receiver_id); } if ($deleteParent) { if (!$deleteParent->delete()) { throw new Exception('Sender message deleting error!'); } } $transaction->commit(); return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), $this->id, __METHOD__); } return false; }
Removes message. @return bool
entailment
public function search($params) { $subquery = (new Query()) ->select(['m2.replyto']) ->from(['m1' => Message::tableName()]) ->leftJoin(['m2' => Message::tableName()], 'm1.replyto = m2.id') ->where(['is not', 'm2.replyto', null]); $query = static::find()->where(['and', ['receiver_id' => User::loggedId()], ['!=', 'receiver_status', self::STATUS_DELETED], ['not in', 'message_id', $subquery] ]); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $dataProvider->sort->attributes['senderName'] = [ 'asc' => [ User::tableName() . '.username' => SORT_ASC, User::tableName() . '.id' => SORT_ASC ], 'desc' => [ User::tableName() . '.username' => SORT_DESC, User::tableName() . '.id' => SORT_DESC ], 'default' => SORT_ASC ]; $dataProvider->sort->defaultOrder = ['id' => SORT_DESC]; $dataProvider->pagination->pageSize = Yii::$app->session->get('per-page', 20); if (!($this->load($params) && $this->validate())) { $dataProvider->query->joinWith(['message' => function ($q) { $q->joinWith(['sender']); }]); return $dataProvider; } $dataProvider->query->andFilterWhere(['like', 'topic', $this->topic]); if (preg_match('/^(forum|orum|rum|um|m)?#([0-9]+)$/', strtolower($this->senderName), $matches)) { $dataProvider->query->joinWith(['message' => function ($q) use ($matches) { $q->joinWith(['sender' => function ($q) use ($matches) { $q->andFilterWhere(['and', [User::tableName() . '.id' => $matches[2]], ['or', ['username' => ''], ['username' => null] ] ]); }]); }]); } elseif (preg_match('/^([0-9]+)$/', $this->senderName, $matches)) { $dataProvider->query->joinWith(['message' => function ($q) use ($matches) { $q->joinWith(['sender' => function ($q) use ($matches) { $q->andFilterWhere(['or', ['like', 'username', $this->senderName], ['and', ['id' => $matches[1]], ['or', ['username' => ''], ['username' => null] ] ], ]); }]); }]); } else { $dataProvider->query->joinWith(['message' => function ($q) { $q->joinWith(['sender' => function ($q) { $q->andFilterWhere(['like', User::tableName() . '.username', $this->senderName]); }]); }]); } return $dataProvider; }
Searches for messages. @return ActiveDataProvider
entailment
public function markRead() { if ($this->receiver_status == Message::STATUS_NEW) { $this->receiver_status = Message::STATUS_READ; if ($this->save()) { Podium::getInstance()->podiumCache->deleteElement('user.newmessages', $this->receiver_id); } } }
Marks message read. @since 0.2
entailment
protected function addAdmin() { if ($this->module->userComponent !== true) { return $this->addInheritedAdmin(); } $transaction = $this->db->beginTransaction(); try { $admin = new User(); $admin->setScenario('installation'); $admin->setAttributes([ 'username' => self::DEFAULT_USERNAME, 'status' => User::STATUS_ACTIVE, 'role' => User::ROLE_ADMIN, ], false); $admin->generateAuthKey(); $admin->setPassword(self::DEFAULT_USERNAME); if (!$admin->save()) { throw new Exception(VarDumper::dumpAsString($admin->errors)); } if (!$this->authManager->assign($this->authManager->getRole(Rbac::ROLE_ADMIN), $admin->id)) { throw new Exception('Error during Administrator privileges setting!'); } $transaction->commit(); return $this->returnSuccess( Yii::t('podium/flash', 'Administrator account has been created.') . ' ' . Html::tag('strong', Yii::t('podium/flash', 'Login') . ':') . ' ' . Html::tag('kbd', self::DEFAULT_USERNAME) . ' ' . Html::tag('strong', Yii::t('podium/flash', 'Password') . ':') . ' ' . Html::tag('kbd', self::DEFAULT_USERNAME) . '<br>' . Html::tag('strong', Yii::t('podium/flash', 'Remember to change these credentials after first login!'), ['class' => 'text-danger']) ); } catch (Exception $e) { $transaction->rollBack(); return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during account creating') ); } }
Adds Administrator account. @return string result message.
entailment
protected function addInheritedAdmin() { if (empty($this->module->adminId)) { $this->type = self::TYPE_WARNING; return Yii::t('podium/flash', 'No administrator privileges have been set!'); } try { $identity = Podium::getInstance()->user->identityClass; $inheritedUser = $identity::findIdentity($this->module->adminId); if (!$inheritedUser) { throw new Exception('Can not find administrator account!'); } $userNameField = $this->module->userNameField; if ($userNameField !== null && empty($inheritedUser->$userNameField)) { throw new Exception('Can not find administrator username!'); } } catch (Exception $e) { return $this->returnWarning(Yii::t('podium/flash', 'Cannot find inherited user of given ID. No administrator privileges have been set.')); } $transaction = $this->db->beginTransaction(); try { $admin = new User(); $admin->setScenario('installation'); $admin->setAttributes([ 'inherited_id' => $this->module->adminId, 'username' => $userNameField ? $inheritedUser->$userNameField : self::DEFAULT_USERNAME, 'status' => User::STATUS_ACTIVE, 'role' => User::ROLE_ADMIN, ], false); if (!$admin->save()) { throw new Exception(VarDumper::dumpAsString($admin->errors)); } if (!$this->authManager->assign($this->authManager->getRole(Rbac::ROLE_ADMIN), $admin->id)) { throw new Exception('Error during Administrator privileges setting!'); } $transaction->commit(); return $this->returnSuccess(Yii::t('podium/flash', 'Administrator privileges have been set for the user of ID {id}.', [ 'id' => $this->module->adminId ])); } catch (Exception $e) { $transaction->rollBack(); return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during account creating') ); } }
Adds Administrator account for inherited User Identity. @return string result message. @since 0.2
entailment
protected function addConfig() { try { $this->db->createCommand()->batchInsert( PodiumConfig::tableName(), ['name', 'value'], [ ['activation_token_expire', PodiumConfig::SECONDS_ACTIVATION_TOKEN_EXPIRE], ['allow_polls', PodiumConfig::FLAG_ALLOW_POLLS], ['email_token_expire', PodiumConfig::SECONDS_EMAIL_TOKEN_EXPIRE], ['from_email', PodiumConfig::DEFAULT_FROM_EMAIL], ['from_name', PodiumConfig::DEFAULT_FROM_NAME], ['hot_minimum', PodiumConfig::HOT_MINIMUM], ['maintenance_mode', PodiumConfig::MAINTENANCE_MODE], ['max_attempts', PodiumConfig::MAX_SEND_ATTEMPTS], ['members_visible', PodiumConfig::FLAG_MEMBERS_VISIBLE], ['merge_posts', PodiumConfig::FLAG_MERGE_POSTS], ['meta_description', PodiumConfig::META_DESCRIPTION], ['meta_keywords', PodiumConfig::META_KEYWORDS], ['name', PodiumConfig::PODIUM_NAME], ['password_reset_token_expire', PodiumConfig::SECONDS_PASSWORD_RESET_TOKEN_EXPIRE], ['recaptcha_secretkey', ''], ['recaptcha_sitekey', ''], ['registration_off', PodiumConfig::REGISTRATION_OFF], ['use_captcha', PodiumConfig::FLAG_USE_CAPTCHA], ['use_wysiwyg', PodiumConfig::FLAG_USE_WYSIWYG], ['version', Podium::getInstance()->version], ] )->execute(); return $this->returnSuccess(Yii::t('podium/flash', 'Default Config settings have been added.')); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during settings adding') ); } }
Adds config default settings. @return string result message.
entailment
protected function addContent() { try { $default = Content::defaultContent(); $this->db->createCommand()->batchInsert( Content::tableName(), ['name', 'topic', 'content'], [ [ Content::TERMS_AND_CONDS, $default[Content::TERMS_AND_CONDS]['topic'], $default[Content::TERMS_AND_CONDS]['content'] ], [ Content::EMAIL_REGISTRATION, $default[Content::EMAIL_REGISTRATION]['topic'], $default[Content::EMAIL_REGISTRATION]['content'] ], [ Content::EMAIL_PASSWORD, $default[Content::EMAIL_PASSWORD]['topic'], $default[Content::EMAIL_PASSWORD]['content'] ], [ Content::EMAIL_REACTIVATION, $default[Content::EMAIL_REACTIVATION]['topic'], $default[Content::EMAIL_REACTIVATION]['content'] ], [ Content::EMAIL_NEW, $default[Content::EMAIL_NEW]['topic'], $default[Content::EMAIL_NEW]['content'] ], [ Content::EMAIL_SUBSCRIPTION, $default[Content::EMAIL_SUBSCRIPTION]['topic'], $default[Content::EMAIL_SUBSCRIPTION]['content'] ], ] )->execute(); return $this->returnSuccess(Yii::t('podium/flash', 'Default Content has been added.')); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during content adding') ); } }
Adds default content. @return string result message.
entailment
protected function addRules() { try { (new Rbac())->add($this->authManager); return $this->returnSuccess(Yii::t('podium/flash', 'Access roles have been created.')); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during access roles creating') ); } }
Adds permission rules. @return string result message.
entailment
public function nextStep() { $currentStep = Yii::$app->session->get(self::SESSION_KEY, 0); if ($currentStep === 0) { Yii::$app->session->set(self::SESSION_STEPS, count($this->steps)); } $maxStep = Yii::$app->session->get(self::SESSION_STEPS, 0); $this->type = self::TYPE_ERROR; $this->table = '...'; if ($currentStep >= $maxStep) { return [ 'drop' => false, 'type' => $this->type, 'result' => Yii::t('podium/flash', 'Weird... Installation should already complete...'), 'percent' => 100 ]; } if (!isset($this->steps[$currentStep])) { return [ 'drop' => false, 'type' => $this->type, 'result' => Yii::t('podium/flash', 'Installation aborted! Can not find the requested installation step.'), 'percent' => 100, ]; } $this->table = $this->steps[$currentStep]['table']; $result = call_user_func_array([$this, $this->steps[$currentStep]['call']], $this->steps[$currentStep]['data']); Yii::$app->session->set(self::SESSION_KEY, ++$currentStep); return [ 'drop' => false, 'type' => $this->type, 'result' => $result, 'table' => $this->rawTable, 'percent' => $this->countPercent($currentStep, $maxStep), ]; }
Proceeds next installation step. @return array @since 0.2
entailment
public function nextDrop() { $drops = $this->countDrops(); if (count($drops)) { $currentStep = Yii::$app->session->get(self::SESSION_KEY, 0); $maxStep = Yii::$app->session->get(self::SESSION_STEPS, 0); if ($currentStep < $maxStep) { $this->type = self::TYPE_ERROR; $this->table = '...'; if (!isset($drops[$currentStep])) { return [ 'drop' => false, 'type' => $this->type, 'result' => Yii::t('podium/flash', 'Installation aborted! Can not find the requested drop step.'), 'percent' => 100, ]; } $this->table = $drops[$currentStep]['table']; $result = $this->dropTable(); if ($result === true) { Yii::$app->session->set(self::SESSION_KEY, ++$currentStep); return $this->nextDrop(); } Yii::$app->session->set(self::SESSION_KEY, ++$currentStep); return [ 'drop' => true, 'type' => $this->type, 'result' => $result, 'table' => $this->rawTable, 'percent' => $this->countPercent($currentStep, $maxStep), ]; } } Yii::$app->session->set(self::SESSION_KEY, 0); return $this->nextStep(); }
Proceeds next drop step. @return array @since 0.2
entailment
protected function countDrops() { $steps = array_reverse($this->steps); $drops = []; foreach ($steps as $step) { if (isset($step['call']) && $step['call'] === 'createTable') { $drops[] = $step; } } if (Yii::$app->session->get(self::SESSION_KEY, 0) === 0) { Yii::$app->session->set(self::SESSION_STEPS, count($drops)); } return $drops; }
Returns list of drops. @return array
entailment
public function actionDeletepost($cid = null, $fid = null, $tid = null, $pid = null) { $post = Post::verify($cid, $fid, $tid, $pid); 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']); } if ($post->thread->locked == 1 && !User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $post->thread])) { $this->info(Yii::t('podium/flash', 'This thread is locked.')); return $this->redirect([ 'forum/thread', 'cid' => $post->forum->category->id, 'fid' => $post->forum->id, 'id' => $post->thread->id, 'slug' => $post->thread->slug ]); } if (!User::can(Rbac::PERM_DELETE_OWN_POST, ['post' => $post]) && !User::can(Rbac::PERM_DELETE_POST, ['item' => $post])) { $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('post'); if ($postData) { if ($postData != $post->id) { $this->error(Yii::t('podium/flash', 'Sorry! There was an error while deleting the post.')); } else { if ($post->podiumDelete()) { $this->success(Yii::t('podium/flash', 'Post has been deleted.')); if (Thread::find()->where(['id' => $post->thread->id])->exists()) { return $this->redirect([ 'forum/forum', 'cid' => $post->forum->category->id, 'id' => $post->forum->id, 'slug' => $post->forum->slug ]); } return $this->redirect([ 'forum/thread', 'cid' => $post->forum->category->id, 'fid' => $post->forum->id, 'id' => $post->thread->id, 'slug' => $post->thread->slug ]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while deleting the post.')); } } return $this->render('deletepost', ['model' => $post]); }
Deleting the post 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 post ID @return string|Response
entailment
public function actionDeleteposts($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']); } if (!User::can(Rbac::PERM_DELETE_POST, ['item' => $thread])) { $this->error(Yii::t('podium/flash', 'Sorry! You do not have the required permission to perform this action.')); return $this->redirect(['forum/index']); } $posts = Yii::$app->request->post('post'); if ($posts) { if (!is_array($posts)) { $this->error(Yii::t('podium/flash', 'You have to select at least one post.')); } else { if ($thread->podiumDeletePosts($posts)) { $this->success(Yii::t('podium/flash', 'Posts have been deleted.')); if (Thread::find()->where(['id' => $thread->id])->exists()) { return $this->redirect([ 'forum/thread', 'cid' => $thread->forum->category->id, 'fid' => $thread->forum->id, 'id' => $thread->id, 'slug' => $thread->slug ]); } return $this->redirect([ 'forum', 'cid' => $thread->forum->category->id, 'id' => $thread->forum->id, 'slug' => $thread->forum->slug ]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while deleting the posts.')); } } return $this->render('deleteposts', [ 'model' => $thread, 'dataProvider' => (new Post())->search($thread->forum->id, $thread->id) ]); }
Deleting the posts of given category ID, forum ID, thread 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 actionEdit($cid = null, $fid = null, $tid = null, $pid = null) { $post = Post::verify($cid, $fid, $tid, $pid); 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']); } if ($post->thread->locked == 1 && !User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $post->thread])) { $this->info(Yii::t('podium/flash', 'This thread is locked.')); return $this->redirect([ 'forum/thread', 'cid' => $post->forum->category->id, 'fid' => $post->forum->id, 'id' => $post->thread->id, 'slug' => $post->thread->slug ]); } if (!User::can(Rbac::PERM_UPDATE_OWN_POST, ['post' => $post]) && !User::can(Rbac::PERM_UPDATE_POST, ['item' => $post])) { $this->error(Yii::t('podium/flash', 'Sorry! You do not have the required permission to perform this action.')); return $this->redirect(['forum/index']); } $isFirstPost = false; $firstPost = Post::find()->where([ 'thread_id' => $post->thread->id, 'forum_id' => $post->forum->id ])->orderBy(['id' => SORT_ASC])->limit(1)->one(); if ($firstPost->id == $post->id) { $post->scenario = 'firstPost'; $post->topic = $post->thread->name; $isFirstPost = true; } $postData = Yii::$app->request->post(); $preview = false; if ($post->load($postData)) { if ($post->validate()) { if (isset($postData['preview-button'])) { $preview = true; } else { if ($post->podiumEdit($isFirstPost)) { $this->success(Yii::t('podium/flash', 'Post has been updated.')); return $this->redirect(['show', 'id' => $post->id]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while updating the post. Contact administrator about this problem.')); } } } return $this->render('edit', [ 'preview' => $preview, 'model' => $post, 'isFirstPost' => $isFirstPost ]); }
Editing the post of given category ID, forum ID, thread ID and own ID. If this is the first post in thread user can change the thread name. @param int $cid category ID @param int $fid forum ID @param int $tid thread ID @param int $pid post ID @return string|Response
entailment
public function actionMoveposts($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']); } if (!User::can(Rbac::PERM_MOVE_POST, ['item' => $thread])) { $this->error(Yii::t('podium/flash', 'Sorry! You do not have the required permission to perform this action.')); return $this->redirect(['forum/index']); } if (Yii::$app->request->post()) { $posts = Yii::$app->request->post('post'); $newthread = Yii::$app->request->post('newthread'); $newname = Yii::$app->request->post('newname'); $newforum = Yii::$app->request->post('newforum'); if (empty($posts) || !is_array($posts)) { $this->error(Yii::t('podium/flash', 'You have to select at least one post.')); } else { if (!is_numeric($newthread) || $newthread < 0) { $this->error(Yii::t('podium/flash', 'You have to select a thread for this posts to be moved to.')); } else { if ($newthread == 0 && (empty($newname) || empty($newforum) || !is_numeric($newforum) || $newforum < 1)) { $this->error(Yii::t('podium/flash', 'If you want to move posts to a new thread you have to enter its name and select parent forum.')); } else { if ($newthread == $thread->id) { $this->error(Yii::t('podium/flash', 'Are you trying to move posts from this thread to this very same thread?')); } else { if ($thread->podiumMovePostsTo($newthread, $posts, $newname, $newforum)) { $this->success(Yii::t('podium/flash', 'Posts have been moved.')); if (Thread::find()->where(['id' => $thread->id])->exists()) { return $this->redirect([ 'forum/thread', 'cid' => $thread->forum->category->id, 'fid' => $thread->forum->id, 'id' => $thread->id, 'slug' => $thread->slug ]); } return $this->redirect([ 'forum/forum', 'cid' => $thread->forum->category->id, 'id' => $thread->forum->id, 'slug' => $thread->forum->slug ]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while moving the posts.')); } } } } } $categories = Category::find()->orderBy(['name' => SORT_ASC]); $forums = Forum::find()->orderBy(['name' => SORT_ASC]); $threads = Thread::find()->orderBy(['name' => SORT_ASC]); $list = [0 => Yii::t('podium/view', 'Create new thread')]; $listforum = []; $options = []; foreach ($categories->each() as $cat) { $catlist = []; foreach ($forums->each() as $for) { $forlist = []; if ($for->category_id == $cat->id) { $catlist[$for->id] = (User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $for]) ? '* ' : '') . Html::encode($cat->name) . ' &raquo; ' . Html::encode($for->name); foreach ($threads->each() as $thr) { if ($thr->category_id == $cat->id && $thr->forum_id == $for->id) { $forlist[$thr->id] = (User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $thr]) ? '* ' : '') . Html::encode($cat->name) . ' &raquo; ' . Html::encode($for->name) . ' &raquo; ' . Html::encode($thr->name); if ($thr->id == $thread->id) { $options[$thr->id] = ['disabled' => true]; } } } $list[Html::encode($cat->name) . ' > ' . Html::encode($for->name)] = $forlist; } } $listforum[Html::encode($cat->name)] = $catlist; } return $this->render('moveposts', [ 'model' => $thread, 'list' => $list, 'options' => $options, 'listforum' => $listforum, 'dataProvider' => (new Post())->search($thread->forum->id, $thread->id) ]); }
Moving the posts of given category ID, forum ID, thread 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 actionPost($cid = null, $fid = null, $tid = null, $pid = null) { $thread = Thread::find()->where([ 'id' => $tid, 'category_id' => $cid, 'forum_id' => $fid ])->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']); } if ($thread->locked == 1 && !User::can(Rbac::PERM_UPDATE_THREAD, ['item' => $thread])) { $this->info(Yii::t('podium/flash', 'This thread is locked.')); return $this->redirect([ 'forum/thread', 'cid' => $thread->forum->category->id, 'fid' => $thread->forum->id, 'id' => $thread->id, 'slug' => $thread->slug ]); } if (!User::can(Rbac::PERM_CREATE_POST)) { $this->error(Yii::t('podium/flash', 'Sorry! You do not have the required permission to perform this action.')); return $this->redirect(['forum/index']); } $model = new Post(); $model->subscribe = 1; $postData = Yii::$app->request->post(); $replyFor = null; if (is_numeric($pid) && $pid > 0) { $replyFor = Post::find()->where(['id' => $pid])->limit(1)->one(); if ($replyFor) { $model->content = Helper::prepareQuote($replyFor, Yii::$app->request->post('quote')); } } $preview = false; $previous = Post::find()->where(['thread_id' => $thread->id])->orderBy(['id' => SORT_DESC])->limit(1)->one(); if ($model->load($postData)) { $model->thread_id = $thread->id; $model->forum_id = $thread->forum->id; $model->author_id = User::loggedId(); if ($model->validate()) { if (isset($postData['preview-button'])) { $preview = true; } else { if ($model->podiumNew($previous)) { $this->success(Yii::t('podium/flash', 'New reply has been added.')); if (!empty($previous) && $previous->author_id == User::loggedId() && $this->module->podiumConfig->get('merge_posts')) { return $this->redirect(['forum/show', 'id' => $previous->id]); } return $this->redirect(['forum/show', 'id' => $model->id]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while adding the reply. Contact administrator about this problem.')); } } } return $this->render('post', [ 'replyFor' => $replyFor, 'preview' => $preview, 'model' => $model, 'thread' => $thread, 'previous' => $previous, ]); }
Creating the post of given category ID, forum ID and thread ID. This can be reply to selected post of given ID. @param int $cid category ID @param int $fid forum ID @param int $tid thread ID @param int $pid ID of post to reply to @return string|Response
entailment
public function actionReport($cid = null, $fid = null, $tid = null, $pid = null) { $post = Post::verify($cid, $fid, $tid, $pid); 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']); } if (User::can(Rbac::PERM_UPDATE_POST, ['item' => $post])) { $this->info(Yii::t('podium/flash', "You don't have to report this post since you are allowed to modify it.")); return $this->redirect([ 'forum/edit', 'cid' => $post->forum->category->id, 'fid' => $post->forum->id, 'tid' => $post->thread->id, 'pid' => $post->id ]); } if ($post->author_id == User::loggedId()) { $this->info(Yii::t('podium/flash', 'You can not report your own post. Please contact the administrator or moderators if you have got any concerns regarding your post.')); return $this->redirect([ 'forum/thread', 'cid' => $post->forum->category->id, 'fid' => $post->forum->id, 'id' => $post->thread->id, 'slug' => $post->thread->slug ]); } $model = new Message(); $model->scenario = 'report'; if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->podiumReport($post)) { $this->success(Yii::t('podium/flash', 'Thank you for your report. The moderation team will take a look at this post.')); return $this->redirect([ 'forum/thread', 'cid' => $post->forum->category->id, 'fid' => $post->forum->id, 'id' => $post->thread->id, 'slug' => $post->thread->slug ]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while notifying the moderation team. Contact administrator about this problem.')); } return $this->render('report', ['model' => $model, 'post' => $post]); }
Reporting the post of given category ID, forum ID, thread ID, own ID and slug. @param int $cid category ID @param int $fid forum ID @param int $tid thread ID @param int $pid post ID @return string|Response
entailment