sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function searchAdvanced() { if (!$this->nextPage) { Yii::$app->session->set('forum-search', [ 'query' => $this->query, 'match' => $this->match, 'author' => $this->author, 'dateFrom' => $this->dateFrom, 'dateFromStamp' => $this->dateFromStamp, 'dateTo' => $this->dateTo, 'dateToStamp' => $this->dateToStamp, 'forums' => $this->forums, 'type' => $this->type, 'display' => $this->display ]); } if ($this->type == 'topics') { return $this->searchTopics(); } return $this->searchPosts(); }
Advanced search. @return ActiveDataProvider
entailment
public function init() { parent::init(); $this->setAliases(['@podium' => '@vendor/bizley/podium/src']); if (Yii::$app instanceof WebApplication) { $this->podiumComponent->registerComponents(); $this->layout = 'main'; if (!is_string($this->slugGenerator)) { $this->slugGenerator = PodiumSluggableBehavior::className(); } } else { $this->podiumComponent->registerConsoleComponents(); } }
Initializes the module for Web application. Sets Podium alias (@podium) and layout. Registers user identity, authorization, translations, formatter, db, and cache. @throws InvalidConfigException
entailment
public function bootstrap($app) { if ($app instanceof WebApplication) { $this->addUrlManagerRules($app); $this->setPodiumLogTarget($app); } elseif ($app instanceof ConsoleApplication) { $this->controllerNamespace = 'bizley\podium\console'; } }
Bootstrap method to be called during application bootstrap stage. Adding routing rules and log target. @param Application $app the application currently running
entailment
public function afterAction($action, $result) { if (Yii::$app instanceof WebApplication && !in_array($action->id, ['import', 'run', 'update', 'level-up'], true)) { Activity::add(); } return parent::afterAction($action, $result); }
Registers user activity after every action. @see Activity::add() @param Action $action the action just executed @param mixed $result the action return result @return mixed the processed action result
entailment
protected function addUrlManagerRules($app) { $app->urlManager->addRules([new GroupUrlRule([ 'prefix' => $this->id, 'rules' => require __DIR__ . '/url-rules.php', ])], true); }
Adds UrlManager rules. @param Application $app the application currently running @since 0.2
entailment
protected function setPodiumLogTarget($app) { $dbTarget = new DbTarget; $dbTarget->logTable = '{{%podium_log}}'; $dbTarget->categories = ['bizley\podium\*']; $dbTarget->logVars = []; $app->log->targets['podium'] = $dbTarget; }
Sets Podium log target. @param Application $app the application currently running @since 0.2
entailment
public function getPodiumComponent() { if ($this->_component === null) { $this->_component = new PodiumComponent($this); } return $this->_component; }
Returns Podium component service. @return PodiumComponent @since 0.6
entailment
public function passwordRequirements($attribute) { if (!preg_match('~\p{Lu}~', $this->$attribute) || !preg_match('~\p{Ll}~', $this->$attribute) || !preg_match('~[0-9]~', $this->$attribute) || mb_strlen($this->$attribute, 'UTF-8') < 6 || mb_strlen($this->$attribute, 'UTF-8') > 100) { $this->addError($attribute, Yii::t('podium/view', 'Password must contain uppercase and lowercase letter, digit, and be at least 6 characters long.')); } }
Finds out if unencrypted password fulfill requirements. @param string $attribute
entailment
public static function findByActivationToken($token) { if (!static::isActivationTokenValid($token)) { return null; } return static::find()->where(['activation_token' => $token, 'status' => self::STATUS_REGISTERED])->limit(1)->one(); }
Finds registered user by activation token. @param string $token activation token @return static|null
entailment
public static function findByEmailToken($token) { if (!static::isEmailTokenValid($token)) { return null; } return static::find()->where(['email_token' => $token, 'status' => self::STATUS_ACTIVE])->limit(1)->one(); }
Finds active user by email token. @param string $token activation token @return static|null
entailment
public static function findByKeyfield($keyfield, $status = self::STATUS_ACTIVE) { if ($status === null) { return static::find()->where(['or', ['email' => $keyfield], ['username' => $keyfield]])->limit(1)->one(); } return static::find()->where(['and', ['status' => $status], ['or', ['email' => $keyfield], ['username' => $keyfield]]])->limit(1)->one(); }
Finds user of given status by username or email. @param string $keyfield value to compare @param int $status @return static|null
entailment
public static function findByPasswordResetToken($token, $status = self::STATUS_ACTIVE) { if (!static::isPasswordResetTokenValid($token)) { return null; } if ($status == null) { return static::find()->where(['password_reset_token' => $token])->limit(1)->one(); } return static::find()->where(['password_reset_token' => $token, 'status' => $status])->limit(1)->one(); }
Finds user of given status by password reset token @param string $token password reset token @param string|null $status user status or null @return static|null
entailment
public static function isActivationTokenValid($token) { $expire = Podium::getInstance()->podiumConfig->get('activation_token_expire'); if ($expire === null) { $expire = 3 * 24 * 60 * 60; } return static::isTokenValid($token, $expire); }
Finds out if activation token is valid. @param string $token activation token @return bool
entailment
public static function isTokenValid($token, $expire) { if (empty($token) || empty($expire)) { return false; } $parts = explode('_', $token); $timestamp = (int)end($parts); return $timestamp + (int)$expire >= time(); }
Finds out if given token type is valid. @param string $token activation token @param int $expire expire time @return bool
entailment
public function validateCurrentPassword($attribute) { if (!$this->hasErrors()) { if (!$this->validatePassword($this->currentPassword)) { $this->addError($attribute, Yii::t('podium/view', 'Current password is incorrect.')); } } }
Validates current password. @param string $attribute
entailment
public function validatePassword($password) { $podium = Podium::getInstance(); if ($podium->userComponent !== true) { $password_hash = empty($podium->userPasswordField) ? 'password_hash' : $podium->userPasswordField; if (!empty($podium->user->identity->$password_hash)) { return Yii::$app->security->validatePassword($password, $podium->user->identity->$password_hash); } return false; } return Yii::$app->security->validatePassword($password, $this->password_hash); }
Validates password. In case of inherited user component password hash is compared to password hash stored in Podium::getInstance()->user->identity so this method should not be used with User instance other than currently logged in one. @param string $password password to validate @return bool if password provided is valid for current user
entailment
public function validateUsername($attribute) { if (!$this->hasErrors()) { if (!preg_match('/^[\p{L}][\w\p{L}]{2,254}$/u', $this->username)) { $this->addError($attribute, Yii::t('podium/view', 'Username must start with a letter, contain only letters, digits and underscores, and be at least 3 characters long.')); } } }
Validates username. Custom method is required because JS ES5 (and so do Yii 2) doesn't support regex unicode features. @param string $attribute
entailment
public function isMod($userId = null) { return (new Query())->from(Mod::tableName())->where(['forum_id' => $this->id, 'user_id' => $userId])->exists(); }
Checks if user of given ID is moderator of this forum. @param int $userId @return bool
entailment
public function searchForMods($params) { $query = static::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'defaultPageSize' => 10, 'forcePageParam' => false ], ]); $dataProvider->sort->defaultOrder = ['name' => SORT_ASC]; if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere(['name' => $this->name]); return $dataProvider; }
Searches for forums on admin page. @param type $params @return ActiveDataProvider
entailment
public function getMods() { $mods = Podium::getInstance()->podiumCache->getElement('forum.moderators', $this->id); if ($mods === false) { $mods = []; $modteam = User::find()->select(['id', 'role'])->where([ 'status' => User::STATUS_ACTIVE, 'role' => [User::ROLE_ADMIN, User::ROLE_MODERATOR] ]); foreach ($modteam->each() as $user) { if ($user->role == User::ROLE_ADMIN) { $mods[] = $user->id; continue; } if ((new Query())->from(Mod::tableName())->where([ 'forum_id' => $this->id, 'user_id' => $user->id ])->exists()) { $mods[] = $user->id; } } Podium::getInstance()->podiumCache->setElement('forum.moderators', $this->id, $mods); } return $mods; }
Returns list of moderators for this forum. @return int[]
entailment
public function isMod($userId = null) { if (in_array($userId ?: User::loggedId(), $this->getMods())) { return true; } return false; }
Checks if user is moderator for this forum. @param int|null $userId user ID or null for current signed in. @return bool
entailment
public function search($categoryId = null, $onlyVisible = false) { $query = static::find(); if ($categoryId) { $query->andWhere(['category_id' => $categoryId]); } if ($onlyVisible) { $query->joinWith(['category' => function ($query) { $query->andWhere([Category::tableName() . '.visible' => 1]); }]); $query->andWhere([static::tableName() . '.visible' => 1]); } $dataProvider = new ActiveDataProvider(['query' => $query]); $dataProvider->sort->defaultOrder = ['sort' => SORT_ASC, 'id' => SORT_ASC]; return $dataProvider; }
Searches forums. @param int|null $categoryId @return ActiveDataProvider
entailment
public static function verify($categoryId = null, $id = null, $slug = null, $guest = true) { if (!is_numeric($categoryId) || $categoryId < 1 || !is_numeric($id) || $id < 1 || empty($slug)) { return null; } return static::find()->joinWith(['category' => function ($query) use ($guest) { if ($guest) { $query->andWhere([Category::tableName() . '.visible' => 1]); } }])->where([ static::tableName() . '.id' => $id, static::tableName() . '.slug' => $slug, static::tableName() . '.category_id' => $categoryId, ])->limit(1)->one(); }
Returns the verified forum. @param int $categoryId forum category ID @param int $id forum ID @param string $slug forum slug @param bool $guest whether caller is guest or registered user @return Forum @since 0.2
entailment
public function newOrder($order) { $sorter = new Sorter(); $sorter->target = $this; $sorter->order = $order; $sorter->query = (new Query()) ->from(static::tableName()) ->where(['and', ['!=', 'id', $this->id], ['category_id' => $this->category_id] ]) ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC]) ->indexBy('id'); return $sorter->run(); }
Sets new forums order. @param int $order new forum sorting order number @return bool @since 0.2
entailment
public function requiredAnswers() { $this->editAnswers = array_unique($this->editAnswers); $filtered = []; foreach ($this->editAnswers as $answer) { if (!empty(trim($answer))) { $filtered[] = trim($answer); } } $this->editAnswers = $filtered; if (count($this->editAnswers) < 2) { $this->addError('editAnswers', Yii::t('podium/view', 'You have to add at least 2 options.')); } }
Filters and validates poll answers.
entailment
public function init() { parent::init(); $this->db = Instance::ensure($this->module->db, Connection::className()); if ($this->db->driverName === 'mysql') { $this->tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } }
Initialize component.
entailment
protected function addColumn($col, $type) { if (empty($col)) { return Yii::t('podium/flash', 'Installation aborted! Column name missing.'); } if (empty($type)) { return Yii::t('podium/flash', 'Installation aborted! Column type missing.'); } try { $this->db->createCommand()->addColumn($this->table, $col, $type)->execute(); return $this->returnSuccess(Yii::t('podium/flash', 'Table column {name} has been added', ['name' => $col])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table column {name} adding', ['name' => $col]) ); } }
Adds column to database table. @param string $col column name @param string $type column schema @return string result message
entailment
protected function addForeign($key, $ref, $col, $delete = null, $update = null) { if (empty($key)) { return Yii::t('podium/flash', 'Installation aborted! Foreign key name missing.'); } if (empty($ref)) { return Yii::t('podium/flash', 'Installation aborted! Foreign key reference missing.'); } if (empty($col)) { return Yii::t('podium/flash', 'Installation aborted! Referenced columns missing.'); } try { $this->db->createCommand()->addForeignKey( $this->getForeignName($key), $this->table, $key, $this->getTableName($ref), $col, $delete, $update )->execute(); return $this->returnSuccess(Yii::t('podium/flash', 'Table foreign key {name} has been added', [ 'name' => $this->getForeignName($key) ])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table foreign key {name} adding', [ 'name' => $this->getForeignName($key) ]) ); } }
Creates database table foreign key. @param string|array $key key columns @param string $ref key reference table @param string|array $col reference table columns @param string $delete ON DELETE action @param string $update ON UPDATE action @return string result message @since 0.2
entailment
protected function addIndex($name, $cols) { if (empty($name)) { return Yii::t('podium/flash', 'Installation aborted! Index name missing.'); } if (empty($cols)) { return Yii::t('podium/flash', 'Installation aborted! Index columns missing.'); } try { $this->db->createCommand()->createIndex($this->getIndexName($name), $this->table, $cols)->execute(); return $this->returnSuccess(Yii::t('podium/flash', 'Table index {name} has been added', [ 'name' => $this->getIndexName($name) ])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table index {name} adding', [ 'name' => $this->getIndexName($name) ]) ); } }
Creates database table index. @param string $name index name @param array $cols columns @return string result message @since 0.2
entailment
protected function createTable($schema) { if (empty($schema)) { return Yii::t('podium/flash', 'Installation aborted! Database schema missing.'); } try { $this->db->createCommand()->createTable($this->table, $schema, $this->tableOptions)->execute(); return $this->returnSuccess(Yii::t('podium/flash', 'Table {name} has been created', ['name' => $this->rawTable])); } catch (Exception $e) { if ($this->_table != 'log') { // in case of creating log table don't try to log error in it if it's not available Yii::error($e->getMessage(), __METHOD__); } return Yii::t('podium/flash', 'Error during table {name} creating', [ 'name' => $this->rawTable ]) . ': ' . Html::tag('pre', $e->getMessage()); } }
Creates database table. @param array $schema table schema @return string result message @since 0.2
entailment
protected function dropTable() { try { if ($this->db->schema->getTableSchema($this->table, true) !== null) { $this->db->createCommand()->dropTable($this->table)->execute(); return $this->returnWarning(Yii::t('podium/flash', 'Table {name} has been dropped', ['name' => $this->rawTable])); } return true; } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table {name} dropping', [ 'name' => $this->rawTable ]) ); } }
Drops current database table if it exists. @return string|bool result message or true if no table to drop.
entailment
protected function dropColumn($col) { if (empty($col)) { return Yii::t('podium/flash', 'Installation aborted! Column name missing.'); } try { $this->db->createCommand()->dropColumn($this->table, $col)->execute(); return $this->returnWarning(Yii::t('podium/flash', 'Table column {name} has been dropped', ['name' => $col])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table column {name} dropping', ['name' => $col]) ); } }
Drops database table column. @param string $col column name @return string result message
entailment
protected function dropForeign($name) { if (empty($name)) { return Yii::t('podium/flash', 'Installation aborted! Foreign key name missing.'); } try { $this->db->createCommand()->dropForeignKey($this->getForeignName($name), $this->table)->execute(); return $this->returnWarning(Yii::t('podium/flash', 'Table foreign key {name} has been dropped', [ 'name' => $this->getForeignName($name) ])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table foreign key {name} dropping', [ 'name' => $this->getForeignName($name) ]) ); } }
Drops database table foreign key. @param string $name key name @return string result message
entailment
protected function dropIndex($name) { if (empty($name)) { return Yii::t('podium/flash', 'Installation aborted! Index name missing.'); } try { $this->db->createCommand()->dropIndex($this->getIndexName($name), $this->table)->execute(); return $this->returnWarning(Yii::t('podium/flash', 'Table index {name} has been dropped', [ 'name' => $this->getIndexName($name) ])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table index {name} dropping', [ 'name' => $this->getIndexName($name) ]) ); } }
Drops database table index. @param string $name index name @return string result message
entailment
protected function rename($name) { if (empty($name)) { return Yii::t('podium/flash', 'Installation aborted! New table name missing.'); } try { $this->db->createCommand()->renameTable($this->table, $this->getTableName($name))->execute(); return $this->returnSuccess(Yii::t('podium/flash', 'Table {name} has been renamed to {new}', [ 'name' => $this->rawTable, 'new' => $this->getTableName($name) ])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table {name} renaming to {new}', [ 'name' => $this->rawTable, 'new' => $this->getTableName($name) ]) ); } }
Renames database table. @param string $name table new name @return string result message
entailment
protected function renameColumn($col, $name) { if (empty($col)) { return Yii::t('podium/flash', 'Installation aborted! Column name missing.'); } if (empty($name)) { return Yii::t('podium/flash', 'Installation aborted! New column name missing.'); } try { $this->db->createCommand()->renameColumn($this->table, $col, $name)->execute(); return $this->returnSuccess(Yii::t('podium/flash', 'Table column {name} has been renamed to {new}', [ 'name' => $col, 'new' => $name ])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during table column {name} renaming to {new}', [ 'name' => $col, 'new' => $name ]) ); } }
Renames database table column. @param string $col column name @param string $name column new name @return string result message
entailment
public function returnError($exception, $method, $message) { Yii::error($exception, $method); return $message . ':' . Html::tag('pre', $exception); }
Returns error message. Logs error. @param string $exception exception message @param string $method method name @param string $message custom message @return string
entailment
public function search() { $query = static::find()->where(['and', ['is not', 'post_id', null], ['like', 'word', $this->query] ])->joinWith(['posts.author', 'posts.thread']); if (Podium::getInstance()->user->isGuest) { $query->joinWith(['posts.forum' => function($q) { $q->where([Forum::tableName() . '.visible' => 1]); }]); } $query->groupBy(['post_id', 'word_id']); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => [ 'defaultOrder' => ['thread_id' => SORT_DESC], 'attributes' => [ 'thread_id' => [ 'asc' => ['thread_id' => SORT_ASC], 'desc' => ['thread_id' => SORT_DESC], 'default' => SORT_DESC, ], ] ], ]); return $dataProvider; }
Returns data provider for simple search. @return ActiveDataProvider
entailment
public function registerComponents() { $this->registerDbConnection(); $this->registerIdentity(); $this->registerCache(); $this->registerAuthorization(); $this->registerFormatter(); $this->registerTranslations(); }
Registers required components. @throws InvalidConfigException
entailment
public function getComponent($name) { $configurationName = $name . 'Component'; if (is_string($this->module->$configurationName)) { return Yii::$app->get($this->module->$configurationName); } return $this->module->get('podium_' . $name); }
Returns instance of component of given name. @param string $name @return object component of the specified ID @throws InvalidConfigException
entailment
public function registerAuthorization() { if ($this->module->rbacComponent !== true && !is_string($this->module->rbacComponent) && !is_array($this->module->rbacComponent)) { throw new InvalidConfigException('Invalid value for the rbacComponent parameter.'); } if (is_string($this->module->rbacComponent)) { return; } $this->module->set('podium_rbac', is_array($this->module->rbacComponent) ? $this->module->rbacComponent : [ 'class' => 'yii\rbac\DbManager', 'db' => $this->module->db, 'itemTable' => '{{%podium_auth_item}}', 'itemChildTable' => '{{%podium_auth_item_child}}', 'assignmentTable' => '{{%podium_auth_assignment}}', 'ruleTable' => '{{%podium_auth_rule}}', 'cache' => $this->module->cache ]); }
Registers user authorization. @throws InvalidConfigException
entailment
public function registerFormatter() { if ($this->module->formatterComponent !== true && !is_string($this->module->formatterComponent) && !is_array($this->module->formatterComponent)) { throw new InvalidConfigException('Invalid value for the formatterComponent parameter.'); } if (is_string($this->module->formatterComponent)) { return; } $this->module->set('podium_formatter', is_array($this->module->formatterComponent) ? $this->module->formatterComponent : [ 'class' => 'yii\i18n\Formatter', 'timeZone' => 'UTC', ]); }
Registers formatter with default time zone. @throws InvalidConfigException
entailment
public function registerIdentity() { if ($this->module->userComponent !== true && !is_string($this->module->userComponent) && !is_array($this->module->userComponent)) { throw new InvalidConfigException('Invalid value for the userComponent parameter.'); } if (is_string($this->module->userComponent)) { return; } $this->module->set('podium_user', is_array($this->module->userComponent) ? $this->module->userComponent : [ 'class' => 'bizley\podium\web\User', 'identityClass' => 'bizley\podium\models\User', 'enableAutoLogin' => true, 'loginUrl' => $this->module->loginUrl, 'identityCookie' => [ 'name' => 'podium', 'httpOnly' => true, 'secure' => $this->module->secureIdentityCookie, ], 'idParam' => '__id_podium', ]); }
Registers user identity. @throws InvalidConfigException
entailment
public function registerDbConnection() { if (!is_string($this->module->dbComponent) && !is_array($this->module->dbComponent)) { throw new InvalidConfigException('Invalid value for the dbComponent parameter.'); } if (is_array($this->module->dbComponent)) { $this->module->set('podium_db', $this->module->dbComponent); } }
Registers DB connection. @throws InvalidConfigException
entailment
public function registerCache() { if ($this->module->cacheComponent !== false && !is_string($this->module->cacheComponent) && !is_array($this->module->cacheComponent)) { throw new InvalidConfigException('Invalid value for the cacheComponent parameter.'); } if (is_string($this->module->cacheComponent)) { return; } $this->module->set('podium_cache', is_array($this->module->cacheComponent) ? $this->module->cacheComponent : ['class' => 'yii\caching\DummyCache']); }
Registers cache. @throws InvalidConfigException
entailment
public function search() { $loggedId = User::loggedId(); $query = 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'), ['new_last_seen' => null], ['edited_last_seen' => null], ]); }], false); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'defaultPageSize' => 10, 'forcePageParam' => false ], ]); $dataProvider->sort->defaultOrder = ['edited_post_at' => SORT_ASC, 'id' => SORT_ASC]; $dataProvider->pagination->pageSize = Yii::$app->session->get('per-page', 20); return $dataProvider; }
Searches for threads with unread posts. @param array $params @return ActiveDataProvider
entailment
public function beforeAction($action) { if (!parent::beforeAction($action)) { return false; } $warnings = Yii::$app->session->getFlash('warning'); $maintenance = $this->maintenanceCheck($action, $warnings); if ($maintenance !== false) { return $maintenance; } $email = $this->emailCheck($warnings); if ($email !== false) { return $email; } $upgrade = $this->upgradeCheck($warnings); if ($upgrade !== false) { return $upgrade; } return true; }
Adds warning for maintenance mode. Redirects all users except administrators (if this mode is on). Adds warning about missing email. @param Action $action the action to be executed. @return bool|Response
entailment
public static function warnings() { return [ 'maintenance' => Yii::t('podium/flash', 'Podium is currently in the Maintenance mode. All users without Administrator privileges are redirected to {maintenancePage}. You can switch the mode off at {settingsPage}.', [ 'maintenancePage' => Html::a(Yii::t('podium/flash', 'Maintenance page'), ['forum/maintenance']), 'settingsPage' => Html::a(Yii::t('podium/flash', 'Settings page'), ['admin/settings']), ]), 'email' => Yii::t('podium/flash', 'No e-mail address has been set for your account! Go to {link} to add one.', [ 'link' => Html::a(Yii::t('podium/view', 'Profile') . ' > ' . Yii::t('podium/view', 'Account Details'), ['profile/details']) ]), 'old_version' => Yii::t('podium/flash', 'It looks like there is a new version of Podium database! {link}', [ 'link' => Html::a(Yii::t('podium/view', 'Update Podium'), ['install/level-up']) ]), 'new_version' => Yii::t('podium/flash', 'Module version appears to be older than database! Please verify your database.') ]; }
Returns warning messages. @return array @since 0.2
entailment
public function maintenanceCheck($action, $warnings) { if ($this->module->podiumConfig->get('maintenance_mode') != '1') { return false; } if ($action->id === 'maintenance') { return false; } if ($warnings) { foreach ($warnings as $warning) { if ($warning === static::warnings()['maintenance']) { if (!User::can(Rbac::ROLE_ADMIN)) { return $this->redirect(['forum/maintenance']); } return false; } } } $this->warning(static::warnings()['maintenance'], false); if (!User::can(Rbac::ROLE_ADMIN)) { return $this->redirect(['forum/maintenance']); } return false; }
Performs maintenance check. @param Action $action the action to be executed. @param array $warnings Flash warnings @return bool|Response @since 0.2
entailment
public function emailCheck($warnings) { if ($warnings) { foreach ($warnings as $warning) { if ($warning === static::warnings()['email']) { return false; } } } $user = User::findMe(); if ($user && empty($user->email)) { $this->warning(static::warnings()['email'], false); } return false; }
Performs email check. @param array $warnings Flash warnings @return bool @since 0.2
entailment
public function upgradeCheck($warnings) { if (!User::can(Rbac::ROLE_ADMIN)) { return false; } if ($warnings) { foreach ($warnings as $warning) { if ($warning === static::warnings()['old_version']) { return false; } if ($warning === static::warnings()['new_version']) { return false; } } } $result = Helper::compareVersions( explode('.', $this->module->version), explode('.', $this->module->podiumConfig->get('version')) ); if ($result === '>') { $this->warning(static::warnings()['old_version'], false); } elseif ($result === '<') { $this->warning(static::warnings()['new_version'], false); } return false; }
Performs upgrade check. @param array $warnings Flash warnings @return bool @since 0.2
entailment
public function init() { parent::init(); try { if (!empty($this->module->accessChecker)) { $this->accessType = call_user_func($this->module->accessChecker, $this->module->user); } if ($this->accessType === -1) { if (!empty($this->module->denyCallback)) { call_user_func($this->module->denyCallback, $this->module->user); return false; } return $this->goHome(); } if (!$this->module->user->isGuest) { $user = User::findMe(); if ($this->module->userComponent !== true && $this->accessType === 1) { if (empty($user)) { if (!User::createInheritedAccount()) { throw new InvalidConfigException('There was an error while creating inherited user account. Podium can not run with the current configuration. Please contact administrator about this problem.'); } $this->success(Yii::t('podium/flash', 'Hey! Your new forum account has just been automatically created! Go to {link} to complement it.', [ 'link' => Html::a(Yii::t('podium/view', 'Profile'), ['profile/details']) ])); } elseif (!User::updateInheritedAccount()) { throw new InvalidConfigException('There was an error while updating inherited user account. Podium can not run with the current configuration. Please contact administrator about this problem.'); } } if ($user && $user->status == User::STATUS_BANNED) { return $this->redirect(['forum/ban']); } if ($user && !empty($user->meta->timezone)) { $this->module->formatter->timeZone = $user->meta->timezone; } } } catch (Exception $exc) { Yii::$app->response->redirect([$this->module->prepareRoute('install/run')]); } }
Creates inherited user account. Redirects banned user to proper view. Sets user's time zone.
entailment
public function getParsedSignature() { if (Podium::getInstance()->podiumConfig->get('use_wysiwyg') == '0') { $parser = new GithubMarkdown(); $parser->html5 = true; return $parser->parse($this->signature); } return $this->signature; }
Returns signature Markdown-parsed if WYSIWYG editor is switched off. @return string @since 0.6
entailment
public function add(DbManager $authManager) { $viewThread = $authManager->getPermission(self::PERM_VIEW_THREAD); if (!($viewThread instanceof Permission)) { $viewThread = $authManager->createPermission(self::PERM_VIEW_THREAD); $viewThread->description = 'View Podium thread'; $authManager->add($viewThread); } $viewForum = $authManager->getPermission(self::PERM_VIEW_FORUM); if (!($viewForum instanceof Permission)) { $viewForum = $authManager->createPermission(self::PERM_VIEW_FORUM); $viewForum->description = 'View Podium forum'; $authManager->add($viewForum); } $createThread = $authManager->getPermission(self::PERM_CREATE_THREAD); if (!($createThread instanceof Permission)) { $createThread = $authManager->createPermission(self::PERM_CREATE_THREAD); $createThread->description = 'Create Podium thread'; $authManager->add($createThread); } $createPost = $authManager->getPermission(self::PERM_CREATE_POST); if (!($createPost instanceof Permission)) { $createPost = $authManager->createPermission(self::PERM_CREATE_POST); $createPost->description = 'Create Podium post'; $authManager->add($createPost); } $moderatorRule = $authManager->getRule('isPodiumModerator'); if (!($moderatorRule instanceof ModeratorRule)) { $moderatorRule = new ModeratorRule(); $authManager->add($moderatorRule); } $updatePost = $authManager->getPermission(self::PERM_UPDATE_POST); if (!($updatePost instanceof Permission)) { $updatePost = $authManager->createPermission(self::PERM_UPDATE_POST); $updatePost->description = 'Update Podium post'; $updatePost->ruleName = $moderatorRule->name; $authManager->add($updatePost); } $authorRule = $authManager->getRule('isPodiumAuthor'); if (!($authorRule instanceof AuthorRule)) { $authorRule = new AuthorRule(); $authManager->add($authorRule); } $updateOwnPost = $authManager->getPermission(self::PERM_UPDATE_OWN_POST); if (!($updateOwnPost instanceof Permission)) { $updateOwnPost = $authManager->createPermission(self::PERM_UPDATE_OWN_POST); $updateOwnPost->description = 'Update own Podium post'; $updateOwnPost->ruleName = $authorRule->name; $authManager->add($updateOwnPost); $authManager->addChild($updateOwnPost, $updatePost); } $deletePost = $authManager->getPermission(self::PERM_DELETE_POST); if (!($deletePost instanceof Permission)) { $deletePost = $authManager->createPermission(self::PERM_DELETE_POST); $deletePost->description = 'Delete Podium post'; $deletePost->ruleName = $moderatorRule->name; $authManager->add($deletePost); } $deleteOwnPost = $authManager->getPermission(self::PERM_DELETE_OWN_POST); if (!($deleteOwnPost instanceof Permission)) { $deleteOwnPost = $authManager->createPermission(self::PERM_DELETE_OWN_POST); $deleteOwnPost->description = 'Delete own Podium post'; $deleteOwnPost->ruleName = $authorRule->name; $authManager->add($deleteOwnPost); $authManager->addChild($deleteOwnPost, $deletePost); } $user = $authManager->getRole(self::ROLE_USER); if (!($user instanceof Role)) { $user = $authManager->createRole(self::ROLE_USER); $authManager->add($user); $authManager->addChild($user, $viewThread); $authManager->addChild($user, $viewForum); $authManager->addChild($user, $createThread); $authManager->addChild($user, $createPost); $authManager->addChild($user, $updateOwnPost); $authManager->addChild($user, $deleteOwnPost); } $updateThread = $authManager->getPermission(self::PERM_UPDATE_THREAD); if (!($updateThread instanceof Permission)) { $updateThread = $authManager->createPermission(self::PERM_UPDATE_THREAD); $updateThread->description = 'Update Podium thread'; $updateThread->ruleName = $moderatorRule->name; $authManager->add($updateThread); } $deleteThread = $authManager->getPermission(self::PERM_DELETE_THREAD); if (!($deleteThread instanceof Permission)) { $deleteThread = $authManager->createPermission(self::PERM_DELETE_THREAD); $deleteThread->description = 'Delete Podium thread'; $deleteThread->ruleName = $moderatorRule->name; $authManager->add($deleteThread); } $pinThread = $authManager->getPermission(self::PERM_PIN_THREAD); if (!($pinThread instanceof Permission)) { $pinThread = $authManager->createPermission(self::PERM_PIN_THREAD); $pinThread->description = 'Pin Podium thread'; $pinThread->ruleName = $moderatorRule->name; $authManager->add($pinThread); } $lockThread = $authManager->getPermission(self::PERM_LOCK_THREAD); if (!($lockThread instanceof Permission)) { $lockThread = $authManager->createPermission(self::PERM_LOCK_THREAD); $lockThread->description = 'Lock Podium thread'; $lockThread->ruleName = $moderatorRule->name; $authManager->add($lockThread); } $moveThread = $authManager->getPermission(self::PERM_MOVE_THREAD); if (!($moveThread instanceof Permission)) { $moveThread = $authManager->createPermission(self::PERM_MOVE_THREAD); $moveThread->description = 'Move Podium thread'; $moveThread->ruleName = $moderatorRule->name; $authManager->add($moveThread); } $movePost = $authManager->getPermission(self::PERM_MOVE_POST); if (!($movePost instanceof Permission)) { $movePost = $authManager->createPermission(self::PERM_MOVE_POST); $movePost->description = 'Move Podium post'; $movePost->ruleName = $moderatorRule->name; $authManager->add($movePost); } $banUser = $authManager->getPermission(self::PERM_BAN_USER); if (!($banUser instanceof Permission)) { $banUser = $authManager->createPermission(self::PERM_BAN_USER); $banUser->description = 'Ban Podium user'; $authManager->add($banUser); } $moderator = $authManager->getRole(self::ROLE_MODERATOR); if (!($moderator instanceof Role)) { $moderator = $authManager->createRole(self::ROLE_MODERATOR); $authManager->add($moderator); $authManager->addChild($moderator, $updatePost); $authManager->addChild($moderator, $updateThread); $authManager->addChild($moderator, $deletePost); $authManager->addChild($moderator, $deleteThread); $authManager->addChild($moderator, $pinThread); $authManager->addChild($moderator, $lockThread); $authManager->addChild($moderator, $moveThread); $authManager->addChild($moderator, $movePost); $authManager->addChild($moderator, $banUser); $authManager->addChild($moderator, $user); } $deleteUser = $authManager->getPermission(self::PERM_DELETE_USER); if (!($deleteUser instanceof Permission)) { $deleteUser = $authManager->createPermission(self::PERM_DELETE_USER); $deleteUser->description = 'Delete Podium user'; $authManager->add($deleteUser); } $promoteUser = $authManager->getPermission(self::PERM_PROMOTE_USER); if (!($promoteUser instanceof Permission)) { $promoteUser = $authManager->createPermission(self::PERM_PROMOTE_USER); $promoteUser->description = 'Promote Podium user'; $authManager->add($promoteUser); } $createForum = $authManager->getPermission(self::PERM_CREATE_FORUM); if (!($createForum instanceof Permission)) { $createForum = $authManager->createPermission(self::PERM_CREATE_FORUM); $createForum->description = 'Create Podium forum'; $authManager->add($createForum); } $updateForum = $authManager->getPermission(self::PERM_UPDATE_FORUM); if (!($updateForum instanceof Permission)) { $updateForum = $authManager->createPermission(self::PERM_UPDATE_FORUM); $updateForum->description = 'Update Podium forum'; $authManager->add($updateForum); } $deleteForum = $authManager->getPermission(self::PERM_DELETE_FORUM); if (!($deleteForum instanceof Permission)) { $deleteForum = $authManager->createPermission(self::PERM_DELETE_FORUM); $deleteForum->description = 'Delete Podium forum'; $authManager->add($deleteForum); } $createCategory = $authManager->getPermission(self::PERM_CREATE_CATEGORY); if (!($createCategory instanceof Permission)) { $createCategory = $authManager->createPermission(self::PERM_CREATE_CATEGORY); $createCategory->description = 'Create Podium category'; $authManager->add($createCategory); } $updateCategory = $authManager->getPermission(self::PERM_UPDATE_CATEGORY); if (!($updateCategory instanceof Permission)) { $updateCategory = $authManager->createPermission(self::PERM_UPDATE_CATEGORY); $updateCategory->description = 'Update Podium category'; $authManager->add($updateCategory); } $deleteCategory = $authManager->getPermission(self::PERM_DELETE_CATEGORY); if (!($deleteCategory instanceof Permission)) { $deleteCategory = $authManager->createPermission(self::PERM_DELETE_CATEGORY); $deleteCategory->description = 'Delete Podium category'; $authManager->add($deleteCategory); } $settings = $authManager->getPermission(self::PERM_CHANGE_SETTINGS); if (!($settings instanceof Permission)) { $settings = $authManager->createPermission(self::PERM_CHANGE_SETTINGS); $settings->description = 'Change Podium settings'; $authManager->add($settings); } $admin = $authManager->getRole(self::ROLE_ADMIN); if (!($admin instanceof Role)) { $admin = $authManager->createRole(self::ROLE_ADMIN); $authManager->add($admin); $authManager->addChild($admin, $deleteUser); $authManager->addChild($admin, $promoteUser); $authManager->addChild($admin, $createForum); $authManager->addChild($admin, $updateForum); $authManager->addChild($admin, $deleteForum); $authManager->addChild($admin, $createCategory); $authManager->addChild($admin, $updateCategory); $authManager->addChild($admin, $deleteCategory); $authManager->addChild($admin, $settings); $authManager->addChild($admin, $moderator); } }
Adds RBAC rules.
entailment
public function actions() { return [ 'lock' => [ 'class' => 'bizley\podium\actions\ThreadAction', 'permission' => Rbac::PERM_LOCK_THREAD, 'boolAttribute' => 'locked', 'switcher' => 'podiumLock', 'onMessage' => Yii::t('podium/flash', 'Thread has been locked.'), 'offMessage' => Yii::t('podium/flash', 'Thread has been unlocked.') ], 'pin' => [ 'class' => 'bizley\podium\actions\ThreadAction', 'permission' => Rbac::PERM_PIN_THREAD, 'boolAttribute' => 'pinned', 'switcher' => 'podiumPin', 'onMessage' => Yii::t('podium/flash', 'Thread has been pinned.'), 'offMessage' => Yii::t('podium/flash', 'Thread has been unpinned.') ], ]; }
Returns separated thread actions. @return array @since 0.6
entailment
public function actionDelete($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_THREAD, ['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']); } $postData = Yii::$app->request->post('thread'); if ($postData) { if ($postData != $thread->id) { $this->error(Yii::t('podium/flash', 'Sorry! There was an error while deleting the thread.')); } else { if ($thread->podiumDelete()) { $this->success(Yii::t('podium/flash', 'Thread has been deleted.')); 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 deleting the thread.')); } } return $this->render('delete', ['model' => $thread]); }
Deleting 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 actionMove($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_THREAD, ['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']); } $forum = Yii::$app->request->post('forum'); if ($forum) { if (!is_numeric($forum) || $forum < 1 || $forum == $thread->forum->id) { $this->error(Yii::t('podium/flash', 'You have to select the new forum.')); } else { if ($thread->podiumMoveTo($forum)) { $this->success(Yii::t('podium/flash', 'Thread has been moved.')); return $this->redirect([ 'forum/thread', 'cid' => $thread->forum->category->id, 'fid' => $thread->forum->id, 'id' => $thread->id, 'slug' => $thread->slug ]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while moving the thread.')); } } $categories = Category::find()->orderBy(['name' => SORT_ASC]); $forums = Forum::find()->orderBy(['name' => SORT_ASC]); $list = []; $options = []; foreach ($categories->each() as $cat) { $catlist = []; foreach ($forums->each() as $for) { 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); if ($for->id == $thread->forum->id) { $options[$for->id] = ['disabled' => true]; } } } $list[Html::encode($cat->name)] = $catlist; } return $this->render('move', [ 'model' => $thread, 'list' => $list, 'options' => $options ]); }
Moving 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 actionNewThread($cid = null, $fid = null) { if (!User::can(Rbac::PERM_CREATE_THREAD)) { $this->error(Yii::t('podium/flash', 'Sorry! You do not have the required permission to perform this action.')); return $this->redirect(['forum/index']); } $forum = Forum::find()->where(['id' => $fid, 'category_id' => $cid])->limit(1)->one(); 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']); } $model = new Thread(); $model->scenario = 'new'; $model->subscribe = 1; $preview = false; $postData = Yii::$app->request->post(); if ($model->load($postData)) { $model->posts = 0; $model->views = 0; $model->category_id = $forum->category->id; $model->forum_id = $forum->id; $model->author_id = User::loggedId(); if ($model->validate()) { if (isset($postData['preview-button'])) { $preview = true; } else { if ($model->podiumNew()) { $this->success(Yii::t('podium/flash', 'New thread has been created.')); return $this->redirect([ 'forum/thread', 'cid' => $forum->category->id, 'fid' => $forum->id, 'id' => $model->id, 'slug' => $model->slug ]); } $this->error(Yii::t('podium/flash', 'Sorry! There was an error while creating the thread. Contact administrator about this problem.')); } } } return $this->render('new-thread', [ 'preview' => $preview, 'model' => $model, 'forum' => $forum, ]); }
Creating the thread of given category ID and forum ID. @param int $cid category ID @param int $fid forum ID @return string|Response
entailment
public function run($id = null, $slug = null) { if (!is_numeric($id) || $id < 1 || empty($slug)) { $this->controller->error(Yii::t('podium/flash', 'Sorry! We can not find the user you are looking for.')); return $this->controller->redirect(['members/index']); } $user = User::find()->where(['and', ['id' => $id], ['or', ['slug' => $slug], ['slug' => ''], ['slug' => null], ] ])->limit(1)->one(); if (empty($user)) { $this->controller->error(Yii::t('podium/flash', 'Sorry! We can not find the user you are looking for.')); return $this->controller->redirect(['members/index']); } return $this->controller->render($this->view, ['user' => $user]); }
Runs action. @param int $id user ID @param string $slug user slug @return string|Response
entailment
public function isMessageReceiver($userId) { if ($this->messageReceivers) { foreach ($this->messageReceivers as $receiver) { if ($receiver->receiver_id == $userId) { return true; } } } return false; }
Checks if user is a message receiver. @param int $userId @return bool
entailment
public function send() { $transaction = static::getDb()->beginTransaction(); try { $this->sender_id = User::loggedId(); $this->sender_status = self::STATUS_READ; if (!$this->save()) { throw new Exception('Message saving error!'); } $count = count($this->receiversId); foreach ($this->receiversId as $receiver) { if (!(new Query())->select('id')->from(User::tableName())->where(['id' => $receiver, 'status' => User::STATUS_ACTIVE])->exists()) { if ($count == 1) { throw new Exception('No active receivers to send message to!'); } continue; } $message = new MessageReceiver(); $message->message_id = $this->id; $message->receiver_id = $receiver; $message->receiver_status = self::STATUS_NEW; if (!$message->save()) { throw new Exception('MessageReceiver saving error!'); } Podium::getInstance()->podiumCache->deleteElement('user.newmessages', $receiver); } $transaction->commit(); $sessionKey = 'messages.' . $this->sender_id; if (Yii::$app->session->has($sessionKey)) { $sentAlready = explode('|', Yii::$app->session->get($sessionKey)); $sentAlready[] = time(); Yii::$app->session->set($sessionKey, implode('|', $sentAlready)); } else { Yii::$app->session->set($sessionKey, time()); } return true; } catch (Exception $e) { $transaction->rollBack(); Log::error($e->getMessage(), $this->id, __METHOD__); } return false; }
Sends message. @return bool
entailment
public static function tooMany($userId) { $sessionKey = 'messages.' . $userId; if (Yii::$app->session->has($sessionKey)) { $sentAlready = explode('|', Yii::$app->session->get($sessionKey)); $validated = []; foreach ($sentAlready as $t) { if (preg_match('/^[0-9]+$/', $t)) { if ($t > time() - self::SPAM_WAIT * 60) { $validated[] = $t; } } } Yii::$app->session->set($sessionKey, implode('|', $validated)); if (count($validated) >= self::SPAM_MESSAGES) { return true; } } return false; }
Checks if user sent already more than SPAM_MESSAGES in last SPAM_WAIT minutes. @param int $userId @return bool
entailment
public function remove() { $transaction = static::getDb()->beginTransaction(); try { $clearCache = false; if ($this->sender_status == self::STATUS_NEW) { $clearCache = true; } $this->scenario = 'remove'; if (empty($this->messageReceivers)) { if (!$this->delete()) { throw new Exception('Message removing error!'); } if ($clearCache) { Podium::getInstance()->podiumCache->deleteElement('user.newmessages', $this->sender_id); } $transaction->commit(); return true; } $allDeleted = true; foreach ($this->messageReceivers as $mr) { if ($mr->receiver_status != MessageReceiver::STATUS_DELETED) { $allDeleted = false; break; } } if ($allDeleted) { foreach ($this->messageReceivers as $mr) { if (!$mr->delete()) { throw new Exception('Received message removing error!'); } } if (!$this->delete()) { throw new Exception('Message removing error!'); } if ($clearCache) { Podium::getInstance()->podiumCache->deleteElement('user.newmessages', $this->sender_id); } $transaction->commit(); return true; } $this->sender_status = self::STATUS_DELETED; if (!$this->save()) { throw new Exception('Message status changing error!'); } if ($clearCache) { Podium::getInstance()->podiumCache->deleteElement('user.newmessages', $this->sender_id); } $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 podiumReport($post = null) { try { if (empty($post)) { throw new Exception('Reported post missing'); } $logged = User::loggedId(); $this->sender_id = $logged; $this->topic = Yii::t('podium/view', 'Complaint about the post #{id}', ['id' => $post->id]); if (Podium::getInstance()->podiumConfig->get('use_wysiwyg') == '0') { $this->content .= "\n\n---\n" . '[' . Yii::t('podium/view', 'Direct link to this post') . '](' . Url::to(['forum/show', 'id' => $post->id]) . ')' . "\n\n---\n" . '**' . Yii::t('podium/view', 'Post contents') . '**' . $post->content; } else { $this->content .= '<hr>' . Html::a(Yii::t('podium/view', 'Direct link to this post'), ['forum/show', 'id' => $post->id]) . '<hr>' . '<p>' . Yii::t('podium/view', 'Post contents') . '</p>' . '<blockquote>' . $post->content . '</blockquote>'; } $this->sender_status = self::STATUS_DELETED; if (!$this->save()) { throw new Exception('Saving complaint error!'); } $receivers = []; $mods = $post->forum->mods; $stamp = time(); foreach ($mods as $mod) { if ($mod != $logged) { $receivers[] = [$this->id, $mod, self::STATUS_NEW, $stamp, $stamp]; } } if (empty($receivers)) { throw new Exception('No one to send report to'); } if (!Podium::getInstance()->db->createCommand()->batchInsert( MessageReceiver::tableName(), ['message_id', 'receiver_id', 'receiver_status', 'created_at', 'updated_at'], $receivers )->execute()) { throw new Exception('Reports saving error!'); } Podium::getInstance()->podiumCache->delete('user.newmessages'); Log::info('Post reported', $post->id, __METHOD__); return true; } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Performs post report sending to moderators. @param Post $post reported post @return bool @since 0.2
entailment
public function markRead() { if ($this->sender_status == self::STATUS_NEW) { $this->sender_status = self::STATUS_READ; if ($this->save()) { Podium::getInstance()->podiumCache->deleteElement('user.newmessages', $this->sender_id); } } }
Marks message read. @since 0.2
entailment
public function getParsedContent() { if (Podium::getInstance()->podiumConfig->get('use_wysiwyg') == '0') { $parser = new GithubMarkdown(); $parser->html5 = true; return $parser->parse($this->content); } return $this->content; }
Returns content Markdown-parsed if WYSIWYG editor is switched off. @return string @since 0.6
entailment
public function begin($key, $view, $duration = 60) { $properties['id'] = $this->_cachePrefix . $key; $properties['view'] = $view; $properties['duration'] = $duration; $cache = FragmentCache::begin($properties); if ($cache->getCachedContent() !== false) { $this->end(); return false; } return true; }
Begins FragmentCache widget. Usage: if (Podium::getInstance()->cache->beginCache('key', $this)) { $this->endCache(); } @param string $key the key identifying the content to be cached. @param View $view view object @param int $duration number of seconds that the data can remain valid in cache. Use 0 to indicate that the cached data will never expire. @return bool @since 0.2
entailment
public static function clearAfter($what) { $cache = new static; switch ($what) { case 'userDelete': $cache->delete('forum.latestposts'); // no break case 'activate': $cache->delete('members.fieldlist'); $cache->delete('forum.memberscount'); break; case 'categoryDelete': case 'forumDelete': case 'threadDelete': case 'postDelete': $cache->delete('forum.threadscount'); $cache->delete('forum.postscount'); $cache->delete('user.threadscount'); $cache->delete('user.postscount'); $cache->delete('forum.latestposts'); break; case 'threadMove': case 'postMove': $cache->delete('forum.threadscount'); $cache->delete('forum.postscount'); $cache->delete('forum.latestposts'); break; case 'newThread': $cache->delete('forum.threadscount'); $cache->deleteElement('user.threadscount', User::loggedId()); // no break case 'newPost': $cache->delete('forum.postscount'); $cache->delete('forum.latestposts'); $cache->deleteElement('user.postscount', User::loggedId()); break; } }
Clears several elements at once. @param string $what action identifier @since 0.2
entailment
public function deleteElement($key, $element) { $cache = $this->get($key); if ($cache !== false && isset($cache[$element])) { unset($cache[$element]); return $this->set($key, $cache); } return true; }
Deletes the value of element with the specified key from cache array. @param string $key a key identifying the value to be deleted from cache. @param string $element a key of the element. @return bool
entailment
public function getElement($key, $element) { $cache = $this->get($key); if ($cache !== false && isset($cache[$element])) { return $cache[$element]; } return false; }
Retrieves the value of element from array cache with the specified key. @param string $key the key identifying the cached value. @param string $element the key of the element. @return mixed the value of element stored in cache array, false if the value is not in the cache, expired, array key does not exist or the dependency associated with the cached data has changed.
entailment
public function set($key, $value, $duration = 0) { return $this->engine->set($this->_cachePrefix . $key, $value, $duration); }
Stores the value identified by the key into cache. @param string $key the key identifying the value to be cached. @param mixed $value the value to be cached @param int $duration the number of seconds in which the cached value will expire. 0 means never expire. @return bool
entailment
public function setElement($key, $element, $value, $duration = 0) { $cache = $this->get($key); if ($cache === false) { $cache = []; } $cache[$element] = $value; return $this->set($key, $cache, $duration); }
Stores the value for the element into cache array identified by the key. @param string $key the key identifying the value to be cached. @param string $element the key of the element. @param mixed $value the value to be cached @param int $duration the number of seconds in which the cached value will expire. 0 means never expire. @return bool
entailment
public function getUser($status = User::STATUS_ACTIVE) { if ($this->_user === false) { $this->_user = User::findByKeyfield($this->username, $status); } return $this->_user; }
Returns user. @param int $status @return User
entailment
public function run() { $user = $this->getUser(User::STATUS_REGISTERED); 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->generateActivationToken(); 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 reactivating.'), true ]; } if (!$this->sendReactivationEmail($user)) { return [ true, Yii::t('podium/flash', 'Sorry! There was some error while sending you the account activation link. Contact administrator about this problem.'), true ]; } return [ false, Yii::t('podium/flash', 'The account activation link has been sent to your e-mail address.'), true ]; }
Generates new activation token. @return array $error flag, $message text, $back flag
entailment
protected function sendReactivationEmail(User $user) { $forum = Podium::getInstance()->podiumConfig->get('name'); $email = Content::fill(Content::EMAIL_REACTIVATION); if ($email !== false) { $link = Url::to(['account/activate', 'token' => $user->activation_token], true); return Email::queue( $user->email, str_replace('{forum}', $forum, $email->topic), str_replace('{forum}', $forum, str_replace('{link}', Html::a($link, $link), $email->content)), !empty($user->id) ? $user->id : null ); } return false; }
Sends reactivation email. @param User $user @return bool @since 0.2
entailment
protected static function addGuest($ip, $url) { $activity = static::find()->where(['ip' => $ip, 'user_id' => null])->limit(1)->one(); if (empty($activity)) { $activity = new static; $activity->ip = $ip; } $activity->url = $url; return $activity->save(); }
Adds guest activity. @param string $ip @param string $url @return bool @since 0.6
entailment
protected static function addUser($ip, $url) { if (!$user = User::findMe()) { return false; } $activity = static::find()->where(['user_id' => $user->id])->limit(1)->one(); if (!$activity) { $activity = new static; $activity->user_id = $user->id; } $activity->username = $user->podiumName; $activity->user_role = $user->role; $activity->user_slug = $user->podiumSlug; $activity->url = $url; $activity->ip = $ip; $activity->anonymous = !empty($user->meta) ? $user->meta->anonymous : 0; return $activity->save(); }
Adds registered user activity. @param string $ip @param string $url @return bool @since 0.6
entailment
public static function add() { try { $ip = Yii::$app->request->userIp; $url = Yii::$app->request->url; if (empty($ip)) { $ip = '0.0.0.0'; } if (Podium::getInstance()->user->isGuest) { if (static::addGuest($ip, $url)) { return true; } } else { if (static::addUser($ip, $url)) { return true; } } Log::error('Cannot log user activity', null, __METHOD__); } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); } return false; }
Adds user activity. @return bool
entailment
public static function deleteUser($id) { $activity = static::find()->where(['user_id' => $id])->limit(1)->one(); if (empty($activity) || !$activity->delete()) { Log::error('Cannot delete user activity', $id, __METHOD__); return; } Podium::getInstance()->podiumCache->delete('forum.lastactive'); }
Deletes user activity. @param int $id
entailment
public static function updateName($id, $username, $slug) { $activity = static::find()->where(['user_id' => $id])->limit(1)->one(); if (empty($activity)) { Log::error('Cannot update user activity', $id, __METHOD__); return; } $activity->username = $username; $activity->user_slug = $slug; if (!$activity->save()) { Log::error('Cannot update user activity', $id, __METHOD__); return; } Podium::getInstance()->podiumCache->delete('forum.lastactive'); }
Updates username after change. @param int $id @param string $username @param string $slug
entailment
public static function updateRole($id, $role) { $activity = static::find()->where(['user_id' => $id])->limit(1)->one(); if (empty($activity)) { Log::error('Cannot update user activity', $id, __METHOD__); return; } $activity->user_role = $role; if (!$activity->save()) { Log::error('Cannot update user activity', $id, __METHOD__); return; } Podium::getInstance()->podiumCache->delete('forum.lastactive'); }
Updates role after change. @param int $id @param int $role
entailment
public static function lastActive() { $last = Podium::getInstance()->podiumCache->get('forum.lastactive'); if ($last === false) { $time = time() - 15 * 60; $last = [ 'count' => static::find()->where(['>', 'updated_at', $time])->count(), 'members' => static::find()->where(['and', ['>', 'updated_at', $time], ['is not', 'user_id', null], ['anonymous' => 0] ])->count(), 'anonymous' => static::find()->where(['and', ['>', 'updated_at', $time], ['is not', 'user_id', null], ['anonymous' => 1] ])->count(), 'guests' => static::find()->where(['and', ['>', 'updated_at', $time], ['user_id' => null] ])->count(), 'names' => [], ]; $members = static::find()->where(['and', ['>', 'updated_at', $time], ['is not', 'user_id', null], ['anonymous' => 0] ]); foreach ($members->each() as $member) { $last['names'][$member->user_id] = [ 'name' => $member->username, 'role' => $member->user_role, 'slug' => $member->user_slug, ]; } Podium::getInstance()->podiumCache->set('forum.lastactive', $last, 60); } return $last; }
Updates tracking. @return array
entailment
public static function totalMembers() { $members = Podium::getInstance()->podiumCache->get('forum.memberscount'); if ($members === false) { $members = User::find()->where(['!=', 'status', User::STATUS_REGISTERED])->count(); Podium::getInstance()->podiumCache->set('forum.memberscount', $members); } return $members; }
Counts number of registered users. @return int
entailment
public static function totalPosts() { $posts = Podium::getInstance()->podiumCache->get('forum.postscount'); if ($posts === false) { $posts = Post::find()->count(); Podium::getInstance()->podiumCache->set('forum.postscount', $posts); } return $posts; }
Counts number of created posts. @return int
entailment
public static function totalThreads() { $threads = Podium::getInstance()->podiumCache->get('forum.threadscount'); if ($threads === false) { $threads = Thread::find()->count(); Podium::getInstance()->podiumCache->set('forum.threadscount', $threads); } return $threads; }
Counts number of created threads. @return int
entailment
public function getVersionSteps() { if ($this->_versionSteps === null) { $currentVersion = Yii::$app->session->get(self::SESSION_VERSION, 0); $versionSteps = []; foreach ($this->steps as $version => $steps) { if (Helper::compareVersions(explode('.', $currentVersion), explode('.', $version)) == '<') { $versionSteps += $steps; } } $this->_versionSteps = $versionSteps; } return $this->_versionSteps; }
Returns update steps from next new version. @return array @since 0.2
entailment
protected function updateValue($name, $value) { if (empty($name)) { return Yii::t('podium/flash', 'Installation aborted! Column name missing.'); } if ($value === null) { return Yii::t('podium/flash', 'Installation aborted! Column value missing.'); } try { Podium::getInstance()->podiumConfig->set($name, $value); return $this->returnSuccess(Yii::t('podium/flash', 'Config setting {name} has been updated to {value}.', [ 'name' => $name, 'value' => $value, ])); } catch (Exception $e) { return $this->returnError($e->getMessage(), __METHOD__, Yii::t('podium/flash', 'Error during configuration updating') ); } }
Updates database value in config table. @param string $name config key @param string $value config value @return string result message @since 0.2
entailment
public function export() { $tableName = Podium::getInstance()->db->quoteTableName($this->logTable); $sql = "INSERT INTO $tableName ([[level]], [[category]], [[log_time]], [[ip]], [[message]], [[model]], [[user]]) VALUES (:level, :category, :log_time, :ip, :message, :model, :user)"; $command = Podium::getInstance()->db->createCommand($sql); foreach ($this->messages as $message) { list($text, $level, $category, $timestamp) = $message; $extracted = [ 'msg' => '', 'model' => null, ]; if (is_array($text) && (isset($text['msg']) || isset($text['model']))) { if (isset($text['msg'])) { if (!is_string($text['msg'])) { $extracted['msg'] = VarDumper::export($text['msg']); } else { $extracted['msg'] = $text['msg']; } } if (isset($text['model'])) { $extracted['model'] = $text['model']; } } elseif (is_string($text)) { $extracted['msg'] = $text; } else { $extracted['msg'] = VarDumper::export($text); } if (substr($category, 0, 14) == 'bizley\podium\\') { $category = substr($category, 14); } $request = Yii::$app->getRequest(); $command->bindValues([ ':level' => $level, ':category' => $category, ':log_time' => $timestamp, ':ip' => $request instanceof Request ? $request->getUserIP() : null, ':message' => $extracted['msg'], ':model' => $extracted['model'], ':user' => Log::blame(), ])->execute(); } }
Stores log messages to DB.
entailment
public function run() { $size = 20; $saved = Yii::$app->session->get('per-page'); if (in_array($saved, $this->pageSizes)) { $size = $saved; } $selected = Yii::$app->request->get('per-page'); if (in_array($selected, $this->pageSizes)) { $size = $selected; } Yii::$app->session->set('per-page', $size); return Html::tag('div', Html::tag('div', Html::label(Yii::t('podium/view', 'Results per page'), 'per-page') . ' ' . Html::dropDownList('per-page', $size, $this->pageSizes, ['class' => 'form-control input-sm', 'id' => 'per-page']), ['class' => 'form-group'] ), ['class' => 'pull-right form-inline']) . '<br><br>'; }
Rendering the widget dropdown. Default page size is 20. @return string
entailment
public static function blame() { if (Yii::$app instanceof Application && !Podium::getInstance()->user->isGuest) { return User::loggedId(); } return null; }
Returns ID of user responsible for logged action. @return int|null
entailment
public static function error($msg, $model = null, $category = 'application') { Yii::error([ 'msg' => $msg, 'model' => $model, ], $category); }
Calls for error log. @param mixed $msg Message @param string $model Model @param string $category
entailment
public static function info($msg, $model = null, $category = 'application') { Yii::info([ 'msg' => $msg, 'model' => $model, ], $category); }
Calls for info log. @param mixed $msg Message @param string $model Model @param string $category
entailment
public static function warning($msg, $model = null, $category = 'application') { Yii::warning([ 'msg' => $msg, 'model' => $model, ], $category); }
Calls for warning log. @param mixed $msg Message @param string $model Model @param string $category
entailment
public function requiredPollAnswers() { if ($this->pollAdded) { $this->pollAnswers = array_unique($this->pollAnswers); $filtered = []; foreach ($this->pollAnswers as $answer) { if (!empty(trim($answer))) { $filtered[] = trim($answer); } } $this->pollAnswers = $filtered; if (count($this->pollAnswers) < 2) { $this->addError('pollAnswers', Yii::t('podium/view', 'You have to add at least 2 options.')); } } }
Filters and validates poll answers. @since 0.5
entailment
public function getFirstNewNotSeen() { return $this ->hasOne(Post::className(), ['thread_id' => 'id']) ->where(['>', 'created_at', $this->userView ? $this->userView->new_last_seen : 0]) ->orderBy(['id' => SORT_ASC]); }
First new not seen post relation. @return Post
entailment
public function getFirstEditedNotSeen() { return $this ->hasOne(Post::className(), ['thread_id' => 'id']) ->where(['>', 'edited_at', $this->userView ? $this->userView->edited_last_seen : 0]) ->orderBy(['id' => SORT_ASC]); }
First edited not seen post relation. @return Post
entailment
public function checkAccess() { if (YII_ENV === 'test') { return true; } $ip = Yii::$app->request->getUserIP(); foreach ($this->module->allowedIPs as $filter) { if ($filter === '*' || $filter === $ip || (($pos = strpos($filter, '*')) !== false && !strncmp($ip, $filter, $pos))) { return true; } } echo Yii::t('podium/view', 'Access to Podium installation is denied due to IP address restriction.'); Yii::warning('Access to Podium installation is denied due to IP address restriction. The requested IP is ' . $ip, __METHOD__); return false; }
Checks if user's IP is on the allowed list. @see Podium::$allowedIPs This method is copied from yii2-gii module. @author Qiang Xue <[email protected]> @return bool
entailment
public function actionImport() { $result = ['error' => Yii::t('podium/view', 'Error')]; if (Yii::$app->request->isPost) { $drop = Yii::$app->request->post('drop'); if ($drop !== null) { $installation = new Installation(); if ((is_bool($drop) && $drop) || $drop === 'true') { $result = $installation->nextDrop(); } else { $result = $installation->nextStep(); } } } return Json::encode($result); }
Importing the databases structures. @return string
entailment
public function actionRun() { Yii::$app->session->set(Installation::SESSION_KEY, 0); if ($this->module->userComponent !== true && empty($this->module->adminId)) { $this->warning(Yii::t('podium/flash', "{userComponent} is set to custom but no administrator ID has been set with {adminId} parameter. Administrator privileges will not be set.", [ 'userComponent' => '$userComponent', 'adminId' => '$adminId' ])); } return $this->render('run', ['version' => $this->module->version]); }
Running the installation. @return string
entailment
public function actionUpdate() { $result = ['error' => Yii::t('podium/view', 'Error')]; if (Yii::$app->request->isPost) { $result = (new Update())->nextStep(); } return Json::encode($result); }
Updating the databases structures. @return string
entailment