repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/controllers/AdminUserEmailController.php
src/controllers/AdminUserEmailController.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 31.05.2015 */ namespace skeeks\cms\controllers; use skeeks\cms\backend\BackendAction; use skeeks\cms\backend\controllers\BackendModelStandartController; use skeeks\cms\models\CmsUserEmail; use skeeks\yii2\form\fields\HtmlBlock; use skeeks\yii2\form\fields\TextField; use yii\helpers\ArrayHelper; /** * Class AdminUserEmailController * @package skeeks\cms\controllers */ class AdminUserEmailController extends BackendModelStandartController { public function init() { $this->name = "Управление email адресами"; $this->modelShowAttribute = "value"; $this->modelClassName = CmsUserEmail::className(); $this->permissionName = 'cms/admin-user'; $this->generateAccessActions = false; parent::init(); } /** * @inheritdoc */ public function actions() { $actions = ArrayHelper::merge(parent::actions(), [ "create" => [ 'fields' => [$this, 'updateFields'], 'size' => BackendAction::SIZE_SMALL, 'buttons' => ['save'], /*"accessCallback" => function ($model) { $cmsUserEmail = new CmsUserEmail(); $cmsUserEmail->load(\Yii::$app->request->get()); if ($model) { return \Yii::$app->user->can("cms/admin-user/manage", ['model' => $cmsUserEmail->cmsUser]); } return false; },*/ ], "update" => [ 'fields' => [$this, 'updateFields'], 'size' => BackendAction::SIZE_SMALL, 'buttons' => ['save'], "accessCallback" => function ($model) { if ($this->model) { return \Yii::$app->user->can("cms/admin-user/manage", ['model' => $this->model->cmsUser]); } return false; }, ], "delete" => [ "accessCallback" => function ($model) { if ($this->model) { return \Yii::$app->user->can("cms/admin-user/manage", ['model' => $this->model->cmsUser]); } return false; }, ], ]); return $actions; } public function updateFields($action) { $model = $action->model; $model->load(\Yii::$app->request->get()); $result = [ [ 'class' => HtmlBlock::class, 'content' => '<div class="row no-gutters"><div class="col-12" style="max-width: 500px;">', ], 'value' => [ 'class' => TextField::class, 'elementOptions' => [ 'placeholder' => 'Email', 'autocomplete' => 'off', ], ], [ 'class' => HtmlBlock::class, 'content' => '</div><div class="col-12" style="max-width: 500px;">', ], 'name' => [ 'class' => TextField::class, 'elementOptions' => [ 'placeholder' => 'Например рабочий email', ], ], [ 'class' => HtmlBlock::class, 'content' => '</div></div>', ], [ 'class' => HtmlBlock::class, 'content' => '<div style="display: none;">', ], 'cms_user_id', [ 'class' => HtmlBlock::class, 'content' => '</div>', ], ]; return $result; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/controllers/AdminCmsContentTypeController.php
src/controllers/AdminCmsContentTypeController.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 15.05.2015 */ namespace skeeks\cms\controllers; use skeeks\cms\backend\actions\BackendGridModelRelatedAction; use skeeks\cms\backend\controllers\BackendModelStandartController; use skeeks\cms\backend\grid\DefaultActionColumn; use skeeks\cms\models\CmsContentType; use skeeks\cms\queryfilters\QueryFiltersEvent; use skeeks\cms\rbac\CmsManager; use yii\helpers\ArrayHelper; use yii\helpers\Html; /** * Class AdminCmsContentTypeController * @package skeeks\cms\controllers */ class AdminCmsContentTypeController extends BackendModelStandartController { public function init() { $this->name = \Yii::t('skeeks/cms', 'Content management'); $this->modelShowAttribute = "name"; $this->modelClassName = CmsContentType::class; $this->generateAccessActions = false; $this->permissionName = CmsManager::PERMISSION_ROLE_ADMIN_ACCESS; parent::init(); } /** * @inheritdoc */ public function actions() { return ArrayHelper::merge(parent::actions(), [ 'index' => [ "filters" => [ 'visibleFilters' => [ 'q', ], 'filtersModel' => [ 'rules' => [ ['q', 'safe'], ], 'attributeDefines' => [ 'q', ], 'fields' => [ 'q' => [ 'label' => 'Поиск', 'elementOptions' => [ 'placeholder' => 'Поиск', ], 'on apply' => function (QueryFiltersEvent $e) { /** * @var $query ActiveQuery */ $query = $e->dataProvider->query; if ($e->field->value) { $query->andWhere([ 'or', ['like', CmsContentType::tableName().'.name', $e->field->value], ['like', CmsContentType::tableName().'.id', $e->field->value], ['like', CmsContentType::tableName().'.code', $e->field->value], ]); $query->groupBy([CmsContentType::tableName().'.id']); } }, ], ], ], ], 'grid' => [ 'defaultOrder' => [ 'priority' => SORT_ASC, ], 'visibleColumns' => [ 'checkbox', 'actions', 'custom', 'content', 'priority', ], 'columns' => [ 'custom' => [ 'attribute' => "name", 'viewAttribute' => "asText", 'class' => DefaultActionColumn::class ], 'content' => [ 'label' => "Контент", 'format' => "raw", 'value' => function (CmsContentType $model) { $contents = \yii\helpers\ArrayHelper::map($model->cmsContents, 'id', 'name'); return implode(', ', $contents); }, ], ], ], ], "create" => [ 'fields' => [$this, 'updateFields'], ], "update" => [ 'fields' => [$this, 'updateFields'], ], "content" => [ 'class' => BackendGridModelRelatedAction::class, 'accessCallback' => true, 'name' => "Контент", 'icon' => 'fa fa-list', 'controllerRoute' => "/cms/admin-cms-content", 'relation' => ['content_type' => 'code'], 'priority' => 600, 'on gridInit' => function($e) { /** * @var $action BackendGridModelRelatedAction */ $action = $e->sender; $action->relatedIndexAction->backendShowings = false; $visibleColumns = $action->relatedIndexAction->grid['visibleColumns']; //ArrayHelper::removeValue($visibleColumns, 'cms_site_id'); $action->relatedIndexAction->grid['visibleColumns'] = $visibleColumns; }, ], ]); } public function updateFields($action) { return [ 'name', 'code', 'priority', ]; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/controllers/ModelPropertiesController.php
src/controllers/ModelPropertiesController.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 14.04.2015 */ namespace skeeks\cms\controllers; use skeeks\cms\models\forms\PasswordChangeForm; use skeeks\cms\models\User; use skeeks\cms\relatedProperties\models\RelatedElementModel; use Yii; use skeeks\cms\models\searchs\User as UserSearch; use yii\filters\VerbFilter; use yii\helpers\ArrayHelper; use yii\web\Controller; use yii\web\Response; use yii\widgets\ActiveForm; /** * Class ModelPropertiesController * @package skeeks\cms\controllers */ class ModelPropertiesController extends Controller { /** * @return array */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'validate' => ['post'], 'submit' => ['post'], ], ], ]); } /** * Процесс отправки формы * @return array */ public function actionSubmit() { if (\Yii::$app->request->isAjax && !\Yii::$app->request->isPjax) { \Yii::$app->response->format = Response::FORMAT_JSON; $response = [ 'success' => false, 'message' => 'Произошла ошибка', ]; if (\Yii::$app->request->post('sx-model') && \Yii::$app->request->post('sx-model-value')) { $modelClass = \Yii::$app->request->post('sx-model'); $modelValue = \Yii::$app->request->post('sx-model-value'); /** * @var RelatedElementModel $modelForm */ $modelForm = $modelClass::find()->where(['id' => $modelValue])->one(); if (method_exists($modelForm, "createPropertiesValidateModel")) { $validateModel = $modelForm->createPropertiesValidateModel(); } else { $validateModel = $modelForm->getRelatedPropertiesModel(); } if ($validateModel->load(\Yii::$app->request->post()) && $validateModel->validate()) { $validateModel->save(); $response['success'] = true; $response['message'] = 'Успешно отправлена'; } else { $response['message'] = 'Форма заполнена неправильно'; } return $response; } } } /** * Валидация данных с формы * @return array */ public function actionValidate() { if (\Yii::$app->request->isAjax && !\Yii::$app->request->isPjax) { if (\Yii::$app->request->post('sx-model') && \Yii::$app->request->post('sx-model-value')) { $modelClass = \Yii::$app->request->post('sx-model'); $modelValue = \Yii::$app->request->post('sx-model-value'); /** * @var $modelForm Form */ $modelForm = $modelClass::find()->where(['id' => $modelValue])->one(); if (method_exists($modelForm, "createPropertiesValidateModel")) { $model = $modelForm->createPropertiesValidateModel(); } else { $model = $modelForm->getRelatedPropertiesModel(); } $model->load(\Yii::$app->request->post()); \Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/controllers/SavedFilterController.php
src/controllers/SavedFilterController.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (�����) * @date 14.04.2016 */ namespace skeeks\cms\controllers; use skeeks\cms\base\Controller; use skeeks\cms\helpers\UrlHelper; use skeeks\cms\models\CmsSavedFilter; use skeeks\cms\models\CmsTree; use skeeks\cms\models\Tree; use Yii; use yii\web\NotFoundHttpException; /** * * @property CmsSavedFilter $model * * @author Semenov Alexander <semenov@skeeks.com> */ class SavedFilterController extends Controller { /** * @var CmsSavedFilter */ public $_model = false; public function init() { if ($this->model && \Yii::$app->cmsToolbar) { $controller = \Yii::$app->createController('cms/admin-cms-saved-filter')[0]; $adminControllerRoute = [ '/cms/admin-cms-saved-filter/update', $controller->requestPkParamName => $this->model->{$controller->modelPkAttribute} ]; $urlEditModel = \skeeks\cms\backend\helpers\BackendUrlHelper::createByParams($adminControllerRoute) ->enableEmptyLayout() ->url; \Yii::$app->cmsToolbar->editUrl = $urlEditModel; } parent::init(); } /** * @return array|bool|null|CmsSavedFilter */ public function getModel() { if ($this->_model !== false) { return $this->_model; } if (!$id = \Yii::$app->request->get('id')) { $this->_model = null; return false; } if (!$this->_model) { $this->_model = CmsSavedFilter::find()->where([ 'id' => $id ])->one(); } return $this->_model; } /** * @return $this|string * @throws NotFoundHttpException */ public function actionView() { if (!$this->model) { throw new NotFoundHttpException(\Yii::t('skeeks/cms', 'Page not found')); } $cmsTree = clone $this->model->cmsTree; \Yii::$app->cms->setCurrentTree($cmsTree); \Yii::$app->breadcrumbs->setPartsByTree($cmsTree)->append([ 'name' => $this->model->name, 'url' => $this->model->url, ]); $viewFile = $this->action->id; if (!$this->model->isAllowIndex) { \Yii::$app->seo->setNoIndexNoFollow(); } if ($cmsTree) { if ($cmsTree->view_file) { $viewFile = $cmsTree->view_file; } else { if ($cmsTree->treeType) { if ($cmsTree->treeType->view_file) { $viewFile = $cmsTree->treeType->view_file; } else { $viewFile = $cmsTree->treeType->code; } } } } $viewFile = "@app/views/modules/cms/tree/" . $viewFile; $this->_initStandartMetaData(); $cmsTree->description_short = $this->model->description_short; $cmsTree->description_full = $this->model->description_full; $cmsTree->name = $this->model->seoName; $cmsTree->seoName = $this->model->seoName; if ($this->model->meta_title) { $cmsTree->meta_title = $this->model->meta_title; } if ($this->model->meta_description) { $cmsTree->meta_description = $this->model->meta_description; } if ($this->model->meta_keywords) { $cmsTree->meta_keywords = $this->model->meta_keywords; } $result = $this->render($viewFile, [ 'model' => $cmsTree, 'savedFilter' => $this->model ]); return $result; } /** * @return $this */ protected function _initStandartMetaData() { /** * @var $model CmsSavedFilter */ $model = $this->model; //Заголовок if (!$title = $model->meta_title) { if (isset($model->seoName)) { $title = $model->seoName; } } $this->view->title = $title; $this->view->registerMetaTag([ 'property' => 'og:title', 'content' => $title, ], 'og:title'); //Ключевые слова if ($meta_keywords = $model->meta_keywords) { $this->view->registerMetaTag([ "name" => 'keywords', "content" => $meta_keywords ], 'keywords'); } //Описание if ($meta_descripption = $model->meta_description) { $description = $meta_descripption; } elseif ($model->description_short) { $description = $model->description_short; } else { if (isset($model->name)) { if ($model->name != $model->seoName) { $description = $model->seoName; } else { $description = $model->name; } } } $description = trim(strip_tags($description)); $this->view->registerMetaTag([ "name" => 'description', "content" => $description ], 'description'); $this->view->registerMetaTag([ 'property' => 'og:description', 'content' => $description, ], 'og:description'); //Картика $imageAbsoluteSrc = null; if ($model->image) { $imageAbsoluteSrc = $model->image->absoluteSrc; } if ($imageAbsoluteSrc) { $this->view->registerMetaTag([ 'property' => 'og:image', 'content' => $imageAbsoluteSrc, ], 'og:image'); } $this->view->registerMetaTag([ 'property' => 'og:url', 'content' => $model->getUrl(true), ], 'og:url'); $this->view->registerMetaTag([ 'property' => 'og:type', 'content' => 'website', ], 'og:type'); return $this; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/controllers/AdminCmsContractorOurController.php
src/controllers/AdminCmsContractorOurController.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 31.05.2015 */ namespace skeeks\cms\controllers; use skeeks\cms\backend\actions\BackendGridModelAction; use skeeks\cms\backend\actions\BackendModelAction; use skeeks\cms\backend\actions\BackendModelCreateAction; use skeeks\cms\backend\BackendController; use skeeks\cms\backend\controllers\BackendModelStandartController; use skeeks\cms\backend\widgets\ControllerActionsWidget; use skeeks\cms\grid\BooleanColumn; use skeeks\cms\grid\ImageColumn2; use skeeks\cms\helpers\Image; use skeeks\cms\helpers\RequestResponse; use skeeks\cms\models\CmsContractor; use skeeks\cms\rbac\CmsManager; use skeeks\cms\widgets\AjaxFileUploadWidget; use skeeks\yii2\dadataClient\models\PartyModel; use skeeks\yii2\form\fields\FieldSet; use skeeks\yii2\form\fields\HtmlBlock; use skeeks\yii2\form\fields\NumberField; use skeeks\yii2\form\fields\SelectField; use skeeks\yii2\form\fields\TextareaField; use skeeks\yii2\form\fields\TextField; use skeeks\yii2\form\fields\WidgetField; use yii\base\Event; use yii\base\Exception; use yii\bootstrap\Alert; use yii\data\ActiveDataProvider; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\helpers\Url; /** * @author Semenov Alexander <semenov@skeeks.com> */ class AdminCmsContractorOurController extends BackendModelStandartController { public function init() { $this->name = \Yii::t('skeeks/cms', "Юр. Лица"); $this->modelShowAttribute = "asText"; $this->modelClassName = CmsContractor::class; $this->generateAccessActions = false; $this->permissionName = CmsManager::PERMISSION_ROLE_ADMIN_ACCESS; parent::init(); } /** * @inheritdoc */ public function actions() { return ArrayHelper::merge(parent::actions(), [ 'index' => [ 'on beforeRender' => function (Event $e) { $e->content = Alert::widget([ 'closeButton' => false, 'options' => [ 'class' => 'alert-default', ], 'body' => <<<HTML <p>Добавьте компании на которые вы получаете деньги, на которые заключаете договора в этот раздел. То есть, ваши компании и ИП.</p> HTML , ]); }, "filters" => [ 'visibleFilters' => [ 'id', 'name', ], ], 'grid' => [ 'on init' => function (Event $e) { /** * @var $dataProvider ActiveDataProvider * @var $query ActiveQuery */ $query = $e->sender->dataProvider->query; $query->our()->cmsSite(); /*$paymentsQuery = CrmPayment::find()->select(['count(*)'])->where([ 'or', ['sender_crm_contractor_id' => new Expression(CmsContractor::tableName().".id")], ['receiver_crm_contractor_id' => new Expression(CmsContractor::tableName().".id")], ]); $contactsQuery = CmsContractorMap::find()->select(['count(*)'])->where([ 'crm_company_id' => new Expression(CmsContractor::tableName().".id"), ]); $senderQuery = CrmPayment::find()->select(['sum(amount) as amount'])->where([ 'sender_crm_contractor_id' => new Expression(CmsContractor::tableName().".id"), ]); $receiverQuery = CrmPayment::find()->select(['sum(amount) as amount'])->where([ 'receiver_crm_contractor_id' => new Expression(CmsContractor::tableName().".id"), ]); $query->select([ CmsContractor::tableName().'.*', 'count_payemnts' => $paymentsQuery, 'count_contacts' => $contactsQuery, 'sum_send_amount' => $senderQuery, 'sum_receiver_amount' => $receiverQuery, ]);*/ }, 'defaultOrder' => [ 'id' => SORT_DESC, ], 'visibleColumns' => [ 'checkbox', 'actions', 'custom', //'code', 'is_active', 'priority', ], 'columns' => [ 'custom' => [ 'format' => 'raw', 'value' => function (CmsContractor $model) { $data = []; $data[] = Html::a($model->asText, "#", ['class' => 'sx-trigger-action']); $info = implode("<br />", $data); return "<div class='row no-gutters'> <div class='sx-trigger-action' style='width: 50px;'> <a href='#' style='text-decoration: none; border-bottom: 0;'> <img src='".($model->cmsImage ? $model->cmsImage->src : Image::getCapSrc())."' style='max-width: 50px; max-height: 50px; border-radius: 5px;' /> </a> </div> <div class='my-auto' style='margin-left: 5px;'>".$info."</div></div>";; }, ], 'is_active' => [ 'class' => BooleanColumn::class, ], 'image_id' => [ 'class' => ImageColumn2::class, ], ], ], ], 'bankData' => [ 'class' => BackendModelAction::class, 'name' => 'Банковские реквизиты', 'priority' => 500, 'callback' => [$this, 'bankData'], 'icon' => 'far fa-file-alt', /*'accessCallback' => function ($action) { $model = $action->model; if ($model) { return (bool)(in_array($model->type, [CrmContractor::TYPE_LEGAL, CrmContractor::TYPE_IP])); } return false; },*/ ], "create" => [ 'fields' => [$this, 'updateFields'], ], "update" => [ 'fields' => [$this, 'updateFields'], ], ]); } public function updateFields($action) { /** * @var $model CmsContractor */ $model = $action->model; $model->load(\Yii::$app->request->get()); $mainFieldSet = []; if ($model->isNewRecord) { $model->is_our = 1; $mainFieldSet = [ [ 'class' => HtmlBlock::class, 'content' => <<<HTML <div class="col-12" style="margin-top: 15px;margin-bottom: 15px;"> <div class="d-flex"> <input type="text" id="sx-inn" style="max-width: 350px;" class="form-control" placeholder="Укажите ИНН" /> <button class="btn btn-default sx-btn-auto-inn">Найти и заполнить</button> </div> </div> HTML , ], 'contractor_type' => [ 'class' => SelectField::class, 'items' => CmsContractor::optionsForType(), /*'elementOptions' => [ 'data' => [ 'form-reload' => 'true', ], ],*/ ], ]; } else { $mainFieldSet = [ [ 'class' => HtmlBlock::class, 'content' => '<div style="display: none;">', ], 'contractor_type' => [ 'class' => SelectField::class, 'items' => CmsContractor::optionsForType(), /*'elementOptions' => [ 'data' => [ 'form-reload' => 'true', ], ],*/ ], [ 'class' => HtmlBlock::class, 'content' => '</div>', ], ]; } \Yii::$app->view->registerCss(<<<CSS .sx-fiz-block, .sx-name-block { display: none; } CSS ); $ip = CmsContractor::TYPE_INDIVIDUAL; $legal = CmsContractor::TYPE_LEGAL; $innSearchData = Url::to(['dadata-inn']); \skeeks\cms\admin\assets\JqueryMaskInputAsset::register(\Yii::$app->view); \Yii::$app->view->registerJs(<<<JS $("#cmscontractor-phone").mask("+7 999 999-99-99"); function updateFields() { $(".sx-fiz-block").hide(); $(".sx-name-block").hide(); var contType = $("#cmscontractor-contractor_type").val(); if (contType == '{$ip}') { $(".sx-fiz-block").show(); } if (contType == '{$legal}') { $(".sx-name-block").show(); } } $("#cmscontractor-contractor_type").on("change", function() { updateFields(); }); $(".sx-btn-auto-inn").on("click", function() { var inn = $("#sx-inn").val(); var ajaxQuery = sx.ajax.preparePostQuery('{$innSearchData}'); ajaxQuery.setData({ 'inn' : inn }); var ajaxHandler = new sx.classes.AjaxHandlerStandartRespose(ajaxQuery); ajaxHandler.on("success", function(e, response) { var companyData = response.data; $("#cmscontractor-address").val(companyData.data.address.unrestricted_value); $("#cmscontractor-mailing_address").val(companyData.data.address.unrestricted_value); $("#cmscontractor-mailing_postcode").val(companyData.data.address.data.postal_code); $("#cmscontractor-inn").val(companyData.data.inn); $("#cmscontractor-kpp").val(companyData.data.kpp); $("#cmscontractor-okpo").val(companyData.data.okpo); $("#cmscontractor-ogrn").val(companyData.data.ogrn); if (companyData.data.type == 'LEGAL') { $("#cmscontractor-contractor_type").val("legal"); $("#cmscontractor-name").val(companyData.unrestricted_value); $("#cmscontractor-full_name").val(companyData.unrestricted_value); } else if (companyData.data.type == 'INDIVIDUAL') { $("#cmscontractor-contractor_type").val("individual"); $("#cmscontractor-name").val(companyData.unrestricted_value); $("#cmscontractor-first_name").val(companyData.data.fio.name); $("#cmscontractor-last_name").val(companyData.data.fio.surname); $("#cmscontractor-patronymic").val(companyData.data.fio.patronymic); } $("#cmscontractor-contractor_type").trigger("change"); }); ajaxHandler.on("error", function() { }); ajaxQuery.execute(); return false; }); updateFields(); JS ); $mainFieldSet = ArrayHelper::merge($mainFieldSet, [ [ 'class' => HtmlBlock::class, 'content' => '<div style="display: none;">', ], 'is_our', [ 'class' => HtmlBlock::class, 'content' => '</div><div class="sx-fiz-block">', ], 'last_name', 'first_name', 'patronymic', [ 'class' => HtmlBlock::class, 'content' => '</div><div class="sx-name-block">', ], 'name', 'international_name', 'full_name', [ 'class' => HtmlBlock::class, 'content' => '</div>', ], 'cms_image_id' => [ 'class' => WidgetField::class, 'widgetClass' => AjaxFileUploadWidget::class, 'widgetConfig' => [ 'accept' => 'image/*', 'multiple' => false, ], ], ]); $fieldSet2 = [ 'address' => [ 'class' => TextareaField::class, ], 'mailing_address' => [ 'class' => TextareaField::class, ], 'mailing_postcode' => [ 'class' => NumberField::class, ], 'phone', 'email', 'description' => [ /*'class' => WidgetField::class, 'widgetClass' => Ckeditor::class*/ 'class' => TextareaField::class, ], ]; $fieldSet3 = [ 'stamp_id' => [ 'class' => WidgetField::class, 'widgetClass' => AjaxFileUploadWidget::class, 'widgetConfig' => [ 'accept' => 'image/*', 'multiple' => false, ], ], 'director_signature_id' => [ 'class' => WidgetField::class, 'widgetClass' => AjaxFileUploadWidget::class, 'widgetConfig' => [ 'accept' => 'image/*', 'multiple' => false, ], ], 'signature_accountant_id' => [ 'class' => WidgetField::class, 'widgetClass' => AjaxFileUploadWidget::class, 'widgetConfig' => [ 'accept' => 'image/*', 'multiple' => false, ], ], ]; /*if (!in_array($model->contractor_type, [CmsContractor::TYPE_INDIVIDUAL])) { $fieldSetLegal = [ 'inn', 'kpp', 'ogrn', 'okpo', ]; } else { $fieldSetLegal = [ 'inn', ]; }*/ if ($model->isNewRecord) { $fieldSetLegal = [ 'inn', 'kpp', 'ogrn', 'okpo', ]; } else { $fieldSetLegal = [ 'inn' => [ 'class' => TextField::class, 'elementOptions' => [ 'disabled' => 'disabled' ] ], 'kpp', 'ogrn', 'okpo', ]; } /*if ($model->isNewRecord) { unset($mainFieldSet['contractor_type']); }*/ $result = [ 'main' => [ 'class' => FieldSet::class, 'name' => 'Основное', 'fields' => $mainFieldSet, ], 'legal' => [ 'class' => FieldSet::class, 'name' => 'Юридические данные', 'fields' => $fieldSetLegal, ], 'address' => [ 'class' => FieldSet::class, 'name' => 'Адрес и контакты', 'fields' => $fieldSet2, ], 'additional' => [ 'class' => FieldSet::class, 'name' => 'Дополнительные данные', 'fields' => $fieldSet3, ], ]; return $result; } public function actionDadataInn() { $rr = new RequestResponse(); try { if ($inn = \Yii::$app->request->post("inn")) { $dadata = \Yii::$app->dadataClient->suggest->findByIdParty($inn); if (isset($dadata[0]) && $dadata[0]) { //Создать компанию $party = new PartyModel($dadata[0]); $rr->success = true; $rr->message = "Данные заполнены"; $rr->data = $party->toArray(); } else { throw new Exception("По этом ИНН ничего не надйено!"); } } } catch (\Exception $e) { $rr->success = false; $rr->message = $e->getMessage(); } return $rr; } public function bankData() { if ($controller = \Yii::$app->createController('/cms/admin-cms-contractor-bank')) { /** * @var $controller BackendController * @var $indexAction BackendGridModelAction */ $controller = $controller[0]; $controller->actionsMap = [ 'index' => [ 'configKey' => $this->action->uniqueId, ], ]; if ($indexAction = ArrayHelper::getValue($controller->actions, 'index')) { $indexAction->url = $this->action->urlData; $indexAction->filters = false; $visibleColumns = $indexAction->grid['visibleColumns']; ArrayHelper::removeValue($visibleColumns, 'cms_contractor_id'); $indexAction->backendShowings = false; $indexAction->grid['visibleColumns'] = $visibleColumns; $indexAction->grid['columns']['actions']['isOpenNewWindow'] = true; $indexAction->grid['on init'] = function (Event $e) { $dataProvider = $e->sender->dataProvider; $dataProvider->query->andWhere(['cms_contractor_id' => $this->model->id]); }; $indexAction->on('beforeRender', function (Event $event) use ($controller) { if ($createAction = ArrayHelper::getValue($controller->actions, 'create')) { /** * @var $createAction BackendModelCreateAction */ $createAction->name = "Добавить реквизиты"; $createAction->url = ArrayHelper::merge($createAction->urlData, ['cms_contractor_id' => $this->model->id]); $createAction->isVisible = true; $event->content = ControllerActionsWidget::widget([ 'actions' => [$createAction], 'isOpenNewWindow' => true, /*'button' => [ 'class' => 'btn btn-primary', //'style' => 'font-size: 11px; cursor: pointer;', 'tag' => 'button', 'label' => 'Добавить реквизиты', ],*/ 'minViewCount' => 1, 'itemTag' => 'button', 'itemOptions' => ['class' => 'btn btn-primary'], ])."<br>"; } }); return $indexAction->run(); } } return '1'; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/gridView/PaginationConfig.php
src/cmsWidgets/gridView/PaginationConfig.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 25.05.2015 */ namespace skeeks\cms\cmsWidgets\gridView; use skeeks\cms\base\Component; use yii\data\DataProviderInterface; /** * @property string $modelClassName; название класса модели с которой идет работа * @property DataProviderInterface $dataProvider; готовый датапровайдер с учетом настроек виджета * @property array $resultColumns; готовый конфиг для построения колонок * * Class ShopProductFiltersWidget * @package skeeks\cms\cmsWidgets\filters */ class PaginationConfig extends Component { /** * @var string name of the parameter storing the current page index. * @see params */ public $pageParam = 'page'; /** * @var string name of the parameter storing the page size. * @see params */ public $pageSizeParam = 'per-page'; /** * @var int the default page size. This property will be returned by [[pageSize]] when page size * cannot be determined by [[pageSizeParam]] from [[params]]. */ public $defaultPageSize = 20; /** * @var array|false the page size limits. The first array element stands for the minimal page size, and the second * the maximal page size. If this is false, it means [[pageSize]] should always return the value of [[defaultPageSize]]. */ public $pageSizeLimitMin = 1; /** * @var int */ public $pageSizeLimitMax = 50; public function rules() { return [ [['pageParam', 'pageSizeParam', 'defaultPageSize'], 'required'], [['pageParam', 'pageSizeParam'], 'string'], ['defaultPageSize', 'integer'], ['pageSizeLimitMin', 'integer'], ['pageSizeLimitMax', 'integer'], ]; } public function attributeLabels() { return [ 'pageParam' => \Yii::t('skeeks/cms', 'Parameter name pages, pagination'), 'defaultPageSize' => \Yii::t('skeeks/cms', 'Number of records on one page'), 'pageSizeLimitMin' => \Yii::t('skeeks/cms', 'The minimum allowable value for pagination'), 'pageSizeLimitMax' => \Yii::t('skeeks/cms', 'The maximum allowable value for pagination'), 'pageSizeParam' => \Yii::t('skeeks/cms', 'pageSizeParam'), ]; } /** * @return array */ public function getConfigFormFields() { return [ 'defaultPageSize' => [ 'elementOptions' => [ 'type' => 'number', ], ], 'pageSizeLimitMin' => [ 'elementOptions' => [ 'type' => 'number', ], ], 'pageSizeLimitMax' => [ 'elementOptions' => [ 'type' => 'number', ], ], 'pageParam', 'pageSizeParam', ]; } /** * @param DataProviderInterface $dataProvider * @return $this */ public function initDataProvider(DataProviderInterface $dataProvider) { $dataProvider->getPagination()->defaultPageSize = $this->defaultPageSize; $dataProvider->getPagination()->pageParam = $this->pageParam; $dataProvider->getPagination()->pageSizeParam = $this->pageSizeParam; $dataProvider->getPagination()->pageSizeLimit = [ (int)$this->pageSizeLimitMin, (int)$this->pageSizeLimitMax, ]; return $this; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/contentElements/ContentElementsCmsWidget.php
src/cmsWidgets/contentElements/ContentElementsCmsWidget.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 25.05.2015 */ namespace skeeks\cms\cmsWidgets\contentElements; use skeeks\cms\base\WidgetRenderable; use skeeks\cms\components\Cms; use skeeks\cms\models\CmsContent; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsContentElementTree; use skeeks\cms\query\CmsContentElementActiveQuery; use skeeks\cms\widgets\formInputs\selectTree\SelectTree; use skeeks\yii2\form\fields\BoolField; use skeeks\yii2\form\fields\FieldSet; use skeeks\yii2\form\fields\SelectField; use skeeks\yii2\form\fields\WidgetField; use yii\caching\TagDependency; use yii\data\ActiveDataProvider; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; /** * Class СontentElementsCmsWidget * @package skeeks\cms\cmsWidgets\contentElements */ class ContentElementsCmsWidget extends WidgetRenderable { public $contentElementClass = '\skeeks\cms\models\CmsContentElement'; //Навигация public $enabledPaging = CMS::BOOL_Y; public $enabledPjaxPagination = CMS::BOOL_Y; public $pageSize = 10; public $pageSizeLimitMin = 1; public $pageSizeLimitMax = 50; public $pageParamName = 'page'; //Сортировка public $orderBy = "published_at"; public $order = SORT_DESC; //Дополнительные настройки public $label = null; public $enabledSearchParams = CMS::BOOL_Y; public $enabledCurrentTree = CMS::BOOL_Y; public $enabledCurrentTreeChild = CMS::BOOL_Y; public $enabledCurrentTreeChildAll = CMS::BOOL_Y; public $tree_ids = []; //Условия для запроса public $limit = 0; public $active = "Y"; public $createdBy = []; public $content_ids = []; public $enabledActiveTime = CMS::BOOL_N; public $enabledRunCache = Cms::BOOL_N; public $runCacheDuration = 0; public $activeQueryCallback; public $dataProviderCallback; /** * Additionaly, any data * * @var array */ public $data = []; /** * @see (new ActiveQuery)->with * @var array */ public $with = ['image', 'cmsTree']; /** * When a sample of elements does a search and table of multiple links. Slowly on large databases! * При выборке элементов делает поиск и по таблице множественных связей. Медленно на больших базах данных! * @var bool */ public $isJoinTreeMap = true; public $options = []; /** * @var ActiveDataProvider */ public $dataProvider = null; public static function descriptorConfig() { return array_merge(parent::descriptorConfig(), [ 'name' => \Yii::t('skeeks/cms', 'Отображение элементов'), ]); } public function init() { parent::init(); $this->initActiveQuery(); } /** * @return $this */ public function initActiveQuery() { $className = $this->contentElementClass; $this->initDataProvider(); /** * @var $query CmsContentElementActiveQuery */ $query = $this->dataProvider->query; $query->cmsSite(); if ($this->createdBy) { $this->dataProvider->query->andWhere([$className::tableName().'.created_by' => $this->createdBy]); } if ($this->active) { $query->active(); } if ($this->content_ids) { $query->andWhere([$className::tableName().'.content_id' => $this->content_ids]); } if ($this->limit) { $query->limit($this->limit); } $treeIds = (array)$this->tree_ids; if ($this->enabledCurrentTree == Cms::BOOL_Y) { $tree = \Yii::$app->cms->currentTree; if ($tree) { if ($this->enabledCurrentTreeChild == Cms::BOOL_Y) { if ($this->enabledCurrentTreeChildAll == Cms::BOOL_Y) { $treeIds = $tree->getDescendants()->select(['id'])->indexBy('id')->asArray()->all(); $treeIds = array_keys($treeIds); } else { if ($childrens = $tree->children) { foreach ($childrens as $chidren) { $treeIds[] = $chidren->id; } } } } $treeIds[] = $tree->id; } } if ($treeIds) { foreach ($treeIds as $key => $treeId) { if (!$treeId) { unset($treeIds[$key]); } } if ($treeIds) { /** * @var $query ActiveQuery */ $query = $this->dataProvider->query; if ($this->isJoinTreeMap === true) { $query->joinWith('cmsContentElementTrees'); $query->andWhere([ 'or', [$className::tableName().'.tree_id' => $treeIds], [CmsContentElementTree::tableName().'.tree_id' => $treeIds], ]); } else { $query->andWhere([$className::tableName().'.tree_id' => $treeIds]); } } } /*if ($this->enabledActiveTime == Cms::BOOL_Y) { $query->publishedTime(); }*/ /** * */ if ($this->with) { $this->dataProvider->query->with($this->with); } $this->dataProvider->query->groupBy([$className::tableName().'.id']); if ($this->activeQueryCallback && is_callable($this->activeQueryCallback)) { $callback = $this->activeQueryCallback; $callback($this->dataProvider->query); } if ($this->dataProviderCallback && is_callable($this->dataProviderCallback)) { $callback = $this->dataProviderCallback; $callback($this->dataProvider); } return $this; } public function initDataProvider() { $className = $this->contentElementClass; $this->dataProvider = new ActiveDataProvider([ 'query' => $className::find(), ]); if ($this->enabledPaging == Cms::BOOL_Y) { $this->dataProvider->getPagination()->defaultPageSize = $this->pageSize; $this->dataProvider->getPagination()->pageParam = $this->pageParamName; $this->dataProvider->getPagination()->pageSizeLimit = [ (int)$this->pageSizeLimitMin, (int)$this->pageSizeLimitMax, ]; } else { $this->dataProvider->pagination = false; } if ($this->orderBy) { $this->dataProvider->getSort()->defaultOrder = [ $this->orderBy => (int)$this->order, ]; } return $this; } public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'enabledPaging' => \Yii::t('skeeks/cms', 'Enable paging'), 'enabledPjaxPagination' => \Yii::t('skeeks/cms', 'Enable ajax navigation'), 'pageParamName' => \Yii::t('skeeks/cms', 'Parameter name pages, pagination'), 'pageSize' => \Yii::t('skeeks/cms', 'Number of records on one page'), 'pageSizeLimitMin' => \Yii::t('skeeks/cms', 'The minimum allowable value for pagination'), 'pageSizeLimitMax' => \Yii::t('skeeks/cms', 'The maximum allowable value for pagination'), 'orderBy' => \Yii::t('skeeks/cms', 'Sort by what parameter'), 'order' => \Yii::t('skeeks/cms', 'Sorting direction'), 'label' => \Yii::t('skeeks/cms', 'Title'), 'enabledSearchParams' => \Yii::t('skeeks/cms', 'Take into account the parameters from search string (for filtering)'), 'limit' => \Yii::t('skeeks/cms', 'The maximum number of entries in the sample ({limit})', ['limit' => 'limit']), 'active' => \Yii::t('skeeks/cms', 'Active'), 'createdBy' => \Yii::t('skeeks/cms', 'Selecting the user records'), 'content_ids' => \Yii::t('skeeks/cms', 'Elements of content'), 'enabledCurrentTree' => \Yii::t('skeeks/cms', 'For the colection taken into account the current section (which shows the widget)'), 'enabledCurrentTreeChild' => \Yii::t('skeeks/cms', 'For the colection taken into account the current section and its subsections'), 'enabledCurrentTreeChildAll' => \Yii::t('skeeks/cms', 'For the colection taken into account the current section and all its subsections'), 'tree_ids' => \Yii::t('skeeks/cms', 'Show items linked to sections'), 'enabledActiveTime' => \Yii::t('skeeks/cms', 'Take into consideration activity time'), 'enabledRunCache' => 'Включить кэширование', 'runCacheDuration' => 'Время жизни кэша', ]); } public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ 'enabledActiveTime' => \Yii::t('skeeks/cms', "Will be considered time of beginning and end of the publication"), ]); } public function rules() { return ArrayHelper::merge(parent::rules(), [ [['enabledPaging'], 'string'], [['enabledPjaxPagination'], 'string'], [['pageParamName'], 'string'], [['pageSize'], 'string'], [['orderBy'], 'string'], [['order'], 'integer'], [['label'], 'string'], [['label'], 'string'], [['enabledSearchParams'], 'string'], [['limit'], 'integer'], [['pageSizeLimitMin'], 'integer'], [['pageSizeLimitMax'], 'integer'], [['active'], 'string'], [['createdBy'], 'safe'], [['content_ids'], 'safe'], [['enabledCurrentTree'], 'string'], [['enabledCurrentTreeChild'], 'string'], [['enabledCurrentTreeChildAll'], 'string'], [['tree_ids'], 'safe'], [['enabledActiveTime'], 'string'], [['enabledRunCache'], 'string'], [['runCacheDuration'], 'integer'], ]); } /** * @return array */ public function getConfigFormFields() { return [ /*'template' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Template'), 'fields' => [ 'viewFile', ], ],*/ 'pagination' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Pagination'), 'fields' => [ 'enabledPaging' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ], 'enabledPjaxPagination' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ], 'pageSize' => [ 'elementOptions' => [ 'type' => 'number', ], ], 'pageSizeLimitMin' => [ 'elementOptions' => [ 'type' => 'number', ], ], 'pageSizeLimitMax' => [ 'elementOptions' => [ 'type' => 'number', ], ], 'pageParamName', ], ], 'filtration' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Filtration'), 'fields' => [ 'active' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', ], /*'enabledActiveTime' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ],*/ 'createdBy' => [ 'class' => SelectField::class, 'items' => \yii\helpers\ArrayHelper::map( \skeeks\cms\models\User::find()->cmsSite()->active()->all(), 'id', 'displayName' ), ], 'content_ids' => [ 'class' => SelectField::class, 'items' => CmsContent::getDataForSelect(), 'multiple' => true, ], 'enabledCurrentTree' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ], 'enabledCurrentTreeChild' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ], 'enabledCurrentTreeChildAll' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ], 'tree_ids' => [ 'class' => WidgetField::class, 'widgetClass' => SelectTree::class, 'widgetConfig' => [ 'mode' => SelectTree::MOD_MULTI, 'attributeMulti' => 'tree_ids', ], ], 'enabledSearchParams' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ], ], ], 'sort' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Sorting and quantity'), 'fields' => [ 'limit' => [ 'elementOptions' => [ 'type' => 'number', ], ], 'orderBy' => [ 'class' => SelectField::class, 'items' => (new \skeeks\cms\models\CmsContentElement())->attributeLabels(), ], 'order' => [ 'class' => SelectField::class, 'items' => [ SORT_ASC => \Yii::t('skeeks/cms', 'ASC (from lowest to highest)'), SORT_DESC => \Yii::t('skeeks/cms', 'DESC (from highest to lowest)'), ], ], ], ], 'additionally' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Additionally'), 'fields' => [ 'label', ], ], 'cache' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Cache settings'), 'fields' => [ 'enabledRunCache' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ], 'runCacheDuration' => [ 'elementOptions' => [ 'type' => 'number', ], ], ], ], ]; } public function run() { $cacheKey = $this->getCacheKey().'run'; $dependency = new TagDependency([ 'tags' => [ $this->className().(string)$this->namespace, (new CmsContentElement())->getTableCacheTagCmsSite(), $this->namespace, $this->cmsUser ? $this->cmsUser->cacheTag : '', $this->cmsSite ? $this->cmsSite->cacheTag : '', ], ]); $result = \Yii::$app->cache->get($cacheKey); if ($result === false || $this->enabledRunCache == Cms::BOOL_N) { $result = parent::run(); \Yii::$app->cache->set($cacheKey, $result, (int)$this->runCacheDuration, $dependency); } return $result; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/treeMenu/TreeMenuCmsWidget.php
src/cmsWidgets/treeMenu/TreeMenuCmsWidget.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 25.05.2015 */ namespace skeeks\cms\cmsWidgets\treeMenu; use skeeks\cms\base\WidgetRenderable; use skeeks\cms\components\Cms; use skeeks\cms\models\CmsSite; use skeeks\cms\models\CmsTree; use skeeks\cms\models\Tree; use skeeks\cms\widgets\formInputs\selectTree\DaterangeInputWidget; use skeeks\cms\widgets\formInputs\selectTree\SelectTreeInputWidget; use skeeks\yii2\form\fields\BoolField; use skeeks\yii2\form\fields\FieldSet; use skeeks\yii2\form\fields\FieldSetEnd; use skeeks\yii2\form\fields\SelectField; use skeeks\yii2\form\fields\WidgetField; use yii\caching\TagDependency; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; /** * @deprecated * * @use TreeMenuCmsWidget * * @author Semenov Alexander <semenov@skeeks.com> */ class TreeMenuCmsWidget extends WidgetRenderable { /** * Родительский раздел дерева * @var null */ public $treePid = null; /** * @var null */ public $treeParentCode = null; /** * Выбор только активных пунктов * @var string */ public $active = Cms::BOOL_Y; /** * Добавить условие уровня раздела * @var null */ public $level = null; /** * Название * @var null */ public $label = null; /** * Условие выборки по сайтам * @var array */ public $site_ids = []; /** * Сортировка по умолчанию * @var string */ public $orderBy = "priority"; public $order = SORT_ASC; /** * Установить лимит * @var int */ public $limit = false; /** * Добавить условие выборки разделов, только текущего сайта * @var string */ public $enabledCurrentSite = Cms::BOOL_Y; /** * Включить выключить кэш * @var string */ public $enabledRunCache = Cms::BOOL_Y; public $runCacheDuration = 0; /** * Типы разделов * @var array */ public $tree_type_ids = []; /** * Дополнительный activeQueryCallback * @var */ public $activeQueryCallback; /** * @see (new ActiveQuery)->with * @var array */ public $with = ['children']; /** * @var ActiveQuery */ public $activeQuery = null; public $text = ''; public static function descriptorConfig() { return array_merge(parent::descriptorConfig(), [ 'name' => 'Меню разделов', ]); } public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'treePid' => \Yii::t('skeeks/cms', 'The parent section'), 'active' => \Yii::t('skeeks/cms', 'Activity'), 'level' => \Yii::t('skeeks/cms', 'The nesting level'), 'label' => \Yii::t('skeeks/cms', 'Header'), 'site_ids' => \Yii::t('skeeks/cms', 'Linking to sites'), 'orderBy' => \Yii::t('skeeks/cms', 'Sorting'), 'order' => \Yii::t('skeeks/cms', 'Sorting direction'), 'enabledCurrentSite' => \Yii::t('skeeks/cms', 'Consider the current site'), 'enabledRunCache' => \Yii::t('skeeks/cms', 'Enable caching'), 'runCacheDuration' => \Yii::t('skeeks/cms', 'Cache lifetime'), 'tree_type_ids' => \Yii::t('skeeks/cms', 'Section types'), 'limit' => \Yii::t('skeeks/cms', 'The maximum number of entries in the sample ({limit})', ['limit' => 'limit']), ]); } public function attributeHints() { return array_merge(parent::attributeHints(), [ 'enabledCurrentSite' => \Yii::t('skeeks/cms', 'If you select "yes", then the sample section, add the filter condition, sections of the site, which is called the widget'), 'level' => \Yii::t('skeeks/cms', 'Adds the sample sections, the condition of nesting choice. 0 - will not use this condition at all.'), ]); } public function rules() { return ArrayHelper::merge(parent::rules(), [ ['text', 'string'], [['viewFile', 'label', 'active', 'orderBy', 'enabledCurrentSite', 'enabledRunCache'], 'string'], [['treePid', 'level', 'runCacheDuration', 'limit'], 'integer'], [['order'], 'integer'], [['site_ids'], 'safe'], [['tree_type_ids'], 'safe'], ]); } /** * @return array */ public function getConfigFormFields() { return [ 'template' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Template'), 'fields' => [ 'viewFile', ], ], 'filtration' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Filtration'), 'fields' => [ 'enabledCurrentSite' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', ], 'active' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', ], 'tree_type_ids' => [ 'class' => SelectField::class, 'items' => \yii\helpers\ArrayHelper::map( \skeeks\cms\models\CmsTreeType::find()->all(), 'id', 'name' ), 'multiple' => true, ], 'level' => [ 'elementOptions' => [ 'type' => 'number', ], ], 'site_ids' => [ 'class' => SelectField::class, 'items' => \yii\helpers\ArrayHelper::map( \skeeks\cms\models\CmsSite::find()->active()->all(), 'id', 'name' ), 'multiple' => true, ], 'treePid' => [ 'class' => WidgetField::class, 'widgetClass' => SelectTreeInputWidget::class, 'widgetConfig' => [ 'isAllowNodeSelectCallback' => function ($tree) { /*if (in_array($tree->id, $childrents)) { return false; }*/ return true; }, 'treeWidgetOptions' => [ 'models' => CmsTree::findRoots()->cmsSite()->all(), ], ], ], ], ], 'sort' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Sorting'), 'fields' => [ 'orderBy' => [ 'class' => SelectField::class, 'items' => (new \skeeks\cms\models\Tree())->attributeLabels(), ], 'order' => [ 'class' => SelectField::class, 'items' => [ SORT_ASC => \Yii::t('skeeks/cms', 'ASC (from lowest to highest)'), SORT_DESC => \Yii::t('skeeks/cms', 'DESC (from highest to lowest)'), ], ], 'limit', ], ], 'additionally' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Additionally'), 'fields' => [ 'label', ], ], 'cache' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Cache settings'), 'fields' => [ 'enabledRunCache' => [ 'class' => BoolField::class, 'trueValue' => 'Y', 'falseValue' => 'N', 'allowNull' => false, ], 'runCacheDuration' => [ 'elementOptions' => [ 'type' => 'number', ], ], ], ], ]; } public function init() { parent::init(); $this->initActiveQuery(); } /** * Инициализация acitveQuery * @return $this */ public function initActiveQuery() { $this->activeQuery = Tree::find(); if ($this->treePid) { $this->activeQuery->andWhere(['pid' => $this->treePid]); } elseif ($this->treeParentCode) { $tree = CmsTree::find()->where(['code' => $this->treeParentCode])->one(); if ($tree) { $this->activeQuery->andWhere(['pid' => $tree->id]); } } if ($this->level) { $this->activeQuery->andWhere(['level' => $this->level]); } if ($this->active) { $this->activeQuery->andWhere(['active' => $this->active]); } if ($this->site_ids) { $cmsSites = CmsSite::find()->where(['id' => $this->site_ids])->all(); if ($cmsSites) { $ids = ArrayHelper::map($cmsSites, 'id', 'id'); $this->activeQuery->andWhere(['cms_site_id' => $ids]); } } if ($this->enabledCurrentSite == Cms::BOOL_Y && \Yii::$app->skeeks->site) { $this->activeQuery->andWhere(['cms_site_id' => \Yii::$app->skeeks->site->id]); } if ($this->orderBy) { $this->activeQuery->orderBy([$this->orderBy => (int)$this->order]); } if ($this->tree_type_ids) { $this->activeQuery->andWhere(['tree_type_id' => $this->tree_type_ids]); } if ($this->with) { $this->activeQuery->with($this->with); } if (!$this->limit) { $this->limit = 200; } if ($this->limit) { $this->activeQuery->limit($this->limit); } if ($this->activeQueryCallback && is_callable($this->activeQueryCallback)) { $callback = $this->activeQueryCallback; $callback($this->activeQuery); } return $this; } public function run() { $key = $this->getCacheKey().'run'; $dependency = new TagDependency([ 'tags' => [ $this->className().(string)$this->namespace, (new Tree())->getTableCacheTagCmsSite(), ], ]); $result = \Yii::$app->cache->get($key); if ($result === false || !$this->is_cache) { $result = parent::run(); \Yii::$app->cache->set($key, $result, (int)$this->runCacheDuration, $dependency); } return $result; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/filters/_form.php
src/cmsWidgets/filters/_form.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 27.05.2015 */ /* @var $this yii\web\View */ /* @var $contentType \skeeks\cms\models\CmsContentType */ /* @var $model \skeeks\cms\shop\cmsWidgets\filters\ShopProductFiltersWidget */ ?> <?= $form->fieldSet(\Yii::t('skeeks/cms', 'Showing')); ?> <?= $form->field($model, 'viewFile')->textInput(); ?> <?= $form->fieldSetEnd(); ?> <?= $form->fieldSet(\Yii::t('skeeks/cms', 'Data source')); ?> <?= $form->fieldSelect($model, 'content_id', \skeeks\cms\models\CmsContent::getDataForSelect()); ?> <?php /*= $form->fieldSelectMulti($model, 'searchModelAttributes', [ 'image' => \Yii::t('skeeks/cms', 'Filter by photo'), 'hasQuantity' => \Yii::t('skeeks/cms', 'Filter by availability') ]); */ ?> <?php /*= $form->field($model, 'searchModelAttributes')->dropDownList([ 'image' => \Yii::t('skeeks/cms', 'Filter by photo'), 'hasQuantity' => \Yii::t('skeeks/cms', 'Filter by availability') ], [ 'multiple' => true, 'size' => 4 ]); */ ?> <?php if ($model->cmsContent) : ?> <?= $form->fieldSelectMulti($model, 'realatedProperties', \yii\helpers\ArrayHelper::map($model->cmsContent->cmsContentProperties, 'code', 'name')); ?> <?php else : ?> Дополнительные свойства появятся после сохранения настроек <?php endif; ?> <?= $form->fieldSetEnd(); ?>
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/filters/ContentElementFiltersWidget.php
src/cmsWidgets/filters/ContentElementFiltersWidget.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 25.05.2015 */ namespace skeeks\cms\cmsWidgets\filters; use skeeks\cms\base\Widget; use skeeks\cms\base\WidgetRenderable; use skeeks\cms\cmsWidgets\filters\models\SearchProductsModel; use skeeks\cms\components\Cms; use skeeks\cms\helpers\UrlHelper; use skeeks\cms\models\CmsContent; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsContentElementTree; use skeeks\cms\models\Search; use skeeks\cms\models\searchs\SearchRelatedPropertiesModel; use skeeks\cms\shop\models\ShopTypePrice; use yii\base\DynamicModel; use yii\data\ActiveDataProvider; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\helpers\Json; use yii\widgets\ActiveForm; /** * @property CmsContent $cmsContent; * * Class ShopProductFiltersWidget * @package skeeks\cms\cmsWidgets\filters */ class ContentElementFiltersWidget extends WidgetRenderable { //Навигация public $content_id; public $searchModelAttributes = []; public $realatedProperties = []; /** * @var bool Учитывать только доступные фильтры для текущей выборки */ public $onlyExistsFilters = false; /** * @var array (Массив ids записей, для показа только нужных фильтров) */ public $elementIds = []; /** * @var SearchProductsModel */ public $searchModel = null; /** * @var SearchRelatedPropertiesModel */ public $searchRelatedPropertiesModel = null; public static function descriptorConfig() { return array_merge(parent::descriptorConfig(), [ 'name' => 'Фильтры', ]); } public function init() { parent::init(); if (!$this->searchModelAttributes) { $this->searchModelAttributes = []; } if (!$this->searchModel) { $this->searchModel = new \skeeks\cms\cmsWidgets\filters\models\SearchProductsModel(); } if (!$this->searchRelatedPropertiesModel && $this->cmsContent) { $this->searchRelatedPropertiesModel = new SearchRelatedPropertiesModel(); $this->searchRelatedPropertiesModel->initCmsContent($this->cmsContent); } $this->searchModel->load(\Yii::$app->request->get()); if ($this->searchRelatedPropertiesModel) { $this->searchRelatedPropertiesModel->load(\Yii::$app->request->get()); } } public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'content_id' => \Yii::t('skeeks/cms', 'Content'), 'searchModelAttributes' => \Yii::t('skeeks/cms', 'Fields'), 'realatedProperties' => \Yii::t('skeeks/cms', 'Properties'), ]); } public function rules() { return ArrayHelper::merge(parent::rules(), [ [['content_id'], 'integer'], [['searchModelAttributes'], 'safe'], [['realatedProperties'], 'safe'], ]); } public function renderConfigForm(ActiveForm $form) { echo \Yii::$app->view->renderFile(__DIR__ . '/_form.php', [ 'form' => $form, 'model' => $this ], $this); } /** * @return CmsContent */ public function getCmsContent() { return CmsContent::findOne($this->content_id); } /** * @param ActiveDataProvider $activeDataProvider */ public function search(ActiveDataProvider $activeDataProvider) { if ($this->onlyExistsFilters) { /** * @var $query \yii\db\ActiveQuery */ $query = clone $activeDataProvider->query; $query->with = []; $query->select(['cms_content_element.id as mainId', 'cms_content_element.id as id'])->indexBy('mainId'); $ids = $query->asArray()->all(); $this->elementIds = array_keys($ids); } $this->searchModel->search($activeDataProvider); if ($this->searchRelatedPropertiesModel) { $this->searchRelatedPropertiesModel->search($activeDataProvider); } } /** * * Получение доступных опций для свойства * @param CmsContentProperty $property * @return $this|array|\yii\db\ActiveRecord[] */ public function getRelatedPropertyOptions($property) { $options = []; if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_ELEMENT) { $propertyType = $property->handler; if ($this->elementIds) { $availables = \skeeks\cms\models\CmsContentElementProperty::find() ->select(['value_enum']) ->indexBy('value_enum') ->andWhere(['element_id' => $this->elementIds]) ->andWhere(['property_id' => $property->id]) ->asArray() ->all(); $availables = array_keys($availables); } $options = \skeeks\cms\models\CmsContentElement::find() ->active() ->andWhere(['content_id' => $propertyType->content_id]); if ($this->elementIds) { $options->andWhere(['id' => $availables]); } $options = $options->select(['id', 'name'])->asArray()->all(); $options = \yii\helpers\ArrayHelper::map( $options, 'id', 'name' ); } elseif ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_LIST) { $options = $property->getEnums()->select(['id', 'value']); if ($this->elementIds) { $availables = \skeeks\cms\models\CmsContentElementProperty::find() ->select(['value_enum']) ->indexBy('value_enum') ->andWhere(['element_id' => $this->elementIds]) ->andWhere(['property_id' => $property->id]) ->asArray() ->all(); $availables = array_keys($availables); $options->andWhere(['id' => $availables]); } $options = $options->asArray()->all(); $options = \yii\helpers\ArrayHelper::map( $options, 'id', 'value' ); } return $options; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/filters/models/SearchProductsModel.php
src/cmsWidgets/filters/models/SearchProductsModel.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 25.05.2015 */ namespace skeeks\cms\cmsWidgets\filters\models; use skeeks\cms\base\Widget; use skeeks\cms\base\WidgetRenderable; use skeeks\cms\components\Cms; use skeeks\cms\helpers\UrlHelper; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsContentElementTree; use skeeks\cms\models\Search; use skeeks\cms\models\Tree; use skeeks\cms\shop\cmsWidgets\filters\ShopProductFiltersWidget; use yii\base\InvalidParamException; use yii\base\Model; use yii\data\ActiveDataProvider; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\helpers\Json; /** * Class SearchProductsModel * @package skeeks\cms\shop\cmsWidgets\filters\models */ class SearchProductsModel extends Model { public $image; public function rules() { return [ [['image'], 'string'], ]; } public function attributeLabels() { return [ 'image' => \Yii::t('skeeks/cms', 'With photo'), ]; } /** * @param $params * @return ActiveDataProvider * @throws \yii\base\InvalidConfigException */ public function search(ActiveDataProvider $dataProvider) { $query = $dataProvider->query; if ($this->image == Cms::BOOL_Y) { $query->andWhere([ 'or', ['!=', 'cms_content_element.image_id', null], ['!=', 'cms_content_element.image_id', ""], ]); } else { if ($this->image == Cms::BOOL_N) { $query->andWhere([ 'or', ['cms_content_element.image_id' => null], ['cms_content_element.image_id' => ""], ]); } } return $dataProvider; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/filters/views/default.php
src/cmsWidgets/filters/views/default.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 13.10.2015 */ /* @var $this yii\web\View */ /* @var $widget \skeeks\cms\shop\cmsWidgets\filters\ShopProductFiltersWidget */ ?> <? $this->registerJs(<<<JS (function(sx, $, _) { sx.classes.FiltersForm = sx.classes.Component.extend({ _init: function() {}, _onDomReady: function() { var self = this; this.JqueryForm = $("#sx-filters-form"); $("input, checkbox, select", this.JqueryForm).on("change", function() { self.JqueryForm.submit(); }); }, _onWindowReady: function() {} }); new sx.classes.FiltersForm(); })(sx, sx.$, sx._); JS ) ?> <?php $form = \skeeks\cms\base\widgets\ActiveForm::begin([ 'options' => [ 'id' => 'sx-filters-form', 'data-pjax' => '1' ], 'method' => 'get', 'action' => "/" . \Yii::$app->request->getPathInfo(), ]); ?> <?php if ($widget->searchModel) : ?> <?php if (in_array('image', $widget->searchModelAttributes)) : ?> <?= $form->fieldSelect($widget->searchModel, "image", [ '' => \skeeks\cms\shop\Module::t('skeeks/cms', 'Does not matter'), 'Y' => \skeeks\cms\shop\Module::t('skeeks/cms', 'With photo'), 'N' => \skeeks\cms\shop\Module::t('skeeks/cms', 'Without photo'), ]); ?> <?php endif; ?> <?php endif; ?> <?php if ($properties = $widget->searchRelatedPropertiesModel->properties) : ?> <?php foreach ($properties as $property) : ?> <?php if (in_array($property->code, $widget->realatedProperties)) : ?> <?php if (in_array($property->property_type, [ \skeeks\cms\relatedProperties\PropertyType::CODE_ELEMENT, \skeeks\cms\relatedProperties\PropertyType::CODE_LIST ])) : ?> <?= $form->field($widget->searchRelatedPropertiesModel, $property->code)->checkboxList( $widget->getRelatedPropertyOptions($property) , ['class' => 'sx-filters-checkbox-options']); ?> <?php elseif ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_NUMBER) : ?> <div class="form-group"> <label class="control-label"><?= $property->name; ?></label> <div class="row"> <div class="col-md-6"> <?= $form->field($widget->searchRelatedPropertiesModel, $widget->searchRelatedPropertiesModel->getAttributeNameRangeFrom($property->code))->textInput([ 'placeholder' => 'от' ])->label(false); ?> </div> <div class="col-md-6"> <?= $form->field($widget->searchRelatedPropertiesModel, $widget->searchRelatedPropertiesModel->getAttributeNameRangeTo($property->code))->textInput([ 'placeholder' => 'до' ])->label(false); ?> </div> </div> </div> <?php else : ?> <?php $propertiesValues = \skeeks\cms\models\CmsContentElementProperty::find()->select(['value'])->where([ 'property_id' => $property->id, 'element_id' => $widget->elementIds ])->all(); ?> <?php if ($propertiesValues) : ?> <div class="row"> <div class="col-md-12"> <?= $form->field($widget->searchRelatedPropertiesModel, $property->code)->dropDownList( \yii\helpers\ArrayHelper::merge(['' => ''], \yii\helpers\ArrayHelper::map( $propertiesValues, 'value', 'value' ))); ?> </div> </div> <?php endif; ?> <?php endif; ?> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> <button class="btn btn-primary"><?= \Yii::t('skeeks/cms', 'Apply'); ?></button> <?php \skeeks\cms\base\widgets\ActiveForm::end(); ?>
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/breadcrumbs/BreadcrumbsCmsWidget.php
src/cmsWidgets/breadcrumbs/BreadcrumbsCmsWidget.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 25.05.2015 */ namespace skeeks\cms\cmsWidgets\breadcrumbs; use skeeks\cms\base\WidgetRenderable; /** * Class breadcrumbs * @package skeeks\cms\cmsWidgets\Breadcrumbs */ class BreadcrumbsCmsWidget extends WidgetRenderable { public static function descriptorConfig() { return array_merge(parent::descriptorConfig(), [ 'name' => \Yii::t('skeeks/cms', 'Breadcrumbs') ]); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/text/TextCmsWidget.php
src/cmsWidgets/text/TextCmsWidget.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 25.05.2015 */ namespace skeeks\cms\cmsWidgets\text; use skeeks\cms\base\Widget; use skeeks\cms\widgets\formInputs\comboText\ComboTextInputWidget; use skeeks\yii2\form\fields\WidgetField; use yii\helpers\ArrayHelper; /** * Class TextCmsWidget * @package skeeks\cms\cmsWidgets\text */ class TextCmsWidget extends Widget { public $text = ''; protected $_obContent = ''; protected $_is_begin = false; public static function descriptorConfig() { return array_merge(parent::descriptorConfig(), [ 'name' => 'Текст', ]); } public static function begin($config = []) { $widget = parent::begin($config); $widget->_is_begin = true; ob_start(); ob_implicit_flush(false); return $widget; } public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'text' => 'Текст', ]); } public function rules() { return ArrayHelper::merge(parent::rules(), [ ['text', 'string'], ]); } /** * @return array */ public function getConfigFormFields() { return [ 'text' => [ 'class' => WidgetField::class, 'widgetClass' => ComboTextInputWidget::class, ], ]; } public function run() { if ($this->_is_begin) { $this->_obContent = ob_get_clean(); if (!$this->text) { $this->text = $this->_obContent; } } return $this->text; } /** * @return array */ public function getCallableData() { $attributes = parent::getCallableData(); if (!$attributes['attributes']['text']) { $attributes['attributes']['text'] = $this->_obContent; } return $attributes; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/cmsWidgets/tree/TreeCmsWidget.php
src/cmsWidgets/tree/TreeCmsWidget.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 25.05.2015 */ namespace skeeks\cms\cmsWidgets\tree; use skeeks\cms\backend\widgets\ActiveFormBackend; use skeeks\cms\base\WidgetRenderable; use skeeks\cms\models\CmsTree; use skeeks\cms\query\CmsActiveQuery; use skeeks\cms\widgets\formInputs\selectTree\SelectTreeInputWidget; use skeeks\yii2\form\fields\BoolField; use skeeks\yii2\form\fields\FieldSet; use skeeks\yii2\form\fields\FieldSetEnd; use skeeks\yii2\form\fields\NumberField; use skeeks\yii2\form\fields\SelectField; use skeeks\yii2\form\fields\WidgetField; use yii\caching\Dependency; use yii\caching\TagDependency; use yii\db\ActiveQuery; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; /** * * Example 1 * <?php * $widget = \skeeks\cms\cmsWidgets\tree\TreeCmsWidget::beginWidget('menu-top'); * $widget->descriptor->name = 'Главное верхнее меню'; * $widget->viewFile = '@app/views/widgets/TreeMenuCmsWidget/menu-top'; * $widget::end(); * ?> * * Example 2 * <?php * $widget = \skeeks\cms\cmsWidgets\tree\TreeCmsWidget::beginWidget('sub-catalog'); * $widget->descriptor->name = 'Подразделы каталога'; * $widget->viewFile = '@app/views/widgets/TreeMenuCmsWidget/sub-catalog-small'; * $widget->parent_tree_id = $model->id; * $widget->activeQuery->with('image'); * $widget::end(); * ?> * * Example 3 * <?php * $catalogTree = \skeeks\cms\models\CmsTree::find()->cmsSite()->joinWith('treeType as treeType')->andWhere(['treeType.code' => 'catalog'])->orderBy(['level' => SORT_ASC])->limit(1)->one(); * $config = []; * if ($catalogTree) { * $config['parent_tree_id'] = $catalogTree->id; * } * $widget = \skeeks\cms\cmsWidgets\tree\TreeCmsWidget::beginWidget('home-tree-slider', $config); * $widget->descriptor->name = 'Слайдер разделов'; * $widget->viewFile = '@app/views/widgets/TreeMenuCmsWidget/revolution-slider'; * $widget->is_has_image_only = true; * $widget->activeQuery->with('image'); * $widget::end(); * ?> * * @property CmsActiveQuery $activeQuery * * @author Semenov Alexander <semenov@skeeks.com> */ class TreeCmsWidget extends WidgetRenderable { /** * @var null */ public $limit = 200; /** * @var null */ public $parent_tree_id = null; /** * @var null */ public $is_active_only = true; /** * @var null */ public $is_has_image_only = false; /** * @var array */ public $tree_type_ids = []; /** * @var string */ public $viewFile = ''; /** * @var string */ public $cmsTreeClass = CmsTree::class; /** * Сортировка по умолчанию * @var string */ public $sorting_option = "priority"; /** * @var int */ public $sorting_direction = SORT_ASC; /** * @var bool */ public $is_cache = true; /** * @var bool */ public $is_cache_unique_for_user = false; public static function descriptorConfig() { return array_merge(parent::descriptorConfig(), [ 'name' => \Yii::t('skeeks/cms', 'Подразделы'), ]); } protected $_activeQuery = null; /** * @return CmsActiveQuery|null */ public function getActiveQuery() { if ($this->_activeQuery === null) { $class = $this->cmsTreeClass; $table = $class::tableName(); $this->_activeQuery = $class::find(); /** * @var $query CmsActiveQuery */ $query = $this->_activeQuery; $query->cmsSite(); if ($this->limit) { $query->limit($this->limit); } /** * */ if ($this->tree_type_ids) { $query->andWhere([$table.".tree_type_id" => $this->tree_type_ids]); } if ($this->parent_tree_id) { $query->andWhere([$table.'.pid' => $this->parent_tree_id]); } else { $query->andWhere([$table.'.level' => 1]); } if ($this->is_active_only) { $query->active(); } if ($this->is_has_image_only) { $query->andWhere(['is not', $table.'.image_id', null]); } $this->initSorting($query); } return $this->_activeQuery; } /** * @param ActiveQuery $query * @return $this */ public function initSorting(ActiveQuery $query) { $class = $this->cmsTreeClass; $table = $class::tableName(); $direction = $this->sorting_direction; if ($this->sorting_option) { if ($this->sorting_option == 'has_image') { $query->orderBy([$table.'.image_id' => (int)$direction]); } else { $query->orderBy([$table.'.'.$this->sorting_option => (int)$direction]); } } return $this; } public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'limit' => \Yii::t('skeeks/cms', 'Максимальное количество разделов'), 'is_active_only' => \Yii::t('skeeks/cms', 'Показывать только активные разделы?'), 'is_has_image_only' => \Yii::t('skeeks/cms', 'Показывать только разделы с фото?'), 'tree_type_ids' => \Yii::t('skeeks/cms', 'Типы разделов'), 'sorting_option' => \Yii::t('skeeks/cms', 'Параметр сортировки'), 'sorting_direction' => \Yii::t('skeeks/cms', 'Направление сортировки'), 'parent_tree_id' => \Yii::t('skeeks/cms', 'Корневой раздел'), ]); } public function attributeHints() { return array_merge(parent::attributeHints(), [ 'limit' => 'Задайте максимальное количество разделов, которое может отображаться в этом виджете', 'is_active_only' => 'Эта настройка включает отображение только активных разделов (скрытые разделы отображаться не будут!)', 'tree_type_ids' => 'Показывать разделы только выбранных типов, если ничего не указано то будут показаны разделы всех типов', 'parent_tree_id' => 'Если корневой раздел не задан, то будут отображаться разделы самого верхнего уровня', ]); } public function rules() { return ArrayHelper::merge(parent::rules(), [ ['parent_tree_id', 'integer'], ['sorting_option', 'string'], ['sorting_direction', 'integer'], ['tree_type_ids', 'safe'], ['is_has_image_only', 'boolean'], ['is_active_only', 'boolean'], ['limit', 'integer', 'max' => 400], ]); } /** * @return ActiveForm */ public function beginConfigForm() { return ActiveFormBackend::begin(); } /** * @return array */ public function getConfigFormFields() { $result = [ 'filters' => [ 'class' => FieldSet::class, 'name' => 'Фильтрация и количество', 'fields' => [ 'limit' => [ 'class' => NumberField::class, ], 'is_active_only' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'is_has_image_only' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'tree_type_ids' => [ 'class' => SelectField::class, 'items' => \yii\helpers\ArrayHelper::map( \skeeks\cms\models\CmsTreeType::find()->all(), 'id', 'name' ), 'multiple' => true, ], 'sorting_option' => [ 'class' => SelectField::class, 'items' => [ 'priority' => 'Приоритет', 'name' => 'Название', 'has_image' => 'Наличие картинки', ], ], 'sorting_direction' => [ 'class' => SelectField::class, 'items' => [ SORT_ASC => \Yii::t('skeeks/cms', 'ASC (from lowest to highest)'), SORT_DESC => \Yii::t('skeeks/cms', 'DESC (from highest to lowest)'), ], ], 'parent_tree_id' => [ 'class' => WidgetField::class, 'widgetClass' => SelectTreeInputWidget::class, 'widgetConfig' => [ 'isAllowNodeSelectCallback' => function ($tree) { /*if (in_array($tree->id, $childrents)) { return false; }*/ return true; }, 'treeWidgetOptions' => [ 'models' => CmsTree::findRoots()->cmsSite()->all(), ], ], ], ], ], ]; $result = ArrayHelper::merge($result, $this->_getConfigFormCache()); return $result; } /** * @return \yii\caching\ChainedDependency|Dependency */ public function getCacheDependency() { $dependency = parent::getCacheDependency(); $dependency->dependencies[] = new TagDependency([ 'tags' => [ (new CmsTree())->getTableCacheTagCmsSite(), ], ]); return $dependency; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/console/controllers/ImageController.php
src/console/controllers/ImageController.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\console\controllers; use skeeks\imagine\Image; use skeeks\cms\models\CmsStorageFile; use yii\base\Exception; use yii\db\Expression; use yii\helpers\ArrayHelper; use yii\helpers\Console; /** * @author Semenov Alexander <semenov@skeeks.com> */ class ImageController extends \yii\console\Controller { protected function _wait($time = 10) { for ($i = 0; $i <= $time; $i ++) { $else = $time - $i; $this->stdout("\tСтарт через {$else} сек...\n"); sleep(1); } } /** * @param $maxHeight Максимальная высота картинки * @param $maxFileSize Размер файла в МБ * @param $quantity Качество на выходе * @return void */ public function actionResizeOriginalImagesVertical($maxHeight = 1600, $maxFileSize = 1, $quantity = 95) { $query = CmsStorageFile::find() ->andWhere(['>', 'image_height', 'image_width']) ->andWhere(['>', 'image_height', $maxHeight]) ->andWhere(['>', 'size', 1024*1024*$maxFileSize]) ->orderBy(['size' => SORT_DESC]) ; if ($total = $query->count()) { $sizeQuery = clone $query; $sizeQuery->select(['sumsize' => new Expression('sum(size)')]); $data = $sizeQuery->asArray()->one(); $formatedSumSize = \Yii::$app->formatter->asShortSize((float)ArrayHelper::getValue($data, 'sumsize')); $this->stdout("Неоптимизированных картинок: {$total} шт. ({$formatedSumSize}) \n"); } else { $this->stdout("Неоптимизированных картинок нет\n"); return; } $this->_wait(5); /** * @var CmsStorageFile $storageFile */ foreach ($query->each(50) as $storageFile) { $fileRoot = $storageFile->getRootSrc(); $this->stdout("\tКартинка: {$storageFile->id}\n"); $this->stdout("\t\t{$fileRoot}\n"); $this->stdout("\t\tРазрешение: {$storageFile->image_width}x{$storageFile->image_height}\n"); $fileSize = filesize($fileRoot); $fileSizeFormated = \Yii::$app->formatter->asShortSize($fileSize); $this->stdout("\t\tРазмер: {$fileSizeFormated}\n"); $size = Image::getImagine()->open($fileRoot)->getSize(); $width = ($size->getWidth() * $maxHeight) / $size->getHeight(); $newWidth = (int)round($width); $newHeight = $maxHeight; $this->stdout("\t\tНовое разрешение: {$newWidth}x{$newHeight}\n"); Image::thumbnail($fileRoot, $newWidth, $newHeight)->save($fileRoot,[ 'jpeg_quality' => $quantity, 'webp_quality' => $quantity, ]); $newSize = Image::getImagine()->open($fileRoot)->getSize(); $storageFile->image_height = $newSize->getHeight(); $storageFile->image_width = $newSize->getWidth(); clearstatcache(); $fileSize = filesize($fileRoot); $fileSizeFormated = \Yii::$app->formatter->asShortSize($fileSize); $this->stdout("\t\tНовый размер файла: {$fileSizeFormated}\n"); $storageFile->size = $fileSize; if (!$storageFile->save()) { $error = "Не сохранились данные по новой картинке: " . print_r($storageFile->errors, true); //throw new Exception("Не сохранились данные по новой картинке: " . print_r($storageFile->errors, true)); $this->stdout("\t\t{$error}\n"); continue; } $this->stdout("\t\tsaved\n"); } } /** * Изменение размера у оригинальных картинок в хранилище * * @param int $maxWidth * @param int $maxHeight * * @throws Exception */ public function actionResizeOriginalImages($maxWidth = 1920, $maxHeight = 1200, $quantity = 100) { $query = CmsStorageFile::find() ->andWhere(['>', 'image_height', $maxHeight]) ->andWhere(['>', 'image_width', $maxWidth]) //->orderBy(['image_width' => SORT_DESC]) ->orderBy(['size' => SORT_DESC]) ; if ($total = $query->count()) { $sizeQuery = clone $query; $sizeQuery->select(['sumsize' => new Expression('sum(size)')]); $data = $sizeQuery->asArray()->one(); $formatedSumSize = \Yii::$app->formatter->asShortSize((float)ArrayHelper::getValue($data, 'sumsize')); $this->stdout("Неоптимизированных картинок: {$total} шт. ({$formatedSumSize}) \n"); } else { $this->stdout("Неоптимизированных картинок нет\n"); return; } $this->_wait(5); /** * @var CmsStorageFile $storageFile */ foreach ($query->each(50) as $storageFile) { $fileRoot = $storageFile->getRootSrc(); $this->stdout("\tКартинка: {$storageFile->id}\n"); $this->stdout("\t\t{$fileRoot}\n"); $this->stdout("\t\tРазрешение: {$storageFile->image_width}x{$storageFile->image_height}\n"); $fileSize = filesize($fileRoot); $fileSizeFormated = \Yii::$app->formatter->asShortSize($fileSize); $this->stdout("\t\tРазмер: {$fileSizeFormated}\n"); $size = Image::getImagine()->open($fileRoot)->getSize(); $height = ($size->getHeight() * $maxWidth) / $size->getWidth(); $newHeight = (int)round($height); $newWidth = $maxWidth; $this->stdout("\t\tНовое разрешение: {$newWidth}x{$newHeight}\n"); Image::thumbnail($fileRoot, $newWidth, $newHeight)->save($fileRoot,[ 'jpeg_quality' => $quantity, 'webp_quality' => $quantity, ]); $newSize = Image::getImagine()->open($fileRoot)->getSize(); $storageFile->image_height = $newSize->getHeight(); $storageFile->image_width = $newSize->getWidth(); clearstatcache(); $fileSize = filesize($fileRoot); $fileSizeFormated = \Yii::$app->formatter->asShortSize($fileSize); $this->stdout("\t\tНовый размер файла: {$fileSizeFormated}\n"); $storageFile->size = $fileSize; if (!$storageFile->save()) { $error = "Не сохранились данные по новой картинке: " . print_r($storageFile->errors, true); //throw new Exception("Не сохранились данные по новой картинке: " . print_r($storageFile->errors, true)); $this->stdout("\t\t{$error}\n"); continue; } $this->stdout("\t\tsaved\n"); } } /** * * Пересчет размеравсех файлов в хранилище * * @return $this * @throws Exception */ public function actionRecalculateFileSize() { $query = CmsStorageFile::find(); if ($total = $query->count()) { $this->stdout("Файлов в хранилище: {$total} \n"); } else { $this->stdout("Нет файлов в хранилище\n"); return ""; } clearstatcache(); /** * @var CmsStorageFile $storageFile */ foreach ($query->each(50) as $storageFile) { $fileRoot = $storageFile->getRootSrc(); $this->stdout("\tФайл: {$storageFile->id}\n"); $fileSize = filesize($fileRoot); if ($fileSize != $storageFile->size) { $oldSize = \Yii::$app->formatter->asShortSize($storageFile->size); $newSize = \Yii::$app->formatter->asShortSize($fileSize); $this->stdout("\t\tOld size: $oldSize\n", Console::FG_RED); $this->stdout("\t\tNew size: $newSize\n", Console::FG_RED); $storageFile->size = $fileSize; if (!$storageFile->save()) { throw new Exception("Не сохранились данные по Файлу: " . print_r($storageFile->errors, true)); } else { $this->stdout("\t\tsaved\n"); } } } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/console/controllers/UpdateController.php
src/console/controllers/UpdateController.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\console\controllers; use skeeks\cms\components\Cms; use skeeks\cms\models\CmsAgent; use skeeks\cms\models\CmsContent; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsContentElementProperty; use skeeks\cms\models\CmsContentProperty; use skeeks\cms\models\CmsContentProperty2content; use skeeks\cms\models\CmsSearchPhrase; use skeeks\cms\models\CmsTree; use skeeks\cms\models\CmsUser; use skeeks\cms\models\StorageFile; use skeeks\sx\Dir; use Yii; use yii\base\Event; use yii\console\Controller; use yii\console\controllers\HelpController; use yii\helpers\ArrayHelper; use yii\helpers\Console; use yii\helpers\FileHelper; /** * Class UpdateController * @package skeeks\cms\console\controllers */ class UpdateController extends Controller { /** * Update user name to first and last name */ public function actionUserNameToFirstName() { ini_set("memory_limit", "1G"); if (!CmsUser::find()->count()) { $this->stdout("Content not found!\n", Console::BOLD); return; } $this->stdout("1. Cms user name normalize!\n", Console::FG_YELLOW); /** * @var CmsUser $cmsUser */ foreach (CmsUser::find()->orderBy(['id' => SORT_ASC])->each(10) as $cmsUser) { $this->stdout("\t User: {$cmsUser->id}\n", Console::FG_YELLOW); if (!$cmsUser->_to_del_name) { $this->stdout("\t NOT found property: _to_del_name\n", Console::FG_YELLOW); continue; } $name = $cmsUser->_to_del_name; $nameData = explode(" ", $name); if (isset($nameData[0])) { $cmsUser->first_name = trim($nameData[0]); } if (isset($nameData[1])) { $cmsUser->last_name = trim($nameData[1]); } if (isset($nameData[2])) { $cmsUser->patronymic = trim($nameData[2]); } if ($cmsUser->save()) { $this->stdout("\t Updated name: {$cmsUser->name}\n", Console::FG_GREEN); } else { $this->stdout("\t NOT updated name: {$cmsUser->id}\n", Console::FG_RED); } } } /** * */ public function actionContentPropertyResave() { ini_set("memory_limit", "1G"); if (!$count = CmsContentElement::find()->count()) { $this->stdout("Content elements not found!\n", Console::BOLD); return; } $this->stdout("Content elements found: {$count}\n", Console::BOLD); /** * @var $element CmsContentElement */ foreach (CmsContentElement::find() //->orderBy(['id' => SORT_ASC]) ->each(10) as $element) { $this->stdout("\t Element: {$element->id}", Console::FG_YELLOW); if ($element->relatedPropertiesModel->save()) { $this->stdout(" - saved\n", Console::FG_GREEN); } else { $this->stdout(" - NOT saved\n", Console::FG_RED); } } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/console/controllers/InitController.php
src/console/controllers/InitController.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\console\controllers; use skeeks\cms\helpers\FileHelper; use yii\console\Controller; /** * Project SkeekS CMS initialization * * @package skeeks\cms\console\controllers */ class InitController extends Controller { public function actionIndex() { $conf = [ 'setWritable' => [ 'console/runtime', 'common/runtime', 'frontend/runtime', 'frontend/web/assets', ], 'setExecutable' => [ 'yii', ], ]; echo "\n Start initialization ...\n\n"; $callbacks = ['setCookieValidationKey', 'setWritable', 'setExecutable', 'createSymlink']; foreach ($callbacks as $callback) { if (!empty($conf[$callback])) { $this->$callback(ROOT_DIR, $conf[$callback]); } } echo "\n ... initialization completed.\n\n"; } function getFileList($root, $basePath = '') { $files = []; $handle = opendir($root); while (($path = readdir($handle)) !== false) { if ($path === '.git' || $path === '.svn' || $path === '.' || $path === '..') { continue; } $fullPath = "$root/$path"; $relativePath = $basePath === '' ? $path : "$basePath/$path"; if (is_dir($fullPath)) { $files = array_merge($files, $this->getFileList($fullPath, $relativePath)); } else { $files[] = $relativePath; } } closedir($handle); return $files; } function copyFile($root, $source, $target, &$all, $params) { if (!is_file($root . '/' . $source)) { echo " skip $target ($source not exist)\n"; return true; } if (is_file($root . '/' . $target)) { if (file_get_contents($root . '/' . $source) === file_get_contents($root . '/' . $target)) { echo " unchanged $target\n"; return true; } if ($all) { echo " overwrite $target\n"; } else { echo " exist $target\n"; echo " ...overwrite? [Yes|No|All|Quit] "; $answer = !empty($params['overwrite']) ? $params['overwrite'] : trim(fgets(STDIN)); if (!strncasecmp($answer, 'q', 1)) { return false; } else { if (!strncasecmp($answer, 'y', 1)) { echo " overwrite $target\n"; } else { if (!strncasecmp($answer, 'a', 1)) { echo " overwrite $target\n"; $all = true; } else { echo " skip $target\n"; return true; } } } } file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source)); return true; } echo " generate $target\n"; @mkdir(dirname($root . '/' . $target), 0777, true); file_put_contents($root . '/' . $target, file_get_contents($root . '/' . $source)); return true; } function setWritable($root, $paths) { foreach ($paths as $writable) { if (!is_dir("$root/$writable")) { echo " create dir and chmod 0777 $writable\n"; FileHelper::createDirectory("$root/$writable", 0777); } else { echo " chmod 0777 $writable\n"; @chmod("$root/$writable", 0777); } } } function setExecutable($root, $paths) { foreach ($paths as $executable) { echo " chmod 0755 $executable\n"; @chmod("$root/$executable", 0755); } } function setCookieValidationKey($root, $paths) { foreach ($paths as $file) { echo " generate cookie validation key in $file\n"; $file = $root . '/' . $file; $length = 32; $bytes = openssl_random_pseudo_bytes($length); $key = strtr(substr(base64_encode($bytes), 0, $length), '+/=', '_-.'); $content = preg_replace('/(("|\')cookieValidationKey("|\')\s*=>\s*)(""|\'\')/', "\\1'$key'", file_get_contents($file)); file_put_contents($file, $content); } } function createSymlink($root, $links) { foreach ($links as $link => $target) { echo " symlink " . $root . "/" . $target . " " . $root . "/" . $link . "\n"; //first removing folders to avoid errors if the folder already exists @rmdir($root . "/" . $link); @symlink($root . "/" . $target, $root . "/" . $link); } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/console/controllers/MigrateController.php
src/console/controllers/MigrateController.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\console\controllers; use skeeks\cms\models\User; use skeeks\cms\modules\admin\controllers\AdminController; use skeeks\cms\rbac\AuthorRule; use Yii; use yii\helpers\ArrayHelper; use yii\helpers\Console; use yii\helpers\FileHelper; /** * Working with the mysql database * * @package skeeks\cms\controllers */ class MigrateController extends \yii\console\controllers\MigrateController { protected $_runtimeMigrationPath = '@runtime/db-migrate'; /** * This method is invoked right before an action is to be executed (after all possible filters.) * It checks the existence of the [[migrationPath]]. * @param \yii\base\Action $action the action to be executed. * @return boolean whether the action should continue to be executed. */ public function beforeAction($action) { $this->migrationPath = \Yii::getAlias($this->_runtimeMigrationPath); $this->_copyMigrations(); return parent::beforeAction($action); } /** * @throws \Exception * @throws \yii\base\ErrorException * @throws \yii\base\Exception */ protected function _copyMigrations() { $this->stdout("Copy the migration files in a single directory\n", Console::FG_YELLOW); $tmpMigrateDir = \Yii::getAlias($this->_runtimeMigrationPath); FileHelper::removeDirectory($tmpMigrateDir); FileHelper::createDirectory($tmpMigrateDir); if (!is_dir($tmpMigrateDir)) { $this->stdout("Could not create a temporary directory migration\n"); die; } $this->stdout("\tCreated a directory migration\n"); if ($dirs = $this->_findMigrationDirs()) { foreach ($dirs as $path) { FileHelper::copyDirectory($path, $tmpMigrateDir); } } $this->stdout("\tThe copied files modules migrations\n"); $appMigrateDir = \Yii::getAlias("@console/migrations"); if (is_dir($appMigrateDir)) { FileHelper::copyDirectory($appMigrateDir, $tmpMigrateDir); } $this->stdout("\tThe copied files app migrations\n\n"); } /** * @return array */ private function _findMigrationDirs() { $result = []; foreach ($this->_findMigrationPossibleDirs() as $migrationPath) { if (is_dir($migrationPath)) { $result[] = $migrationPath; } } return $result; } /** * @return array */ private function _findMigrationPossibleDirs() { $result = []; foreach (\Yii::$app->extensions as $code => $data) { if ($data['alias']) { foreach ($data['alias'] as $code => $path) { $migrationsPath = $path . '/migrations'; $result[] = $migrationsPath; } } } return $result; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/console/controllers/UtilsController.php
src/console/controllers/UtilsController.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\console\controllers; use skeeks\cms\components\storage\ClusterLocal; use skeeks\cms\models\CmsAgent; use skeeks\cms\models\CmsContent; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsContentProperty; use skeeks\cms\models\CmsContentProperty2content; use skeeks\cms\models\CmsSearchPhrase; use skeeks\cms\models\CmsStorageFile; use skeeks\cms\models\CmsTree; use skeeks\cms\models\CmsUserPhone; use skeeks\cms\models\StorageFile; use skeeks\cms\shop\models\ShopCmsContentElement; use skeeks\cms\Skeeks; use yii\base\Exception; use yii\console\Controller; use yii\console\controllers\HelpController; use yii\db\Expression; use yii\helpers\ArrayHelper; use yii\helpers\Console; use yii\helpers\FileHelper; /** * Productivity SkeekS CMS * * @package skeeks\cms\console\controllers */ class UtilsController extends Controller { /** * Получение списка всех возможных консольных команд * Используется в console ssh для автокомплита */ public function actionAllCmd() { /** * @var $controllerHelp HelpController */ $controllerHelp = \Yii::$app->createController('help')[0]; $commands = $controllerHelp->getCommands(); foreach ($controllerHelp->getCommands() as $controller) { $subController = \Yii::$app->createController($controller)[0]; $actions = $controllerHelp->getActions($subController); if ($actions) { foreach ($actions as $actionId) { $commands[] = $controller."/".$actionId; } } }; $this->stdout(implode("\n", $commands)); } /** * Читка всех сгенерированных миниатюр */ public function actionClearAllThumbnails() { /** * @var $files StorageFile[] */ ini_set('memory_limit', '2048M'); if ($files = StorageFile::find()->count()) { /** * @var $file CmsStorageFile */ foreach (StorageFile::find()->orderBy(['id' => SORT_ASC])->each(100) as $file) { $this->stdout("{$file->id}"); if ($file->deleteTmpDir()) { $this->stdout(" - true\n", Console::FG_GREEN); } else { $this->stdout(" - false\n", Console::FG_RED); } } } } /*private $_dir_level = 0; private $_dir_current = 0; private function _clearStorageFilesDir($dir, $level) { $this->stdout("{$dir} - {$level}\n"); $dirs = FileHelper::findDirectories($dir); $files = FileHelper::findFiles($dir); if ($files) { foreach ($files as $filePath) { } } if ($dirs) { foreach ($dirs as $subDir) { $this->_clearStorageFilesDir($subDir, $level + 1); } } } public function _actionClearStorageFiles($isDelete = 0) { $cluster = \Yii::$app->storage->getCluster(); if ($cluster instanceof ClusterLocal) { if (!$cluster->rootBasePath) { throw new Exception("Не задана rootBasePath у " . $cluster->id); } $totalStorageSize = StorageFile::find() ->cluster($cluster->id) ->select(["id", 'total_size' => new Expression("SUM(size)")]) ->asArray() ->one(); print_r($totalStorageSize); die; $totalStorageFies = StorageFile::find() ->cluster($cluster->id) ->count(); $this->stdout("{$cluster->id}\n"); $this->stdout("Total files: {$totalStorageFies}\n"); $this->stdout("Total file size: {$totalStorageFies}\n"); $this->_clearStorageFilesDir($cluster->rootBasePath, $level = 1); } }*/ /** * Tree normalization */ public function actionNormalizeTree() { if (!CmsTree::find()->count()) { $this->stdout("Tree not found!\n", Console::BOLD); return; } $this->stdout("1. Tree normalize pids!\n", Console::FG_YELLOW); /** * @var CmsTree $tree */ foreach (CmsTree::find()->orderBy(['id' => SORT_ASC])->andWhere(['level' => 0])->each(10) as $tree) { $this->_normalizeTreePids($tree); } } protected function _normalizeTreePids(CmsTree $tree) { if ($tree->level == 0) { $this->stdout("\tStart normalize tree: {$tree->id} - {$tree->name}\n", Console::BOLD); if ((int)$tree->pids != (int)$tree->id) { if (\Yii::$app->db->createCommand()->update(CmsTree::tableName(), [ 'pids' => $tree->id, ], ['id' => $tree->id])->execute()) { $this->stdout("\t{$tree->id} - {$tree->name}: is normalized\n", Console::FG_GREEN); } else { $this->stdout("\t{$tree->id} - {$tree->name}: not save!\n", Console::FG_RED); return false; } } } else { $newPids = $tree->parent->pids."/".$tree->id; if ($newPids != $tree->pids) { if (\Yii::$app->db->createCommand()->update(CmsTree::tableName(), [ 'pids' => $newPids, ], ['id' => $tree->id])->execute()) { $this->stdout("\t{$tree->id} - {$tree->name}: is normalized\n", Console::FG_GREEN); } else { $this->stdout("\t{$tree->id} - {$tree->name}: not save!\n", Console::FG_RED); return false; } } } if ($tree->children) { foreach ($tree->children as $tree) { $this->_normalizeTreePids($tree); } } } /** * Tree normalization */ public function actionNormalizeContent() { if (!CmsContent::find()->count()) { $this->stdout("Content not found!\n", Console::BOLD); return; } $this->stdout("1. Tree normalize content!\n", Console::FG_YELLOW); /** * @var CmsContentProperty $cmsContentProperty */ foreach (CmsContentProperty::find()->orderBy(['id' => SORT_ASC])->each(10) as $cmsContentProperty) { $this->stdout("\t content property: {$cmsContentProperty->name}\n", Console::FG_YELLOW); if (!$cmsContentProperty->content_id) { continue; } if (!CmsContentProperty2content::find() ->where(['cms_content_id' => $cmsContentProperty->content_id]) ->andWhere(['cms_content_property_id' => $cmsContentProperty->id]) ->exists() ) { if ((new CmsContentProperty2content([ 'cms_content_id' => $cmsContentProperty->content_id, 'cms_content_property_id' => $cmsContentProperty->id, ]))->save()) { $this->stdout("\t Created: {$cmsContentProperty->name}\n", Console::FG_GREEN); } else { $this->stdout("\t NOT Created: {$cmsContentProperty->name}\n", Console::FG_RED); } } } } /** * Обновляет адреса страниц элементов контента * @param null $contentId */ public function actionUpdateContentElementCodes($contentId = null) { ini_set('memory_limit', '4095M'); // 4 GBs minus 1 MB $base_memory_usage = memory_get_usage(); $this->memoryUsage(memory_get_usage(), $base_memory_usage); $contentElementClass = CmsContentElement::class; if (class_exists(ShopCmsContentElement::class)) { $contentElementClass = ShopCmsContentElement::class; } $query = $contentElementClass::find()//->andWhere(['>', 'id', 202300]) ; if ($contentId) { $query->andWhere(['content_id' => $contentId]); } if (!$count = $query->count()) { $this->stdout("Content elements not found!\n", Console::BOLD); return; } $this->stdout("1. Found elements: {$count}!\n", Console::BOLD); foreach ($query->orderBy([ 'content_id' => SORT_ASC, 'id' => SORT_ASC, ])->each(10) as $cmsContentElement) { $this->stdout("\t{$cmsContentElement->id}: {$cmsContentElement->name}\n"); try { $cmsContentElement->code = ''; if (!$cmsContentElement->save()) { $this->stdout("\tError:".print_r($cmsContentElement->errors, true)."\n", Console::FG_RED); sleep(5); } } catch (\Exception $e) { $this->stdout("\tError:".$e->getMessage()."\n", Console::FG_RED); sleep(5); } //$this->stdout($this->memoryUsage(memory_get_usage(), $base_memory_usage) . "\n"); } } public function memoryUsage($usage, $base_memory_usage) { return \Yii::$app->formatter->asSize($usage - $base_memory_usage); } /** * Deleting content items * * @param null $contentId content id */ public function actionRemoveContentElements($contentId = null) { $query = CmsContentElement::find()->cmsSite(); if ($contentId) { $query->andWhere(['content_id' => $contentId]); } if (!$count = $query->count()) { $this->stdout("Content elements not found!\n", Console::BOLD); return; } $this->stdout("1. Found elements: {$count}!\n", Console::BOLD); foreach ($query->orderBy([ 'content_id' => SORT_ASC, 'id' => SORT_ASC, ])->each(10) as $cmsContentElement) { $this->stdout("\t{$cmsContentElement->id}: {$cmsContentElement->name}"); if ($cmsContentElement->delete()) { $this->stdout(" - deleted\n", Console::FG_GREEN); } else { $this->stdout(" - NOT deleted\n", Console::FG_RED); } } } /** * Приведение телефонов пользователей к единому формату * * @return void */ public function actionNormalizeUserPhones() { $q = CmsUserPhone::find(); $this->stdout("Found: {$q->count()}!\n", Console::BOLD); $this->stdout("Wait: 5 sec....\n", Console::BOLD); sleep(5); /** * @var */ foreach ($q->each() as $userPhone) { $this->stdout("\t{$userPhone->value}\n"); $phone = $userPhone->value; $first = substr($phone, 0, 1); if ($first == 8) { $newPhone = substr($phone, 1, strlen($phone)); $newPhone = trim("+7".$newPhone); $userPhone->value = $newPhone; $this->stdout("\t\t new -> {$newPhone}\n"); } elseif ($first == 9) { $newPhone = trim("+7".$phone); $userPhone->value = $newPhone; $this->stdout("\t\t new -> {$newPhone}\n"); } if (!$userPhone->save()) { $this->stdout("\t\tошибка!\n"); } } } /** * Удаляет файлы которые остались в хранилище но нет в базе хранилища * * @return void */ public function actionRemoveEmptyDirs($onlyCheck = 1) { /*set_time_limit(0); ini_set("memory_limit", "50G");*/ Skeeks::unlimited(); $clusters = \Yii::$app->storage->getClusters(); foreach ($clusters as $cluster) { $this->stdout("Хранилище: {$cluster->name}", Console::BG_BLUE); $this->stdout("\n"); if (!$cluster instanceof ClusterLocal) { $this->stdout("Это не локальное хранилище!\n"); continue; } if ($onlyCheck != 1) { $this->stdout("Запуск скрипта через 5 сек."); sleep(1); $this->stdout(" (5"); sleep(1); $this->stdout(" 4"); sleep(1); $this->stdout(" 3"); sleep(1); $this->stdout(" 2"); sleep(1); $this->stdout(" 1)\n\n"); sleep(1); } $dirs = FileHelper::findDirectories($cluster->rootBasePath, ['recursive' => true]); $realFileSizes = 0; foreach ($dirs as $dirPath) { if (!is_dir($dirPath)) { continue; } /*$this->stdout("--------------\n");*/ $this->stdout("{$dirPath}\n"); $files = FileHelper::findFiles($dirPath, ['recursive' => true]); if ($files) { $realFileSizesTmp = 0; foreach ($files as $filePath) { /*$this->stdout("\t\t{$filePath}\n", Console::FG_RED); $this->stdout("\t\t\t" . \Yii::$app->formatter->asShortSize(filesize($filePath)) . "\n", Console::FG_GREEN);*/ $realFileSizesTmp = $realFileSizesTmp + filesize($filePath); } $realFileSizes = $realFileSizes + $realFileSizesTmp; $this->stdout("\t" . \Yii::$app->formatter->asShortSize($realFileSizesTmp) . "\n", Console::FG_GREEN); /*$this->stdout("\t" . \Yii::$app->formatter->asShortSize($realFileSizesTmp) . "\n", Console::FG_GREEN); $this->stdout("\ttotal: " . \Yii::$app->formatter->asShortSize($realFileSizes) . "\n", Console::FG_GREEN); if ($realFileSizes > 1024*5) { die; }*/ } else { if ($onlyCheck == 1) { $this->stdout("\tУдалить пустая\n", Console::FG_RED); } else { FileHelper::removeDirectory($dirPath); $this->stdout("\tУдалить пустая\n", Console::FG_RED); } } } //TODO: размер считается некорректно //$this->stdout("\tРазмер всех файлов: " . \Yii::$app->formatter->asShortSize($realFileSizes) . "\n", Console::FG_GREEN); } } /** * Удаляет файлы которые остались в хранилище но нет в базе хранилища * * @return void */ public function actionRemoveFilesNotStorage($onlyCheck = 1) { //Skeeks::unlimited(); Skeeks::unlimited(); $clusters = \Yii::$app->storage->getClusters(); foreach ($clusters as $cluster) { /*$this->stdout("cluster: {$cluster->id}\n"); $this->stdout("cluster: {$cluster->rootBasePath}\n");*/ //sleep(3); $totalStorageSize = StorageFile::find() /*->cluster($cluster->id)*/ ->andWhere(['cluster_id' => $cluster->id]) ->select(["id", 'total_size' => new Expression("SUM(size)")]) ->asArray() ->one(); $totalStorageFies = StorageFile::find() /*->cluster($cluster->id)*/ ->andWhere(['cluster_id' => $cluster->id]) ->count(); $this->stdout("Хранилище: {$cluster->name}", Console::BG_BLUE); $this->stdout("\n"); $this->stdout("Total files: {$totalStorageFies}\n"); if (ArrayHelper::getValue($totalStorageSize, "total_size")) { $this->stdout("Total files size: " . \Yii::$app->formatter->asShortSize(ArrayHelper::getValue($totalStorageSize, "total_size")) . "\n\n"); } else { $this->stdout("Total files size: " . 0 . "\n\n"); } if (!$cluster instanceof ClusterLocal) { $this->stdout("Это не локальное хранилище!\n"); continue; } if ($onlyCheck != 1) { $this->stdout("Запуск скрипта через 5 сек."); sleep(1); $this->stdout(" (5"); sleep(1); $this->stdout(" 4"); sleep(1); $this->stdout(" 3"); sleep(1); $this->stdout(" 2"); sleep(1); $this->stdout(" 1)\n\n"); sleep(1); } $counterFiles = 0; $counterFileSizes = 0; $needDeleteFiles = 0; $needDeleteFileSizes = 0; $realFileSizes = 0; $firstLevel = FileHelper::findFiles($cluster->rootBasePath, ['recursive' => true]); foreach ($firstLevel as $filePath) { $realFileSizes = $realFileSizes + filesize($filePath); //$this->stdout("{$filePath}\n"); //Нормализация пути к файлу $clusterFilePath = str_replace($cluster->rootBasePath, "", $filePath); $tmpExplode = explode("/", $clusterFilePath); foreach ($tmpExplode as $c => $f) { if (!$f) { unset($tmpExplode[$c]); } } $clusterFilePath = implode("/", $tmpExplode); //Проверка уровня в хранилище $arr = explode("/", $clusterFilePath); $fileDirLevel = count($arr) - 1; $arr = explode("/", $clusterFilePath); if ($fileDirLevel < $cluster->directoryLevel) { $counterFiles = $counterFiles + 1; $counterFileSizes = $counterFileSizes + filesize($filePath); $this->stdout("\t{$clusterFilePath}\n"); $this->stdout("\t\tМеньше уровня удалить!\n"); $needDeleteFiles = $needDeleteFiles + 1; $needDeleteFileSizes = $needDeleteFileSizes + filesize($filePath); if ($onlyCheck == 1) { } else { if (!unlink($filePath)) { throw new Exception("Не удаляется файл"); } } } elseif ($fileDirLevel > $cluster->directoryLevel) { /*$this->stdout("\t{$clusterFilePath} " . $fileDirLevel . "\n"); $this->stdout("\t\tБольше уровня не трогать!\n");*/ } else { $counterFiles = $counterFiles + 1; $counterFileSizes = $counterFileSizes + filesize($filePath); /*$this->stdout("\t{$clusterFilePath} " . $fileDirLevel . "\n"); $this->stdout("\t\tПроверить в базе!\n");*/ $cmsStorageFile = StorageFile::find() ->andWhere(['cluster_id' => $cluster->id]) ->andWhere(['cluster_file' => $clusterFilePath]) //->clusterFile($cluster->id, $clusterFilePath) ->one(); if (!$cmsStorageFile) { $this->stdout("\t{$clusterFilePath}\n"); $this->stdout("\t\tНет в базе удалить!\n"); $needDeleteFiles = $needDeleteFiles + 1; $needDeleteFileSizes = $needDeleteFileSizes + filesize($filePath); if ($onlyCheck == 1) { } else { if (!unlink($filePath)) { throw new Exception("Не удаляется файл"); } } } } } $this->stdout("Total files (data from db): {$totalStorageFies}\n"); $this->stdout("Total files size (data from db): " . \Yii::$app->formatter->asShortSize(ArrayHelper::getValue($totalStorageSize, "total_size")) . "\n\n"); $this->stdout("Calc total files (all, with thumbs): " . \Yii::$app->formatter->asShortSize($realFileSizes) . "\n"); $this->stdout("Calc total files: {$counterFiles}\n"); $this->stdout("Calc files size: " . \Yii::$app->formatter->asShortSize($counterFileSizes) . "\n\n"); $this->stdout("Calc files for delete: {$needDeleteFiles}\n"); $this->stdout("Calc files size for delete: " . \Yii::$app->formatter->asShortSize($needDeleteFileSizes) . "\n\n"); //check $deltaFiles = $counterFiles - $needDeleteFiles; $deltaFilesSizes = $counterFileSizes - $needDeleteFileSizes; $this->stdout("Calc after delete: {$deltaFiles}\n"); $this->stdout("Calc after delete: " . \Yii::$app->formatter->asShortSize($deltaFilesSizes) . "\n\n"); if ($deltaFiles == $totalStorageFies) { $this->stdout("Данные по количеству сходятся, можно запускать скритп!\n", Console::FG_GREEN); } if ($deltaFilesSizes == ArrayHelper::getValue($totalStorageSize, "total_size")) { $this->stdout("Данные по размеру сходятся, можно запускать скритп!\n", Console::FG_GREEN); } } } /** * Удаляет файлы которые остались в хранилище но нет в базе хранилища * * @return void */ public function _actionRemoveFilesNotStorage($onlyCheck = 1) { $clusters = \Yii::$app->storage->getClusters(); foreach ($clusters as $cluster) { $this->stdout("cluster: {$cluster->id}\n"); $this->stdout("cluster: {$cluster->rootBasePath}\n"); //sleep(3); $totalStorageSize = StorageFile::find() ->cluster($cluster->id) ->select(["id", 'total_size' => new Expression("SUM(size)")]) ->asArray() ->one(); $totalStorageFies = StorageFile::find() ->cluster($cluster->id) ->count(); $this->stdout("{$cluster->id}\n"); $this->stdout("Total files: {$totalStorageFies}\n"); $this->stdout("Total files size: " . \Yii::$app->formatter->asShortSize(ArrayHelper::getValue($totalStorageSize, "total_size")) . "\n\n"); $this->stdout("Запуск скрипта через 5 сек."); sleep(1); $this->stdout(" (5"); sleep(1); $this->stdout(" 4"); sleep(1); $this->stdout(" 3"); sleep(1); $this->stdout(" 2"); sleep(1); $this->stdout(" 1)\n\n"); sleep(1); $counterFiles = 0; $counterFileSizes = 0; $needDeleteFiles = 0; $needDeleteFileSizes = 0; $firstLevel = FileHelper::findDirectories($cluster->rootBasePath, ['recursive' => false]); foreach ($firstLevel as $firstLevelDir) { $this->stdout("\t{$firstLevelDir}\n"); continue; $secondLevel = FileHelper::findDirectories($firstLevelDir, ['recursive' => false]); if ($secondLevel) { foreach ($secondLevel as $secondLevelDir) { $this->stdout("\t\t{$secondLevelDir}\n"); $thirdLevel = FileHelper::findDirectories($secondLevelDir, ['recursive' => false]); if ($thirdLevel) { foreach ($thirdLevel as $thirdLevelDir) { $this->stdout("\t\t\t{$thirdLevelDir}\n"); $files = FileHelper::findFiles($thirdLevelDir, ['recursive' => false]); if ($files) { foreach ($files as $file) { $cluster_file_name = str_replace($cluster->rootBasePath . "/", "", $file); $cmsStorageFile = StorageFile::find()->clusterFile($cluster->id, $cluster_file_name)->one(); if (!$cmsStorageFile) { $this->stdout("\t\t\t\t{$file}\n"); $this->stdout("\t\t\t\tУдалить!\n"); $this->stdout("\t\t\t\t{$cluster->id}\n"); $this->stdout("\t\t\t\t{$cluster_file_name}\n"); unlink($file); } else { //$this->stdout("\t\t\t\tНЕ Удалять!\n"); } } } else { $this->stdout("\t\t\tNo Files!!!\n"); FileHelper::removeDirectory($thirdLevelDir); } } } /*if ($files) { foreach ($files as $file) { $this->stdout("\t\t\t{$file}\n"); } }*/ } } } } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/console/controllers/CacheController.php
src/console/controllers/CacheController.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\console\controllers; use skeeks\cms\helpers\FileHelper; use yii\helpers\ArrayHelper; use yii\helpers\Console; /** * Allows you to flush cache. * * see list of available components to flush: * * yii cms/cache * * flush particular components specified by their names: * * yii cms/cache/flush first second third * * flush all cache components that can be found in the system * * yii cms/cache/flush-all * * * yii cms/cache/flush-runtimes * yii cms/cache/flush-assets * yii cms/cache/flush-tmp-config * * Note that the command uses cache components defined in your console application configuration file. If components * configured are different from web application, web application cache won't be cleared. In order to fix it please * duplicate web application cache components in console config. You can use any component names. * * @author Alexander Makarov <sam@rmcreative.ru> * @author Mark Jebri <mark.github@yandex.ru> * @since 2.0 */ class CacheController extends \yii\console\controllers\CacheController { /** * Clear rintimes directories */ public function actionFlushRuntimes() { $paths = ArrayHelper::getValue(\Yii::$app->cms->tmpFolderScheme, 'runtime'); $this->stdout("Clear runtimes directories\n", Console::FG_YELLOW); if ($paths) { foreach ($paths as $path) { $realPath = \Yii::getAlias($path); $this->stdout("\tClear runtime directory: {$realPath}\n"); FileHelper::removeDirectory(\Yii::getAlias($path)); FileHelper::createDirectory(\Yii::getAlias($path)); } } } /** * Clear asstes directories */ public function actionFlushAssets() { $paths = ArrayHelper::getValue(\Yii::$app->cms->tmpFolderScheme, 'assets'); $this->stdout("Clear assets directories\n", Console::FG_YELLOW); if ($paths) { foreach ($paths as $path) { $realPath = \Yii::getAlias($path); $this->stdout("\tClear asset directory: {$realPath}\n"); FileHelper::removeDirectory(\Yii::getAlias($path)); FileHelper::createDirectory(\Yii::getAlias($path)); } } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/Storage.php
src/components/Storage.php
<?php /** * Storage * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 17.10.2014 * @since 1.0.0 */ namespace skeeks\cms\components; /** * Class Storage * @package skeeks\cms\components */ class Storage extends storage\Storage { }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/User.php
src/components/User.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components; /** * @author Semenov Alexander <semenov@skeeks.com> */ class User extends \yii\web\User { public $preLoginSessionName = '__preLogin'; public function preLogin($user) { \Yii::$app->session->set($this->preLoginSessionName, $user->id); return $this; } public function getPreLoginIdentity() { } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/Adult.php
src/components/Adult.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components; use skeeks\cms\assets\AdultAsset; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsTree; use skeeks\cms\web\View; use yii\base\Component; use yii\bootstrap\Modal; use yii\helpers\Json; use yii\helpers\Url; /** * @property boolean $isAllowAdult * * @author Semenov Alexander <semenov@skeeks.com> */ class Adult extends Component { /** * @var string */ public $sesstion_adult_name = 'IS_ALLOW_ADULT'; /** * @var bool */ protected $_is_blocked = false; /** * @var bool */ protected $_is_registered_blocked_asset = false; /** * @var string */ public $is_adult_css_class = "sx-adult"; /** * @var string */ public $blocked_btn_text = '<span class="sx-full-text"><i class="far fa-eye-slash"></i> Товар для взрослых</span><span class="sx-mini-text">18+</span>'; /** * @var string */ public $blocked_asset = AdultAsset::class; /** * @return bool */ public function getIsAllowAdult() { return (bool)\Yii::$app->session->get($this->sesstion_adult_name, false); } /** * @param int $value * @return $this */ public function setIsAllowAdult(bool $value = true) { \Yii::$app->session->set($this->sesstion_adult_name, (int) $value); return $this; } /** * @param CmsContentElement|CmsTree $model * @return bool */ public function isBlocked($model) { //Если элемент или раздел не имеет признака для взрослых, то он не заблокирован if (!$model->is_adult) { return false; } //Если это авторизованный пользователь то показываем ему контент для взрослых if (!\Yii::$app->user->isGuest) { return false; } //Если пользователь уже согласился с тем что ему доступен контент 18+ if ($this->isAllowAdult) { return false; } $this->_is_blocked = true; //1 рез регистрируются скрипты и css if ($this->_is_registered_blocked_asset === false) { $this->_is_registered_blocked_asset = true; if (!\Yii::$app->request->isPjax || !\Yii::$app->request->isAjax) { $assetClass = $this->blocked_asset; $assetClass::register(\Yii::$app->view); $jsData = Json::encode([ 'backend' => Url::to(['/cms/ajax/adult']) ]); \Yii::$app->view->registerJs(<<<JS new sx.classes.Adult({$jsData}); JS ); \Yii::$app->view->on(View::EVENT_BEGIN_BODY, function ($e) { $modal = Modal::begin([ 'options' => [ 'id' => 'sx-adult-modal', 'class' => 'sx-adult-modal', ], 'header' => 'Подтвердите свой возраст', 'toggleButton' => false, ]); echo <<<HTML <p>Данный раздел предназначен только для посетителей, достигших возраста 18 лет!</p> <p><button class="btn btn-primary sx-btn-yes">Да, мне есть 18 лет</button> <button class="btn btn-secondary sx-btn-no">Нет</button></p> HTML; $modal::end(); }); } } //todo: тут надо проверить дал ли гость согласие на 18+ return true; } /** * @param CmsContentElement|CmsTree $model * @return string */ public function renderCssClass($model) { if ($this->isBlocked($model)) { return $this->is_adult_css_class; } return ""; } /** * @param $model * @return string */ public function renderBlocked($model) { if ($this->isBlocked($model)) { return <<<HTML <div class="sx-adult-block"> <div class="sx-adult-blur"></div> <div href="#" class="btn btn-default sx-adult-block-text"> {$this->blocked_btn_text} </div> </div> HTML ; } return ""; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/UpaBackendComponent.php
src/components/UpaBackendComponent.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link https://skeeks.com/ * @copyright (c) 2010 SkeekS * @date 11.03.2017 */ namespace skeeks\cms\components; use skeeks\cms\backend\BackendComponent; use yii\helpers\Url; use yii\web\Application; /** * Class UpaBackendComponent * @package skeeks\cms\upa */ class UpaBackendComponent extends BackendComponent { /** * @var string */ public $controllerPrefix = "upa"; /** * @var array */ public $urlRule = [ 'urlPrefix' => '~upa', ]; /*protected $_menu = [ 'data' => [ 'personal' => [ 'name' => 'Настройки', 'items' => [ [ 'url' => ['/personal-info/index'], 'name' => 'Личные настройки', ], ], ], ] ];*/ public function _run() { \Yii::$app->on(Application::EVENT_BEFORE_ACTION, function () { //Для работы с системой управления сайтом, будем требовать от пользователя реальные данные if (\Yii::$app->user->isGuest === false) { if (!in_array(\Yii::$app->controller->action->uniqueId, [ 'cms/upa-personal/password', ])) { $user = \Yii::$app->user->identity; if (!$user->password_hash && \Yii::$app->cms->pass_is_need_change) { \Yii::$app->response->redirect(Url::to(['/cms/upa-personal/password'])); } } if (\Yii::$app->cms->is_need_user_data) { if (!in_array(\Yii::$app->controller->uniqueId, [ 'admin/error', ]) && !in_array(\Yii::$app->controller->action->uniqueId, [ 'cms/upa-personal/password', 'cms/upa-personal/update', ]) ) { $user = \Yii::$app->user->identity; foreach (\Yii::$app->cms->is_need_user_data as $code) { if (!$user->{$code}) { \Yii::$app->response->redirect(Url::to(['/cms/upa-personal/update'])); return true; } } } } } }); return parent::_run(); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/LegalComponent.php
src/components/LegalComponent.php
<?php /** * Breadcrumbs * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 15.01.2015 * @since 1.0.0 */ namespace skeeks\cms\components; use skeeks\cms\assets\CmsAsset; use skeeks\cms\backend\widgets\ActiveFormBackend; use skeeks\cms\base\Component; use skeeks\cms\base\components\Descriptor; use skeeks\cms\models\Site; use skeeks\cms\models\TreeType; use skeeks\cms\widgets\formInputs\comboText\ComboTextInputWidget; use skeeks\yii2\form\fields\FieldSet; use skeeks\yii2\form\fields\HtmlBlock; use skeeks\yii2\form\fields\TextareaField; use skeeks\yii2\form\fields\TextField; use skeeks\yii2\form\fields\WidgetField; use yii\helpers\ArrayHelper; use yii\helpers\Url; /** * @property string $textCookie; * @property string $textPersonalData; * @property string $textPrivacyPolicy; * @property string $textCookieAlert; * * Class LegalComponent * @package skeeks\cms\components */ class LegalComponent extends Component { public $operator = ""; public $site = ""; public $email = ""; public $details = ""; public $doc_privacy_policy = ""; /** * @var string */ public $doc_cookie = ""; public $doc_personal_data = ""; public $cookie_message_template = ""; public $default_cookie_message_template = "Мы используем файлы <a href='{url_cookie}'>cookie</a>.<br>Продолжая находиться на сайте, вы соглашаетесь с этим.<br><a href='#' class='sx-trigger-allow-cookie'>Принимаю</a>"; /** * Можно задать название и описание компонента * @return array */ static public function descriptorConfig() { return array_merge(parent::descriptorConfig(), [ 'name' => "Правовая информация", 'description' => 'Все что нужно для соблюдения закона 152-ФЗ', 'image' => [ CmsAsset::class, 'img/legal.jpg', ], ]); } public function rules() { return ArrayHelper::merge(parent::rules(), [ [ [ 'operator', 'site', 'email', 'details', 'doc_privacy_policy', 'doc_cookie', 'doc_personal_data', 'cookie_message_template', ], 'string', ], [ [ 'email', ], 'email', 'enableIDN' => true ], ]); } public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'operator' => "Оператор", 'site' => "Веб сайт", 'email' => "E-mail", 'details' => "Реквизиты организации, ИП или физ. лица", 'doc_privacy_policy' => "Политика конфиденциальности", 'doc_cookie' => "Политика обработки файлов cookie", 'doc_personal_data' => "Политика в отношении обработки персональных данных", 'cookie_message_template' => "Сообщение об использовании cookie", ]); } public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ 'operator' => "Используется в документах, подставляется в нужные места", 'site' => "Используется в документах, подставляется в нужные места", 'email' => "Используется в документах, подставляется в нужные места", 'details' => "Используется в документах, подставляется в нужные места", 'doc_privacy_policy' => "Вы можете самостоятельно сформировать этот документ или не заполняйте это поле и тогда документ будет сгенерирован автоматически.", 'doc_cookie' => "Вы можете самостоятельно сформировать этот документ или не заполняйте это поле и тогда документ будет сгенерирован автоматически.", 'doc_personal_data' => "Вы можете самостоятельно сформировать этот документ или не заполняйте это поле и тогда документ будет сгенерирован автоматически.", 'cookie_message_template' => "{url_cookie} - ссылка на страницу документа о cookie<br>sx-trigger-allow-cookie - обязательный класс для кнопки согласия<br>", ]); } /** * @return ActiveForm */ public function beginConfigForm() { return ActiveFormBackend::begin(); } /** * @return array */ public function getConfigFormFields() { $url1 = \yii\helpers\Url::to(['/cms/legal/privacy-policy']); $url2 = \yii\helpers\Url::to(['/cms/legal/cookie']); $url3 = \yii\helpers\Url::to(['/cms/legal/personal-data']); return [ 'main' => [ 'class' => FieldSet::class, 'name' => "Данные подставляемые в документы", 'fields' => [ 'operator' => [ 'class' => TextField::class, 'elementOptions' => [ 'placeholder' => "ИП Котов Владимир Петрович", ], ], 'site' => [ 'class' => TextField::class, 'elementOptions' => [ 'placeholder' => "skeeks.com", ], ], 'email' => [ 'class' => TextField::class, 'elementOptions' => [ 'placeholder' => "legal@skeeks.com", ], ], 'details' => [ 'class' => TextareaField::class, 'elementOptions' => [ 'placeholder' => "ИП Семенов Александр Сергеевич — Индивидуальный предприниматель Семенов Александр Сергеевич; ОГРНИП 316504400051472, ИНН 400403130765; юридический адрес — 141501, Московская область, г. Солнечногорск, Молодежный проезд, д. 3, кв. 103", ], ], [ 'class' => HtmlBlock::class, 'content' => <<<HTML <div class="sx-block"> <p>Заполнив данные в полях выше, сайт сгенерирует необходимые документы для соблюдейния закона 152-ФЗ и подставит эти данные в эти документы.</p> <ul class="list-unstyled sx-col-menu"> <li><a href="{$url1}" target="_blank" data-pjax="0">Политика конфиденциальности</a></li> <li><a href="{$url2}" target="_blank" data-pjax="0">Политика обработки файлов cookie</a></li> <li><a href="{$url2}" target="_blank" data-pjax="0">Политика в отношении обработки персональных данных</a></li> </ul> </div> HTML , ], ], ], 'docs' => [ 'class' => FieldSet::class, 'name' => "Документы", 'elementOptions' => [ 'isOpen' => false, ], 'fields' => [ 'doc_privacy_policy' => [ 'class' => WidgetField::class, 'widgetClass' => ComboTextInputWidget::class, ], 'doc_cookie' => [ 'class' => WidgetField::class, 'widgetClass' => ComboTextInputWidget::class, ], 'doc_personal_data' => [ 'class' => WidgetField::class, 'widgetClass' => ComboTextInputWidget::class, ], ] ], 'additinal' => [ 'class' => FieldSet::class, 'name' => "Дополнительно", 'elementOptions' => [ 'isOpen' => false, ], 'fields' => [ 'cookie_message_template' => [ 'class' => TextareaField::class, 'elementOptions' => [ 'placeholder' => "Мы используем файлы <a href='{url_cookie}'>cookie</a>. Продолжая находиться на сайте, вы соглашаетесь с этим.<br><a href='#' class='sx-trigger-allow-cookie'>Принимаю</a>", ], ], ] ], ]; } public $template_privacy_policy = <<<TEXT <p>Политика в отношении обработки персональных данных </p> <h2>1. Общие положения </h2> <p>Настоящая политика обработки персональных данных составлена в соответствии с требованиями Федерального закона от 27.07.2006. №152-ФЗ &laquo;О персональных данных&raquo; (далее - Закон о персональных данных) и определяет порядок обработки персональных данных и меры по обеспечению безопасности персональных данных, предпринимаемые &quot;{operator}&quot; (далее &ndash; Оператор). </p> <p>1.1. Оператор ставит своей важнейшей целью и условием осуществления своей деятельности соблюдение прав и свобод человека и гражданина при обработке его персональных данных, в том числе защиты прав на неприкосновенность частной жизни, личную и семейную тайну. </p> <p>1.2. Настоящая политика Оператора в отношении обработки персональных данных (далее &ndash; Политика) применяется ко всей информации, которую Оператор может получить о посетителях веб-сайта {site}. </p> <h2>2. Основные понятия, используемые в Политике </h2> <p>2.1. Автоматизированная обработка персональных данных &ndash; обработка персональных данных с помощью средств вычислительной техники. </p> <p>2.2. Блокирование персональных данных &ndash; временное прекращение обработки персональных данных (за исключением случаев, если обработка необходима для уточнения персональных данных). </p> <p>2.3. Веб-сайт &ndash; совокупность графических и информационных материалов, а также программ для ЭВМ и баз данных, обеспечивающих их доступность в сети интернет по сетевому адресу {site}. </p> <p>2.4. Информационная система персональных данных &mdash; совокупность содержащихся в базах данных персональных данных, и обеспечивающих их обработку информационных технологий и технических средств. </p> <p>2.5. Обезличивание персональных данных &mdash; действия, в результате которых невозможно определить без использования дополнительной информации принадлежность персональных данных конкретному Пользователю или иному субъекту персональных данных. </p> <p>2.6. Обработка персональных данных &ndash; любое действие (операция) или совокупность действий (операций), совершаемых с использованием средств автоматизации или без использования таких средств с персональными данными, включая сбор, запись, систематизацию, накопление, хранение, уточнение (обновление, изменение), извлечение, использование, передачу (распространение, предоставление, доступ), обезличивание, блокирование, удаление, уничтожение персональных данных. </p> <p>2.7. Оператор &ndash; государственный орган, муниципальный орган, юридическое или физическое лицо, самостоятельно или совместно с другими лицами организующие и (или) осуществляющие обработку персональных данных, а также определяющие цели обработки персональных данных, состав персональных данных, подлежащих обработке, действия (операции), совершаемые с персональными данными. </p> <p>2.8. Персональные данные &ndash; любая информация, относящаяся прямо или косвенно к определенному или определяемому Пользователю веб-сайта Оператора. </p> <p>2.9. Персональные данные, разрешенные субъектом персональных данных для распространения, - персональные данные, доступ неограниченного круга лиц к которым предоставлен субъектом персональных данных путем дачи согласия на обработку персональных данных, разрешенных субъектом персональных данных для распространения в порядке, предусмотренном Законом о персональных данных (далее - персональные данные, разрешенные для распространения). </p> <p>2.10. Пользователь &ndash; любой посетитель веб-сайта Оператора. </p> <p>2.11. Предоставление персональных данных &ndash; действия, направленные на раскрытие персональных данных определенному лицу или определенному кругу лиц. </p> <p>2.12. Распространение персональных данных &ndash; любые действия, направленные на раскрытие персональных данных неопределенному кругу лиц (передача персональных данных) или на ознакомление с персональными данными неограниченного круга лиц, в том числе обнародование персональных данных в средствах массовой информации, размещение в информационно-телекоммуникационных сетях или предоставление доступа к персональным данным каким-либо иным способом. </p> <p>2.13. Трансграничная передача персональных данных &ndash; передача персональных данных на территорию иностранного государства органу власти иностранного государства, иностранному физическому или иностранному юридическому лицу. </p> <p>2.14. Уничтожение персональных данных &ndash; любые действия, в результате которых персональные данные уничтожаются безвозвратно с невозможностью дальнейшего восстановления содержания персональных данных в информационной системе персональных данных и (или) уничтожаются материальные носители персональных данных. </p> <h2>3. Основные права и обязанности Оператора </h2> <p>3.1. Оператор имеет право: </p> <p>&ndash; получать от субъекта персональных данных достоверные информацию и/или документы, содержащие персональные данные; </p> <p>&ndash; в случае отзыва субъектом персональных данных согласия на обработку персональных данных Оператор вправе продолжить обработку персональных данных без согласия субъекта персональных данных при наличии оснований, указанных в Законе о персональных данных; </p> <p>&ndash; самостоятельно определять состав и перечень мер, необходимых и достаточных для обеспечения выполнения обязанностей, предусмотренных Законом о персональных данных и принятыми в соответствии с ним нормативными правовыми актами, если иное не предусмотрено Законом о персональных данных или другими федеральными законами. </p> <p>3.2. Оператор обязан: </p> <p>&ndash; предоставлять субъекту персональных данных по его просьбе информацию, касающуюся обработки его персональных данных; </p> <p>&ndash; организовывать обработку персональных данных в порядке, установленном действующим законодательством РФ; </p> <p>&ndash; отвечать на обращения и запросы субъектов персональных данных и их законных представителей в соответствии с требованиями Закона о персональных данных; </p> <p>&ndash; сообщать в уполномоченный орган по защите прав субъектов персональных данных по запросу этого органа необходимую информацию в течение 30 дней с даты получения такого запроса; </p> <p>&ndash; публиковать или иным образом обеспечивать неограниченный доступ к настоящей Политике в отношении обработки персональных данных; </p> <p>&ndash; принимать правовые, организационные и технические меры для защиты персональных данных от неправомерного или случайного доступа к ним, уничтожения, изменения, блокирования, копирования, предоставления, распространения персональных данных, а также от иных неправомерных действий в отношении персональных данных; </p> <p>&ndash; прекратить передачу (распространение, предоставление, доступ) персональных данных, прекратить обработку и уничтожить персональные данные в порядке и случаях, предусмотренных Законом о персональных данных; </p> <p>&ndash; исполнять иные обязанности, предусмотренные Законом о персональных данных. </p> <h2>4. Основные права и обязанности субъектов персональных данных </h2> <p>4.1. Субъекты персональных данных имеют право: </p> <p>&ndash; получать информацию, касающуюся обработки его персональных данных, за исключением случаев, предусмотренных федеральными законами. Сведения предоставляются субъекту персональных данных Оператором в доступной форме, и в них не должны содержаться персональные данные, относящиеся к другим субъектам персональных данных, за исключением случаев, когда имеются законные основания для раскрытия таких персональных данных. Перечень информации и порядок ее получения установлен Законом о персональных данных; </p> <p>&ndash; требовать от оператора уточнения его персональных данных, их блокирования или уничтожения в случае, если персональные данные являются неполными, устаревшими, неточными, незаконно полученными или не являются необходимыми для заявленной цели обработки, а также принимать предусмотренные законом меры по защите своих прав; </p> <p>&ndash; выдвигать условие предварительного согласия при обработке персональных данных в целях продвижения на рынке товаров, работ и услуг; </p> <p>&ndash; на отзыв согласия на обработку персональных данных; </p> <p>&ndash; обжаловать в уполномоченный орган по защите прав субъектов персональных данных или в судебном порядке неправомерные действия или бездействие Оператора при обработке его персональных данных; </p> <p>&ndash; на осуществление иных прав, предусмотренных законодательством РФ. </p> <p>4.2. Субъекты персональных данных обязаны: </p> <p>&ndash; предоставлять Оператору достоверные данные о себе; </p> <p>&ndash; сообщать Оператору об уточнении (обновлении, изменении) своих персональных данных. </p> <p>4.3. Лица, передавшие Оператору недостоверные сведения о себе, либо сведения о другом субъекте персональных данных без согласия последнего, несут ответственность в соответствии с законодательством РФ. </p> <p>5. Оператор может обрабатывать следующие персональные данные Пользователя </p> <p>5.1. Фамилия, имя, отчество. </p> <p>5.2. Электронный адрес. </p> <p>5.3. Номера телефонов. </p> <p>5.4. Год, месяц, дата и место рождения. </p> <p>5.5. Адрес </p> <p>5.5. Также на сайте происходит сбор и обработка обезличенных данных о посетителях (в т.ч. файлов &laquo;cookie&raquo;) с помощью сервисов интернет-статистики (Яндекс Метрика и других). </p> <p>5.6. Вышеперечисленные данные далее по тексту Политики объединены общим понятием Персональные данные. </p> <p>5.7. Обработка специальных категорий персональных данных, касающихся расовой, национальной принадлежности, политических взглядов, религиозных или философских убеждений, интимной жизни, Оператором не осуществляется. </p> <p>5.8. Обработка персональных данных, разрешенных для распространения, из числа специальных категорий персональных данных, указанных в ч. 1 ст. 10 Закона о персональных данных, допускается, если соблюдаются запреты и условия, предусмотренные ст. 10.1 Закона о персональных данных. </p> <p>5.9. Согласие Пользователя на обработку персональных данных, разрешенных для распространения, оформляется отдельно от других согласий на обработку его персональных данных. При этом соблюдаются условия, предусмотренные, в частности, ст. 10.1 Закона о персональных данных. Требования к содержанию такого согласия устанавливаются уполномоченным органом по защите прав субъектов персональных данных. </p> <p>5.9.1 Согласие на обработку персональных данных, разрешенных для распространения, Пользователь предоставляет Оператору непосредственно. </p> <p>5.9.2 Оператор обязан в срок не позднее трех рабочих дней с момента получения указанного согласия Пользователя опубликовать информацию об условиях обработки, о наличии запретов и условий на обработку неограниченным кругом лиц персональных данных, разрешенных для распространения. </p> <p>5.9.3 Передача (распространение, предоставление, доступ) персональных данных, разрешенных субъектом персональных данных для распространения, должна быть прекращена в любое время по требованию субъекта персональных данных. Данное требование должно включать в себя фамилию, имя, отчество (при наличии), контактную информацию (номер телефона, адрес электронной почты или почтовый адрес) субъекта персональных
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
true
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/ConsoleComponent.php
src/components/ConsoleComponent.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 01.11.2015 */ namespace skeeks\cms\components; use yii\base\Component; /** * Class ConsoleComponent * @package skeeks\cms\components */ class ConsoleComponent extends Component { /** * @param $cmd * @return string */ public function execute($cmd) { if (function_exists('system')) { return $this->executeSystem($cmd); } else { list($output, $error, $code) = $this->executeProcOpen($cmd); return trim($output); } } /** * @param $command * @return string */ public function executeSystem($command) { if (function_exists('system')) { ob_start(); @system($command); $result = ob_get_clean(); $result = trim($result); return $result; } return ""; } /** * @param $command * @return array */ public function executeProcOpen($command) { $descriptors = array( 0 => array("pipe", "r"), // stdin - read channel 1 => array("pipe", "w"), // stdout - write channel 2 => array("pipe", "w"), // stdout - error channel 3 => array("pipe", "r"), // stdin - This is the pipe we can feed the password into ); $process = @proc_open($command, $descriptors, $pipes); if (!is_resource($process)) { die("Can't open resource with proc_open."); } // Nothing to push to input. fclose($pipes[0]); $output = stream_get_contents($pipes[1]); fclose($pipes[1]); $error = stream_get_contents($pipes[2]); fclose($pipes[2]); // TODO: Write passphrase in pipes[3]. fclose($pipes[3]); // Close all pipes before proc_close! $code = proc_close($process); return array($output, $error, $code); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/Breadcrumbs.php
src/components/Breadcrumbs.php
<?php /** * Breadcrumbs * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 15.01.2015 * @since 1.0.0 */ namespace skeeks\cms\components; use skeeks\cms\base\components\Descriptor; use skeeks\cms\models\Site; use skeeks\cms\models\Tree; use skeeks\cms\models\TreeType; use yii\base\Component; /** * Class Cms * @package skeeks\cms\components */ class Breadcrumbs extends Component { /** * @var array */ public $parts = []; public function init() { parent::init(); } /** * @param array $data * @return $this */ public function append($data) { if (is_array($data)) { $this->parts[] = $data; } else { if (is_string($data)) { $this->parts[] = [ 'name' => $data ]; } } return $this; } /** * @param Tree $tree * @return $this */ public function setPartsByTree(Tree $tree) { $parents = $tree->parents; $parents[] = $tree; foreach ($parents as $tree) { $this->append([ 'name' => $tree->name, 'url' => $tree->url, 'data' => [ 'model' => $tree ], ]); } return $this; } public function createBase($baseData = []) { if (!$baseData) { $baseData = [ 'name' => \Yii::t('yii', 'Home'), 'url' => '/' ]; } $this->parts = []; $this->append($baseData); return $this; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/Imaging.php
src/components/Imaging.php
<?php /** * Imaging * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 11.12.2014 * @since 1.0.0 */ namespace skeeks\cms\components; use skeeks\cms\components\imaging\Filter; use skeeks\cms\components\imaging\filters\Thumbnail; use skeeks\cms\components\imaging\Preview; use skeeks\cms\components\storage\ClusterLocal; use skeeks\cms\components\storage\SkeeksSuppliersCluster; use skeeks\cms\helpers\Image; use skeeks\cms\models\StorageFile; use yii\base\Component; use yii\helpers\ArrayHelper; /** * Class Imaging * @package skeeks\cms\components */ class Imaging extends Component { /** * @var array Расширения файлов с которыми работают фильтры. Может и не совсем правильно указывать их тут... но пока будет так. */ public $extensions = [ "jpg", "png", "jpeg", "webp", "gif" ]; /** * @var string Соль подмешивается к параметрам */ public $sold = "sold_for_check_params"; /** * Константа для разбора URL - это некая метка, с этого момента идет указание фильтра */ const THUMBNAIL_PREFIX = "sx-filter__"; const STORAGE_FILE_PREFIX = "sx-o-file__"; const DEFAULT_THUMBNAIL_FILENAME = "sx-file"; //TODO: подумать над этим /*public $previewFilters = [ 'micro' => [ 'local' => [ 'class' => Thumbnail::class, ], 'sx' => [ 'class' => Thumbnail::class, ] ], 'small' => [ 'local' => [ 'class' => Thumbnail::class, ], 'sx' => [ 'class' => Thumbnail::class, ] ], 'medium' => [ 'local' => [ 'class' => Thumbnail::class, ], 'sx' => [ 'class' => Thumbnail::class, ] ], 'big' => [ 'local' => [ 'class' => Thumbnail::class, ], 'sx' => [ 'class' => Thumbnail::class, ] ], ];*/ /** * @param StorageFile $image * @param Filter $filter * @param $nameForSave * @param $isWebP * @return Preview|void */ public function getPreview(StorageFile $image = null, Filter $filter, $nameForSave = '', $isWebP = null) { if (!$image) { return new Preview([ 'src' => Image::getCapSrc(), ]); } if ($image->cluster instanceof ClusterLocal) { $data = $filter->getDimensions($image); $data['src'] = $this->thumbnailUrlOnRequest($image->src, $filter, $nameForSave, $isWebP); return new Preview($data); } if ($image->cluster instanceof SkeeksSuppliersCluster) { $data = $filter->getDimensions($image); $data['src'] = (string) ArrayHelper::getValue($image->sx_data, "previews.{$filter->sx_preview}.src", ""); return new Preview($data); } return new Preview([ 'width' => $image->image_width, 'height' => $image->image_height, 'src' => $image->absoluteSrc, ]); } /** * Собрать URL на thumbnail, который будет сгенерирован автоматически в момент запроса. * * @deprecated * * @param $originalSrc Путь к оригинальному изображению * @param Filter $filter Объект фильтр, который будет заниматься преобразованием * @param string $nameForSave Название для сохраненеия файла (нужно для сео) * @param null|boolean $isWebP Если передано null - настройки будут взяты из настроек сайта; true - не важно какие настройки картика будет webp; false - картинка не изменит расширение * @return string */ public function thumbnailUrlOnRequest($originalSrc, Filter $filter, $nameForSave = '', $isWebP = null) { $originalSrc = (string)$originalSrc; $extension = static::getExtension($originalSrc); if (!$extension) { return $originalSrc; } if ($isWebP === null) { if (isset(\Yii::$app->seo)) { //Если параметр не передан принудительно, то нужно взять из настроек сайта if (isset(\Yii::$app->mobileDetect) && \Yii::$app->mobileDetect->isDesktop) { $isWebP = (bool) \Yii::$app->seo->is_webp; } else { $isWebP = (bool) \Yii::$app->seo->is_mobile_webp; } } } $outExtension = null; if ($isWebP === true) { $outExtension = "webp"; } if ($outExtension === null) { $outExtension = $extension; } if (!$this->isAllowExtension($extension)) { return $originalSrc; } if (!$nameForSave) { $nameForSave = static::DEFAULT_THUMBNAIL_FILENAME; } $params = []; if ($filter->getConfig()) { $params = $filter->getConfig(); } if ($outExtension != $extension) { $params['ext'] = $extension; } $replacePart = DIRECTORY_SEPARATOR . static::THUMBNAIL_PREFIX . $filter->id . ($params ? DIRECTORY_SEPARATOR . $this->getParamsCheckString($params) : "") . DIRECTORY_SEPARATOR . $nameForSave; $imageSrcResult = str_replace('.' . $extension, $replacePart . '.' . $outExtension, $originalSrc); if ($params) { $imageSrcResult = $imageSrcResult . '?' . http_build_query($params); } return $imageSrcResult; } /** * @param $extension * @return bool */ public function isAllowExtension($extension) { return (bool)in_array(strtolower($extension), $this->extensions); } /** * @param $filePath * @return string|bool */ public static function getExtension($filePath) { $parts = explode(".", $filePath); $extension = end($parts); if (!$extension) { return false; } //Убираются гет параметры $extension = explode("?", $extension); $extension = $extension[0]; return $extension; } /** * Проверочная строка параметров. * * @param array $params * @return string */ public function getParamsCheckString($params = []) { if ($params) { return md5($this->sold . http_build_query($params)); } return ""; } /** * @depricated * * @param $imageSrc * @param Filter $filter */ public function getImagingUrl($imageSrc, Filter $filter) { return $this->thumbnailUrlOnRequest($imageSrc, $filter); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/Cms.php
src/components/Cms.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 27.03.2015 */ namespace skeeks\cms\components; use skeeks\cms\assets\CmsAsset; use skeeks\cms\backend\widgets\SelectModelDialogStorageFileSrcWidget; use skeeks\cms\base\Module; use skeeks\cms\helpers\ComposerHelper; use skeeks\cms\helpers\FileHelper; use skeeks\cms\models\CmsCallcheckProvider; use skeeks\cms\models\CmsExtension; use skeeks\cms\models\CmsLang; use skeeks\cms\models\CmsSite; use skeeks\cms\models\CmsSmsProvider; use skeeks\cms\models\CmsUser; use skeeks\cms\models\Site; use skeeks\cms\models\Tree; use skeeks\cms\models\TreeType; use skeeks\cms\rbac\CmsManager; use skeeks\cms\relatedProperties\PropertyType; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeBool; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeElement; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeFile; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeList; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeListMulti; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeNumber; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeRadioList; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeSelect; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeSelectMulti; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeStorageFile; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeString; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeText; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeTextarea; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeTextInput; use skeeks\cms\relatedProperties\propertyTypes\PropertyTypeTree; use skeeks\cms\relatedProperties\userPropertyTypes\UserPropertyTypeColor; use skeeks\cms\relatedProperties\userPropertyTypes\UserPropertyTypeComboText; use skeeks\cms\relatedProperties\userPropertyTypes\UserPropertyTypeDate; use skeeks\cms\relatedProperties\userPropertyTypes\UserPropertyTypeSelectFile; use skeeks\yii2\form\fields\BoolField; use skeeks\yii2\form\fields\FieldSet; use skeeks\yii2\form\fields\NumberField; use skeeks\yii2\form\fields\SelectField; use skeeks\yii2\form\fields\WidgetField; use Yii; use yii\base\Event; use yii\base\InvalidParamException; use yii\console\Application; use yii\helpers\ArrayHelper; use yii\helpers\Url; use yii\web\UserEvent; use yii\web\View; /** * @property Tree $currentTree * * @property CmsLang[] $languages * * @property string $version * @property string $homePage * @property string $cmsName * * @property \skeeks\cms\modules\admin\Module $moduleAdmin * @property \skeeks\cms\Module $moduleCms * @property CmsLang $cmsLanguage * @property PropertyType[] $relatedHandlers * @property array $relatedHandlersDataForSelect * * @property CmsSmsProvider $smsProvider * @property CmsCallcheckProvider $callcheckProvider * @property string $afterAuthUrl * * @package skeeks\cms\components */ class Cms extends \skeeks\cms\base\Component { public $after_auth_url = ['/cms/upa-personal/view', 'is_default' => 1]; /** * Разршение на доступ к персональной части */ const UPA_PERMISSION = 'cms-upa-permission'; const BOOL_Y = "Y"; const BOOL_N = "N"; private static $_huck = 'Z2VuZXJhdG9y'; /** * @var string E-Mail администратора сайта (отправитель по умолчанию). */ public $adminEmail = 'admin@skeeks.com'; /** * @var string Это изображение показывается в тех случаях, когда не найдено основное. */ public $noImageUrl; /** * @var string Это изображение показывается в тех случаях, когда не найдено основное. */ public $image1px; /** * @var array */ public $registerRoles = [ CmsManager::ROLE_USER, ]; /** * Авторизация на сайте разрешена только с проверенными email * @var bool */ public $auth_only_email_is_approved = 0; /** * @var int */ public $email_approved_key_length = 32; /** * @var int */ public $approved_key_is_letter = 1; //После регистрации пользователю будут присвоены эти роли /** * @var string язык по умолчанию */ public $languageCode = ""; /** * @var int Reset password token one hour later */ public $passwordResetTokenExpire = 3600; /** * @var int */ public $pass_required_length = 8; public $pass_required_need_number = 1; public $pass_required_need_uppercase = 0; public $pass_required_need_lowercase = 1; public $pass_required_need_specialChars = 0; public $pass_is_need_change = 1; public $is_need_user_data = []; public $is_allow_auth_by_email = 1; public $auth_submit_code_always = 0; /** * @var int */ public $tree_max_code_length = 64; /** * @var int */ public $element_max_code_length = 48; /** * Время последней активности когда считается что пользователь онлайн * @var int */ public $userOnlineTime = 60; //1 минута public $modelsMap = [ ]; static public function descriptorConfig() { return array_merge(parent::descriptorConfig(), [ //'name' => \Yii::t('skeeks/mail', 'Mailer'), 'image' => [CmsAsset::class, 'img/box-en.svg'], ]); } /** * @return string */ public function getAfterAuthUrl() { return Url::to($this->after_auth_url); } /** * Схема временных папок * Чистятся в момент нажатия на кнопку чистки временных файлов * * @var array */ public $tmpFolderScheme = [ 'runtime' => [ '@frontend/runtime', '@console/runtime', ], 'assets' => [ '@webroot/assets', ], ]; protected $_languages = null; /** * @var Tree */ protected $_tree = null; private $_relatedHandlers = []; /*public function renderConfigFormFields(ActiveForm $form) { echo \Yii::$app->view->renderFile(__DIR__.'/cms/_form.php', [ 'form' => $form, 'model' => $this, ], $this); }*/ /** * @return CmsSite * @deprecated */ public function getSite() { return \Yii::$app->skeeks->site; } public function getLanguages() { if ($this->_languages === null) { $this->_languages = CmsLang::find()->active()->orderBy(['priority' => SORT_ASC])->indexBy('code')->all(); } return (array)$this->_languages; } public function init() { parent::init(); //Название проекта. if (\Yii::$app->skeeks->site) { \Yii::$app->name = \Yii::$app->skeeks->site->name; } //Язык if ($this->languageCode) { \Yii::$app->language = $this->languageCode; } else { $this->languageCode = \Yii::$app->language; } $this->relatedHandlers = ArrayHelper::merge([ PropertyTypeText::class => [ 'class' => PropertyTypeText::class, ], PropertyTypeNumber::class => [ 'class' => PropertyTypeNumber::class, ], /*PropertyTypeRange::class => [ 'class' => PropertyTypeRange::class, ],*/ PropertyTypeBool::class => [ 'class' => PropertyTypeBool::class, ], PropertyTypeList::class => [ 'class' => PropertyTypeList::class, ], PropertyTypeTree::class => [ 'class' => PropertyTypeTree::class, ], PropertyTypeElement::class => [ 'class' => PropertyTypeElement::class, ], PropertyTypeStorageFile::class => [ 'class' => PropertyTypeStorageFile::class, ], UserPropertyTypeDate::class => [ 'class' => UserPropertyTypeDate::class, ], UserPropertyTypeComboText::class => [ 'class' => UserPropertyTypeComboText::class, ], UserPropertyTypeColor::class => [ 'class' => UserPropertyTypeColor::class, ], UserPropertyTypeSelectFile::class => [ 'class' => UserPropertyTypeSelectFile::class, ], ], $this->relatedHandlers); if (\Yii::$app instanceof Application) { } else { //web init if (!$this->noImageUrl) { $this->noImageUrl = CmsAsset::getAssetUrl('img/image-not-found.jpg'); } //web init if (!$this->image1px) { //$this->image1px = CmsAsset::getAssetUrl('img/1px.jpg'); $this->image1px = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAAtJREFUGFdjYAACAAAFAAGq1chRAAAAAElFTkSuQmCC"; } \Yii::$app->view->on(View::EVENT_BEGIN_PAGE, function (Event $e) { if (!\Yii::$app->request->isAjax && !\Yii::$app->request->isPjax) { \Yii::$app->response->getHeaders()->setDefault('X-Powered-CMS', $this->cmsName." {$this->homePage}"); /** * @var $view View */ $view = $e->sender; if (!isset($view->metaTags[self::$_huck])) { $view->registerMetaTag([ "name" => base64_decode(self::$_huck), "content" => $this->cmsName." — {$this->homePage}", ], self::$_huck); } if (!isset($view->metaTags['cmsmagazine'])) { $view->registerMetaTag([ "name" => 'cmsmagazine', "content" => "7170fe3a42c6f80cd95fd8bce765333d", ], 'cmsmagazine'); } $view->registerLinkTag([ 'rel' => 'icon', 'type' => \Yii::$app->skeeks->site->faviconType, 'href' => \Yii::$app->skeeks->site->faviconUrl, ]); } }); \Yii::$app->user->on(\yii\web\User::EVENT_AFTER_LOGIN, function (UserEvent $e) { $e->identity->logged_at = \Yii::$app->formatter->asTimestamp(time()); $e->identity->save(false); if (\Yii::$app->admin->requestIsAdmin) { \Yii::$app->user->identity->updateLastAdminActivity(); } }); } } public function rules() { return ArrayHelper::merge(parent::rules(), [ [['adminEmail', 'noImageUrl', 'languageCode'], 'string'], [['adminEmail'], 'email'], [['adminEmail'], 'email'], [['registerRoles'], 'safe'], [['auth_only_email_is_approved'], 'integer'], [['email_approved_key_length'], 'integer'], [['approved_key_is_letter'], 'integer'], [['is_need_user_data'], 'safe'], [['pass_is_need_change'], 'integer'], [['is_allow_auth_by_email'], 'integer'], [['auth_submit_code_always'], 'integer'], [['pass_required_length'], 'integer'], [['pass_required_need_number'], 'integer'], [['pass_required_need_uppercase'], 'integer'], [['pass_required_need_lowercase'], 'integer'], [['pass_required_need_specialChars'], 'integer'], ]); } public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'adminEmail' => 'Основной Email Администратора сайта', 'noImageUrl' => 'Изображение заглушка', 'languageCode' => 'Язык по умолчанию', 'registerRoles' => 'При регистрации добавлять в группу', 'auth_only_email_is_approved' => 'Разрешить авторизацию на сайте только с подтвержденными email?', 'email_approved_key_length' => 'Длина проверочного кода', 'approved_key_is_letter' => 'Проверочный код содержит буквы?', 'auth_submit_code_always' => 'Всегда отправлять проверочный код на email или телефон', 'is_allow_auth_by_email' => 'Разрешить авторизацию по Email', 'pass_is_need_change' => 'Требовать установки постоянного пароля?', 'is_need_user_data' => 'Требовать от пользователя заполнения этих данных.', 'pass_required_length' => 'Минимальная длина пароля', 'pass_required_need_number' => 'Пароль должен содержать хотя бы одну цифру', 'pass_required_need_uppercase' => 'Пароль должен содержать хотя бы одну заглавную букву', 'pass_required_need_lowercase' => 'Пароль должен содержать хотя бы одну строчную букву', 'pass_required_need_specialChars' => 'Пароль должен содержать хотя бы один спецсимвол', ]); } public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ 'adminEmail' => 'E-Mail администратора сайта. Этот email будет отображаться как отправитель, в отправленных письмах с сайта.', 'noImageUrl' => 'Это изображение показывается в тех случаях, когда не найдено основное.', 'registerRoles' => 'Так же после созданию пользователя, ему будут назначены, выбранные группы.', 'auth_only_email_is_approved' => 'Если эта опция включена то пользователь, который не подтвердил свой email не сможет авторизоваться на сайте.', 'pass_is_need_change' => 'Если авторизация произошла через код подтверждения (телефон, email), то после авторизации будет предолжено установить постоянный пароль.', 'is_need_user_data' => 'После авторизации будет предолжено указать эти данные.', 'auth_submit_code_always' => 'Постоянный пароль не спрашивается, всегда отправляется сообщение на email или телефон.', ]); } /** * @return array */ public function getConfigFormFields() { return [ 'template' => [ 'class' => FieldSet::class, 'name' => \Yii::t('skeeks/cms', 'Main'), 'fields' => [ 'adminEmail', 'noImageUrl' => [ 'class' => WidgetField::class, 'widgetClass' => SelectModelDialogStorageFileSrcWidget::class, ], ], ], 'lang' => [ 'class' => FieldSet::class, 'name' => 'Языковые настройки', 'fields' => [ 'languageCode' => [ 'class' => SelectField::class, 'items' => \yii\helpers\ArrayHelper::map( \skeeks\cms\models\CmsLang::find()->active()->all(), 'code', 'name' ), ], ], ], 'auth' => [ 'class' => FieldSet::class, 'name' => 'Авторизация', 'fields' => [ 'registerRoles' => [ 'class' => SelectField::class, 'multiple' => true, 'items' => \yii\helpers\ArrayHelper::map(\Yii::$app->authManager->getRoles(), 'name', 'description'), ], /*'auth_only_email_is_approved' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'email_approved_key_length', 'approved_key_is_letter' => [ 'class' => BoolField::class, 'allowNull' => false, ],*/ 'auth_submit_code_always' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'is_allow_auth_by_email' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'pass_is_need_change' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'is_need_user_data' => [ 'class' => SelectField::class, 'multiple' => true, 'items' => [ 'first_name' => "Имя", 'last_name' => "Фамилия", 'patronymic' => "Отчество", 'email' => "Email", 'phone' => "Телефон", ], ], 'pass_required_length' => [ 'class' => NumberField::class, ], 'pass_required_need_number' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'pass_required_need_uppercase' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'pass_required_need_lowercase' => [ 'class' => BoolField::class, 'allowNull' => false, ], 'pass_required_need_specialChars' => [ 'class' => BoolField::class, 'allowNull' => false, ], ], ], ]; } /** * @return string */ public function logo() { return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIoAAACYCAYAAAA7mXH0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAClFJREFUeNrsnbF2m8gXxj/npBc6OanNVtnOygsgohew0qhIY/wCidK4dIhKNcF+AePGhZtVXkCL9QKLO6f6ozonx9IT+F9wtYvJjAQSIGa43zk+2khaGIYf3713ZkAHT09PYLE26QV3AYtBYTEoLAaFxaCwGBQWg8JiMSgsBoXFoLCq1tPT07M/FvDrx2uXeXj+x44ils1dwKFnk5sYAEzuCQZlkzoADrkbGJSszsLhh0HJJA4/DEqmRLbDXcGgZM1VWAwKg8Kg5E9cTQEgLSqVWQBechcAAMJfP14vAExSTtIBEHD3sKOsBthaiMdOPuH5GAqHHwYlEwwMCoOSSSZ3AYOykr3msy53D4OyTUXEoHB4+VdLAHccfhiUTaC0Xr35aQNoA/gMYMFdxOMoAGCI3nz15ucCgMfdU7KjWLeRad1GKpSXR4K8xFbtRH4MPpgfgw+mcqDMBmYEwLVuI4Ovx9IhMQD4ZYbJsnOUCYCgrrCscY6OYpAEAPxL+0ZNUGYD06ccoK6xfpEnb6mpPADGpX3jq57MugCurNsIs4Hp1KmHX735Gf768fqtAIxQETfxAZwAOC17Xwfpe3kODg7KSGwjxJNtn2cDkyuJYiBxAFwBmF/aN4UlsbJ7u6oaR3Hp9Zt1GzkJgFzrNmJwNkPhfQw+uAJIkn2rvqOkXAUA3tHr3/R6XbewVMPwsuq3BYB/6N+FukkdHAUAhqlqKJl8nVi3kc9YrIUE1GeBwKn1cRRylQDrZ2S/zgamy4gAH4MPQwDf1nzl/tK+KbyMr4OjZLkCviRzmIYnqt9yOHTpqhSU2cAM8HxmVqSrJsOSSlRluru0bwJtQckRVxsJS0ZIKs1N9pKjSHKVJb22BF99OxuYYUMg6VCimu6HdP/cXdo3dlntqEuOIroiPAB9yfcCRWagy4IEAJxUf+0l2d+LoyRcxZgNzA79ewLgWPDV5WxgGkXv/3zWsxFP/hmJ16QWiIfyV6/hyJouSgJlIYHk+6V906fvhAAWZbrJOkfZ58IlR5DF24IOaxUERof2aUOwBkWi49Q27unK90fWtOyQuExVNv19ut7eHEXiMqKxg63HVs5nPYPgGKL4h+PMEQ+Aebs6DQ3Pf0kf96V9U3mYkTlKrUAhWMLEFX+/Ck1bADKkv1YFzb4GMNwFGAot/x53GYNpKiaz6zSU/HdWSBwAEV2hrYrafAIgOp/13H0dd6NCT8JVXADIE3LOZz2TQkGem7bmBFUg+byDeJX+UY5t3gNwtslhVjPE+wg5yoWeLXORPkGyyUGWiCckJwCCrKGCQplNCWU/436GI2vqq9aX2oJCoeYqg3O4ACZFlLi0TyeDe12MrOmQQdk/JD6eT8MLASnryqaxGH9DRXU9sqYOg1JfSC4IkkUFbRGVt0rCohUoG8LNEkB/ZE2DitvUodznUOUwpA0oZPd/r6k4+iNrGu2pbQZVULIq6bTuCa4WoNCJiCRVxz0Au4pQswMsS2pjqBooqj3NYFJnSACA2mBTm9Jq4flaYWWkDCg0VtKVXKVOHSARwDIXfHy04wjuXqRE6CE7DyWJ4vuRNZ3UFO4O/ru1Ig23WSe4dQk9QwkkF3WFhJwlBPBVEoI8Dj3lgCK6Kmtv4SNr6kpC0Ak5JYNS4JiJKIEd1tG6JXJyXAAMSoFuMldpwo0G/+5yAMSg5HQTUzIeoWKJKWrzISW8tdfWa2Yf7bMh4mWLqyslSLwu2sE4LKB9fcn7nmqUjKypfz7reYIw6hQRgv6c3nUQLxC36a3VaxfA54de1ysUlEf7zEE8+hm2g/G6HMBINCT5+oW2s0o4QyRWsreDcZ4qxRa8912h3CStCX6fyLRzAtFHvKBqBUYHm9fHGBu2udqOKXNrkaMEVE306WSHiZMdAIjawTgimDaplQDomAB6m8NtbEn7oBEoR+eznpEFfnKNv7bYb0T/v0kw2AnIOom2uZkdhSBwHu0zI2GLMrfYRh1kePQV5SctzUAJ1vRJkLHvtpH35/RONNu+WtDlP/S6Mah57+uhsOMB8B7tsz5Bc5xyi21k7vK9Ok+oZchTFuez3hy/Dx5mBcXcctfpc/Wd4MicBmRKZimvmDzaZyY5jLMGlM904H3Jd7IerCjs3EF9RQJQjB0vstVa4BDyx2UsKf/wHnrdKG+jc5XH7WActYPxkBp8CvGIY9gOxk47GBsA3iO+52VZwFWhi4IdQoqZOvHXAN4/9LrGQ6/rSEL6nM6V+dDrDreBZOvymMKSD8B/tM9scpnjtI2unIjymj52vy0y1BQeI4cbRQAmkrDRSYUX76HXLSSn2/ne43YwDgAEibAUrQtfO+5ugQaLXGMTSBfbhpdSQUlVS0Ow9glSERfj7jlKDWQzDvuRaqAYGvS5nWN8hUHZsjo4UmkNh0QdSW7BoBRc4SgbfmimuKViNVdbUGjuQ7SSvQ91JapaliqMNtc9RxGFnxOFw48I8okKDa87KL7kfeXKcFrSeciglBN+Qkn4GSroKq4k7DAoBckTvNdSyVXWuImnyjHUHhRaRD2XuIqpACSGzE0YlGpsW5WbqFyZm6i0pFMJUNa4yjHdk1xXN7EBfFLdTVRyFNkYBAD4dQxBFHKkVZtqC8SVAYVuovouCUGTGlZBviTk3Kn4tEjVJgUdiBd1H9XJyun+nWNJyHGgoJQChexalpOc0AmqQyn8aU3IiRiU6kLQV8nHn+hE7RMS2UMIr1UMOcqCQrC4knwFAK72UQnRzLAMknsovvrvhcJtdyAe3q+8EqJEeiL5ePWAvwWDsr98xYb8oXpV5itDSYWjBSSAHs/CNyB/pOi7sh9MTM71vzWQhCr1py6PD81bCVWR2MpyD1fl21+1AyVRCV1LSmajglwprbuRNfWgkV5odCxu1a5C1VUrR1sYlBq4SgTxTex2ibsVbXte9Q82MCj5NakBKBNoKN1AEV3JrRLzlCMGRc3wI6syOhU2I2JQWFlzJQaF1UwxKCwGhcWgsBgUFoPCYlBYDIpqEq3SN4veSZ1vPGNQsikUvOeWMIw/FLw31xWUlxoe0wS//+ztIYCAfkY22HZpIq1m6yBeRiCa5wl0BUX5pZCCk2lAvjSybP2h+hC+tksh0yK3cPew6wtd53m0dJSEs/j4/UeUytL1yJo6OvRbYxwl4SwO4p+EWZa8q6+6QNJIR0kloA7ilfpHBW32nhJXT7dwI3MU7UFhcehhVaiXTTlQuok8KKBsVvIOQM5RsucpIYobW9EWlqaHngWKXfQcQdNF1I12FHIVA/Fz1YwCoHN0eEIBVz2swkF52aROOJ/1hkU4im43oHPoeQ6Jj+KG9K91HY1tdOih0vifgjf7Tseb0Rtd9VAZe1rgJk91hIRDz3NnKSJHCZuWzHLVw+KqZ42z9AH8tUW48ZsKEE8KZpfR5INvJCj0O34XOcthr8mgNDpHoclCF/EjttIPFF4iXtHvN6nCyZzMslgcelgMCotBYTEoLAaFxaCwGBQWi0FhMSgsBoXFoLAYFBaDwmJQWCyx/j8AlfxVB+udqqUAAAAASUVORK5CYII='; } /** * @return null|\skeeks\cms\modules\admin\Module */ public function getModuleAdmin() { return \Yii::$app->getModule("admin"); } /** * @return null|\skeeks\cms\Module */ public function getModuleCms() { return \Yii::$app->getModule("cms"); } /** * @param Tree $tree * @return $this */ public function setCurrentTree(Tree $tree) { $this->_tree = $tree; return $this; } /** * @return Tree */ public function getCurrentTree() { return $this->_tree; } /** * @return bool * @deprecated */ public function generateTmpConfig() { $configs = FileHelper::findExtensionsFiles(['/config/main.php']); $configs = array_unique(array_merge( [ \Yii::getAlias('@skeeks/cms/config/main.php'), ], $configs )); $result = []; foreach ($configs as $filePath) { $fileData = (array)include $filePath; $result = \yii\helpers\ArrayHelper::merge($result, $fileData); } if (!file_exists(dirname(TMP_CONFIG_FILE_EXTENSIONS))) { mkdir(dirname(TMP_CONFIG_FILE_EXTENSIONS), 0777, true); } $string = var_export($result, true); file_put_contents(TMP_CONFIG_FILE_EXTENSIONS, "<?php\n\nreturn $string;\n"); // invalidate opcache of extensions.php if exists if (function_exists('opcache_invalidate')) { opcache_invalidate(TMP_CONFIG_FILE_EXTENSIONS, true); } return file_exists(TMP_CONFIG_FILE_EXTENSIONS); } /** * Да/нет * @return array */ public function booleanFormat() { return [ self::BOOL_Y => Yii::t('yii', 'Yes', [], \Yii::$app->formatter->locale), self::BOOL_N => Yii::t('yii', 'No', [], \Yii::$app->formatter->locale), ]; } /** * @return array|null|CmsLang */ public function getCmsLanguage() { return CmsLang::find()->where(['code' => \Yii::$app->language])->one(); } /** * @return array */ public function getRelatedHandlersDataForSelect() { $baseTypes = []; $userTypes = []; if ($this->relatedHandlers) { foreach ($this->relatedHandlers as $id => $handler) { if ($handler instanceof PropertyTypeBool || $handler instanceof PropertyTypeText || $handler instanceof PropertyTypeNumber || $handler instanceof PropertyTypeList || $handler instanceof PropertyTypeFile || $handler instanceof PropertyTypeTree || $handler instanceof PropertyTypeElement || $handler instanceof PropertyTypeStorageFile ) { $baseTypes[$handler->id] = $handler->name; } else { $userTypes[$handler->id] = $handler->name; } } } return [ \Yii::t('skeeks/cms', 'Base types') => $baseTypes, \Yii::t('skeeks/cms', 'Custom types') => $userTypes, ]; } /** * @return PropertyType[] list of handlers. */ public function getRelatedHandlers() { $handlers = []; foreach ($this->_relatedHandlers as $id => $handler) { $handlers[$id] = $this->getRelatedHandler($id); } return $handlers; } /** * @param array $handlers list of handlers */ public function setRelatedHandlers(array $handlers) { $this->_relatedHandlers = $handlers; } /** * @param string $id service id. * @return PropertyType auth client instance. * @throws InvalidParamException on non existing client request. */ public function getRelatedHandler($id) { if (!array_key_exists($id, $this->_relatedHandlers)) { throw new InvalidParamException("Unknown auth property type '{$id}'."); } if (!is_object($this->_relatedHandlers[$id])) { $this->_relatedHandlers[$id] = $this->createRelatedHandler($id, $this->_relatedHandlers[$id]); } return $this->_relatedHandlers[$id]; } /** * Creates auth client instance from its array configuration. * @param string $id auth client id. * @param array $config auth client instance configuration. * @return PropertyType auth client instance. */ protected function createRelatedHandler($id, $config) { $config['id'] = $id; return \Yii::createObject($config); } /** * Checks if client exists in the hub. * @param string $id client id. * @return boolean whether client exist. */ public function hasRelatedHandler($id) { return array_key_exists($id, $this->_relatedHandlers); } /** * @return string */ public function getVersion() { return (string)ArrayHelper::getValue(\Yii::$app->extensions, 'skeeks/cms.version');
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
true
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/storage/Storage.php
src/components/storage/Storage.php
<?php /** * Storage * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 17.10.2014 * @since 1.0.0 */ namespace skeeks\cms\components\storage; use skeeks\cms\helpers\StringHelper; use skeeks\cms\models\StorageFile; use Yii; use yii\base\Exception; use yii\base\Component; use yii\base\InvalidConfigException; use yii\helpers\ArrayHelper; use yii\helpers\FileHelper; use yii\httpclient\Client; use yii\web\UploadedFile; use yii\helpers\BaseUrl; use \skeeks\sx\File; use \skeeks\sx\Dir; /*interface Storage { public function add($file); public function update($storageFileSrc, $file); public function delete($storageFileSrc); }*/ /** * * @property Cluster[] $clusters * * Class Storage * @package common\components\Storage */ class Storage extends Component { public $components = []; /** * * Загрузить файл в хранилище, добавить в базу, вернуть модель StorageFile * * @param UploadedFile|string|File $file объект UploadedFile или File или rootPath до файла локально или http:// путь к файлу (TODO:: доделать) * @param array $data данные для сохранения в базу * @param null $clusterId идентификатор кластера по умолчанию будет выбран первый из конфигурации * @return StorageFile * @throws Exception */ public function upload($file, $data = [], $clusterId = null) { //Для начала всегда загружаем файл во временную диррикторию $tmpdir = Dir::runtimeTmp(); $tmpfile = $tmpdir->newFile(); $original_file_name = ''; if ($file instanceof UploadedFile) { $extension = File::object($file->name)->getExtension(); $tmpfile->setExtension($extension); $original_file_name = $file->getBaseName(); if (!$file->saveAs($tmpfile->getPath())) { throw new Exception("Файл не загружен во временную диррикторию"); } } else { if ($file instanceof File || (is_string($file) && BaseUrl::isRelative($file))) { /*print_r($file);die;*/ $file = File::object($file); $original_file_name = $file->getBaseName(); $tmpfile->setExtension($file->getExtension()); $tmpfile = $file->move($tmpfile); } else { if (is_string($file) && !BaseUrl::isRelative($file)) { $client = new Client(); $response = $client ->createRequest() ->setUrl($file) ->setOptions([ //'timeout' => 10, 'followLocation' => true, ]) ->send(); if ($response->isOk) { $file_content = $response->content; } else { throw new Exception("Не удалось скачать файл: {$file} " . $response->statusCode); } if (!$file_content) { throw new Exception("Скачанный файл пустой: {$file}"); } $fileNameData = $file; $pos = strpos($fileNameData, "?"); if ($pos !== false) { $fileNameData = substr($fileNameData, 0, $pos); } $extension = pathinfo($fileNameData, PATHINFO_EXTENSION); //Если расширение определено прям в названии файла if ($extension) { $fileNameData = str_replace(".{$extension}", "", $fileNameData); } $fileNameData = str_replace(".", "_", $fileNameData); $fileNameData = str_replace("?", "_", $fileNameData); $fileNameData = str_replace("&", "_", $fileNameData); $original_file_name = pathinfo($fileNameData, PATHINFO_BASENAME); $pos = strpos($extension, "?"); if ($pos === false) { } else { $extension = substr($extension, 0, $pos); } if ($extension) { $tmpfile->setExtension($extension); } $is_file_saved = file_put_contents($tmpfile, $file_content); if (!$is_file_saved) { throw new Exception("Не удалось сохранить файл"); } //Если в ссылке нет расширения //if (!$extension) { $tmpfile = new File($tmpfile->getPath()); try { $mimeType = FileHelper::getMimeType($tmpfile->getPath(), null, false); } catch (InvalidConfigException $e) { throw new Exception("Не удалось пределить расширение файла: ".$e->getMessage()); } if (!$mimeType) { throw new Exception("Не удалось пределить расширение файла"); } $extensions = FileHelper::getExtensionsByMimeType($mimeType); if ($extensions) { if (in_array("jpg", $extensions)) { $extension = 'jpg'; } elseif(in_array("png", $extensions)) { $extension = 'png'; } elseif(in_array("webp", $extensions)) { $extension = 'webp'; } elseif(in_array("gif", $extensions)) { $extension = 'gif'; } else { if (!$extension) { $extension = $extensions[0]; } } $newFile = new File($tmpfile->getPath()); $newFile->setExtension($extension); if ($tmpfile->getExtension() != $newFile->getExtension()) { $tmpfile = $tmpfile->copy($newFile); } } //} if (!strpos($original_file_name, ".")) { $original_file_name = $original_file_name . "." . $extension; } } else { throw new Exception("Файл должен быть определен как \yii\web\UploadedFile или \skeeks\sx\File или string"); } } } $newData = []; //$data["type"] = $tmpfile->getType(); $newData["mime_type"] = $tmpfile->getMimeType(); $newData["size"] = $tmpfile->size()->getBytes(); $newData["extension"] = $tmpfile->getExtension(); $newData["original_name"] = $original_file_name; //Елси это изображение if ($tmpfile->getType() == 'image') { if (extension_loaded('gd')) { list($width, $height, $type, $attr) = getimagesize($tmpfile->toString()); $newData["image_height"] = $height; $newData["image_width"] = $width; } } if ($cluster = $this->getCluster($clusterId)) { if ($newFileSrc = $cluster->upload($tmpfile)) { $newData = array_merge($newData, [ "cluster_id" => $cluster->id, "cluster_file" => $newFileSrc, ]); } } $data = array_merge((array) $newData, (array) $data); $file = new StorageFile($data); if (!$file->save()) { throw new Exception("Файл не сохранен: " . print_r($file->errors, true)); } return $file; } protected $_clusters = null; /** * @return Cluster[] */ public function getClusters() { if ($this->_clusters === null) { ArrayHelper::multisort($this->components, 'priority'); foreach ($this->components as $id => $data) { if (!is_int($id)) { $data['id'] = $id; } $cluster = \Yii::createObject($data); $this->_clusters[$cluster->id] = $cluster; } } return $this->_clusters; } /** * @param null $id * @return Cluster */ public function getCluster($id = null) { if ($id == null) { foreach ($this->clusters as $clusterId => $cluster) { return $cluster; } } else { return ArrayHelper::getValue($this->clusters, $id); } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/storage/ClusterLocal.php
src/components/storage/ClusterLocal.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components\storage; use skeeks\cms\models\StorageFile; use skeeks\sx\Dir; use skeeks\sx\File; /** * @author Semenov Alexander <semenov@skeeks.com> */ class ClusterLocal extends Cluster { /** * @var bool */ public $publicBaseUrlIsAbsolute = false; public $hostInfo = ""; public function init() { if (!$this->name) { $this->name = \Yii::t('skeeks/cms', "Local storage"); } if (!$this->hostInfo) { $this->hostInfo = \Yii::$app->urlManager->hostInfo; } if (!$this->publicBaseUrl) { $this->publicBaseUrl = \Yii::getAlias("@web/uploads/all"); } else { $this->publicBaseUrl = \Yii::getAlias($this->publicBaseUrl); } if (!$this->rootBasePath) { $this->rootBasePath = \Yii::getAlias("@webroot/uploads/all"); } else { $this->rootBasePath = \Yii::getAlias($this->rootBasePath); } parent::init(); } /** * Добавление файла в кластер * * @param File $tmpFile * @return string * @throws Exception */ public function upload(File $tmpFile) { $clusterFileName = $this->_generateClusterFileName($tmpFile); $dir = $this->rootBasePath; $localPath = $this->getClusterDir($clusterFileName); $clusterFileSrc = $clusterFileName; if ($localPath) { $clusterFileSrc = $localPath.DIRECTORY_SEPARATOR.$clusterFileSrc; } try { $dir = new Dir($dir.DIRECTORY_SEPARATOR.$localPath); $resultFile = $dir->newFile($clusterFileName); $tmpFile->move($resultFile); } catch (\yii\base\Exception $e) { throw new \yii\base\Exception($e->getMessage()); } return $clusterFileSrc; } /** * Удаление файла * * @param $clusterFileSrc * @return bool * @throws Exception */ public function delete(StorageFile $clusterFile) { if (!$clusterFile->cluster_file) { //Если не задан путь к файлу, то не нужно удлаять, может удалиться все хранилище return true; } $file = new File($this->getRootSrc($clusterFile)); if ($file->isExist()) { $file->remove(); } return true; } /** * Удаление временной папки * * @param $clusterFileUniqSrc * @return bool|mixed */ public function deleteTmpDir(StorageFile $clusterFile) { if (!$clusterFile->cluster_file) { //Если не задан путь к файлу, то не нужно удлаять, может удалиться все хранилище return true; } if ($this->rootBasePath == $this->rootTmpDir($clusterFile)) { //Если не задан путь к файлу, то не нужно удлаять, может удалиться все хранилище return true; } $dir = new Dir($this->rootTmpDir($clusterFile), false); if ($dir->isExist()) { $dir->remove(); } return true; } public function update($clusterFileUniqSrc, $file) { } /** * @param $clusterFileUniqSrc * @return string */ public function getAbsoluteUrl(StorageFile $clusterFile) { if ($this->publicBaseUrlIsAbsolute) { return $this->getPublicUrl($clusterFile); } else { return $this->hostInfo . $this->getPublicUrl($clusterFile); } } /** * @param $clusterFileUniqSrc * @return string */ public function getAbsoluteBaseNameUrl(StorageFile $clusterFile) { if ($this->publicBaseUrlIsAbsolute) { return $this->getPublicBaseNameUrl($clusterFile); } else { return $this->hostInfo . $this->getPublicBaseNameUrl($clusterFile); } } /** * Свободное место на сервере * @return float */ public function getFreeSpace() { if ($this->existsRootPath()) { return (float)disk_free_space($this->rootBasePath); } return (float)0; } /** * @return bool */ public function existsRootPath() { if (is_dir($this->rootBasePath)) { return true; } //Создать папку для файлов если ее нет $dir = new Dir($this->rootBasePath); if ($dir->make()) { return true; } return false; } /** * Всего столько места. * @return float */ public function getTotalSpace() { if ($this->existsRootPath()) { return (float)disk_total_space($this->rootBasePath); } return (float)0; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/storage/Cluster.php
src/components/storage/Cluster.php
<?php /** * Storage * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 17.10.2014 * @since 1.0.0 */ namespace skeeks\cms\components\storage; use skeeks\cms\components\Imaging; use skeeks\cms\models\StorageFile; use Yii; use yii\base\Component; use \skeeks\sx\File; use \skeeks\sx\Dir; use yii\base\Model; /** * Class Cluster * @package skeeks\cms\components\storage */ abstract class Cluster extends Model { public $id; public $name; public $priority = 100; public $publicBaseUrl; // http://c1.s.skeeks.com/uploads/ public $rootBasePath; // /var/www/sites/test.ru/frontend/web/uploads/ /** * @var integer the level of sub-directories to store uploaded files. Defaults to 1. * If the system has huge number of uploaded files (e.g. one million), you may use a bigger value * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system * is not over burdened with a single directory having too many files. */ public $directoryLevel = 3; /** * @param $file * @return string $clusterFileUniqSrc */ abstract public function upload(File $file); /** * @param $clusterFileUniqSrc * @param $file * @return mixed */ abstract public function update($clusterFileUniqSrc, $file); /** * @param $clusterFileUniqSrc * @return mixed */ abstract public function delete(StorageFile $clusterFile); /** * Удаление папки с преьвюшками * * @param $clusterFileUniqSrc * @return mixed */ abstract public function deleteTmpDir(StorageFile $clusterFile); /** * Путь до папки с временными файлами превью например * * @param $clusterFileUniqSrc * @return string */ public function rootTmpDir(StorageFile $clusterFile) { $file = new File($this->getRootSrc($clusterFile)); return $file->getDirName() . "/" . $file->getFileName(); } /** * Полный публичный путь до файла. * * @param $clusterFileSrc * @return string */ public function getRootSrc(StorageFile $clusterFile) { return $this->rootBasePath . DIRECTORY_SEPARATOR . $clusterFile->cluster_file; } /** * Полный публичный путь до файла. * Например /uploads/all/f4/df/sadfsd/sdfsdfsd/asdasd.jpg * * @param $clusterFileSrc * @return string */ public function getPublicUrl(StorageFile $clusterFile) { return $this->publicBaseUrl . "/" . $clusterFile->cluster_file; } /** * @param $clusterFileUniqSrc * @return string */ public function getAbsoluteUrl(StorageFile $clusterFile) { return $this->getPublicUrl($clusterFile); } /** * Полный публичный путь до файла. * Например /uploads/all/f4/df/sadfsd/sdfsdfsd/asdasd.jpg * * @param $clusterFileSrc * @return string */ public function getPublicBaseNameUrl(StorageFile $clusterFile) { $data = explode(".", $clusterFile->cluster_file); return $this->publicBaseUrl . "/" . $data[0] . "/" . Imaging::STORAGE_FILE_PREFIX . "/" . $clusterFile->downloadName; } /** * @param $clusterFileUniqSrc * @return string */ public function getAbsoluteBaseNameUrl(StorageFile $clusterFile) { return $this->getPublicBaseNameUrl($clusterFile); } /** * * Дирриктория где будет лежать файл, определяется по имени файла * * @param $newName * @return string */ public function getClusterDir($newName) { $localDir = ""; if ($this->directoryLevel > 0) { $count = 0; for ($i = 0; $i < $this->directoryLevel; ++$i) { $count++; if (($prefix = substr($newName, $i + $i, 2)) !== false) { if ($count > 1) { $localDir .= DIRECTORY_SEPARATOR; } $localDir .= $prefix; } } } return $localDir; } /** * * Геренрация названия файла, уникального названия. * * @param $originalFileName * @return string */ protected function _generateClusterFileName(File $originalFileName) { $originalFileName->getExtension(); // generate a unique file name $newName = md5(microtime() . rand(0, 100)); return $originalFileName->getExtension() ? $newName . "." . $originalFileName->getExtension() : $newName; } /** * Свободное место на сервере * @return float */ public function getFreeSpace() { return 0; } /** * Всего столько места. * @return float */ public function getTotalSpace() { return 0; } /** * Занятое место * @return float */ public function getUsedSpace() { return (float)($this->getTotalSpace() - $this->getFreeSpace()); } /** * Свободно процентов * @return float */ public function getFreeSpacePct() { return ($this->getFreeSpace() * 100) / $this->getTotalSpace(); } /** * Занято в процентах * @return float */ public function getUsedSpacePct() { return (float)(100 - $this->getFreeSpacePct()); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/storage/Exception.php
src/components/storage/Exception.php
<?php /** * Exception * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 21.10.2014 * @since 1.0.0 */ namespace skeeks\cms\components\storage; use Yii; use skeeks\cms\Exception as CmsException; /** * Class Exception * @package skeeks\cms\components\storage */ class Exception extends CmsException { }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/storage/SkeeksSuppliersCluster.php
src/components/storage/SkeeksSuppliersCluster.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components\storage; use skeeks\cms\models\StorageFile; use skeeks\sx\File; use yii\helpers\ArrayHelper; /** * @author Semenov Alexander <semenov@skeeks.com> */ class SkeeksSuppliersCluster extends Cluster { const IMAGE_PREVIEW_MICRO = "micro"; const IMAGE_PREVIEW_SMALL = "small"; const IMAGE_PREVIEW_MEDIUM = "medium"; const IMAGE_PREVIEW_BIG = "big"; public function init() { if (!$this->name) { $this->name = \Yii::t('skeeks/cms', "SkeekS Suppliers"); } parent::init(); } /** * Полный публичный путь до файла. * Например /uploads/all/f4/df/sadfsd/sdfsdfsd/asdasd.jpg * * @param $clusterFileSrc * @return string */ public function getPublicUrl(StorageFile $clusterFile) { return ArrayHelper::getValue($clusterFile, "sx_data.src", ""); } /** * @param $clusterFileUniqSrc * @return string */ public function getAbsoluteUrl(StorageFile $clusterFile) { return ArrayHelper::getValue($clusterFile, "sx_data.src", ""); } /** * Добавление файла в кластер * * @param File $tmpFile * @return string * @throws Exception */ public function upload(File $tmpFile) { throw new \yii\base\Exception("Не поддерживает загрузку"); } /** * Удаление файла * * @param $clusterFileSrc * @return bool * @throws Exception */ public function delete(StorageFile $clusterFile) { return true; } /** * Удаление временной папки * * @param $clusterFileUniqSrc * @return bool|mixed */ public function deleteTmpDir(StorageFile $clusterFile) { return true; } public function update($clusterFileUniqSrc, $file) { } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/storage/StorageEvent.php
src/components/storage/StorageEvent.php
<?php /** * StorageEvent * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 17.10.2014 * @since 1.0.0 */ namespace skeeks\cms\components\storage; use yii\base\Event; /** * Class StorageEvent * @package skeeks\cms\components\storage */ class StorageEvent extends Event { /** * @var boolean if message was sent successfully. */ public $isSuccessful; /** * @var boolean whether to continue sending an email. Event handlers of * [[\yii\mail\BaseMailer::EVENT_BEFORE_SEND]] may set this property to decide whether * to continue send or not. */ public $isValid = true; }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/imaging/Filter.php
src/components/imaging/Filter.php
<?php /** * Filter * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 11.12.2014 * @since 1.0.0 */ namespace skeeks\cms\components\imaging; use Faker\Provider\File; use skeeks\cms\components\storage\SkeeksSuppliersCluster; use skeeks\cms\models\StorageFile; use yii\base\Component; use yii\helpers\ArrayHelper; use yii\helpers\FileHelper; /** * Class Filter * @package skeeks\cms\components\imaging */ abstract class Filter extends Component { protected $_config = []; /** * Если файл храниться на SkeekS Suppliers Server какую превью брать? * @var string */ public $sx_preview = "micro"; protected $_originalRootFilePath = null; protected $_newRootFilePath = null; public function __construct($config = []) { $this->_config = $config; parent::__construct($config); /** * Из url убрать лишние параметры */ if (isset($this->_config['sx_preview'])) { unset($this->_config['sx_preview']); } } /** * @return string */ public function getId() { return str_replace("\\", '-', $this->className()); } /** * @return array */ public function getConfig() { return $this->_config; } /** * @param $originalFilePath * @return $this */ public function setOriginalRootFilePath($originalRootFilePath) { $this->_originalRootFilePath = (string)$originalRootFilePath; return $this; } /** * @param $originalFilePath * @return $this */ public function setNewRootFilePath($newRootFilePath) { $this->_newRootFilePath = (string)$newRootFilePath; return $this; } /** * @return \skeeks\sx\File * @throws \ErrorException */ public function save() { if (!$this->_originalRootFilePath) { throw new \ErrorException("not configurated original file"); } if (!$this->_newRootFilePath) { throw new \ErrorException("not configurated new file path"); } //Все проверки прошли, результирующая дирректория создана или найдена, результирующий файл можно перезаписывать если он существует //try //{ $this->_createNewDir(); $this->_save(); $file = new \skeeks\sx\File($this->_newRootFilePath); if (!$file->isExist()) { throw new \ErrorException('Файл не найден'); } //} catch (\Cx_Exception $e) //{ // throw new \ErrorException($e->getMessage()); //} return $file; } /** * @param StorageFile $cmsStorageFile * @return int[] */ public function getDimensions(StorageFile $cmsStorageFile) { if ($cmsStorageFile->cluster instanceof SkeeksSuppliersCluster) { return [ 'width' => (int) ArrayHelper::getValue($cmsStorageFile->sx_data, "previews.{$this->sx_preview}.width", 0), 'height' => (int) ArrayHelper::getValue($cmsStorageFile->sx_data, "previews.{$this->sx_preview}.height", 0), ]; } return [ 'width' => 0, 'height' => 0, ]; } /** * @return $this */ protected function _createNewDir() { $newFile = new \skeeks\sx\File($this->_newRootFilePath); if (!FileHelper::createDirectory($newFile->getDir()->getPath())) { throw new \ErrorException("Не удалось создать диррикторию для нового файла"); } return $this; } abstract protected function _save(); }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/imaging/Preview.php
src/components/imaging/Preview.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components\imaging; use yii\base\BaseObject; /** * @property string $cssAspectRatio * * @author Semenov Alexander <semenov@skeeks.com> */ class Preview extends BaseObject { /** * @var int */ public $width; /** * @var int */ public $height; /** * @var string */ public $src; /** * Соотношение сторон для CSS * @return string */ public function getCssAspectRatio() { $result = "1/1"; if ($this->width > 0 && $this->height > 0) { $result = "{$this->width}/{$this->height}"; } return $result; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/imaging/filters/Thumbnail.php
src/components/imaging/filters/Thumbnail.php
<?php /** * Thumbnail * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 11.12.2014 * @since 1.0.0 */ namespace skeeks\cms\components\imaging\filters; use Imagine\Image\ImageInterface; use Imagine\Image\ImagineInterface; use Imagine\Image\ManipulatorInterface; use skeeks\cms\components\storage\SkeeksSuppliersCluster; use skeeks\cms\models\CmsStorageFile; use skeeks\cms\models\StorageFile; use skeeks\imagine\Image; use yii\base\Exception; use yii\helpers\ArrayHelper; /** * Class Thumbnail * @package skeeks\cms\components\imaging\filters */ class Thumbnail extends \skeeks\cms\components\imaging\Filter { public $w = 50; public $h = 50; /** * @var int Качество сохраняемого фото */ public $q; /** * @var int Если не задана ширина или высота, то проверять оригинальный размер файла и новый файл не будет крупнее */ public $s = 1; /** * @var int прозрачность фона картинки 100 - непрозрачный 0 - прозрачный */ public $ta = 100; /** * @var string фоновый цвет превью картинки */ public $tb = "FFF"; public $m = ManipulatorInterface::THUMBNAIL_INSET; public function init() { parent::init(); if (!$this->w && !$this->h) { throw new Exception("Необходимо указать ширину или высоту"); } if (!$this->m) { $this->m = ManipulatorInterface::THUMBNAIL_INSET; } $q = (int)$this->q; if (!$q) { $this->q = (int)\Yii::$app->seo->img_preview_quality; } $q = (int)$this->q; if ($q < 10) { $this->q = 10; } if ($q > 100) { $this->q = 100; } } /** * @param StorageFile $cmsStorageFile * @return array|int[] */ public function getDimensions(StorageFile $cmsStorageFile) { $result = []; if ($cmsStorageFile->cluster instanceof SkeeksSuppliersCluster) { return parent::getDimensions($cmsStorageFile); } if (!$cmsStorageFile->image_height || !$cmsStorageFile->image_width) { return $result; } if (!$this->w) { //Если ширина не указана нужно ее расчитать //Если размер оригинальной кратинки больше, то уменьшаем его if ($this->s == 1) { if ($this->h > $cmsStorageFile->image_height) { $this->h = $cmsStorageFile->image_height; } } $width = ($cmsStorageFile->image_width * $this->h) / $cmsStorageFile->image_height; //Готовый результат $result['width'] = (int)$width; $result['height'] = (int)$this->h; } else { if (!$this->h) { //Если размер оригинальной кратинки больше, то уменьшаем его if ($this->s == 1) { if ($this->w > $cmsStorageFile->image_width) { $this->w = $cmsStorageFile->image_width; } } $height = ($cmsStorageFile->image_height * $this->w) / $cmsStorageFile->image_width; //Готовый результат $result['width'] = (int)$this->w; $result['height'] = (int)round($height); } else { if ($this->m == ManipulatorInterface::THUMBNAIL_OUTBOUND) { //TODO: доработать $result['width'] = (int)$this->w; $result['height'] = (int)$this->h; } else { $result['width'] = (int)$this->w; $result['height'] = (int)$this->h; } } } return $result; } protected function _save() { /*if (!$this->m) { $this->m = ManipulatorInterface::THUMBNAIL_INSET; }*/ if (!$this->w) { //Если ширина не указана нужно ее расчитать $size = Image::getImagine()->open($this->_originalRootFilePath)->getSize(); //Если размер оригинальной кратинки больше, то уменьшаем его if ($this->s == 1) { if ($this->h > $size->getHeight()) { $this->h = $size->getHeight(); } } $width = ($size->getWidth() * $this->h) / $size->getHeight(); Image::thumbnailV2($this->_originalRootFilePath, (int)round($width), $this->h, $this->m, $this->tb, (int) $this->ta)->save($this->_newRootFilePath, [ 'jpeg_quality' => $this->q, 'webp_quality' => $this->q, ]); } else if (!$this->h) { $size = Image::getImagine()->open($this->_originalRootFilePath)->getSize(); //Если размер оригинальной кратинки больше, то уменьшаем его if ($this->s == 1) { if ($this->w > $size->getWidth()) { $this->w = $size->getWidth(); } } $height = ($size->getHeight() * $this->w) / $size->getWidth(); Image::thumbnailV2($this->_originalRootFilePath, $this->w, (int)round($height), $this->m, $this->tb, (int) $this->ta)->save($this->_newRootFilePath, [ 'jpeg_quality' => $this->q, 'webp_quality' => $this->q, ]); } else { $size = Image::getImagine()->open($this->_originalRootFilePath)->getSize(); //Для этого режима важно чтобы оригинальное фото было больше if ($this->m == ImageInterface::THUMBNAIL_OUTBOUND) { if ($size->getWidth() < $this->w || $size->getHeight() < $this->h) { $this->m = ImageInterface::THUMBNAIL_INSET; } } $image = Image::thumbnailV2($this->_originalRootFilePath, $this->w, $this->h, $this->m, $this->tb, (int) $this->ta)->save($this->_newRootFilePath, [ 'jpeg_quality' => $this->q, 'webp_quality' => $this->q, ]); } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/imaging/filters/ThumbnailFix.php
src/components/imaging/filters/ThumbnailFix.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components\imaging\filters; use Imagine\Image\Box; use Imagine\Image\Point; use skeeks\cms\components\imaging\Filter; use skeeks\imagine\Image; /** * @author Semenov Alexander <semenov@skeeks.com> */ class ThumbnailFix extends Filter { public $w = 50; public $h = 0; protected function _save() { $size = Image::getImagine()->open($this->_originalRootFilePath)->getSize(); if (!$this->h) { $this->h = $this->w; } $width = $this->w; $height = $this->h; $box = new Box($width, $height); $palette = new \Imagine\Image\Palette\RGB(); $thumb = Image::getImagine()->create($box, $palette->color('#FFFFFF', 100)); $startX = 0; $startY = 0; /*if ($size->getWidth() < $width) { $startX = ceil($width - $size->getWidth()) / 2; } if ($size->getHeight() < $height) { $startY = ceil($height - $size->getHeight()) / 2; }*/ if ($size->getWidth() >= $size->getHeight()) { //Картинка горизонтальная /*$newWidth = $this->w; $newHeight = ($size->getHeight() * $this->w) / $size->getWidth();*/ $originalImage = Image::getImagine()->open($this->_originalRootFilePath); $originalImage->resize($originalImage->getSize()->widen($this->w));; //$originalImage->save($this->_newRootFilePath); } else { /*$newHeight = $this->w; $newWidth = ($size->getWidth() * $this->w) / $size->getHeight();*/ $originalImage = Image::getImagine()->open($this->_originalRootFilePath); $originalImage->resize($originalImage->getSize()->heighten($this->w));; //$originalImage->save($this->_newRootFilePath); } $size = $originalImage->getSize(); if ($size->getWidth() < $width) { $startX = ceil($width - $size->getWidth()) / 2; } if ($size->getHeight() < $height) { $startY = ceil($height - $size->getHeight()) / 2; } $thumb->paste($originalImage, new Point($startX, $startY)); $thumb->save($this->_newRootFilePath); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/imaging/filters/Crop.php
src/components/imaging/filters/Crop.php
<?php /** * Filter * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 11.12.2014 * @since 1.0.0 */ namespace skeeks\cms\components\imaging\filters; use yii\base\Component; use skeeks\imagine\Image; /** * Class Filter * @package skeeks\cms\components\imaging */ class Crop extends \skeeks\cms\components\imaging\Filter { public $w = 0; public $h = 0; public $s = [0, 0]; protected function _save() { Image::crop($this->_originalRootFilePath, $this->w, $this->h, $this->s)->save($this->_newRootFilePath); Image::thumbnail($this->_originalRootFilePath, $this->w, $this->h, $this->s)->save($this->_newRootFilePath); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/urlRules/UrlRuleContentElement.php
src/components/urlRules/UrlRuleContentElement.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 24.05.2015 */ namespace skeeks\cms\components\urlRules; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsSite; use skeeks\cms\models\Tree; use \yii\base\InvalidConfigException; use yii\helpers\ArrayHelper; use yii\helpers\Url; use yii\web\Application; /** * Class UrlRuleContentElement * @package skeeks\cms\components\urlRules */ class UrlRuleContentElement extends \yii\web\UrlRule { public function init() { if ($this->name === null) { $this->name = __CLASS__; } } /** * //Это можно использовать только в коротких сценариях, иначе произойдет переполнение памяти * @var array */ static public $models = []; /** * @param \yii\web\UrlManager $manager * @param string $route * @param array $params * @return bool|string */ public function createUrl($manager, $route, $params) { if ($route == 'cms/content-element/view') { $contentElement = $this->_getElement($params); if (!$contentElement) { return false; } $url = ''; $cmsTree = ArrayHelper::getValue($params, 'cmsTree'); ArrayHelper::remove($params, 'cmsTree'); $cmsSite = ArrayHelper::getValue($params, 'cmsSite', null); ArrayHelper::remove($params, 'cmsSite'); //We need to build on what that particular section of the settings /*if (!$cmsTree) { $cmsTree = $contentElement->cmsTree; }*/ if ($cmsTree) { $url = $cmsTree->dir . "/"; } //$url .= $contentElement->id . "-" . $contentElement->code; $url .= $contentElement->code . '-' . $contentElement->id; if (strpos($url, '//') !== false) { $url = preg_replace('#/+#', '/', $url); } /** * @see parent::createUrl() */ if ($url !== '') { $url .= ($this->suffix === null ? $manager->suffix : $this->suffix); } /** * @see parent::createUrl() */ if (!empty($params) && ($query = http_build_query($params)) !== '') { $url .= '?' . $query; } //Раздел привязан к сайту, сайт может отличаться от того на котором мы сейчас находимся if (!$cmsSite) { $siteClass = \Yii::$app->skeeks->siteClass; $cmsSite = $siteClass::getById($contentElement->cms_site_id); //$cmsSite = $contentElement->cmsSite; } if ($cmsSite) { if ($cmsSite->cmsSiteMainDomain) { return $cmsSite->url . '/' . $url; } } return $url; } return false; } /** * * @param $params * @return bool|CmsContentElement */ protected function _getElement(&$params) { $id = (int)ArrayHelper::getValue($params, 'id'); $contentElement = ArrayHelper::getValue($params, 'model'); if (!$id && !$contentElement) { return false; } if ($contentElement && $contentElement instanceof CmsContentElement) { if (\Yii::$app instanceof Application) { self::$models[$contentElement->id] = $contentElement; } } else { /** * @var $contentElement CmsContentElement */ if (!$contentElement = ArrayHelper::getValue(self::$models, $id)) { $contentElement = CmsContentElement::findOne(['id' => $id]); if (\Yii::$app instanceof Application) { self::$models[$id] = $contentElement; } } } ArrayHelper::remove($params, 'id'); ArrayHelper::remove($params, 'code'); ArrayHelper::remove($params, 'model'); return $contentElement; } /** * @param \yii\web\UrlManager $manager * @param \yii\web\Request $request * @return array|bool */ public function parseRequest($manager, $request) { if ($this->mode === self::CREATION_ONLY) { return false; } if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) { return false; } $pathInfo = $request->getPathInfo(); if ($this->host !== null) { $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo); } $params = $request->getQueryParams(); $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix); $treeNode = null; if (!$pathInfo) { return false; } if ($suffix) { $pathInfo = substr($pathInfo, 0, strlen($pathInfo) - strlen($suffix)); } if (preg_match('/\/(?<code>\S+)\-(?<id>\d+)$/i', "/" . $pathInfo, $matches)) { return [ 'cms/content-element/view', [ 'id' => $matches['id'], 'code' => $matches['code'] ] ]; } /** * @deprecated */ if (preg_match('/\/(?<id>\d+)\-(?<code>\S+)$/i', "/" . $pathInfo, $matches)) { return [ 'cms/content-element/view', [ 'id' => $matches['id'], 'code' => $matches['code'] ] ]; } return false; /*if (!preg_match('/\/(?<id>\d+)\-(?<code>\S+)$/i', "/" . $pathInfo, $matches)) { return false; }*/ } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/urlRules/UrlRuleTree.php
src/components/urlRules/UrlRuleTree.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components\urlRules; use skeeks\cms\models\CmsSite; use skeeks\cms\models\CmsTree; use skeeks\cms\models\Tree; use yii\caching\TagDependency; use yii\helpers\ArrayHelper; /** * Class UrlRuleTree * @package skeeks\cms\components\urlRules */ class UrlRuleTree extends \yii\web\UrlRule { public function init() { if ($this->name === null) { $this->name = __CLASS__; } } static public $models = []; /** * @param \yii\web\UrlManager $manager * @param string $route * @param array $params * @return bool|string */ public function createUrl($manager, $route, $params) { if ($route == 'cms/tree/view') { $defaultParams = $params; //Из параметров получаем модель дерева, если модель не найдена просто остановка $tree = $this->_getCreateUrlTree($params); if (!$tree) { return false; } //Для раздела задан редиррект if ($tree->redirect) { if (strpos($tree->redirect, '://') !== false) { return $tree->redirect; } else { $url = trim($tree->redirect, '/'); if ($tree->site) { if ($tree->site->cmsSiteMainDomain) { return $tree->site->url.'/'.$url; } else { return $url; } } else { return $url; } } } //Указан редиррект на другой раздел if ($tree->redirect_tree_id) { if ($tree->redirectTree->id != $tree->id) { $paramsNew = ArrayHelper::merge($defaultParams, ['model' => $tree->redirectTree]); $url = $this->createUrl($manager, $route, $paramsNew); return $url; } } //Стандартно берем dir раздела if ($tree->dir) { $url = $tree->dir; } else { $url = ""; } if (strpos($url, '//') !== false) { $url = preg_replace('#/+#', '/', $url); } /** * @see parent::createUrl() */ if ($url !== '') { $url .= ($this->suffix === null ? $manager->suffix : $this->suffix); } /** * @see parent::createUrl() */ if (!empty($params) && ($query = http_build_query($params)) !== '') { $url .= '?'.$query; } //Раздел привязан к сайту, сайт может отличаться от того на котором мы сейчас находимся if ($tree->site) { //TODO:: добавить проверку текущего сайта. В случае совпадения возврат локального пути if ($tree->site->cmsSiteMainDomain) { return $tree->site->url.'/'.$url; } } return $url; } return false; } /** * Поиск раздела по параметрам + удаление лишних * * @param $params * @return null|Tree */ protected function _getCreateUrlTree(&$params) { $id = (int)ArrayHelper::getValue($params, 'id'); $treeModel = ArrayHelper::getValue($params, 'model'); $dir = ArrayHelper::getValue($params, 'dir'); $site_id = ArrayHelper::getValue($params, 'site_id'); ArrayHelper::remove($params, 'id'); ArrayHelper::remove($params, 'model'); ArrayHelper::remove($params, 'dir'); ArrayHelper::remove($params, 'site_id'); if ($treeModel && $treeModel instanceof CmsTree) { $tree = $treeModel; self::$models[$treeModel->id] = $treeModel; return $tree; } if ($id) { $tree = ArrayHelper::getValue(self::$models, $id); if ($tree) { return $tree; } else { $tree = CmsTree::findOne(['id' => $id]); self::$models[$id] = $tree; return $tree; } } if ($dir) { if (!$site_id && \Yii::$app->cms && \Yii::$app->skeeks->site) { $site_id = \Yii::$app->skeeks->site->id; } if ($site_id) { $cmsSite = CmsSite::findOne($site_id); } if (!$cmsSite) { return null; } $tree = CmsTree::findOne([ 'dir' => $dir, 'cms_site_id' => $cmsSite->id, ]); if ($tree) { self::$models[$id] = $tree; return $tree; } } return null; } /** * @param \yii\web\UrlManager $manager * @param \yii\web\Request $request * @return array|bool */ public function parseRequest($manager, $request) { if ($this->mode === self::CREATION_ONLY) { return false; } if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) { return false; } $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix); $pathInfo = $request->getPathInfo(); $normalized = false; if ($this->hasNormalizer($manager)) { $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized); } if ($suffix !== '' && $pathInfo !== '') { $n = strlen($suffix); if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) { $pathInfo = substr($pathInfo, 0, -$n); if ($pathInfo === '') { // suffix alone is not allowed return false; } } else { return false; } } if ($this->host !== null) { $pathInfo = strtolower($request->getHostInfo()).($pathInfo === '' ? '' : '/'.$pathInfo); } $params = $request->getQueryParams(); $treeNode = null; $originalDir = $pathInfo; /*if ($suffix) { $originalDir = substr($pathInfo, 0, (strlen($pathInfo) - strlen($suffix))); }*/ $dependency = new TagDependency([ 'tags' => [ (new CmsTree())->getTableCacheTagCmsSite(), ], ]); //Main page if (!$pathInfo) { $treeNode = CmsTree::getDb()->cache(function ($db) { return CmsTree::find()->where([ "cms_site_id" => \Yii::$app->skeeks->site->id, "level" => 0, ])->one(); }, null, $dependency); } else //второстепенная страница { $treeNode = CmsTree::getDb()->cache(function ($db) use ($originalDir) { return CmsTree::find()->where([ "dir" => $originalDir, "cms_site_id" => \Yii::$app->skeeks->site->id, ])->one(); }, null, $dependency); if (!$treeNode) { //TODO: новое обновление пробуем разобрать и проанализировать dir $dirData = explode("/", $originalDir); $newDir = []; if (count($dirData) > 1) { $last = $dirData[count($dirData) - 1]; $cmsTreeQuery = CmsTree::find()->where([ "code" => $last, "cms_site_id" => \Yii::$app->skeeks->site->id, ]); if ($cmsTreeQuery->count() == 1) { $treeNode = $cmsTreeQuery->one(); } else { $counter = 0; $totalCountDir = count($dirData); foreach ($dirData as $key => $dirPart) { $counter++; unset($dirData[$totalCountDir - $counter]); $checkDir = implode("/", $dirData); $betterNode = CmsTree::find()->where([ "dir" => $checkDir, "cms_site_id" => \Yii::$app->skeeks->site->id, ])->one(); /*print_r($checkDir); echo "<br />";*/ if (!$treeNode && $betterNode) { $treeNode = $betterNode; /*echo "<br />Tree node<br />"; print_r($treeNode->dir); echo "<br />";*/ } /** * @var $betterNode CmsTree */ if ($betterNode) { $tmpQ = $betterNode->getDescendants()->andWhere(['code' => $last]); /*echo "<br />Check better node<br />"; print_r($tmpQ->count()); echo "<br />";*/ if ($tmpQ->count() == 1) { $treeNode = $tmpQ->one(); /*echo "<br />Tree node<br />"; print_r($treeNode->dir); echo "<br />";*/ break; } } } } //die; } } } if ($treeNode) { \Yii::$app->cms->setCurrentTree($treeNode); $params['id'] = $treeNode->id; if ($normalized) { // pathInfo was changed by normalizer - we need also normalize route return $this->getNormalizer($manager)->normalizeRoute(['cms/tree/view', $params]); } else { return ['cms/tree/view', $params]; } } else { return false; } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/urlRules/UrlRuleStorageFile.php
src/components/urlRules/UrlRuleStorageFile.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components\urlRules; use skeeks\cms\components\Imaging; use skeeks\cms\helpers\StringHelper; /** * @author Semenov Alexander <semenov@skeeks.com> */ class UrlRuleStorageFile extends \yii\web\UrlRule { public function init() { if ($this->name === null) { $this->name = __CLASS__; } } /** * @param \yii\web\UrlManager $manager * @param string $route * @param array $params * @return bool|string */ public function createUrl($manager, $route, $params) { return false; } /** * @param \yii\web\UrlManager $manager * @param \yii\web\Request $request * @return array|bool */ public function parseRequest($manager, $request) { $pathInfo = $request->getPathInfo(); $params = $request->getQueryParams(); $extension = Imaging::getExtension($pathInfo); if (!$extension) { return false; } //В адресе должна быть пометка что это фильтр $strposFilter = strpos($pathInfo, "/" . Imaging::STORAGE_FILE_PREFIX); if (!$strposFilter) { return false; } return ['cms/storage-file/get-file', $params]; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/urlRules/UrlRuleSavedFilter.php
src/components/urlRules/UrlRuleSavedFilter.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 24.05.2015 */ namespace skeeks\cms\components\urlRules; use skeeks\cms\models\CmsContentElement; use skeeks\cms\models\CmsContentElementProperty; use skeeks\cms\models\CmsContentProperty; use skeeks\cms\models\CmsSavedFilter; use skeeks\cms\models\CmsSite; use skeeks\cms\models\CmsTree; use \yii\base\InvalidConfigException; use yii\helpers\ArrayHelper; use yii\helpers\Url; use yii\web\Application; /** * Class UrlRuleContentElement * @package skeeks\cms\components\urlRules */ class UrlRuleSavedFilter extends \yii\web\UrlRule { public function init() { if ($this->name === null) { $this->name = __CLASS__; } } /** * //Это можно использовать только в коротких сценариях, иначе произойдет переполнение памяти * @var array */ static public $models = []; /** * @param \yii\web\UrlManager $manager * @param string $route * @param array $params * @return bool|string */ public function createUrl($manager, $route, $params) { if ($route == 'cms/saved-filter/view') { $savedFilter = $this->_getElement($params); if (!$savedFilter) { return false; } $cmsTree = ArrayHelper::getValue($params, 'cmsTree'); ArrayHelper::remove($params, 'cmsTree'); $cmsSite = ArrayHelper::getValue($params, 'cmsSite', null); ArrayHelper::remove($params, 'cmsSite'); $url = $savedFilter->code . '-f' . $savedFilter->id; if (strpos($url, '//') !== false) { $url = preg_replace('#/+#', '/', $url); } /** * @see parent::createUrl() */ if ($url !== '') { $url .= ($this->suffix === null ? $manager->suffix : $this->suffix); } /** * @see parent::createUrl() */ if (!empty($params) && ($query = http_build_query($params)) !== '') { $url .= '?' . $query; } //Раздел привязан к сайту, сайт может отличаться от того на котором мы сейчас находимся if (!$cmsSite) { $siteClass = \Yii::$app->skeeks->siteClass; $cmsSite = $siteClass::getById($savedFilter->cms_site_id); //$cmsSite = $contentElement->cmsSite; } if ($cmsSite) { if ($cmsSite->cmsSiteMainDomain) { return $cmsSite->url . '/' . $url; } } return $url; } return false; } /** * * @param $params * @return bool|CmsContentElement */ protected function _getElement(&$params) { $id = (int)ArrayHelper::getValue($params, 'id'); $savedFilter = ArrayHelper::getValue($params, 'model'); if (!$id && !$savedFilter) { return false; } if ($savedFilter && $savedFilter instanceof CmsSavedFilter) { if (\Yii::$app instanceof Application) { self::$models[$savedFilter->id] = $savedFilter; } } else { /** * @var $savedFilter CmsSavedFilter */ if (!$savedFilter = ArrayHelper::getValue(self::$models, $id)) { $savedFilter = CmsSavedFilter::findOne(['id' => $id]); if (\Yii::$app instanceof Application) { self::$models[$id] = $savedFilter; } } } ArrayHelper::remove($params, 'id'); ArrayHelper::remove($params, 'code'); ArrayHelper::remove($params, 'model'); return $savedFilter; } /** * @param \yii\web\UrlManager $manager * @param \yii\web\Request $request * @return array|bool */ public function parseRequest($manager, $request) { if ($this->mode === self::CREATION_ONLY) { return false; } if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) { return false; } $pathInfo = $request->getPathInfo(); if ($this->host !== null) { $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo); } $params = $request->getQueryParams(); $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix); $treeNode = null; if (!$pathInfo) { return false; } if ($suffix) { $pathInfo = substr($pathInfo, 0, strlen($pathInfo) - strlen($suffix)); } if (preg_match('/\/(?<code>\S+)\-f(?<id>\d+)$/i', "/" . $pathInfo, $matches)) { return [ 'cms/saved-filter/view', [ 'id' => $matches['id'], 'code' => $matches['code'] ] ]; } return false; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/components/urlRules/UrlRuleImagePreview.php
src/components/urlRules/UrlRuleImagePreview.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\components\urlRules; use skeeks\cms\components\Imaging; /** * @author Semenov Alexander <semenov@skeeks.com> */ class UrlRuleImagePreview extends \yii\web\UrlRule { /** * * Добавлять слэш на конце или нет * * @var bool */ public $useLastDelimetr = true; public function init() { if ($this->name === null) { $this->name = __CLASS__; } } /** * @param \yii\web\UrlManager $manager * @param string $route * @param array $params * @return bool|string */ public function createUrl($manager, $route, $params) { return false; } /** * @param \yii\web\UrlManager $manager * @param \yii\web\Request $request * @return array|bool */ public function parseRequest($manager, $request) { $pathInfo = $request->getPathInfo(); $params = $request->getQueryParams(); /*$sourceOriginalFile = File::object($pathInfo); $extension = $sourceOriginalFile->getExtension();*/ $extension = Imaging::getExtension($pathInfo); //Если нет разрешения файла, то правило не срабатывает if (!$extension) { return false; } //preview картинки срабатывают только для определенных расширений $imaging = \Yii::$app->imaging; if (!$imaging->isAllowExtension($extension)) { return false; } //В адресе должна быть пометка что это фильтр $strposFilter = strpos($pathInfo, "/" . Imaging::THUMBNAIL_PREFIX); if (!$strposFilter) { return false; } return ['cms/image-preview/process', $params]; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/forms/TActiveFormHasFieldSets.php
src/forms/TActiveFormHasFieldSets.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\forms; use skeeks\cms\widgets\forms\FieldSetWidget; /** * @author Semenov Alexander <semenov@skeeks.com> */ trait TActiveFormHasFieldSets { /** * @var string */ public $firldSetClass = FieldSetWidget::class; /** * @param $name * @param array $widgetConfig * @return FieldSetWidget */ public function fieldSet($name, $widgetConfig = []) { $class = $this->firldSetClass; $widgetConfig['name'] = $name; $widgetConfig['activeForm'] = $this; return $class::begin($widgetConfig); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/forms/IActiveFormHasFieldSets.php
src/forms/IActiveFormHasFieldSets.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\forms; /** * @property string $icon; * * @author Semenov Alexander <semenov@skeeks.com> */ interface IActiveFormHasFieldSets { /** * @param $name * @param array $widgetConfig * @return FieldSetWidget */ public function fieldSet($name, $widgetConfig = []); }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/forms/TActiveFormHasPjax.php
src/forms/TActiveFormHasPjax.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\forms; use skeeks\cms\widgets\Pjax; use yii\base\WidgetEvent; use yii\helpers\ArrayHelper; /** * @author Semenov Alexander <semenov@skeeks.com> */ trait TActiveFormHasPjax { /** * @var bool */ public $usePjax = true; /** * @var array */ public $pjaxOptions = []; /** * @var string */ public $pjaxClass = Pjax::class; /** * @var null */ public $pjaxWidget = null; /** * @return $this */ protected function _initPjax() { if ($this->usePjax === false) { return $this; } $this->options = ArrayHelper::merge($this->options, [ 'data-pjax' => true, ]); $pjaxClass = $this->pjaxClass; $this->pjaxWidget = $pjaxClass::begin(ArrayHelper::merge([ 'id' => 'sx-pjax-form-'.$this->id, 'enablePushState' => false, 'isShowError' => true, ], $this->pjaxOptions)); //todo: подумать возможно с этим подходом мы как то упускаем exceptions $this->on(self::EVENT_AFTER_RUN, function (WidgetEvent $event) use ($pjaxClass) { ob_start(); ob_implicit_flush(false); echo $event->result; $pjaxClass::end(); $content = ob_get_clean(); $event->result = $content; return $event; }); return $this; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/forms/TActiveFormDynamicReload.php
src/forms/TActiveFormDynamicReload.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\forms; use skeeks\cms\helpers\RequestResponse; use skeeks\cms\widgets\Pjax; use yii\base\WidgetEvent; use yii\helpers\ArrayHelper; /** * @author Semenov Alexander <semenov@skeeks.com> */ trait TActiveFormDynamicReload { /** * @var string */ public $dynamicReloadFieldParam = RequestResponse::DYNAMIC_RELOAD_FIELD_ELEMENT; /** * @var string */ public $dynamicReloadNotSubmit = RequestResponse::DYNAMIC_RELOAD_NOT_SUBMIT; /** * @return $this */ protected function _initDynamicReload() { \Yii::$app->view->registerJs(<<<JS (function(sx, $, _) { sx.classes.FormDynamicReload = sx.classes.Component.extend({ _onDomReady: function() { var self = this; $("[" + this.get('formreload') + "=true]").on('change', function() { self.update(); }); }, update: function() { var self = this; _.delay(function() { var jForm = $("#" + self.get('id')); var jPjax = jForm.closest("[data-pjax-container]"); console.log(jPjax); jForm.append($('<input>', {'type': 'hidden', 'name' : self.get('nosubmit'), 'value': 'true'})); var data = { 'container': "#" + jPjax.attr("id"), 'method': jForm.attr("method"), 'data': jForm.serializeArray() }; console.log(data); $.pjax.reload(data); /*jForm.trigger("submit", { 'pjax' : 'reload' });*/ }, 200); } }); new sx.classes.FormDynamicReload({ 'id' : '{$this->id}', 'formreload' : '{$this->dynamicReloadFieldParam}', 'nosubmit' : '{$this->dynamicReloadNotSubmit}', }); })(sx, sx.$, sx._); JS ); return $this; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/actions/ErrorAction.php
src/actions/ErrorAction.php
<?php /** * ErrorAction * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 04.11.2014 * @since 1.0.0 */ namespace skeeks\cms\actions; use skeeks\cms\helpers\RequestResponse; use Yii; use yii\base\Exception; use yii\base\UserException; use yii\helpers\ArrayHelper; use yii\helpers\Url; use yii\web\NotFoundHttpException; use yii\web\Response; /** * Class ErrorAction * @package skeeks\cms\actions */ class ErrorAction extends \yii\web\ErrorAction { /** * Runs the action * * @return string result content */ public function run() { if (($exception = Yii::$app->getErrorHandler()->exception) === null) { return ''; } if ($exception instanceof \HttpException) { $code = $exception->statusCode; } else { $code = $exception->getCode(); } if ($exception instanceof Exception) { $name = $exception->getName(); } else { $name = $this->defaultName ?: Yii::t('yii', 'Error'); } if ($code) { $name .= " (#$code)"; } if ($exception instanceof UserException) { $message = $exception->getMessage(); } else { $message = $this->defaultMessage ?: Yii::t('yii', 'An internal server error occurred.'); } if (Yii::$app->getRequest()->getIsAjax()) { $rr = new RequestResponse(); $rr->success = false; $rr->message = "$name: $message"; return (array)$rr; } else { //All requests are to our backend //TODO::Add image processing $info = pathinfo(\Yii::$app->request->pathInfo); if ($extension = ArrayHelper::getValue($info, 'extension')) { $extension = \skeeks\cms\helpers\StringHelper::strtolower($extension); if (in_array($extension, ['js', 'css'])) { \Yii::$app->response->format = Response::FORMAT_RAW; if ($extension == 'js') { \Yii::$app->response->headers->set('Content-Type', 'application/javascript'); } if ($extension == 'css') { \Yii::$app->response->headers->set('Content-Type', 'text/css'); } $url = \Yii::$app->request->absoluteUrl; return "/* File: '{$url}' not found */"; } } return $this->controller->render($this->view ?: $this->id, [ 'name' => $name, 'message' => $message, 'exception' => $exception, ]); } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/actions/LogoutAction.php
src/actions/LogoutAction.php
<?php /** * LogoutAction * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 05.11.2014 * @since 1.0.0 */ namespace skeeks\cms\actions; use skeeks\cms\helpers\UrlHelper; use Yii; use yii\base\Action; /** * Class ErrorAction * @package skeeks\cms\actions */ class LogoutAction extends Action { /** * @return static */ public function run() { Yii::$app->user->logout(); if ($ref = UrlHelper::getCurrent()->getRef()) { return Yii::$app->getResponse()->redirect($ref); } else { return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl()); } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/actions/backend/BackendModelMultiDeactivateAction.php
src/actions/backend/BackendModelMultiDeactivateAction.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\actions\backend; use skeeks\cms\backend\actions\BackendModelMultiAction; /** * @author Semenov Alexander <semenov@skeeks.com> */ class BackendModelMultiDeactivateAction extends BackendModelMultiAction { public $attribute = 'is_active'; public $value = false; public function init() { if (!$this->icon) { $this->icon = "fas fa-eye-slash"; } if (!$this->name) { $this->name = \Yii::t('skeeks/cms', "Deactivate"); } parent::init(); } /** * @param $model * @return bool */ public function eachExecute($model) { try { $model->{$this->attribute} = $this->value; return $model->save(false); } catch (\Exception $e) { return false; } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/actions/backend/BackendModelMultiActivateAction.php
src/actions/backend/BackendModelMultiActivateAction.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\actions\backend; use skeeks\cms\backend\actions\BackendModelMultiAction; use skeeks\cms\components\Cms; /** * @author Semenov Alexander <semenov@skeeks.com> */ class BackendModelMultiActivateAction extends BackendModelMultiAction { public $attribute = 'is_active'; public $value = true; public function init() { if (!$this->icon) { $this->icon = "fas fa-eye"; } if (!$this->name) { $this->name = \Yii::t('skeeks/cms', "Activate"); } parent::init(); } /** * @param $model * @return bool */ public function eachExecute($model) { try { $model->{$this->attribute} = $this->value; return $model->save(false); } catch (\Exception $e) { return false; } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/messages/ru/main.php
src/messages/ru/main.php
<?php return [ "Components" => "Компоненты", "Meta Title" => "Заголовок (Meta title)", "Meta Keywords" => "Ключевые слова (Meta Keywords)", "Meta Description" => "Описание (Meta Description)", "Message" => "Сообщение", "Loading" => "Загрузка", "Users" => "Пользователи", "Online" => "Онлайн", "Offline" => "Оффлайн", "Cleaning temporarily downloaded files" => "Чистка временно загружаемых файлов", "Clearing the cache" => "Очистка кэша", "First name" => "Имя", "Last name" => "Фамилия", "Patronymic" => "Отчество", "Update" => "Обновить", "Save" => "Сохранить", "Create" => "Создать", "Delete" => "Удалить", "Apply" => "Применить", "Cancel" => "Отменить", "Copy" => "Копировать", "Move" => "Перенести", "Copy images?" => "Копировать изображения?", "Copy files?" => "Копировать файлы?", "List" => "Список", "Add" => "Добавить", "Edit" => "Редактировать", "Content management" => "Управление контентом", "Property management" => "Управление свойствами", "Managing property values" => "Управление значениями свойств", "Management of languages" => "Управление языковыми версиями", "Properties of elements" => "Свойства элементов", "Number of partitions where the property is filled" => "Количество разделов, где заполнено свойство", "Standard selection element" => "Стандартный элемент выбора", "Selection in the dialog box" => "Выбор в диалоговом окне", "Form element type" => "Тип элемента формы", "Root partition" => "Корневой раздел", "Personal data" => "Личные данные", "Change password" => "Смена пароля", "New password" => "Новый пароль", "New password (again)" => "Новый пароль (еще раз)", "Only shown in sections" => "Показывается только в разделах", "Always shown" => "Показывается всегда", "Yes/No" => "Да/Нет", "Options" => "Опции", "Property" => "Свойство", "Communication with sections" => "Связь с разделами", "Show properties that are filled by someone" => "Показывать свойства, которые заполнены у кого-либо", "Tree" => "Дерево", "Created By" => "Автор", "Updated By" => "Последний обновил", "Created At" => "Время создания", "Updated At" => "Время последнего обновления", "Published At" => "Начало активности", "Published To" => "Окончание активности", "Name" => "Название", "Description Short" => "Короткое описание", "Description Full" => "Подробное описание", "Description" => "Описание", "Unexpected Phone Number Format" => "Неожиданный формат номера телефона", "Descending" => "По убыванию", "Ascending" => "По возрастанию", "Priority" => "Сортировка", "Active" => "Активность", "Multiple" => "Множественное", "Is Required" => "Обязательное", "Code" => "Код", "Hint" => "Подсказка", "Default Value" => "Значение по умолчанию", "Default" => "По умолчанию", "Lang" => "Язык", "Component Settings" => "Настройки компонента", "Smart Filtrable" => "Показывать в умном фильтре", "With Description" => "Выводить поле для описания значения", "Searchable" => "Значения свойства участвуют в поиске", "Filtrable" => "Выводить на странице списка элементов поле для фильтрации по этому свойству", "Linked to sections" => "Привязка к разделам", "Value" => "Значение", "Server Name" => "Имя сервера", "Domain" => "Доменное имя", "Site" => "Сайт", "Status" => "Статус", "Rating" => "Рейтинг", "Phone" => "Телефон", "City" => "Город", "Verification Code" => "Проверочный код", "Display columns" => "Отображаемые колонки", "Hidden columns" => "Скрытые колонки", "Type" => "Тип", "File Type" => "Тип файла", "File Size" => "Размер файла", "Extension" => "Расширение", "Original Filename" => "Оригинальное название файла", "Name To Save" => "Название при скачивании", "Image Width" => "Ширина изображения", "Image Height" => "Высота изображения", "Files" => "Файлы", "Images" => "Изображения", "Content" => "Контент", "Host" => "Хост", 'Username' => 'Пользователь', 'Password' => 'Пароль', 'Charset' => 'Кодировка', "Rule" => "Правило", "Component" => "Компонент", "Editing view files" => "Редактирование шаблонов", "Phone number does not seem to be a valid phone number" => "Некорректный формат номера телефона", "Name of many sections" => "Название многих разделов", "Name of one section" => "Название одного раздела", "The Name One Element" => "Название одного элемента", "The Name Of The Elements (Plural)" => "Название элементов (множественное число)", "View Mode Sections And Elements" => "Режим просмотра разделов и элементов", "The Interface Binding Element to Sections" => "Интерфейс привязки элемента к разделам", "To index for search module" => "Индексировать для модуля поиска", "To start setting up options, save this property." => "Для начала заведения опций, сохраните это свойство.", "Managing partition property values" => "Управление значениями свойств разделов", "The main section" => "Основной раздел", "Main Image (announcement)" => "Главное изображение (для анонса)", "Main Image" => "Главное изображение", "Elements" => "Элементы", "Element" => "Элемент", "Linked to content" => "Связь с контентом", "Linked To Section's Type" => "Связь с типом раздела", "For the content of this code is already in use." => "Для данного контента этот код уже занят.", "For this section of the code is already in use." => "Для данного раздела этот код уже занят.", "For this section's type of the code is already in use." => "Для данного типа раздела этот код уже занят.", "For this subsection of the code is already in use." => "Для данного подраздела этот код уже занят.", "Version" => "Версия", "Aliases" => "Алиасы", "This user can not be removed" => "Этого пользователя нельзя удалить", "You can not delete yourself" => "Нельзя удалять самого себя", "Template" => "Шаблон", "Type of child partitions by default" => "Тип дочерних разделов по умолчанию", "If this parameter is not specified, the child partition is created of the same type as the current one." => "Если этот параметр не будет указан, то дочерний раздел будет создан того же типа что и текущий.", "The path to the template. If not specified, the pattern will be the same code." => "Путь к шаблону. Если не будет указан, то шаблон будет совпадать с кодом.", "Failed to create a section of the tree" => "Не удалось создать раздел дерева", "Failed to create the child element: " => "Не удалось создать дочерний элемент: ", "Unable to move: " => "Не удалось переместить: ", "Incorrect password." => "Некорректный пароль.", "Incorrect username or password." => "Некорректный логин или пароль.", "Sections" => "Разделы", "Section" => "Раздел", "User" => "Пользователь", "Approved" => "Подтвержден", "Phone Number" => "Номер телефона", "Storage" => "Хранилище", "Menu Positions" => "Позиции меню", "Login" => "Логин", "Address" => "Адрес", "Information" => "Информация", "Gender" => "Пол", "Logged At" => "Время последней авторизации", "Last Activity At" => "Время последней активности", "Last Activity In The Admin At" => "Время последней активности в админке", "Image" => "Фото", "Username or Email" => "Логин или Email", "Remember me" => "Запомнить меня", "New Password Confirm" => "Подтверждение пароля", "New passwords do not match" => "Новые пароли не совпадают", "User not found" => "Пользователь не найден", "The request to change the password for" => "Запрос на смену пароля для ", "This login is already in use by another user." => "Этот логин уже занят другим пользователем.", "Sign up at site" => "Регистрация на сайте ", "Sign up" => "Зарегистрироваться", "Saved" => "Сохранено", "Could not save" => "Не удалось сохранить", "No records found" => "Записи не найдены", "Mission complete" => "Задание выполнено", "system administration" => "система администрирования", "Main" => "Основное", "Access" => "Доступ", "Security" => "Безопасность", "Sort by what parameter" => "По какому параметру сортировать", "sorting direction" => "направление сортировки", "Sorting direction" => "Направление сортировки", "Display column" => "Отображаемые колонки", "Admin panel" => "Админ панель", "Setting the admin panel" => "Настройки админ панели", "Additional css and js admin area" => "Дополнительные css и js админки", "Include stylized window confirmation (confirm)" => "Включить стилизованные окошки подтверждения (confirm)", "Include stylized window question with one field (promt)" => "Включить стилизованные окошки вопрос с одним полем (promt)", "Interface language" => "Язык интерфейса", "Turning ajax navigation" => "Включение ajax навигации", "Parameter name pages, pagination" => "Названия парамтера страниц, при постраничной навигации", "Number of records on one page" => "Количество записей на одной странице", "Instruments" => "Инструменты", "Theme of formalization" => "Тема оформления", "Height" => "Высота", "Use code highlighting" => "Использовать подсветку кода", "Theme of {theme} code" => "Тема {theme} подсветки кода", "Time through which block user" => "Время, через которое блокировать пользователя", "The name of the controller" => "Название контроллера", "Are you sure you want to delete this item?" => "Вы уверены, что хотите удалить этот элемент?", "Are you sure you want to permanently delete the selected items?" => "Вы действительно хотите безвозвратно удалить выбранные элементы?", "For {modelname} must specify the model class" => "Для {modelname} необходимо указать класс модели", "the class is not found, you must specify the existing class model" => "класс не нейден, необходимо указать существующий класс модели", "Record deleted successfully" => "Запись успешно удалена", "Record deleted unsuccessfully" => "Не получилось удалить запись", "Changes saved" => "Изминения сохранены", "Managing privileges" => "Управление привилегиями", "Update privileges" => "Обновить привилегии", "Administration" => "Администрирование", "Update completed" => "Обновление завершено", "Saved successfully" => "Успешно сохранено", "Failed to save" => "Не удалось сохранить", "This entry can not be deleted!" => "Эту запись нельзя удалять!", "Managing Roles" => "Управление ролями", "Watch" => "Смотреть", "Lock Mode" => "Режим блокировки", "Password recovery" => "Восстановление пароля", "New password sent to your e-mail" => "Новый пароль отправлен на ваш e-mail", "Link outdated, try to request a password recovery again." => "Ссылка устарела, попробуйте запросить восстановление пароля еще раз.", "Failed log in" => "Не получилось авторизоваться", "Authorization" => "Авторизация", "Unsuccessful attempt authorization" => "Неудачная попытка авторизации", "Check your email address" => "Проверьте ваш email", "Failed send email" => "Не получилось отправить email", "Checking system" => "Проверка системы", "Testing" => "Тесирование", "Test is not found" => "Тест не найден", "Incorrect test" => "Некорректный тест", "Test is not done" => "Тест не выполнен", "Deleting temporary files" => "Удаление временных файлов", "Clearing temporary data" => "Чистка временных данных", "clearing temporary data" => "чистка временных данных", "Cleaning temporary {css} and {js}" => "чистка временных {css} и {js}", "temporary files" => "временные файлы", "current site" => "текущий сайт", "Cache files" => "Файлы кэша", "Files debug information" => "Файлы дебаг информации", "Log files" => "Файлы логов", "Cache cleared" => "Кэш очищен", "Work to database" => "Работа с базой данных", "The cache table has been successfully updated" => "Кэш таблиц успешно обновлен", "A copy created successfully" => "Копия создана успешно", "Testing send email messages from site" => "Тестирование отправки email сообщений с сайта", "Testing sending email" => "Тестирование отправки email", "Submitted" => "Отправлено", "Not sent" => "Не отправлено", "Code generator" => "Генератор кода", "Desktop" => "Рабочий стол", "Main page" => "Главная страница", "Information about the system" => "Информация о системе", "General information" => "Общая информация", "File, automatic paths to the modules successfully updated" => "Файл, автоматических путей к модулям, успешно обновлен", "File, automatic paths to the modules are not updated" => "Файл, автоматических путей к модулям, не обновлен", "Not Specified Places to record" => "Не указано окружение для записи", "File successfully created and written" => "Файл успешно создан и записан", "Failed to write file" => "Не удалось записать файл", "File deleted successfully" => "Файл успешно удален", "Could not delete the file" => "Не удалось удалить файл", "Console" => "Консоль", "{ssh} console" => "{ssh} консоль", "not specified" => "не определен", "{controller} must be inherited from" => "{controller} должен быть наследован от", "Subject" => "Тема сообщения", "To" => "Кому", "From" => "От кого", "Command" => "Комманда", "Data" => "Данные", "recover password" => "восстановить пароль", "Recover password" => "Восстановить пароль", "Log in" => "Войти", "log in" => "Авторизоваться", "I remembered password" => "Я вспомнил пароль", "You have successfully logged in, but not for too long been active in the control panel site." => "Вы успешно авторизованы, но слишком долго не проявляли активность в панеле управления сайтом.", "Please confirm that it is you, and enter your password." => "Пожалуйста, подтвердите что это вы, и введите ваш пароль.", "Additional properties" => "Дополнительные свойства", "You can create your own any properties." => "Вы можете создавать самостоятельно любые свойства.", "Additional properties are not set" => "Дополнительные свойства не заданы", "Full system testing" => "Полное тестирование системы", "Full system scan helps to find the causes of the problems in the work site, and avoid errors in the future. Help for each test will help eliminate the cause of the error." => "Полная проверка системы помогает найти причины проблем в работе сайта и избежать появление ошибок в дальнейшем. Справка по каждому тесту поможет устранить причину ошибки.", "Start testing" => "Начать тестирование", "Stop" => "Остановить", "Testing the system (Progress" => "Тестирование системы (Выполнено", "Test" => "Тест", "Delete temporary files" => "Удалить временные файлы", "Refresh cache table structure" => "Обновить кэш структуры таблиц", "Table structure" => "Структура таблиц", "Number of columns" => "Количество колонок", "Number of foreign keys" => "Количество внешних ключей", "Settings" => "Настройки", "Cache table structure" => "Кэш структуры таблиц", "Cache query" => "Кэш запросов", "Backup" => "Бэкапы", "Make a backup" => "Сделать бэкап", "To create backups of the database used by the utility {mysqldump}, and this tool will only work if the utility is installed on your server." => "Для создания бэкапов базы данных используется утилита {mysqldump}, и данный инструмент работает только в том случае если эта утилита установлена на вашем сервере.", "Directory with files of backups database is not found." => "Дирриктория с файлами бэкапов базы данных не найдена.", "Letter test" => "Тестовое письмо", "Send {email}" => "Отправить {email}", "Result of sending" => "Результат отправки", "Configuration of component {cms} sending {email}" => "Конфигурация {cms} компонента отправки {email}", "Transport" => "Транспорт", "Transport running" => "Транспорт запущен", "Configuration of {php} sending {email}" => "Конфигурация {php} отправки {email}", "The site managment system" => "Система управления сайтом", "Welcome! You are in the site management system." => "Добро пожаловать! Вы находитесь в системе управления сайтом.", "Free place" => "Свободное место", "Number of users" => "Количество пользователей", "At percent ratio" => "В процентном соотношении", "Read more" => "Подробнее", "Total at server" => "Всего на сервере", "Used" => "Занято", "Free" => "Осталось", "Yes" => "Да", "No" => "Нет", "To record" => "Записать", "Project configuration" => "Конфигурация проекта", "{yii} Version" => "Версия {yii}", "Project name" => "Название проекта", "edit" => "изменить", "Environment ({yii_env})" => "Окружение ({yii_env})", "Development mode ({yii_debug})" => "Режим разработки ({yii_debug})", "Mode autogeneration paths to modules {cms} ({e_m_c})" => "Режим автогенерации путей к модулям {cms} ({e_m_c})", "Automatically generated file paths modules {cms} ({agmf})" => "Автоматически сгенерированный файл с путями модулей {cms} ({agmf})", "A folder with file paths to the modules" => "Папка с файлом путей к модулям", "Is not writable" => "Не доступна для записи", "Checks environment variables" => "Проверяются переменные окружения", "Installed {cms} modules" => "Установленные модули {cms}", "Module name" => "Название модуля", "Module version" => "Версия модуля", "All extensions and modules {yii}" => "Все расширения и модули {yii}", "{php} configuration" => "{php} конфигурация", "To main page of admin area" => "На главную страницу админки", "To main page of site" => "Открыть сайтовую часть", "Toggle Full Screen" => "Переключение полноэкранного режима", "Clear cache and temporary files" => "Очистить кэш и временные файлы", "Project settings" => "Настройки проекта", "Your profile" => "Ваш профиль", "Profile" => "Профиль", "Exit" => "Выход", "To block" => "Заблокировать", "Close menu" => "Закрыть меню", "Open menu" => "Открыть меню", "Setting up access to this section" => "Настройки доступа к этому разделу", "Setting up access to the section" => "Настройки доступа к разделу", "Specify which groups of users will have access." => "Укажите пользователи каких групп получат доступ.", "Code privileges" => "Код привилегии", "The list displays only those groups that have access to the system administration." => "В списке показаны только те группы, которые имеют доступ к системе администрирования.", "Go to site {cms}" => "Перейти на сайт {cms}", "Go to site of the developer" => "Перейти на сайт разработчика системы", "Execute command" => "Выполнить комманду", "Choose file" => "Выбрать файл", "Pagination" => "Постраничная навигация", "from smaller to larger" => "от меньшего к большему", "from highest to lowest" => "от большего к меньшему", "Incorrectly configured widget, you must pass an controller object to which is built widget" => "Некорректно сконфигурирован виджет, необходимо передать объект контроллера для которого сроится виджет", "For this controller can not build action" => "У данного контроллера нельзя построить действия", "Possible actions" => "Возможные действия", "On the page" => "На странице", "Button actions" => "Кнопка действий", "Selecting items" => "Выбор элементов", "Sequence number" => "Порядковый номер", "Minimize" => "Свернуть", "Restore" => "Развернуть", "Show at site" => "Показать на сайте", "Create subsection" => "Создать подраздел", "Binding to an element" => "Привязка к элементу", "File" => "Файл", "Combobox" => "Выпадающий список", "Radio Buttons (selecting one value)" => "Радио кнопки (выбор одного значения)", "Element form" => "Элемент формы", "Number" => "Число", "Text" => "Текст", "Text field" => "Текстовое поле", "Text string" => "Текстовая строка", "The number of lines of the text field" => "Количество строк текстового поля", "This INPUT to opened the palette" => "Это инпут в открывающейся политре", "Choice of color" => "Выбор цвета", "Show extended palette of colors" => "Показывать расширенную политру цветов", "Format conservation values" => "Формат сохранения значения", "Use the native color selection" => "Использовать нативный выбор цвета", "Management transparency" => "Управление прозрачностью", "Show input field values" => "Показывать поле для ввода значения", "Generally show the palette" => "Вообще показывать политру", "Types" => "Типы", "Datetime" => "Дата и время", "Only date" => "Только дата", "Standard file selection" => "Стандартный выбор файла", "Multiple choice" => "Множественный выбор", "File manager" => "Файловый менеджер", "File storage" => "Файлы в хранилище", "Product settings" => "Настройки продукта", "Sites" => "Сайты", "Languages" => "Языки", "Section markers" => "Метки разделов", "Server file storage" => "Сервера файлового хранилища", "Settings sections" => "Настройки разделов", "Content settings" => "Настройки контента", "Module settings" => "Настройки модулей", "Agents" => "Агенты", "Users and Access" => "Пользователи и доступ", "User management" => "Управление пользователями", "User properties" => "Свойства пользователей", "The base of {email} addresses" => "База {email} адресов", "Base phones" => "База телефонов", "Searching" => "Поиск", "Statistic" => "Статистика", "Jump list" => "Список переходов", "Phrase list" => "Список фраз", "Sending {email}" => "Отправка {email}", "Additionally" => "Дополнительно", "Local storage" => "Локальное хранилище", "Superuser" => "Суперпользователь", "Unauthorized user" => "Неавторизованный пользователь", "Admin" => "Администратор", "Manager (access to the administration)" => "Менеджер (доступ в администрированию)", "Editor (access to the administration)" => "Редактор (доступ в администрированию)", "Registered user" => "Зарегистрированный пользователь", "Confirmed user" => "Подтвержденный пользователь", "Access to system administration" => "Доступ к системе администрирования", "Access to the site control panel" => "Доступ к панеле управления сайтом", "Updating data records" => "Обновление данных записей", "Updating data own records" => "Обновление данных своих записей", "Updating additional data records" => "Обновление дополнительных данных записей", "Updating additional data own records" => "Обновление дополнительных данных своих записей", "Deleting records" => "Удаление записей", "Deleting own records" => "Удаление своих записей",
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
true
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/messages/ru/user.php
src/messages/ru/user.php
<?php /** * Группа переводов для пользователей * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 29.10.2015 */ return [ 'Name' => 'Имя' ];
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsDeal2bill.php
src/models/CmsDeal2bill.php
<?php namespace skeeks\cms\models; use skeeks\cms\shop\models\ShopBill; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "crm_client_map". * * @property int $id * @property int $created_by * @property int $created_at * @property int $cms_deal_id Сделка * @property int $shop_bill_id Счет * * @property CmsDeal $deal * @property ShopBill $bill */ class CmsDeal2bill extends \skeeks\cms\base\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return '{{%cms_deal2bill}}'; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['cms_deal_id', 'shop_bill_id'], 'integer'], [['cms_deal_id', 'shop_bill_id'], 'required'], [['cms_deal_id', 'shop_bill_id'], 'unique', 'targetAttribute' => ['cms_deal_id', 'shop_bill_id']], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'shop_bill_id' => Yii::t('app', 'Контрагент'), 'cms_deal_id' => Yii::t('app', 'Компания'), ]); } /** * {@inheritdoc} */ public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ ]); } /** * @return \yii\db\ActiveQuery */ public function getDeal() { return $this->hasOne(CmsDeal::class, ['id' => 'cms_deal_id']); } /** * @return \yii\db\ActiveQuery */ public function getBill() { return $this->hasOne(ShopBill::class, ['id' => 'shop_bill_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsContentProperty2tree.php
src/models/CmsContentProperty2tree.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 09.11.2014 * @since 1.0.0 */ namespace skeeks\cms\models; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_content_property2tree". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property integer $cms_content_property_id * @property integer $cms_tree_id * * @property CmsContentProperty $cmsContentProperty * @property CmsTree $cmsTree */ class CmsContentProperty2tree extends Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_content_property2tree}}'; } public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_content_id' => Yii::t('skeeks/cms', 'Linked to content'), 'cms_content_property_id' => Yii::t('skeeks/cms', 'Linked to content'), ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ ['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_content_property_id', 'cms_tree_id'], 'integer' ], [['cms_content_property_id', 'cms_tree_id'], 'required'], [ ['cms_content_property_id', 'cms_tree_id'], 'unique', 'targetAttribute' => ['cms_content_property_id', 'cms_tree_id'], 'message' => 'The combination of Cms Content Property ID and Cms Tree ID has already been taken.' ], [ ['cms_content_property_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsContentProperty::className(), 'targetAttribute' => ['cms_content_property_id' => 'id'] ], [ ['cms_tree_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsTree::className(), 'targetAttribute' => ['cms_tree_id' => 'id'] ], ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsContentProperty() { return $this->hasOne(CmsContentProperty::className(), ['id' => 'cms_content_property_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsTree() { return $this->hasOne(CmsTree::className(), ['id' => 'cms_tree_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsLogFile.php
src/models/CmsLogFile.php
<?php namespace skeeks\cms\models; use Yii; /** * This is the model class for table "{{%cms_content_element_file}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property integer $storage_file_id * @property integer $log_id * @property integer $priority * * @property CmsLog $cmsLog * @property CmsStorageFile $storageFile */ class CmsLogFile extends \skeeks\cms\models\Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_log_file}}'; } /** * @inheritdoc */ public function rules() { return [ [ [ 'created_by', 'updated_by', 'created_at', 'updated_at', 'storage_file_id', 'cms_log_id', 'priority', ], 'integer', ], [['storage_file_id', 'cms_log_id'], 'required'], [ ['storage_file_id', 'cms_log_id'], 'unique', 'targetAttribute' => ['storage_file_id', 'cms_log_id'], 'message' => \Yii::t('skeeks/cms', 'The combination of Storage File ID and Content Element ID has already been taken.'), ], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('skeeks/cms', 'ID'), 'created_by' => Yii::t('skeeks/cms', 'Created By'), 'updated_by' => Yii::t('skeeks/cms', 'Updated By'), 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'storage_file_id' => Yii::t('skeeks/cms', 'Storage File ID'), 'cms_log_id' => Yii::t('skeeks/cms', 'Content Element ID'), 'priority' => Yii::t('skeeks/cms', 'Priority'), ]; } /** * @return \yii\db\ActiveQuery */ public function getLog() { return $this->hasOne(CmsLog::className(), ['id' => 'cms_log_id']); } /** * @return \yii\db\ActiveQuery */ public function getStorageFile() { return $this->hasOne(CmsStorageFile::className(), ['id' => 'storage_file_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsSmsMessage.php
src/models/CmsSmsMessage.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\models; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_sms_message". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property string|null $user_ip * @property int $cms_site_id * @property int|null $cms_sms_provider_id * @property string $phone * @property string|null $message * @property string $status * @property string|null $error_message * @property string|null $provider_status * @property string|null $provider_message_id * * @property boolean $isDelivered * @property boolean $isError * * @property string $statusAsText * @property CmsSite $cmsSite * @property CmsSmsProvider $cmsSmsProvider */ class CmsSmsMessage extends \skeeks\cms\base\ActiveRecord { const STATUS_ERROR = "error"; const STATUS_NEW = "new"; const STATUS_DELIVERED = "delivered"; /** * {@inheritdoc} */ public static function tableName() { return 'cms_sms_message'; } public function statuses() { return [ self::STATUS_NEW => "Новое", self::STATUS_DELIVERED => "Доставлено", self::STATUS_ERROR => "Ошибка", ]; } /** * @return bool */ public function getIsDelivered() { return $this->status == self::STATUS_DELIVERED; } /** * @return bool */ public function getIsError() { return $this->status == self::STATUS_ERROR; } /** * @return string */ public function getStatusAsText() { return (string)ArrayHelper::getValue(self::statuses(), $this->status); } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'cms_sms_provider_id'], 'integer'], [['phone', 'message'], 'required'], [['error_message'], 'string'], [['message'], 'string'], [['user_ip'], 'string', 'max' => 20], [['phone', 'status', 'provider_status'], 'string', 'max' => 255], [['provider_message_id'], 'string', 'max' => 255], [['cms_sms_provider_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSmsProvider::class, 'targetAttribute' => ['cms_sms_provider_id' => 'id']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::class, 'targetAttribute' => ['cms_site_id' => 'id']], [ ['error_message', 'provider_status', 'provider_message_id'], 'default', 'value' => null, ], [ 'status', 'default', 'value' => self::STATUS_NEW, ], [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [ 'user_ip', 'default', 'value' => function () { return \Yii::$app->request->userIP; }, ], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'user_ip' => 'IP', 'cms_sms_provider_id' => 'Sms провайдер', 'phone' => 'Телефон', 'message' => 'Сообщение', 'status' => 'Статус', 'provider_status' => 'Статус sms провайдера', ]); } /** * Gets query for [[CmsSite]]. * * @return \yii\db\ActiveQuery */ public function getCmsSite() { $className = \Yii::$app->skeeks->siteClass; return $this->hasOne($className::className(), ['id' => 'cms_site_id']); } /** * Gets query for [[CmsSite]]. * * @return \yii\db\ActiveQuery */ public function getCmsSmsProvider() { return $this->hasOne(CmsSmsProvider::class, ['id' => 'cms_sms_provider_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsCompany2contractor.php
src/models/CmsCompany2contractor.php
<?php namespace skeeks\cms\models; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "crm_client_map". * * @property int $id * @property int $created_by * @property int $updated_by * @property int $created_at * @property int $updated_at * @property int $cms_company_id Компания * @property int $cms_contractor_id Контрагент * * @property CmsContractor $cmsContractor * @property CmsCompany $cmsCompany */ class CmsCompany2contractor extends \skeeks\cms\base\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return '{{%cms_company2contractor}}'; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['cms_company_id', 'cms_contractor_id'], 'integer'], [['cms_company_id', 'cms_contractor_id'], 'required'], [['cms_company_id', 'cms_contractor_id'], 'unique', 'targetAttribute' => ['cms_company_id', 'cms_contractor_id']], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_contractor_id' => Yii::t('app', 'Контрагент'), 'cms_company_id' => Yii::t('app', 'Компания'), ]); } /** * {@inheritdoc} */ public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsContractor() { return $this->hasOne(CmsContractor::class, ['id' => 'cms_contractor_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsCompany() { return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsDashboard.php
src/models/CmsDashboard.php
<?php namespace skeeks\cms\models; use Yii; /** * This is the model class for table "{{%cms_dashboard}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property string $name * @property integer $cms_user_id * @property integer $priority * @property string $columns * @property string $columns_settings * * @property CmsUser $cmsUser * @property CmsDashboardWidget[] $cmsDashboardWidgets */ class CmsDashboard extends \skeeks\cms\models\Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_dashboard}}'; } /** * @inheritdoc */ public function rules() { return [ [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_user_id', 'priority', 'columns'], 'integer'], [['name'], 'required'], [['columns_settings'], 'string'], [['name'], 'string', 'max' => 255], [['priority'], 'default', 'value' => 100], [['columns'], 'default', 'value' => 1], [['columns'], 'integer', 'max' => 6, 'min' => 1], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('skeeks/cms', 'ID'), 'created_by' => Yii::t('skeeks/cms', 'Created By'), 'updated_by' => Yii::t('skeeks/cms', 'Updated By'), 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'name' => Yii::t('skeeks/cms', 'Name'), 'cms_user_id' => Yii::t('skeeks/cms', 'Cms User ID'), 'priority' => Yii::t('skeeks/cms', 'Priority'), 'columns' => Yii::t('skeeks/cms', 'Number of columns'), 'columns_settings' => Yii::t('skeeks/cms', 'Columns Settings'), ]; } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { return $this->hasOne(CmsUser::className(), ['id' => 'cms_user_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsDashboardWidgets() { return $this->hasMany(CmsDashboardWidget::className(), ['cms_dashboard_id' => 'id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsCompanyCategory.php
src/models/CmsCompanyCategory.php
<?php namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use yii\helpers\ArrayHelper; /** * @property int $id * @property int|null $created_by * @property int|null $created_at * @property string|null $name * @property int $sort */ class CmsCompanyCategory extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%cms_company_category}}'; } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['created_by', 'created_at', 'sort'], 'integer'], [['name'], 'required'], [['name'], 'string', 'max' => 255], [ ['name'], 'unique', 'targetAttribute' => ['name'], //'message' => 'Этот email уже занят' ], [['sort'], 'default', 'value' => 100], ]); } /** * @inheritdoc */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'name' => 'Название', 'sort' => 'Сортировка', ]); } /** * @inheritdoc */ public function attributeHints() { return array_merge(parent::attributeHints(), [ 'name' => 'Обязательное уникальное поле', 'sort' => 'Чем ниже цифра тем выше в списке', ]); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsLang.php
src/models/CmsLang.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 20.05.2015 */ namespace skeeks\cms\models; use skeeks\cms\components\Cms; use skeeks\cms\models\behaviors\HasStorageFile; use Yii; use yii\base\Event; use yii\db\BaseActiveRecord; use yii\helpers\ArrayHelper; /** * This is the model class for table "{{%cms_lang}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property boolean $is_active * @property integer $priority * @property string $code * @property string $name * @property string $description * @property integer $image_id * * @property CmsSite[] $cmsSites * @property CmsStorageFile $image */ class CmsLang extends Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_lang}}'; } public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ HasStorageFile::className() => [ 'class' => HasStorageFile::className(), 'fields' => ['image_id'] ], ]); } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'is_active' => Yii::t('skeeks/cms', 'Active'), 'priority' => Yii::t('skeeks/cms', 'Priority'), 'code' => Yii::t('skeeks/cms', 'Code'), 'name' => Yii::t('skeeks/cms', 'Name'), 'description' => Yii::t('skeeks/cms', 'Description'), 'image_id' => Yii::t('skeeks/cms', 'Image'), ]); } public function attributeHints() { return array_merge(parent::attributeLabels(), [ 'is_active' => \Yii::t('skeeks/cms', 'On the site must be included at least one language'), ]); } /** * @inheritdoc */ public function rules() { return array_merge(parent::rules(), [ [['created_by', 'updated_by', 'created_at', 'updated_at', 'priority'], 'integer'], [['code', 'name'], 'required'], [['code'], 'validateCode'], [['code'], 'string', 'max' => 5], [['name', 'description'], 'string', 'max' => 255], [['code'], 'unique'], ['priority', 'default', 'value' => 500], [['image_id'], 'safe'], [['is_active'], 'boolean'], [ ['image_id'], \skeeks\cms\validators\FileValidator::class, 'skipOnEmpty' => false, 'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'], 'maxFiles' => 1, 'maxSize' => 1024 * 1024 * 2, 'minSize' => 100, ], ]); } public function validateCode($attribute) { if (!preg_match('/^[a-zA-Z]{1}[a-zA-Z0-9-]{1,255}$/', $this->$attribute)) { $this->addError($attribute, \Yii::t('skeeks/cms', 'Use only letters of the alphabet in lower or upper case and numbers, the first character of the letter (Example {code})', ['code' => 'code1'])); } } /** * @return \yii\db\ActiveQuery */ public function getCmsSites() { return $this->hasMany(CmsSite::className(), ['lang_code' => 'code']); } /** * @return \yii\db\ActiveQuery */ public function getImage() { return $this->hasOne(CmsStorageFile::className(), ['id' => 'image_id']); } /** * @deprecated * @return string */ public function getDef() { return \Yii::$app->cms->languageCode == $this->code ? "Y" : "N"; } /** * @deprecated * @return string */ public function getActive() { return $this->is_active ? "Y" : "N"; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsFaq.php
src/models/CmsFaq.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 14.09.2015 */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\behaviors\CmsLogBehavior; use skeeks\cms\behaviors\RelationalBehavior; use skeeks\cms\models\behaviors\traits\HasLogTrait; use skeeks\modules\cms\money\models\Currency; use yii\helpers\ArrayHelper; /** * This is the model class for table "shop_favorite_product". * * @property int $id * @property int|null $created_at * @property int|null $created_by * @property string $name * @property string $response * @property int $is_active * @property int $priority * * @property CmsContentElement[] $contentElements * @property CmsTree[] $trees */ class CmsFaq extends ActiveRecord { use HasLogTrait; public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ RelationalBehavior::class => [ 'class' => RelationalBehavior::class, 'relationNames' => [ 'contentElements', 'trees', ], ], CmsLogBehavior::class => [ 'class' => CmsLogBehavior::class, /*'relation_map' => [ 'cms_company_status_id' => 'status', ],*/ ], ]); } /** * @inheritdoc */ public static function tableName() { return '{{%cms_faq}}'; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['response'], 'string'], [['name'], 'string', 'max' => 100], [['name', 'response'], 'required'], ['priority', 'default', 'value' => 500], ['is_active', 'default', 'value' => 1], [['trees', 'contentElements'], 'safe'], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'name' => 'Вопрос', 'is_active' => 'Показывается?', 'response' => 'Ответ', 'priority' => 'Сортировка', 'trees' => 'Разделы', 'contentElements' => 'Контент', ]); } /** * @return \yii\db\ActiveQuery */ public function getTrees() { return $this->hasMany(CmsTree::class, ['id' => 'cms_tree_id'])->viaTable("cms_faq2tree", ['cms_faq_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getContentElements() { return $this->hasMany(CmsContentElement::class, ['id' => 'cms_content_element_id'])->viaTable("cms_faq2content_element", ['cms_faq_id' => 'id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsContractorMap.php
src/models/CmsContractorMap.php
<?php namespace skeeks\cms\models; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "crm_client_map". * * @property int $id * @property int $created_by * @property int $updated_by * @property int $created_at * @property int $updated_at * @property int $cms_user_id Пользователь * @property int $cms_contractor_id Контакт * * @property CmsContractor $cmsContractor * @property CmsUser $cmsUser */ class CmsContractorMap extends \skeeks\cms\base\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return '{{%cms_contractor_map}}'; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['cms_user_id', 'cms_contractor_id'], 'integer'], [['cms_user_id', 'cms_contractor_id'], 'required'], [['cms_user_id', 'cms_contractor_id'], 'unique', 'targetAttribute' => ['cms_user_id', 'cms_contractor_id']], [['cms_contractor_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsContractor::class, 'targetAttribute' => ['cms_contractor_id' => 'id']], [['cms_user_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::class, 'targetAttribute' => ['cms_user_id' => 'id']], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_contractor_id' => Yii::t('app', 'Контрагент'), 'cms_user_id' => Yii::t('app', 'Пользователь'), ]); } /** * {@inheritdoc} */ public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ ]); } /** * @return \yii\db\ActiveQuery */ public function getCrmContact() { return $this->hasOne(CmsContractor::class, ['id' => 'cms_contractor_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { $userClass = \Yii::$app->user->identityClass; return $this->hasOne($userClass, ['id' => 'cms_user_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsProject.php
src/models/CmsProject.php
<?php namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\behaviors\CmsLogBehavior; use skeeks\cms\behaviors\RelationalBehavior; use skeeks\cms\models\behaviors\HasStorageFile; use skeeks\cms\models\behaviors\traits\HasLogTrait; use skeeks\cms\models\queries\CmsCompanyQuery; use skeeks\cms\models\queries\CmsProjectQuery; use skeeks\cms\models\queries\CmsTaskQuery; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_contractor". * * @property int $id * @property int|null $created_by * @property int|null $created_at * @property string $name Название * @property string|null $description Название * @property int|null $cms_image_id Картинка * @property int|null $cms_company_id Компания * @property int|null $cms_user_id Клиент * @property int $is_active Активность * @property int $is_private Закрытый? * * @property CmsStorageFile|null $cmsImage * @property CmsCompany|null $cmsCompany * @property CmsUser|null $cmsUser * * @property CmsUser[] $users * @property CmsUser[] $managers * @property CmsTask[] $tasks */ class CmsProject extends ActiveRecord { use HasLogTrait; /** * {@inheritdoc} */ public static function tableName() { return 'cms_project'; } public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ RelationalBehavior::class => [ 'class' => RelationalBehavior::class, 'relationNames' => [ 'managers', 'users', ], ], HasStorageFile::class => [ 'class' => HasStorageFile::class, 'fields' => [ 'cms_image_id', ], ], CmsLogBehavior::class => [ 'class' => CmsLogBehavior::class, 'relation_map' => [ 'cms_company_id' => 'cmsCompany', 'cms_user_id' => 'cmsUser', ], ], ]); } /** * {@inheritdoc} */ public function rules() { return array_merge(parent::rules(), [ [['created_by', 'created_at'], 'integer'], [['is_active'], 'integer'], [['is_private'], 'integer'], [['cms_company_id'], 'integer'], [['cms_user_id'], 'integer'], [['name'], 'string', 'max' => 255], [['name'], 'required'], [['description'], 'string'], [ [ 'description', ], 'default', 'value' => null, ], [['cms_image_id'], 'safe'], [ ['cms_image_id'], \skeeks\cms\validators\FileValidator::class, 'skipOnEmpty' => false, 'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'], 'maxFiles' => 1, 'maxSize' => 1024 * 1024 * 10, 'minSize' => 256, ], [['managers'], 'safe'], [['users'], 'safe'], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'name' => 'Название', 'cms_image_id' => 'Изображение', 'description' => 'Описание', 'is_active' => 'Активность', 'is_private' => 'Закрытый?', 'managers' => 'Работают с проектом', 'users' => 'Клиенты', 'cms_company_id' => 'Компания', 'cms_user_id' => 'Клиент', ]); } /** * Gets query for [[CmsImage]]. * * @return \yii\db\ActiveQuery */ public function getCmsImage() { return $this->hasOne(CmsStorageFile::class, ['id' => 'cms_image_id']); } /** * Gets query for [[CmsImage]]. * * @return \yii\db\ActiveQuery */ public function getCmsCompany() { return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_id']); } /** * Gets query for [[CmsImage]]. * * @return \yii\db\ActiveQuery */ public function getCmsUser() { return $this->hasOne(\Yii::$app->user->identityClass, ['id' => 'cms_user_id']); } /** * @return \yii\db\ActiveQuery */ public function getUsers() { $class = \Yii::$app->user->identityClass; return $this->hasMany($class, ['id' => 'cms_user_id']) ->via('cmsProject2users');; } /** * @return \yii\db\ActiveQuery */ public function getManagers() { $class = \Yii::$app->user->identityClass; return $this->hasMany($class, ['id' => 'cms_user_id']) ->via('cmsProject2managers');; } /** * @return \yii\db\ActiveQuery */ public function getCmsProject2managers() { return $this->hasMany(CmsProject2manager::class, ['cms_project_id' => 'id']) ->from(['cmsProject2managers' => CmsProject2manager::tableName()]); } /** * @return \yii\db\ActiveQuery */ public function getCmsProject2users() { return $this->hasMany(CmsProject2user::class, ['cms_project_id' => 'id']) ->from(['cmsProject2users' => CmsProject2user::tableName()])/*->orderBy(['sort' => SORT_ASC])*/ ; } /** * @return \yii\db\ActiveQuery|CmsTaskQuery */ public function getTasks() { return $this->hasMany(CmsTask::class, ['cms_project_id' => 'id']); } /** * @return CmsCompanyQuery|\skeeks\cms\query\CmsActiveQuery */ public static function find() { return (new CmsProjectQuery(get_called_class())); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsContentElementProperty.php
src/models/CmsContentElementProperty.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 17.05.2015 */ namespace skeeks\cms\models; use skeeks\cms\relatedProperties\models\RelatedElementPropertyModel; /** * This is the model class for table "{{%cms_content_element_property}}". * * @property integer $id * @property integer $created_at * @property integer $updated_at * @property integer $property_id * @property integer $element_id * @property string $value * @property integer $value_enum * @property string $value_num * @property string $description * * @property CmsContentProperty $property * @property CmsContentElement $element * @property CmsContentPropertyEnum $valueEnum * * @property CmsContentElement $valueCmsContentElement */ class CmsContentElementProperty extends RelatedElementPropertyModel { public $elementClass = CmsContentElement::class; /** * @inheritdoc */ public static function tableName() { return '{{%cms_content_element_property}}'; } /** * @return \yii\db\ActiveQuery */ public function getProperty() { return $this->hasOne(CmsContentProperty::class, ['id' => 'property_id']); } /** * @return \yii\db\ActiveQuery */ public function getElement() { $class = $this->elementClass; return $this->hasOne($class, ['id' => 'element_id']); } /** * @return \yii\db\ActiveQuery */ public function getValueCmsContentElement() { $class = $this->elementClass; return $this->hasOne($class, ['id' => 'value_element_id']); } /** * @return \yii\db\ActiveQuery */ public function getValueEnum() { $class = $this->elementClass; return $this->hasOne(CmsContentPropertyEnum::class, ['id' => 'value_enum_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsSiteDomain.php
src/models/CmsSiteDomain.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 20.05.2015 */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\helpers\StringHelper; use skeeks\modules\cms\user\models\User; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "{{%cms_site}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * * @property integer $cms_site_id сайт * @property string $domain название домена * @property boolean $is_https работает по https? * @property boolean $is_main основной домен для сайта? * * @property string $url * @property CmsSite $cmsSite */ class CmsSiteDomain extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%cms_site_domain}}'; } public function init() { parent::init(); $this->on(self::EVENT_BEFORE_UPDATE, [$this, '_checkIsMainDomain']); $this->on(self::EVENT_BEFORE_INSERT, [$this, '_checkIsMainDomain']); } public function _checkIsMainDomain($e) { if ($this->is_main) { $mainDomainForSite = $this->cmsSite->cmsSiteMainDomain; if ($mainDomainForSite && $mainDomainForSite->id != $this->id) { $mainDomainForSite->is_main = null; $mainDomainForSite->save(); } } } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'id' => Yii::t('skeeks/cms', 'ID'), 'created_by' => Yii::t('skeeks/cms', 'Created By'), 'updated_by' => Yii::t('skeeks/cms', 'Updated By'), 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'cms_site_id' => Yii::t('skeeks/cms', 'Site'), 'domain' => Yii::t('skeeks/cms', 'Domain'), 'is_https' => Yii::t('skeeks/cms', 'Работает по https?'), 'is_main' => Yii::t('skeeks/cms', 'Основной домен для сайта?'), ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['created_by', 'updated_by', 'created_at', 'updated_at'], 'integer'], [['domain'], 'required'], [['is_main', 'is_https'], 'boolean'], [['is_main', 'is_https'], 'default', 'value' => null], [['is_main', 'is_https'], function($attribute) { if (((int) $this->$attribute) == 0) { $this->$attribute = null; } }], //TODO: добавить для null [['is_main', 'cms_site_id'], 'unique', 'targetAttribute' => ['is_main', 'cms_site_id']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::className(), 'targetAttribute' => ['cms_site_id' => 'id']], [['domain'], 'string', 'max' => 255], [['domain'], 'unique'], [['domain'], 'trim'], [ ['domain'], function ($attribute) { $this->domain = StringHelper::strtolower($this->domain); }, ], [ ['domain'], function ($attribute) { if(filter_var($this->domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) { return true; } $this->addError($attribute, "Доменное имя указано неверно"); return false; }, ], [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsSite() { $class = \Yii::$app->skeeks->siteClass; return $this->hasOne($class, ['id' => 'cms_site_id']); } /** * @return string */ public function getUrl() { return ($this->is_https ? "https://" : "http://") . $this->domain; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsTree.php
src/models/CmsTree.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 23.09.2015 */ namespace skeeks\cms\models; /** * Class CmsTree * @package skeeks\cms\models */ class CmsTree extends Tree { }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsCompany.php
src/models/CmsCompany.php
<?php namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\behaviors\CmsLogBehavior; use skeeks\cms\behaviors\RelationalBehavior; use skeeks\cms\models\behaviors\HasStorageFile; use skeeks\cms\models\behaviors\traits\HasLogTrait; use skeeks\cms\models\queries\CmsCompanyQuery; use skeeks\cms\models\queries\CmsTaskQuery; use skeeks\cms\shop\models\ShopBill; use skeeks\cms\shop\models\ShopPayment; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_contractor". * * @property int $id * @property int|null $created_by * @property int|null $created_at * @property string $name Название * @property string|null $description Название * @property int|null $cms_image_id Картинка * @property string $company_type Тип клиент/поставщик * @property int $cms_company_status_id Сатус компании * * @property CmsStorageFile|null $cmsImage * @property CmsCompanyStatus|null $status * * @property CmsLog[] $logs * @property CmsCompanyEmail[] $emails * @property CmsCompanyPhone[] $phones * @property CmsCompanyLink[] $links * @property CmsCompanyAddress[] $addresses * @property CmsContractor[] $contractors * @property CmsUser[] $users * @property CmsUser[] $managers * @property CmsCompanyCategory[] $categories * * @property CmsDeal[] $deals * @property CmsProject[] $projects * @property CmsTask[] $tasks * * @property CmsCompany2user[] $cmsCompany2users */ class CmsCompany extends ActiveRecord { use HasLogTrait; const COMPANY_TYPE_CLIENT = 'client'; const COMPANY_TYPE_SUPPLIERS = 'supplier'; /** * {@inheritdoc} */ public static function tableName() { return 'cms_company'; } /** * @return queries\CmsLogQuery */ public function getCompanyLogs() { $q = CmsLog::find() ->andWhere([ 'and', ['model_code' => $this->skeeksModelCode], ['model_id' => $this->id], ]); $q->multiple = true; return $q; } /** * @return queries\CmsLogQuery */ public function getLogs() { $q = CmsLog::find() ->andWhere([ 'and', ['model_code' => $this->skeeksModelCode], ['model_id' => $this->id], ]) ->orWhere([ 'and', ['model_code' => (new CmsDeal())->skeeksModelCode], ['model_id' => $this->getDeals()->select(['id'])], ]) ->orWhere([ 'and', ['model_code' => (new ShopBill())->skeeksModelCode], ['model_id' => $this->getBills()->select(['id'])], ]) ->orWhere([ 'and', ['model_code' => (new ShopPayment())->skeeksModelCode], ['model_id' => $this->getPayments()->select(['id'])], ]) ->orWhere([ 'and', ['model_code' => (new CmsTask())->skeeksModelCode], ['model_id' => $this->getTasks()->select(['id'])], ]) ->orWhere([ 'and', ['model_code' => (new CmsProject())->skeeksModelCode], ['model_id' => $this->getProjects()->select(['id'])], ]) ->orderBy(['created_at' => SORT_DESC]); $q->multiple = true; return $q; } public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ HasStorageFile::class => [ 'class' => HasStorageFile::class, 'fields' => [ 'cms_image_id', ], ], RelationalBehavior::class => [ 'class' => RelationalBehavior::class, 'relationNames' => [ 'managers', 'users', 'contractors', 'categories', ], ], CmsLogBehavior::class => [ 'class' => CmsLogBehavior::class, 'relation_map' => [ 'cms_company_status_id' => 'status', ], ], ]); } /** * {@inheritdoc} */ public function rules() { return array_merge(parent::rules(), [ [['created_by', 'created_at'], 'integer'], [['cms_company_status_id'], 'integer'], [['description'], 'string'], [['company_type'], 'string', 'max' => 255], /*[['company_type'], 'required'],*/ [ [ 'company_type', ], 'default', 'value' => self::COMPANY_TYPE_CLIENT, ], [['name'], 'string', 'max' => 255], [['name'], 'required'], [ [ 'description', ], 'default', 'value' => null, ], [['cms_image_id'], 'safe'], [['managers'], 'safe'], [['users'], 'safe'], [['contractors'], 'safe'], [['categories'], 'safe'], [ ['cms_image_id'], \skeeks\cms\validators\FileValidator::class, 'skipOnEmpty' => false, 'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'], 'maxFiles' => 1, 'maxSize' => 1024 * 1024 * 10, 'minSize' => 256, ], /*[['email'], 'string', 'max' => 64], [['email'], 'email'], [['email'], "filter", 'filter' => 'trim'], [ ['email'], "filter", 'filter' => function ($value) { return StringHelper::strtolower($value); }, ]*/ ]); } /** * {@inheritdoc} */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'name' => 'Название', 'cms_image_id' => 'Изображение', 'description' => 'Описание', 'managers' => 'Работают с компанией', 'contractors' => 'Реквизиты', 'cms_company_status_id' => 'Статус', 'categories' => 'Сферы деятельности', 'users' => 'Контакты', 'company_type' => 'Тип компании', ]); } /** * Gets query for [[CmsImage]]. * * @return \yii\db\ActiveQuery */ public function getCmsImage() { return $this->hasOne(CmsStorageFile::class, ['id' => 'cms_image_id']); } /** * @return \yii\db\ActiveQuery */ public function getStatus() { return $this->hasOne(CmsCompanyStatus::class, ['id' => 'cms_company_status_id']); } /** * @return \yii\db\ActiveQuery */ /*public function getLogs() { return $this->hasMany(CmsLog::class, ['cms_company_id' => 'id'])->orderBy(['created_at' => SORT_DESC]); }*/ /** * @return \yii\db\ActiveQuery */ public function getEmails() { return $this->hasMany(CmsCompanyEmail::class, ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getPhones() { return $this->hasMany(CmsCompanyPhone::class, ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getLinks() { return $this->hasMany(CmsCompanyLink::class, ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getAddresses() { return $this->hasMany(CmsCompanyAddress::class, ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getDeals() { return $this->hasMany(CmsDeal::class, ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getBills() { return $this->hasMany(ShopBill::class, ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getPayments() { return $this->hasMany(ShopPayment::class, ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsCompany2managers() { return $this->hasMany(CmsCompany2manager::class, ['cms_company_id' => 'id']) ->from(['cmsCompany2managers' => CmsCompany2manager::tableName()]); } /** * @return \yii\db\ActiveQuery */ public function getCmsCompany2users() { return $this->hasMany(CmsCompany2user::class, ['cms_company_id' => 'id']) ->from(['cmsCompany2users' => CmsCompany2user::tableName()])/*->orderBy(['sort' => SORT_ASC])*/ ; } /** * @return \yii\db\ActiveQuery */ public function getCmsCompany2contractors() { return $this->hasMany(CmsCompany2contractor::class, ['cms_company_id' => 'id']) ->from(['cmsCompany2contractors' => CmsCompany2contractor::tableName()]); } /** * @return \yii\db\ActiveQuery */ public function getContractors() { return $this->hasMany(CmsContractor::class, ['id' => 'cms_contractor_id']) ->via('cmsCompany2contractors');; } /** * @return \yii\db\ActiveQuery */ public function getUsers() { $class = \Yii::$app->user->identityClass; return $this->hasMany($class, ['id' => 'cms_user_id']) ->via('cmsCompany2users');; } /** * @return \yii\db\ActiveQuery */ public function getManagers() { $class = \Yii::$app->user->identityClass; return $this->hasMany($class, ['id' => 'cms_user_id']) ->via('cmsCompany2managers');; } /** * @return \yii\db\ActiveQuery */ public function getCategories() { return $this->hasMany(CmsCompanyCategory::className(), ['id' => 'cms_company_category_id'])->viaTable(CmsCompany2category::tableName(), ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery|CmsTaskQuery */ public function getTasks() { return $this->hasMany(CmsTask::class, ['cms_company_id' => 'id']); } /** * @return \yii\db\ActiveQuery|CmsTaskQuery */ public function getProjects() { return $this->hasMany(CmsProject::class, ['cms_company_id' => 'id']); } /** * @return CmsCompanyQuery|\skeeks\cms\query\CmsActiveQuery */ public static function find() { return (new CmsCompanyQuery(get_called_class())); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsContentElement2cmsUser.php
src/models/CmsContentElement2cmsUser.php
<?php namespace skeeks\cms\models; /** * This is the model class for table "{{%cms_content_element2cms_user}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property integer $cms_user_id * @property integer $cms_content_element_id * * @property CmsContentElement $cmsContentElement * @property CmsUser $cmsUser */ class CmsContentElement2cmsUser extends \skeeks\cms\models\Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_content_element2cms_user}}'; } /** * @inheritdoc */ public function rules() { return [ [ ['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_user_id', 'cms_content_element_id'], 'integer' ], [['cms_user_id', 'cms_content_element_id'], 'required'], [ ['cms_user_id', 'cms_content_element_id'], 'unique', 'targetAttribute' => ['cms_user_id', 'cms_content_element_id'], 'message' => 'The combination of Cms User ID and Cms Content Element ID has already been taken.' ] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'created_by' => 'Created By', 'updated_by' => 'Updated By', 'created_at' => 'Created At', 'updated_at' => 'Updated At', 'cms_user_id' => 'Cms User ID', 'cms_content_element_id' => 'Cms Content Element ID', ]; } /** * @return \yii\db\ActiveQuery */ public function getCmsContentElement() { return $this->hasOne(CmsContentElement::className(), ['id' => 'cms_content_element_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { return $this->hasOne(CmsUser::className(), ['id' => 'cms_user_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsTreeProperty.php
src/models/CmsTreeProperty.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 17.05.2015 */ namespace skeeks\cms\models; use skeeks\cms\relatedProperties\models\RelatedElementPropertyModel; /** * This is the model class for table "{{%cms_content_element_property}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property integer $property_id * @property integer $element_id * @property string $value * @property integer $value_enum * @property string $value_num * @property string $description * * @property CmsTreeTypeProperty $property * @property CmsTree $element */ class CmsTreeProperty extends RelatedElementPropertyModel { /** * @inheritdoc */ public static function tableName() { return '{{%cms_tree_property}}'; } /** * @return \yii\db\ActiveQuery */ public function getProperty() { return $this->hasOne(CmsTreeTypeProperty::className(), ['id' => 'property_id']); } /** * @return \yii\db\ActiveQuery */ public function getElement() { return $this->hasOne(CmsTree::className(), ['id' => 'element_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsUser.php
src/models/CmsUser.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 08.07.2015 */ namespace skeeks\cms\models; /** * Class CmsUser * @package skeeks\cms\models */ class CmsUser extends User { }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsUserEmail.php
src/models/CmsUserEmail.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\models; use skeeks\cms\behaviors\CmsLogBehavior; use skeeks\cms\helpers\StringHelper; use skeeks\cms\models\behaviors\traits\HasLogTrait; use Yii; use yii\base\Exception; use yii\helpers\ArrayHelper; use yii\helpers\Url; /** * This is the model class for table "cms_user_email". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property int $cms_site_id * @property int $cms_user_id * @property string $value Email * @property string|null $name Примечание к Email * @property int $sort * @property int $is_approved Email подтвержден? * @property string|null $approved_key Ключ для подтверждения Email * @property int|null $approved_key_at Время генерация ключа * * @property CmsSite $cmsSite * @property CmsUser $cmsUser */ class CmsUserEmail extends \skeeks\cms\base\ActiveRecord { use HasLogTrait; /** * @inheritdoc */ public static function tableName() { return '{{%cms_user_email}}'; } public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ CmsLogBehavior::class => [ 'class' => CmsLogBehavior::class, 'parent_relation' => 'cmsUser', ], ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'cms_user_id', 'sort', 'is_approved', 'approved_key_at'], 'integer'], [['cms_user_id', 'value'], 'required'], [['value', 'name', 'approved_key'], 'string', 'max' => 255], [['cms_user_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::className(), 'targetAttribute' => ['cms_user_id' => 'id']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::className(), 'targetAttribute' => ['cms_site_id' => 'id']], [['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::className(), 'targetAttribute' => ['created_by' => 'id']], [['updated_by'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::className(), 'targetAttribute' => ['updated_by' => 'id']], [['cms_site_id', 'value'], 'unique', 'targetAttribute' => ['cms_site_id', 'value'], //'message' => 'Этот email уже занят' ], //[['cms_user_id', 'value'], 'unique', 'targetAttribute' => ['cms_user_id', 'value'], 'message' => 'Этот email уже занят'], [['is_approved'], 'default', 'value' => 0], [['name', 'approved_key_at', 'approved_key'], 'default', 'value' => null], [['value'], "filter", 'filter' => 'trim'], [ ['value'], "filter", 'filter' => function ($value) { return StringHelper::strtolower($value); }, ], [['value'], "email", 'enableIDN' => true], ]); } /** * @inheritdoc */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_user_id' => Yii::t('skeeks/cms', 'User'), 'name' => "Описание", 'value' => "Email", ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { $userClass = isset(\Yii::$app->user) ? \Yii::$app->user->identityClass : CmsUser::class; return $this->hasOne($userClass, ['id' => 'cms_user_id']); } /** * @return $this * @throws Exception */ public function genereteApprovedKey() { if (\Yii::$app->cms->approved_key_is_letter) { $this->approved_key = \Yii::$app->security->generateRandomString((int)\Yii::$app->cms->email_approved_key_length); } else { $permitted_chars = '0123456789012345678901234567890123456789'; // Output: 54esmdr0qf $random = substr(str_shuffle($permitted_chars), 0, (int)\Yii::$app->cms->email_approved_key_length); $this->approved_key = $random; } $this->approved_key_at = time(); if (!$this->save()) { throw new Exception('Не сохранились данные ключа: '.print_r($this->errors, true)); } return $this; } /** * @return bool */ public function submitApprovedKey() { \Yii::$app->mailer->view->theme->pathMap = ArrayHelper::merge(\Yii::$app->mailer->view->theme->pathMap, [ '@app/mail' => [ '@skeeks/cms/mail-templates', ], ]); return \Yii::$app->mailer->compose('@app/mail/approve-email', [ 'approveUrl' => $this->approveUrl, 'approveCode' => $this->approved_key, 'email' => $this->value, ]) ->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName]) ->setTo(trim($this->value)) ->setSubject('Подтверждение e-mail') ->send(); } /** * Ссылка на подтверждение email адреса * * @param bool $scheme * @return string */ public function getApproveUrl($scheme = true) { return Url::to(['/cms/auth/approve-email', 'token' => $this->approved_key], $scheme); } /** * @return string */ public function asText() { return $this->value; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsSiteAddress.php
src/models/CmsSiteAddress.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\models\behaviors\HasJsonFieldsBehavior; use skeeks\cms\models\behaviors\HasStorageFile; use skeeks\modules\cms\user\models\User; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_site_address". * * @property int $cms_site_id * @property string|null $name Название адреса (необязательное) * @property string $value Полный адрес * @property float $latitude Широта * @property float $longitude Долгота * @property string|null $work_time Рабочее время * @property int|null $cms_image_id Фото адреса * @property int $priority * * @property string|null $email * @property string|null $phone * @property array|null $workTime * * @property CmsStorageFile $cmsImage * @property CmsSiteAddressEmail|null $cmsSiteAddressPhone * @property CmsSiteAddressEmail|null $cmsSiteAddressEmail * @property CmsSiteAddressEmail[] $cmsSiteAddressEmails * @property CmsSiteAddressPhone[] $cmsSiteAddressPhones * @property CmsSite $cmsSite */ class CmsSiteAddress extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%cms_site_address}}'; } /** * @return array */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ HasStorageFile::class => [ 'class' => HasStorageFile::class, 'fields' => ['cms_image_id'], ], HasJsonFieldsBehavior::className() => [ 'class' => HasJsonFieldsBehavior::className(), 'fields' => ['work_time'], ], ]); } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'value' => 'Полный адрес', 'name' => 'Название', 'cms_image_id' => 'Фото', 'work_time' => 'Время работы', 'latitude' => 'Широта', 'longitude' => 'Долгота', 'coordinates' => '', 'priority' => 'Сортировка', ]); } /** * @inheritdoc */ public function attributeHints() { return array_merge(parent::attributeHints(), [ 'name' => 'Необязтельное поле, можно дать название этому адресу', 'work_time' => 'Если время работы указано не будет, то время работы адреса будет использоваться из настроек сайта.', 'priority' => 'Чем ниже цифра тем выше адрес', ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'priority'], 'integer'], [['cms_site_id', 'value', 'latitude', 'longitude'], 'required'], [['latitude', 'longitude'], 'number'], [['work_time'], 'safe'], [['cms_image_id'], 'safe'], [['name', 'value'], 'string', 'max' => 255], [['cms_site_id', 'value'], 'unique', 'targetAttribute' => ['cms_site_id', 'value']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => \Yii::$app->skeeks->siteClass, 'targetAttribute' => ['cms_site_id' => 'id']], [ [ 'latitude', 'longitude', ], function ($attribute) { if ($this->{$attribute} <= 0) { $this->addError($attribute, 'Адрес указан некорректно'); return false; } return true; }, ], ]); } /** * Gets query for [[CmsSite]]. * * @return \yii\db\ActiveQuery */ public function getCmsSite() { return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_id']); } /** * Gets query for [[CmsImage]]. * * @return \yii\db\ActiveQuery */ public function getCmsImage() { return $this->hasOne(CmsStorageFile::className(), ['id' => 'cms_image_id']); } /** * Gets query for [[CmsSiteAddressEmails]]. * * @return \yii\db\ActiveQuery */ public function getCmsSiteAddressEmail() { $q = $this->getCmsSiteAddressEmails()->limit(1); $q->multiple = false; return $q; } /** * Gets query for [[CmsSiteAddressEmails]]. * * @return \yii\db\ActiveQuery */ public function getCmsSiteAddressPhone() { $q = $this->getCmsSiteAddressPhones()->limit(1); $q->multiple = false; return $q; } /** * Gets query for [[CmsSiteAddressEmails]]. * * @return \yii\db\ActiveQuery */ public function getCmsSiteAddressEmails() { return $this->hasMany(CmsSiteAddressEmail::className(), ['cms_site_address_id' => 'id'])->orderBy(['priority' => SORT_ASC]); } /** * Gets query for [[CmsSiteAddressPhones]]. * * @return \yii\db\ActiveQuery */ public function getCmsSiteAddressPhones() { return $this->hasMany(CmsSiteAddressPhone::className(), ['cms_site_address_id' => 'id'])->orderBy(['priority' => SORT_ASC]); } /** * @return string */ public function getCoordinates() { if (!$this->latitude || !$this->longitude) { return ''; } return $this->latitude.",".$this->longitude; } /** * Основной телефона для адреса * * @return string */ public function getPhone() { if ($this->cmsSiteAddressPhone) { return $this->cmsSiteAddressPhone->value; } if ($phone = $this->cmsSite->cmsSitePhone) { return $phone->value; } return ''; } /** * Основной email для адреса * * @return string */ public function getEmail() { if ($this->cmsSiteAddressEmail) { return $this->cmsSiteAddressEmail->value; } if ($phone = $this->cmsSite->cmsSiteEmail) { return $phone->value; } return ''; } /** * Режим работы * * @return array|string|null */ public function getWorkTime() { if ($this->work_time) { return $this->work_time; } return $this->cmsSite->work_time; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsUserPhone.php
src/models/CmsUserPhone.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 28.02.2015 */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\behaviors\CmsLogBehavior; use skeeks\cms\components\Cms; use skeeks\cms\helpers\StringHelper; use skeeks\cms\models\behaviors\traits\HasLogTrait; use skeeks\cms\validators\PhoneValidator; use Yii; use yii\behaviors\TimestampBehavior; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_user_phone". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property int $cms_site_id * @property int $cms_user_id * @property string $value Телефон * @property string|null $name Примечание к телефону * @property int $sort * @property int $is_approved Телефон подтвержден? * @property string|null $approved_key Ключ для подтверждения телефона * @property int|null $approved_key_at Время генерация ключа * * @property CmsSite $cmsSite * @property CmsUser $cmsUser */ class CmsUserPhone extends ActiveRecord { use HasLogTrait; /** * @inheritdoc */ public static function tableName() { return '{{%cms_user_phone}}'; } public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ CmsLogBehavior::class => [ 'class' => CmsLogBehavior::class, 'parent_relation' => 'cmsUser', ], ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'cms_user_id', 'sort', 'is_approved', 'approved_key_at'], 'integer'], [['cms_user_id', 'value'], 'required'], [['value', 'name', 'approved_key'], 'string', 'max' => 255], [['cms_user_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::className(), 'targetAttribute' => ['cms_user_id' => 'id']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::className(), 'targetAttribute' => ['cms_site_id' => 'id']], [['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::className(), 'targetAttribute' => ['created_by' => 'id']], [['updated_by'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::className(), 'targetAttribute' => ['updated_by' => 'id']], [['cms_site_id', 'value'], 'unique', 'targetAttribute' => ['cms_site_id', 'value'], 'message' => 'Этот телефон уже занят'], //[['cms_user_id', 'value'], 'unique', 'targetAttribute' => ['cms_user_id', 'value'], 'message' => 'Этот телефон уже занят'], [['is_approved'], 'default', 'value' => 0], [['name', 'approved_key_at', 'approved_key'], 'default', 'value' => null], [['value'], "filter", 'filter' => 'trim'], [['value'], "filter", 'filter' => function($value) { return StringHelper::strtolower($value); }], [['value'], PhoneValidator::class], ]); } /** * @inheritdoc */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_user_id' => Yii::t('skeeks/cms', 'User'), 'name' => "Описание", 'value' => "Телефон", ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { $userClass = isset(\Yii::$app->user) ? \Yii::$app->user->identityClass : CmsUser::class; return $this->hasOne($userClass, ['id' => 'cms_user_id']); } /** * @return string */ public function asText() { return $this->value; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsStorageFile.php
src/models/CmsStorageFile.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 19.09.2015 */ namespace skeeks\cms\models; /** * Class CmsStorageFile * @package skeeks\cms\models */ class CmsStorageFile extends StorageFile { }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/User.php
src/models/User.php
<?php /** * User * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 20.10.2014 * @since 1.0.0 */ namespace skeeks\cms\models; use Imagine\Image\ManipulatorInterface; use skeeks\cms\authclient\models\UserAuthClient; use skeeks\cms\base\ActiveRecord; use skeeks\cms\behaviors\CmsLogBehavior; use skeeks\cms\behaviors\RelationalBehavior; use skeeks\cms\helpers\StringHelper; use skeeks\cms\models\behaviors\HasJsonFieldsBehavior; use skeeks\cms\models\behaviors\HasRelatedProperties; use skeeks\cms\models\behaviors\HasStorageFile; use skeeks\cms\models\behaviors\HasSubscribes; use skeeks\cms\models\behaviors\HasTableCache; use skeeks\cms\models\behaviors\HasUserLog; use skeeks\cms\models\behaviors\traits\HasLogTrait; use skeeks\cms\models\behaviors\traits\HasRelatedPropertiesTrait; use skeeks\cms\models\queries\CmsTaskQuery; use skeeks\cms\models\queries\CmsUserQuery; use skeeks\cms\models\queries\CmsUserScheduleQuery; use skeeks\cms\models\queries\CmsWebNotifyQuery; use skeeks\cms\models\user\UserEmail; use skeeks\cms\rbac\models\CmsAuthAssignment; use skeeks\cms\shop\models\ShopBill; use skeeks\cms\shop\models\ShopBonusTransaction; use skeeks\cms\shop\models\ShopPayment; use skeeks\cms\validators\PhoneValidator; use Yii; use yii\base\Exception; use yii\base\NotSupportedException; use yii\behaviors\TimestampBehavior; use yii\db\AfterSaveEvent; use yii\db\Expression; use yii\helpers\ArrayHelper; use yii\web\Application; use yii\web\IdentityInterface; /** * This is the model class for table "{{%cms_user}}". * * @property integer $id * @property string $username * @property string $auth_key * @property string $password_hash * @property string $password_reset_token * @property integer $created_at * @property integer $updated_at * @property integer $image_id * @property string $first_name * @property string $last_name * @property string $patronymic * @property integer $is_company * @property string $company_name * @property integer $birthday_at * @property integer $is_worker сотрудник? * @property string|null $post должность * @property array|null $work_shedule рабочий график * * @property CmsUserSchedule[] $schedules * @property string $gender * @property string $alias * @property integer $is_active * @property integer $updated_by * @property integer $created_by * @property integer $logged_at * @property integer $last_activity_at * @property integer $last_admin_activity_at * @property string $email * @property string $phone * @property integer $cms_site_id * * *** * * @property string $name * @property string $lastActivityAgo * @property string $lastAdminActivityAgo * * @property CmsStorageFile $image * @property string $avatarSrc * @property string $profileUrl * * @property CmsUserAddress[] $cmsUserAddresses * @property CmsUserEmail[] $cmsUserEmails * @property CmsUserPhone[] $cmsUserPhones * @property UserAuthClient[] $cmsUserAuthClients * * @property \yii\rbac\Role[] $roles * @property [] $roleNames * * @property string $displayName * @property string $shortDisplayName * @property string $shortDisplayNameWithAlias * @property string $isOnline Пользователь онлайн? * * @property CmsContentElement2cmsUser[] $cmsContentElement2cmsUsers * @property CmsContentElement[] $favoriteCmsContentElements * @property CmsAuthAssignment[] $cmsAuthAssignments * * @property CmsUserEmail $mainCmsUserEmail * @property CmsUserPhone $mainCmsUserPhone * @property CmsContractor[] $cmsContractors * @property CmsContractorMap[] $cmsContractorMaps * @property ShopBonusTransaction[] $bonusTransactions * @property float $bonusBalance * * @property CmsDepartment[] $departments Отделы где работает сотрудник * @property CmsUser[] $subordinates Подчиненные * @property CmsUser[] $leaders Руководители * * @property CmsUser[] $managers Сотрудники работающие с клиентом * @property CmsCompany[] $companies Сотрудники работающие с клиентом * @property CmsCompany[] $companiesAll Сотрудники работающие с клиентом * @property CmsTask[] $executorTasks Задачи где пользователь является исполнителем * @property CmsWebNotify[] $CmsWebNotifies Веб уведомления * * @property bool $isWorkingNow Сейчас в работе? * */ class User extends ActiveRecord implements IdentityInterface { use HasLogTrait; use HasRelatedPropertiesTrait; /** * @return string */ public function getSkeeksModelCode() { return CmsUser::class; } /** * @inheritdoc */ public static function tableName() { return '{{%cms_user}}'; } /** * Логины которые нельзя удалять, и нельзя менять * @return array */ public static function getProtectedUsernames() { return ['root']; } /** * @inheritdoc */ public function init() { parent::init(); $this->on(self::EVENT_BEFORE_UPDATE, [$this, "_cmsCheckBeforeSave"]); $this->on(self::EVENT_AFTER_INSERT, [$this, "_cmsAfterSave"]); $this->on(self::EVENT_AFTER_UPDATE, [$this, "_cmsAfterSave"]); $this->on(self::EVENT_BEFORE_DELETE, [$this, "checkDataBeforeDelete"]); } /** * @return queries\CmsLogQuery */ public function getUserLogs() { $q = CmsLog::find() ->andWhere([ 'and', ['model_code' => $this->skeeksModelCode], ['model_id' => $this->id], ]); $q->multiple = true; return $q; } /** * @return queries\CmsLogQuery */ public function getLogs() { $q = CmsLog::find() ->andWhere([ 'and', ['model_code' => $this->skeeksModelCode], ['model_id' => $this->id], ]) ->orWhere([ 'and', ['model_code' => (new CmsDeal())->skeeksModelCode], ['model_id' => $this->getDeals()->select(['id'])], ]) ->orWhere([ 'and', ['model_code' => (new ShopBill())->skeeksModelCode], ['model_id' => $this->getBills()->select(['id'])], ]) ->orWhere([ 'and', ['model_code' => (new ShopPayment())->skeeksModelCode], ['model_id' => $this->getPayments()->select(['id'])], ]) ->orWhere([ 'and', ['model_code' => (new CmsTask())->skeeksModelCode], ['model_id' => $this->getTasks()->select(['id'])], ]) ->orWhere([ 'and', ['model_code' => (new ShopBonusTransaction())->skeeksModelCode], ['model_id' => $this->getBonusTransactions()->select(['id'])], ]) ->orderBy(['created_at' => SORT_DESC]); $q->multiple = true; return $q; } public function _cmsCheckBeforeSave($e) { if (\Yii::$app instanceof Application) { if (!isset(\Yii::$app->user)) { return true; } if (!\Yii::$app->user && !\Yii::$app->user->identity) { return true; } if (!$this->is_active && $this->id == \Yii::$app->user->identity->id) { throw new Exception(\Yii::t('skeeks/cms', 'Нельзя деактивировать себя')); } } if ($this->isAttributeChanged('image_id')) { if ($this->image) { if (!$this->image->cmsSite->is_default) { $img = $this->image; $site = CmsSite::find()->default()->one(); $img->cms_site_id = $site->id; $img->update(false, ['cms_site_id']); } } } } public function _cmsAfterSave(AfterSaveEvent $e) { if ($this->_roleNames !== null) { if ($this->roles) { foreach ($this->roles as $roleExist) { if (!in_array($roleExist->name, (array)$this->_roleNames)) { \Yii::$app->authManager->revoke($roleExist, $this->id); } } } foreach ((array)$this->_roleNames as $roleName) { if ($role = \Yii::$app->authManager->getRole($roleName)) { try { if (!\Yii::$app->authManager->getAssignment($roleName, $this->id)) { \Yii::$app->authManager->assign($role, $this->id); } } catch (\Exception $e) { \Yii::error("Ошибка назначения роли: ".$e->getMessage(), self::class); //throw $e; } } else { \Yii::warning("Роль {$roleName} не зарегистрированна в системе", self::class); } } } //TODO: Если сотрудник, надо проверить чтобы добавилась нужная роль CmsManager::ROLE_WORKER //Если пытаюсь поменять главный email if ($this->_mainEmail) { $value = trim(StringHelper::strtolower($this->_mainEmail)); if ($this->mainCmsUserEmail) { $cmsUserEmail = $this->mainCmsUserEmail; if ($cmsUserEmail->value != $value) { $cmsUserEmail->value = $value; if (!$cmsUserEmail->save()) { throw new Exception("Email не обновлен! ".print_r($cmsUserEmail->errors, true)); } } } else { $cmsUserEmail = new CmsUserEmail(); $cmsUserEmail->value = $value; $cmsUserEmail->cms_site_id = $this->cms_site_id; $cmsUserEmail->cms_user_id = $this->id; if (!$cmsUserEmail->save()) { throw new Exception("Email не добавлен! ".print_r($cmsUserEmail->errors, true)); } } } //Если пытаюсь поменять главный телефон if ($this->_mainPhone) { $value = trim(StringHelper::strtolower($this->_mainPhone)); if ($this->mainCmsUserPhone) { $cmsUserPhone = $this->mainCmsUserPhone; if ($cmsUserPhone->value != $value) { $cmsUserPhone->value = $value; if (!$cmsUserPhone->save()) { throw new Exception("Телефон не обновлен! ".print_r($cmsUserPhone->errors, true)); } } } else { $cmsUserPhone = new CmsUserPhone(); $cmsUserPhone->cms_site_id = $this->cms_site_id; $cmsUserPhone->value = $value; $cmsUserPhone->cms_user_id = $this->id; if (!$cmsUserPhone->save()) { throw new Exception("Телефон не обновлен! ".print_r($cmsUserPhone->errors, true)); } } } } /** * @throws Exception */ public function checkDataBeforeDelete($e) { if (in_array($this->username, static::getProtectedUsernames())) { throw new Exception(\Yii::t('skeeks/cms', 'This user can not be removed')); } if (isset(\Yii::$app->user)) { if ($this->id == \Yii::$app->user->identity->id) { throw new Exception(\Yii::t('skeeks/cms', 'You can not delete yourself')); } } } /** * @inheritdoc */ public function behaviors() { $behaviors = array_merge(parent::behaviors(), [ RelationalBehavior::class => [ 'class' => RelationalBehavior::class, ], TimestampBehavior::class, /*HasUserLog::class => [ 'class' => HasUserLog::class, 'no_log_attributes' => [ 'created_at', 'updated_at', 'updated_by', 'last_admin_activity_at', 'last_activity_at', 'created_by' ] ],*/ HasStorageFile::class => [ 'class' => HasStorageFile::class, 'fields' => ['image_id'], ], HasRelatedProperties::class => [ 'class' => HasRelatedProperties::class, 'relatedElementPropertyClassName' => CmsUserProperty::class, 'relatedPropertyClassName' => CmsUserUniversalProperty::class, ], HasJsonFieldsBehavior::class => [ 'class' => HasJsonFieldsBehavior::class, 'fields' => ['work_shedule'], ], CmsLogBehavior::class => [ 'class' => CmsLogBehavior::class, 'no_log_fields' => [ 'last_activity_at', 'last_admin_activity_at', ] /*'relation_map' => [ /*'relation_map' => [ 'cms_company_status_id' => 'status', ],*/ ], ]); if (isset($behaviors[HasTableCache::class])) { unset($behaviors[HasTableCache::class]); } return $behaviors; } /** * @inheritdoc */ public function rules() { return [ ['is_worker', 'default', 'value' => 0], ['is_worker', 'integer'], ['birthday_at', 'default', 'value' => null], ['alias', 'default', 'value' => null], ['is_active', 'default', 'value' => 1], /*['gender', 'default', 'value' => 'men'], ['gender', 'in', 'range' => ['men', 'women']],*/ [['company_name'], 'string'], [['managers'], 'safe'], [ ['company_name'], 'required', 'when' => function () { return $this->is_company; }, ], [['birthday_at'], 'integer'], [['is_company'], 'integer'], ['is_company', 'default', 'value' => 0], [['created_at', 'updated_at', 'cms_site_id', 'is_active'], 'integer'], [['alias'], 'string'], [ ['username'], 'default', 'value' => null, /*'value' => function (self $model) { $userLast = static::find()->orderBy("id DESC")->limit(1)->one(); return "id".($userLast->id + 1); },*/ ], [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::class, 'targetAttribute' => ['cms_site_id' => 'id']], [['image_id'], 'safe'], [ ['image_id'], \skeeks\cms\validators\FileValidator::class, 'skipOnEmpty' => false, 'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'], 'maxFiles' => 1, 'maxSize' => 1024 * 1024 * 5, 'minSize' => 1024, ], [['gender'], 'string'], [ ['username', 'password_hash', 'password_reset_token', 'first_name', 'last_name', 'patronymic'], 'string', 'max' => 255, ], [['auth_key'], 'string', 'max' => 32], [['phone'], 'string', 'max' => 64], [['phone'], PhoneValidator::class], [['phone'], "filter", 'filter' => 'trim'], [ ['phone'], "filter", 'filter' => function ($value) { return StringHelper::strtolower($value); }, ], [ ['phone'], function ($attribute) { $value = StringHelper::strtolower(trim($this->{$attribute})); if ($this->isNewRecord) { if (CmsUserPhone::find()->cmsSite($this->cms_site_id)->andWhere(['value' => $value])->one()) { $this->addError($attribute, "Этот телефон уже занят"); } } else { if (CmsUserPhone::find() ->cmsSite($this->cms_site_id) ->andWhere(['value' => $value]) ->andWhere(['!=', 'cms_user_id', $this->id]) ->one()) { $this->addError($attribute, "Этот телефон уже занят"); } //todo: доработать в будущем /*if ($this->mainCmsUserPhone && $this->mainCmsUserPhone->is_approved && $this->mainCmsUserPhone->value != $value) { $this->addError($attribute, "Этот телефон подтвержден, и его менять нельзя. Добавьте другой телефон, а после удалите этот!"); return false; }*/ } }, ], [['email'], 'string', 'max' => 64], [['email'], 'email', 'enableIDN' => true], [['email'], "filter", 'filter' => 'trim'], [ ['email'], "filter", 'filter' => function ($value) { return StringHelper::strtolower($value); }, ], [ ['email'], function ($attribute) { $value = StringHelper::strtolower(trim($this->{$attribute})); if ($this->isNewRecord) { if (CmsUserEmail::find()->cmsSite($this->cms_site_id)->andWhere(['value' => $value])->one()) { $this->addError($attribute, "Этот email уже занят"); return false; } } else { if (CmsUserEmail::find() ->cmsSite($this->cms_site_id) ->andWhere(['value' => $value]) ->andWhere(['!=', 'cms_user_id', $this->id]) ->one()) { $this->addError($attribute, "Этот email уже занят"); return false; } if ($this->mainCmsUserEmail) { $this->mainCmsUserEmail->value = StringHelper::strtolower($this->mainCmsUserEmail->value); $value = StringHelper::strtolower($value); if ($this->mainCmsUserEmail && $this->mainCmsUserEmail->is_approved && $this->mainCmsUserEmail->value != $value) { $this->addError($attribute, "Этот email подтвержден, и его менять нельзя. Добавьте другой email, а после удалите этот!"); return false; } } } }, ], ['username', 'string', 'min' => 3, 'max' => 25], [['username'], 'unique', 'targetAttribute' => ['cms_site_id', 'username'], 'message' => 'Этот логин уже занят'], [['username'], \skeeks\cms\validators\LoginValidator::class], [['logged_at'], 'integer'], [['last_activity_at'], 'integer'], [['last_admin_activity_at'], 'integer'], [ ['auth_key'], 'default', 'value' => function (self $model) { return \Yii::$app->security->generateRandomString(); }, ], [ ['password_hash'], 'default', 'value' => null, ], [['roleNames'], 'safe'], [['roleNames'], 'default', 'value' => \Yii::$app->cms->registerRoles], [['first_name', 'last_name'], 'trim'], [['work_shedule'], 'safe'], [['post'], 'string', 'max' => 255], [['work_shedule', 'post'], 'default', 'value' => null], ]; } public function extraFields() { return [ 'displayName', 'shortDisplayName', ]; } /** * @inheritdoc */ public function attributeHints() { return [ 'alias' => "Короткое альтернативное название, необязательно к заполнениею.", ]; } public function attributeLabels() { return [ 'id' => Yii::t('skeeks/cms', 'ID'), 'username' => Yii::t('skeeks/cms', 'Login'), 'auth_key' => Yii::t('skeeks/cms', 'Auth Key'), 'password_hash' => Yii::t('skeeks/cms', 'Password Hash'), 'password_reset_token' => Yii::t('skeeks/cms', 'Password Reset Token'), 'email' => Yii::t('skeeks/cms', 'Email'), 'phone' => Yii::t('skeeks/cms', 'Phone'), 'is_active' => Yii::t('skeeks/cms', 'Active'), 'alias' => "Псевдоним", 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'name' => \Yii::t('skeeks/cms/user', 'Name'), //Yii::t('skeeks/cms', 'Name???'), 'first_name' => \Yii::t('skeeks/cms', 'First name'), 'last_name' => \Yii::t('skeeks/cms', 'Last name'), 'patronymic' => \Yii::t('skeeks/cms', 'Patronymic'), 'gender' => Yii::t('skeeks/cms', 'Gender'), 'birthday_at' => Yii::t('skeeks/cms', 'Дата рождения'), 'logged_at' => Yii::t('skeeks/cms', 'Logged At'), 'last_activity_at' => Yii::t('skeeks/cms', 'Last Activity At'), 'last_admin_activity_at' => Yii::t('skeeks/cms', 'Last Activity In The Admin At'), 'image_id' => Yii::t('skeeks/cms', 'Image'), 'roleNames' => Yii::t('skeeks/cms', 'Группы'), 'is_company' => "Тип аккаунта", 'company_name' => "Название компании", 'work_shedule' => "Рабочий график", 'post' => "Должность", 'is_worker' => "Сотрудник?", 'managers' => "Работают с клиентом", ]; } /** * Все возможные свойства связанные с моделью * @return \yii\db\ActiveQuery */ public function getRelatedProperties() { $q = CmsUserUniversalProperty::find()->cmsSite()->sort(); $q->multiple = true; return $q; } /** * Установка последней активности пользователя. Больше чем в настройках. * @return $this */ public function lockAdmin() { $this->last_admin_activity_at = \Yii::$app->formatter->asTimestamp(time()) - (\Yii::$app->admin->blockedTime + 1); $this->save(false); return $this; } /** * Время проявления последней активности на сайте * * @return int */ public function getLastAdminActivityAgo() { $now = \Yii::$app->formatter->asTimestamp(time()); return (int)($now - (int)$this->last_admin_activity_at); } /** * Обновление времени последней актиности пользователя. * Только в том случае, если время его последней актиности больше 10 сек. * @return $this */ public function updateLastAdminActivity() { $now = \Yii::$app->formatter->asTimestamp(time()); if (!$this->lastAdminActivityAgo || $this->lastAdminActivityAgo > 10) { $this->last_activity_at = $now; $this->last_admin_activity_at = $now; $this->save(false); } return $this; } /** * Время проявления последней активности на сайте * * @return int */ public function getLastActivityAgo() { $now = \Yii::$app->formatter->asTimestamp(time()); return (int)($now - (int)$this->last_activity_at); } /** * Обновление времени последней актиности пользователя. * Только в том случае, если время его последней актиности больше 10 сек. * @return $this */ public function updateLastActivity() { $now = \Yii::$app->formatter->asTimestamp(time()); if (!$this->lastActivityAgo || $this->lastActivityAgo > 10) { $this->last_activity_at = $now; $this->save(false); } return $this; } /** * @return \yii\db\ActiveQuery */ public function getImage() { return $this->hasOne(StorageFile::class, ['id' => 'image_id']); } /** * @return \yii\db\ActiveQuery */ public function getStorageFiles() { return $this->hasMany(StorageFile::class, ['created_by' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getUserAuthClients() { return $this->hasMany(UserAuthClient::class, ['user_id' => 'id']); } /** * @return string */ public function getDisplayName() { if ($this->name) { return $this->name; } if ($this->email) { return $this->email; } if ($this->phone) { return $this->phone; } if ($this->username) { return $this->username; } return $this->id; } /** * * TODO: Is depricated > 2.7.1 * * @param string $action * @param array $params * @return string */ public function getPageUrl($action = 'view', $params = []) { return $this->getProfileUrl($action, $params); } /** * @param string $action * @param array $params * @return string */ public function getProfileUrl($action = 'view', $params = []) { $params = ArrayHelper::merge([ "cms/user/".$action, "username" => $this->username, ], $params); return \Yii::$app->urlManager->createUrl($params); } /** * @return string * @deprecated */ public function getName() { $data = []; if ($this->is_company) { $data[] = $this->company_name; } else { if ($this->last_name) { $data[] = $this->last_name; } if ($this->first_name) { $data[] = $this->first_name; } if ($this->patronymic) { $data[] = $this->patronymic; } } return $data ? implode(" ", $data) : null; } public function asText() { return $this->shortDisplayName; if ($this->name) { return parent::asText(); } $lastName = $this->username; return parent::asText()."{$lastName}"; } /** * @return CmsUserQuery|\skeeks\cms\query\CmsActiveQuery */ public static function find() { return (new CmsUserQuery(get_called_class())); } /** * @inheritdoc */ public static function findIdentity($id) { return static::find()->cmsSite()->active()->andWhere(['id' => $id])->one(); } /** * @inheritdoc */ public static function findIdentityByAccessToken($token, $type = null) { throw new NotSupportedException(\Yii::t('skeeks/cms', '"findIdentityByAccessToken" is not implemented.')); } /** * @param string $username * @return static * @deprecated * * Finds user by username * */ public static function findByUsername($username) { return static::find()->cmsSite()->active()->username($username)->one(); } /** * Finds user by email * * @param $email * @return static */ public static function findByEmail($email) { return static::find()->cmsSite()->active()->email($email)->one(); } /** * @param $phone * @return null|CmsUser * @deprecated * */ public static function findByPhone($phone) { return static::find()->cmsSite()->active()->phone($phone)->one(); } /** * @param $value * @return User * @deprecated * * Поиск пользователя по email или логину */ public static function findByUsernameOrEmail($value) { if ($user = static::findByUsername($value)) { return $user; } if ($user = static::findByEmail($value)) { return $user; } return null; } /** * @param string|array $assignments * @return \skeeks\cms\query\CmsActiveQuery */ public static function findByAuthAssignments($assignments) { return static::find() ->cmsSite() ->joinWith('cmsAuthAssignments as cmsAuthAssignments') ->andWhere(['cmsAuthAssignments.item_name' => $assignments]); } /** * Finds user by password reset token * * @param string $token password reset token * @return static|null */ public static function findByPasswordResetToken($token) { if (!static::isPasswordResetTokenValid($token)) { return null; } return static::find()->cmsSite()->active()->andWhere(['password_reset_token' => $token])->one(); } /** * Finds out if password reset token is valid * * @param string $token password reset token * @return boolean */ public static function isPasswordResetTokenValid($token) { if (empty($token)) { return false;
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
true
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/StorageFile.php
src/models/StorageFile.php
<?php /** * StorageFile * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 26.02.2015 */ namespace skeeks\cms\models; use skeeks\cms\components\storage\ClusterLocal; use skeeks\cms\models\behaviors\CanBeLinkedToModel; use skeeks\cms\models\behaviors\HasDescriptionsBehavior; use skeeks\cms\models\behaviors\HasJsonFieldsBehavior; use skeeks\cms\models\helpers\ModelFilesGroup; use skeeks\cms\query\CmsStorageFileActiveQuery; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "{{%cms_storage_file}}". * * @property integer $id * @property string $cluster_id * @property string $cluster_file * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property string $size * @property string $mime_type * @property string $extension * @property string $original_name * @property string $name_to_save * @property string $name * @property string $description_short * @property string $description_full * @property integer $image_height * @property integer $image_width * @property integer $priority * @property integer $cms_site_id * @property integer $external_id * @property integer|null $sx_id * @property array|null $sx_data * * @property string $fileName * * @property string $baseNameSrc * @property string $absoluteBaseNameSrc * * @property string $src * @property string $absoluteSrc * * @property string $downloadName * * @property CmsSite $cmsSite * * @property \skeeks\cms\components\storage\Cluster $cluster */ class StorageFile extends Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_storage_file}}'; } /** * @inheritdoc */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ HasJsonFieldsBehavior::class => [ 'class' => HasJsonFieldsBehavior::class, 'fields' => ['sx_data'] ] ]); } /** * @return CmsUserQuery|\skeeks\cms\query\CmsActiveQuery */ public static function find() { return (new CmsStorageFileActiveQuery(get_called_class())); } /** * @inheritdoc */ public function rules() { return array_merge(parent::rules(), [ [ ['created_by', 'priority', 'updated_by', 'created_at', 'updated_at', 'size', 'cms_site_id', 'image_height', 'image_width', 'sx_id'], 'integer', ], [['description_short', 'description_full'], 'string'], [['cluster_file', 'original_name', 'name'], 'string', 'max' => 400], [['cluster_id', 'mime_type', 'extension'], 'string', 'max' => 255], [['name_to_save'], 'string', 'max' => 255], [ ['cluster_id', 'cluster_file'], 'unique', 'targetAttribute' => ['cluster_id', 'cluster_file'], 'message' => Yii::t('skeeks/cms', 'The combination of Cluster ID and Cluster Src has already been taken.'), ], [ ['sx_id', 'sx_data'], 'default', 'value' => null ], [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::class, 'targetAttribute' => ['cms_site_id' => 'id']], [['external_id'], 'string', 'max' => 255], [['external_id'], 'default', 'value' => null], [ ['cms_site_id', 'external_id'], 'unique', 'targetAttribute' => ['cms_site_id', 'external_id'], 'when' => function (self $model) { return (bool)$model->external_id; }, ], ]); } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'id' => Yii::t('skeeks/cms', 'ID'), 'cluster_id' => Yii::t('skeeks/cms', 'Storage'), 'cluster_file' => Yii::t('skeeks/cms', 'Cluster File'), 'created_by' => Yii::t('skeeks/cms', 'Created By'), 'updated_by' => Yii::t('skeeks/cms', 'Updated By'), 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'size' => Yii::t('skeeks/cms', 'File Size'), 'mime_type' => Yii::t('skeeks/cms', 'File Type'), 'extension' => Yii::t('skeeks/cms', 'Extension'), 'original_name' => Yii::t('skeeks/cms', 'Original FileName'), 'name_to_save' => Yii::t('skeeks/cms', 'Name To Save'), 'name' => Yii::t('skeeks/cms', 'Name'), 'description_short' => Yii::t('skeeks/cms', 'Description Short'), 'description_full' => Yii::t('skeeks/cms', 'Description Full'), 'image_height' => Yii::t('skeeks/cms', 'Image Height'), 'image_width' => Yii::t('skeeks/cms', 'Image Width'), 'sx_id' => Yii::t('skeeks/cms', 'SkeekS Suppliers ID'), ]); } const TYPE_FILE = "file"; const TYPE_IMAGE = "image"; /** * @return bool|int * @throws \Exception */ public function delete() { //Сначала удалить файл try { $cluster = $this->cluster; if (!$cluster) { return parent::delete(); } $cluster->deleteTmpDir($this); $cluster->delete($this); } catch (\common\components\storage\Exception $e) { return false; } return parent::delete(); } /** * @return \yii\db\ActiveQuery */ public function getCmsSite() { $class = \Yii::$app->skeeks->siteClass; return $this->hasOne($class, ['id' => 'cms_site_id']); } /** * @return $this */ public function deleteTmpDir() { $this->cluster->deleteTmpDir($this); return $this; } /** * Тип файла - первая часть mime_type * @return string */ public function getFileType() { $dataMimeType = explode('/', $this->mime_type); return (string)$dataMimeType[0]; } /** * @return bool */ public function isImage() { if ($this->getFileType() == 'image') { return true; } else { return false; } } /** * TODO: Переписать нормально * Обновление информации о файле * * @return $this */ public function updateFileInfo() { $src = $this->src; if ($this->cluster instanceof ClusterLocal) { if (!\Yii::$app->request->hostInfo) { return $this; } $src = \Yii::$app->request->hostInfo.$this->src; } //Елси это изображение if ($this->isImage()) { if (extension_loaded('gd')) { list($width, $height, $type, $attr) = getimagesize($src); $this->image_height = $height; $this->image_width = $width; } } $this->save(); return $this; } /** * @return string */ public function getAbsoluteSrc() { return $this->cluster->getAbsoluteUrl($this); } /** * Путь к файлу * @return string */ public function getSrc() { return $this->cluster->getPublicUrl($this); } /** * @return string */ public function getBaseNameSrc() { return $this->cluster->getPublicBaseNameUrl($this); } /** * @return mixed */ public function getAbsoluteBaseNameSrc() { return $this->cluster->getAbsoluteBaseNameUrl($this); } /** * @return \skeeks\cms\components\storage\Cluster */ public function getCluster() { return \Yii::$app->storage->getCluster($this->cluster_id); } public function fields() { return ArrayHelper::merge(parent::fields(), [ 'baseNameSrc', 'absoluteBaseNameSrc', 'src', 'absoluteSrc', 'rootSrc', ]); } /** * @return string */ public function getFileName() { if ($this->original_name) { return $this->original_name; } else { return $this->cluster_file; } } /** * TODO::is depricated version > 2.6.0 * @return \skeeks\cms\components\storage\Cluster */ public function cluster() { return $this->cluster; } /** * TODO::is depricated version > 2.6.0 * @return string */ public function getRootSrc() { return $this->cluster->getRootSrc($this); } /** * @return StorageFile */ public function copy() { $newFile = \Yii::$app->storage->upload($this->absoluteSrc); $newFile->name = $this->name; $newFile->description_full = $this->description_full; $newFile->description_short = $this->description_short; $newFile->name_to_save = $this->name_to_save; $newFile->original_name = $this->original_name; $newFile->priority = $this->priority; $newFile->save(); return $newFile; } /** * Название файла для сохранения * * @return string */ public function getDownloadName() { if ($this->name_to_save) { return $this->name_to_save.".".$this->extension; } else { if (!strpos($this->original_name, ".")) { return $this->original_name.".".$this->extension; } return $this->original_name; } } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsSitePhone.php
src/models/CmsSitePhone.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\validators\PhoneValidator; use skeeks\modules\cms\user\models\User; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_site_phone". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property int $cms_site_id * @property string $value * @property string $onlyNumber * @property string|null $name * @property int $priority * * @property CmsSite $cmsSite * @property CmsUser $createdBy * @property CmsUser $updatedBy */ class CmsSitePhone extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%cms_site_phone}}'; } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'value' => 'Телефон', 'name' => 'Название', 'priority' => 'Сортировка', ]); } /** * @inheritdoc */ public function attributeHints() { return array_merge(parent::attributeHints(), [ 'name' => 'Необязтельное поле, можно дать название этому номеру телефона', 'priority' => 'Чем ниже цифра тем выше телефон', ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'priority'], 'integer'], [['value'], 'required'], [['value', 'name'], 'string', 'max' => 255], [['cms_site_id', 'value'], 'unique', 'targetAttribute' => ['cms_site_id', 'value']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::className(), 'targetAttribute' => ['cms_site_id' => 'id']], [['value'], 'string', 'max' => 64], [['value'], PhoneValidator::class], ]); } /** * Gets query for [[CmsSite]]. * * @return \yii\db\ActiveQuery */ public function getCmsSite() { return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_id']); } /** * @return string */ public function getOnlyNumber() { if ($this->value) { return self::onlyNumber($this->value); } return ''; } /** * @param string $formatedPhone * @return string */ static public function onlyNumber(string $formatedPhone): string { $formatedPhone = str_replace("-", "", $formatedPhone); //$formatedPhone = str_replace("+", "", $formatedPhone); $formatedPhone = str_replace(" ", "", $formatedPhone); $formatedPhone = str_replace("&nbsp;", "", $formatedPhone); return $formatedPhone; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsWebNotify.php
src/models/CmsWebNotify.php
<?php namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\models\queries\CmsWebNotifyQuery; use yii\helpers\ArrayHelper; /** * @property int $id * * @property int|null $created_at * * @property string $name * @property string|null $comment * * @property string|null $model_code * @property int|null $model_id * * @property int $cms_user_id * * @property bool $is_read * * @property CmsUser $cmsUser */ class CmsWebNotify extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%cms_web_notify}}'; } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ [ 'created_at', 'cms_user_id', ], 'integer', ], [['name', 'comment'], "string"], [['model_code'], "string"], [['model_id'], "integer"], [['is_read'], "integer"], [['comment', 'model_code', 'model_id', 'comment'], 'default', 'value' => null], [['is_read'], 'default', 'value' => 0], [ ['name'], "required", ], ]); } /** * @inheritdoc */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { return $this->hasOne(\Yii::$app->user->identityClass, ['id' => 'cms_user_id']); } public function getHtml() { $items = []; $class = $this->is_read ? "": "sx-not-read"; $time = \Yii::$app->formatter->asRelativeTime($this->created_at); $items[] = <<<HTML <div class="sx-item {$class}"> <div class="sx-item-inner"> <div class="sx-time">{$time}</div> <div class="sx-name">{$this->name}</div> <div class="sx-model"> HTML; if ($this->model) { $items[] = \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::widget([ 'controllerId' => \yii\helpers\ArrayHelper::getValue(\Yii::$app->skeeks->modelsConfig, [$this->model_code, 'controller']), 'modelId' => $this->model_id, 'tag' => 'span', 'isRunFirstActionOnClick' => true, 'content' => $this->model->asText, 'options' => [ 'class' => 'sx-action-trigger', ], ]); } $items[] = <<<HTML </div> </div> </div> HTML; return implode("", $items); } public function getModel() { $classData = (array)ArrayHelper::getValue(\Yii::$app->skeeks->modelsConfig, $this->model_code); if ($classData) { $class = (string)ArrayHelper::getValue($classData, 'class', $this->model_code); if (class_exists($class)) { return $class::find()->andWhere(['id' => $this->model_id])->one(); } } return; } /** * @return CmsWebNotifyQuery */ public static function find() { return new CmsWebNotifyQuery(get_called_class()); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsTreeTypeProperty.php
src/models/CmsTreeTypeProperty.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 09.11.2014 * @since 1.0.0 */ namespace skeeks\cms\models; use skeeks\cms\relatedProperties\models\RelatedPropertyModel; use Yii; /** * This is the model class for table "{{%cms_content_property}}". * * @property integer $tree_type_id * * *** * @property CmsTreeProperty[] $cmsTreeProperties * @property CmsTreeTypeProperty2type[] $cmsTreeTypeProperty2types * @property CmsTreeType[] $cmsTreeTypes * * @property CmsTreeType $treeType * @property CmsTreeTypePropertyEnum[] $enums * @property CmsTreeProperty[] $elementProperties */ class CmsTreeTypeProperty extends RelatedPropertyModel { /** * @inheritdoc */ public static function tableName() { return '{{%cms_tree_type_property}}'; } /** * @return array */ public function behaviors() { return array_merge(parent::behaviors(), [ \skeeks\cms\behaviors\RelationalBehavior::class, ]); } /** * @return \yii\db\ActiveQuery */ public function getElementProperties() { return $this->hasMany(CmsTreeProperty::className(), ['property_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getEnums() { return $this->hasMany(CmsTreeTypePropertyEnum::className(), ['property_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTreeType() { return $this->hasOne(CmsTreeType::className(), ['id' => 'tree_type_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsTreeTypeProperty2types() { return $this->hasMany(CmsTreeTypeProperty2type::className(), ['cms_tree_type_property_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsTreeTypes() { return $this->hasMany(CmsTreeType::className(), ['id' => 'cms_tree_type_id'])->viaTable('cms_tree_type_property2type', ['cms_tree_type_property_id' => 'id']); } public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'cmsTreeTypes' => Yii::t('skeeks/cms', "Linked To Section's Type"), ]); } /** * @inheritdoc */ public function rules() { return array_merge(parent::rules(), [ [['tree_type_id'], 'integer'], [['cmsTreeTypes'], 'safe'], //[['code'], 'unique'], [ ['code', 'tree_type_id'], 'unique', 'targetAttribute' => ['tree_type_id', 'code'], 'message' => \Yii::t('skeeks/cms', "For this section's type of the code is already in use.") ], ]); } public function asText() { $result = parent::asText(); return $result . " ($this->code)"; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsLog.php
src/models/CmsLog.php
<?php namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\models\behaviors\HasJsonFieldsBehavior; use skeeks\cms\models\behaviors\HasStorageFileMulti; use skeeks\cms\models\queries\CmsLogQuery; use yii\helpers\ArrayHelper; use yii\helpers\Html; /** * @property int $id * * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * * @property int|null $cms_company_id * @property int|null $cms_user_id * * @property string|null $model_as_text * @property string|null $model_code * @property int|null $model_id * * @property string|null $sub_model_code * @property int|null $sub_model_id * @property string|null $sub_model_log_type * @property string|null $sub_model_as_text * @property array $data * * @property string $log_type * * @property string|null $comment * * @property CmsCompany $cmsCompany * @property CmsUser $cmsUser * * @property CmsStorageFile[] $files * @property CmsStorageFile[] $logTypeAsText * * * @property ActiveRecord $model * @property ActiveRecord $subModel */ class CmsLog extends ActiveRecord { const LOG_TYPE_COMMENT = "comment"; const LOG_TYPE_DELETE = "delete"; const LOG_TYPE_UPDATE = "update"; const LOG_TYPE_INSERT = "insert"; /** * @inheritdoc */ public static function tableName() { return '{{%cms_log}}'; } static public function typeList() { return [ self::LOG_TYPE_COMMENT => 'Комментарий', self::LOG_TYPE_UPDATE => 'Обновление данных', self::LOG_TYPE_INSERT => 'Создание записи', self::LOG_TYPE_DELETE => 'Удаление', ]; } /** * @return string */ public function getLogTypeAsText() { return (string)ArrayHelper::getValue(\Yii::$app->skeeks->logTypes, $this->log_type, "Прочее"); } /** * @return array */ public function behaviors() { return array_merge(parent::behaviors(), [ HasJsonFieldsBehavior::class => [ 'class' => HasJsonFieldsBehavior::class, 'fields' => ['data'], ], HasStorageFileMulti::class => [ 'class' => HasStorageFileMulti::class, 'relations' => [ [ 'relation' => 'files', 'property' => 'fileIds', ], ], ], ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ [ 'created_by', 'updated_by', 'created_at', 'updated_at' , 'cms_company_id' , 'cms_user_id', ], 'integer', ], [['log_type', 'comment'], "string"], [['data'], "safe"], [['model_code'], "string"], [['model_id'], "integer"], [['model_as_text'], "string"], [['sub_model_code'], "string"], [['sub_model_log_type'], "string"], [['sub_model_id'], "integer"], [['sub_model_as_text'], "string"], [['model_as_text'], 'default', 'value' => null], [['sub_model_as_text'], 'default', 'value' => null], [['data'], 'default', 'value' => null], [['log_type'], 'default', 'value' => self::LOG_TYPE_COMMENT], [['comment', 'cms_company_id', 'cms_user_id'], 'default', 'value' => null], [['sub_model_code', 'sub_model_id', 'sub_model_log_type'], 'default', 'value' => null], /*[['comment'], "filter", 'filter' => 'trim'],*/ [ ['comment'], "required", 'when' => function () { return $this->log_type == self::LOG_TYPE_COMMENT; }, ], [['fileIds'], 'safe'], [ ['fileIds'], \skeeks\cms\validators\FileValidator::class, 'skipOnEmpty' => false, //'extensions' => [''], 'maxFiles' => 50, 'maxSize' => 1024 * 1024 * 100, 'minSize' => 256, ], ]); } /** * @inheritdoc */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_company_id' => "Компания", 'cms_user_id' => "Клиент", 'comment' => "Текст комментария", 'fileIds' => "Файлы", ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsCompany() { return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { return $this->hasOne(\Yii::$app->user->identityClass, ['id' => 'cms_user_id']); } protected $_file_ids = null; /** * @return \yii\db\ActiveQuery */ public function getFiles() { return $this->hasMany(CmsStorageFile::class, ['id' => 'storage_file_id']) ->via('cmsLogFiles') ->orderBy(['priority' => SORT_ASC]); } /** * @return \yii\db\ActiveQuery */ public function getCmsLogFiles() { return $this->hasMany(CmsLogFile::className(), ['cms_log_id' => 'id']); } /** * @return array */ public function getFileIds() { if ($this->_file_ids !== null) { return $this->_file_ids; } if ($this->files) { return ArrayHelper::map($this->files, 'id', 'id'); } return []; } /** * @return \yii\db\ActiveQuery */ public function setFileIds($ids) { $this->_file_ids = $ids; return $this; } public function getModel() { $classData = (array)ArrayHelper::getValue(\Yii::$app->skeeks->modelsConfig, $this->model_code); if ($classData) { $class = (string)ArrayHelper::getValue($classData, 'class', $this->model_code); if (class_exists($class)) { return $class::find()->andWhere(['id' => $this->model_id])->one(); } } return; } public function getSubModel() { $classData = (array)ArrayHelper::getValue(\Yii::$app->skeeks->modelsConfig, $this->sub_model_code); if ($classData) { $class = (string)ArrayHelper::getValue($classData, 'class', $this->sub_model_code); if (class_exists($class)) { return $class::find()->andWhere(['id' => $this->sub_model_id])->one(); } } return; } public function render() { $name = ArrayHelper::getValue(\Yii::$app->skeeks->modelsConfig, [$this->model_code, 'name_one'], $this->model_code); if ($this->log_type == CmsLog::LOG_TYPE_COMMENT) { return $this->comment; } elseif ($this->log_type == CmsLog::LOG_TYPE_INSERT) { $res = []; if ($this->model) { $res[] = "<span title='ID:{$this->model_id}' data-toggle='tooltip'>{$name} «{$this->model_as_text}»</span>"; } else { $res[] = "<span title='ID:{$this->model_id}' data-toggle='tooltip'>{$name} «{$this->model_as_text}»</span>"; } $dataValues = (array)$this->data; if ($dataValues) { foreach ($dataValues as $key => $data) { /*$res[] = "<span>" . (string) ArrayHelper::getValue($data, "name") . ": </span> <s style='color: gray;'>" .(string) ArrayHelper::getValue($data, "old") . "</s> " . Html::tag('span', (string) ArrayHelper::getValue($data, "new", ''), [ 'data-toggle' => 'tooltip', 'data-html' => 'true', 'title' => "<b>Старое значение: </b>" . (string) ArrayHelper::getValue($data, "old"), ]);*/ $as_text = ArrayHelper::getValue($data, "as_text", ''); /*if (is_string($as_text)) { if ($as_text == "") { continue; } }*/ if (is_string($as_text)) { if ($as_text == "") { continue; } } else { if (!$as_text) { continue; } } if (is_array($as_text)) { $as_text = "<div class='sx-hidden-content'><a href='#'>Подробнее</a><div class='sx-hidden'><pre>".print_r($as_text, true)."</pre></div></div>"; } $name = (string)ArrayHelper::getValue($data, "name"); if ($this->subModel) { if ($this->subModel->getAttributeLabel($key)) { $name = $this->subModel->getAttributeLabel($key); } } elseif ($this->model) { if ($this->model->getAttributeLabel($key)) { $name = $this->model->getAttributeLabel($key); } } if ($as_text) { $res[] = "<span>".$name.": </span>".Html::tag('span', $as_text, [ 'data-toggle' => 'tooltip', 'data-html' => 'true', /*'title' => "<b>Старое значение: </b>" . (string) ArrayHelper::getValue($data, "old_as_text"),*/ ]); } } } $result = implode("<br />", $res); return $result; } elseif ($this->log_type == CmsLog::LOG_TYPE_UPDATE) { if ($this->model) { $res = []; $dataValues = (array)$this->data; if ($dataValues) { foreach ($dataValues as $key => $data) { $as_text = ArrayHelper::getValue($data, "as_text", ''); /*if (is_string($as_text)) { if ($as_text == "") { continue; } } else { if (!$as_text) { continue; } }*/ /*if (!$as_text || (is_string($as_text) && $as_text == "") ) { continue; }*/ if (is_array($as_text)) { $as_text = "<div class='sx-hidden-content'><a href='#'>Подробнее</a><div class='sx-hidden'><pre>".print_r($as_text, true)."</pre></div></div>"; } $name = (string)ArrayHelper::getValue($data, "name"); if ($this->subModel) { if ($this->subModel->getAttributeLabel($key)) { $name = $this->subModel->getAttributeLabel($key); } } elseif ($this->model) { if ($this->model->getAttributeLabel($key)) { $name = $this->model->getAttributeLabel($key); } } $res[] = "<span>".$name.": </span>".Html::tag('span', $as_text, [ 'data-toggle' => 'tooltip', 'data-html' => 'true', 'title' => "<b>Старое значение: </b>".(string)ArrayHelper::getValue($data, "old_as_text"), ]); } } $result = implode("<br />", $res); return $result; } else { $res = []; $dataValues = (array)$this->data; if ($dataValues) { foreach ($dataValues as $key => $data) { $res[] = "<span>".(string)ArrayHelper::getValue($data, "name").": </span>".Html::tag('span', (string)ArrayHelper::getValue($data, "as_text", ''), [ 'data-toggle' => 'tooltip', 'data-html' => 'true', 'title' => "<b>Старое значение: </b>".(string)ArrayHelper::getValue($data, "old_as_text"), ]); } } $result = implode("<br />", $res); return $result; return "{$name} «{$this->model_as_text}»"; } } elseif ($this->log_type == CmsLog::LOG_TYPE_DELETE) { return "<span title='ID:{$this->model_id}' data-toggle='tooltip'>{$name} «{$this->model_as_text}»</span>"; } } /** * @return CmsLogQuery */ public static function find() { return new CmsLogQuery(get_called_class()); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsCallcheckProvider.php
src/models/CmsCallcheckProvider.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\models; use skeeks\cms\callcheck\CallcheckHandler; use skeeks\cms\models\behaviors\Serialize; use yii\base\Exception; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_callcheck_provider". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property int $cms_site_id * @property string $name * @property int $priority * @property int|null $is_main * @property string $component * @property string|null $component_config * * @property CallcheckHandler $handler * @property CmsCallcheckMessage[] $cmsCallcheckMessages * @property CmsSite $cmsSite */ class CmsCallcheckProvider extends \skeeks\cms\base\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'cms_callcheck_provider'; } public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ Serialize::class => [ 'class' => Serialize::class, 'fields' => ['component_config'], ], ]); } protected $_handler = null; /** * @return CallcheckHandler */ public function getHandler() { if ($this->_handler !== null) { return $this->_handler; } if ($this->component) { try { $componentConfig = ArrayHelper::getValue(\Yii::$app->cms->callcheckHandlers, $this->component); $component = \Yii::createObject($componentConfig); $component->load($this->component_config, ""); $this->_handler = $component; return $this->_handler; } catch (\Exception $e) { \Yii::error("Related property handler not found '{$this->component}'", self::class); //throw $e; return null; } } return null; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'priority', 'is_main'], 'integer'], [['name', 'component'], 'required'], [['name', 'component'], 'string', 'max' => 255], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::className(), 'targetAttribute' => ['cms_site_id' => 'id']], [ 'is_main', function () { if ($this->is_main != 1) { $this->is_main = null; } }, ], [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], //[['cms_site_id', 'is_main'], 'unique', 'targetAttribute' => ['cms_site_id', 'is_main']], [['component_config'], 'safe'], [['component'], 'string', 'max' => 255], [['component_config', 'component'], 'default', 'value' => null], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_site_id' => 'Сайт', 'name' => 'Название', 'priority' => 'Приоритет', 'is_main' => 'Провайдер по умолчанию?', 'component' => 'Провайдер', 'component_config' => 'настройки провайдера', ]); } /** * Gets query for [[CmsSite]]. * * @return \yii\db\ActiveQuery */ public function getCmsSite() { $className = \Yii::$app->skeeks->siteClass; return $this->hasOne($className::className(), ['id' => 'cms_site_id']); } /** * @param $phone * @param $text * @return CmsSmsMessage * @throws \Exception */ public function callcheck($phone) { $provider_message_id = ''; $message = new CmsCallcheckMessage(); $message->phone = $phone; $message->cms_callcheck_provider_id = $this->id; try { $this->handler->callcheckMessage($message); if (!$message->save()) { throw new Exception(print_r($message->errors, true)); } } catch (\Exception $exception) { $message->status = CmsCallcheckMessage::STATUS_ERROR; $message->error_message = $exception->getMessage(); if (!$message->save()) { throw new Exception(print_r($message->errors, true)); } //throw $exception; } return $message; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsTaskSchedule.php
src/models/CmsTaskSchedule.php
<?php namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\helpers\CmsScheduleHelper; use skeeks\cms\models\queries\CmsTaskScheduleQuery; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_contractor". * * @property int $id * @property int $created_at * @property int $created_by * @property int $cms_user_id Пользователь * @property int $cms_task_id Задача * @property string $start_at Начало работы * @property string $end_at Завершение работы * * @property CmsUser $cmsUser * @property CmsTask $cmsTask */ class CmsTaskSchedule extends ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'cms_task_schedule'; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['created_at', 'created_by', 'cms_task_id', 'cms_user_id'], 'integer'], [['cms_task_id', 'cms_user_id', 'start_at'], 'required'], [ ['start_at'], function () { if ($this->isNewRecord) { if (static::find() ->createdBy() //->task($this->cms_task_id) ->notEnd()->one()) { /*if ($this->cmsTask->notEndCrmTaskSchedule) {*/ $this->addError('end_time', 'У вас уже запущена задача. Для начала сотановите ее.'); return false; } } }, ], [ ['end_at'], function () { if ($this->end_at && $this->start_at >= $this->end_at) { $this->addError('end_at', 'Время начала работы должно быть меньше времени завершения.'); return false; } }, ], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_task_id' => 'Задача', 'cms_user_id' => 'Пользователь', 'start_at' => 'Начало работы', 'end_at' => 'Завершение работы', ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsTask() { return $this->hasOne(CmsTask::class, ['id' => 'cms_task_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { return $this->hasOne(\Yii::$app->user->identityClass, ['id' => 'cms_user_id']); } /** * @return CmsTaskScheduleQuery */ public static function find() { return new CmsTaskScheduleQuery(get_called_class()); } /** * Длительность промежутка в секундах * * @return int */ public function getDuration() { if ($this->end_at) { $end = $this->end_at; } else { $end = time(); } return $end - $this->start_at; } /** * Длительность промежутка в понятном названии * * @return string */ public function getDurationAsText() { return CmsScheduleHelper::durationAsText($this->duration); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsCompany2manager.php
src/models/CmsCompany2manager.php
<?php namespace skeeks\cms\models; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "crm_client_map". * * @property int $id * @property int $created_by * @property int $updated_by * @property int $created_at * @property int $updated_at * @property int $cms_company_id Компания * @property int $cms_user_id Пользователь * * @property CmsUser $cmsUser * @property CmsCompany $cmsCompany */ class CmsCompany2manager extends \skeeks\cms\base\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return '{{%cms_company2manager}}'; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['cms_company_id', 'cms_user_id'], 'integer'], [['cms_company_id', 'cms_user_id'], 'required'], [['cms_company_id', 'cms_user_id'], 'unique', 'targetAttribute' => ['cms_company_id', 'cms_user_id']], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cms_user_id' => Yii::t('app', 'Контрагент'), 'cms_company_id' => Yii::t('app', 'Компания'), ]); } /** * {@inheritdoc} */ public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsUser() { $userClass = \Yii::$app->user->identityClass; return $this->hasOne($userClass, ['id' => 'cms_user_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsCompany() { return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsTaskFile.php
src/models/CmsTaskFile.php
<?php namespace skeeks\cms\models; use Yii; /** * This is the model class for table "{{%cms_content_element_file}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property integer $storage_file_id * @property integer $log_id * @property integer $priority * * @property CmsTask $cmsTask * @property CmsStorageFile $storageFile */ class CmsTaskFile extends \skeeks\cms\models\Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_task_file}}'; } /** * @inheritdoc */ public function rules() { return [ [ [ 'created_by', 'updated_by', 'created_at', 'updated_at', 'storage_file_id', 'cms_task_id', 'priority', ], 'integer', ], [['storage_file_id', 'cms_task_id'], 'required'], [ ['storage_file_id', 'cms_task_id'], 'unique', 'targetAttribute' => ['storage_file_id', 'cms_task_id'], 'message' => \Yii::t('skeeks/cms', 'The combination of Storage File ID and Content Element ID has already been taken.'), ], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('skeeks/cms', 'ID'), 'created_by' => Yii::t('skeeks/cms', 'Created By'), 'updated_by' => Yii::t('skeeks/cms', 'Updated By'), 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'storage_file_id' => Yii::t('skeeks/cms', 'Storage File ID'), 'cms_task_id' => Yii::t('skeeks/cms', 'Content Element ID'), 'priority' => Yii::t('skeeks/cms', 'Priority'), ]; } /** * @return \yii\db\ActiveQuery */ public function getTask() { return $this->hasOne(CmsTask::className(), ['id' => 'cms_task_id']); } /** * @return \yii\db\ActiveQuery */ public function getStorageFile() { return $this->hasOne(CmsStorageFile::className(), ['id' => 'storage_file_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsTreeImage.php
src/models/CmsTreeImage.php
<?php namespace skeeks\cms\models; use Yii; /** * This is the model class for table "{{%cms_tree_image}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property integer $storage_file_id * @property integer $tree_id * @property integer $priority * * @property CmsTree $tree * @property CmsStorageFile $storageFile */ class CmsTreeImage extends \skeeks\cms\models\Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_tree_image}}'; } /** * @inheritdoc */ public function rules() { return [ [ ['created_by', 'updated_by', 'created_at', 'updated_at', 'storage_file_id', 'tree_id', 'priority'], 'integer' ], [['storage_file_id', 'tree_id'], 'required'], [ ['storage_file_id', 'tree_id'], 'unique', 'targetAttribute' => ['storage_file_id', 'tree_id'], 'message' => \Yii::t('skeeks/cms', 'The combination of Storage File ID and Tree ID has already been taken.') ] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('skeeks/cms', 'ID'), 'created_by' => Yii::t('skeeks/cms', 'Created By'), 'updated_by' => Yii::t('skeeks/cms', 'Updated By'), 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'storage_file_id' => Yii::t('skeeks/cms', 'Storage File ID'), 'tree_id' => Yii::t('skeeks/cms', 'Tree ID'), 'priority' => Yii::t('skeeks/cms', 'Priority'), ]; } /** * @return \yii\db\ActiveQuery */ public function getTree() { return $this->hasOne(CmsTree::className(), ['id' => 'tree_id']); } /** * @return \yii\db\ActiveQuery */ public function getStorageFile() { return $this->hasOne(CmsStorageFile::className(), ['id' => 'storage_file_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsContentProperty.php
src/models/CmsContentProperty.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 09.11.2014 * @since 1.0.0 */ namespace skeeks\cms\models; use skeeks\cms\query\CmsContentPropertyActiveQuery; use skeeks\cms\relatedProperties\models\RelatedPropertyModel; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "{{%cms_content_property}}". * @property integer|null $cms_site_id * * @property integer $is_offer_property * @property integer $is_img_offer_property * @property integer $is_vendor * @property integer $is_vendor_code * @property integer $is_country * @property integer $is_sticker * @property integer|null $sx_id * * @property CmsContent[] $cmsContents * @property CmsContentProperty2content[] $cmsContentProperty2contents * * @property CmsContentPropertyEnum[] $enums * @property CmsContentElementProperty[] $elementProperties * * @property CmsContentProperty2tree[] $cmsContentProperty2trees * @property CmsTree[] $cmsTrees * @property CmsSite $cmsSite * @property ShopCmsContentProperty $shopProperty */ class CmsContentProperty extends RelatedPropertyModel { /** * @inheritdoc */ public static function tableName() { return '{{%cms_content_property}}'; } /** * @return array */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ \skeeks\cms\behaviors\RelationalBehavior::class, ]); } /** * @return \yii\db\ActiveQuery */ public function getElementProperties() { return $this->hasMany(CmsContentElementProperty::className(), ['property_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getEnums() { return $this->hasMany(CmsContentPropertyEnum::className(), ['property_id' => 'id']); } /** * @return array */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'cmsContents' => Yii::t('skeeks/cms', 'Linked to content'), 'cmsTrees' => Yii::t('skeeks/cms', 'Linked to sections'), 'cms_site_id' => Yii::t('skeeks/cms', 'Сайт'), 'is_offer_property' => \Yii::t('skeeks/cms', 'Свойство предложения?'), 'is_img_offer_property' => \Yii::t('skeeks/cms', 'Отображать свойство картинкой?'), 'is_vendor' => \Yii::t('skeeks/cms', 'Производитель?'), 'is_vendor_code' => \Yii::t('skeeks/cms', 'Код производителя?'), 'is_country' => \Yii::t('skeeks/cms', 'Страна'), 'is_sticker' => \Yii::t('skeeks/cms', 'Стикер'), 'sx_id' => Yii::t('skeeks/cms', 'SkeekS Suppliers ID'), ]); } /** * @return array */ public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ 'is_img_offer_property' => \Yii::t('skeeks/cms', 'В карточке будет отображатсья картинка при выборе этого варианта.'), 'is_offer_property' => \Yii::t('skeeks/cms', 'Если это свойство является свойством предложения, то оно будет показываться в сложных карточках.'), 'cms_site_id' => Yii::t('skeeks/cms', 'Если сайт не будет выбран, то свойство будет показываться на всех сайтах.'), 'is_sticker' => Yii::t('skeeks/cms', 'Эта характеристика является стикером на товар.'), 'cmsContents' => Yii::t('skeeks/cms', 'Необходимо выбрать в каком контенте будет показываться это свойство.'), 'cmsTrees' => Yii::t('skeeks/cms', 'Так же есть возможность ограничить отображение поля только для определенных разделов. Если будут выбраны разделы, то добавляя элемент в соответствующий раздел будет показываться это поле.'), ]); } /** * @inheritdoc */ public function rules() { $rules = ArrayHelper::merge(parent::rules(), [ [ ['is_vendor', 'is_vendor_code', 'is_sticker', 'is_country', 'is_offer_property', 'is_img_offer_property', 'sx_id'], 'integer', ], /*[ ['is_vendor', 'is_vendor_code', 'is_country', 'is_offer_property'], 'default', 'value' => null, ],*/ /*[ ['is_vendor', 'is_vendor_code', 'is_country', 'is_offer_property'], function ($attr) { if ($this->{$attr} != 1) { $this->{$attr} = null; } }, ],*/ [ ['is_img_offer_property', 'is_offer_property'], 'default', 'value' => 0, ], [ ['sx_id'], 'default', 'value' => null, ], [ ['is_sticker'], 'default', 'value' => null, ], [ ['is_sticker'], function($attribute) { if ($this->{$attribute} == 0) { $this->{$attribute} = null; } } ], [['cmsContents'], 'safe'], [['cmsTrees'], 'safe'], [['code', 'cms_site_id'], 'unique', 'targetAttribute' => ['code', 'cms_site_id']], [['cms_site_id'], 'integer'], [ ['cms_site_id'], 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } /*if (\Yii::$app->skeeks->site->is_default) { return null; } else { return \Yii::$app->skeeks->site->id; }*/ }, ], [['cmsContents'], 'required'], [ ['cms_site_id'], 'required', 'when' => function () { return $this->cmsTrees; }, ] //[['code', 'content_id'], 'unique', 'targetAttribute' => ['content_id', 'code'], 'message' => \Yii::t('skeeks/cms','For the content of this code is already in use.')], ]); return $rules; } /** * @return \yii\db\ActiveQuery */ public function getCmsContentProperty2contents() { return $this->hasMany(CmsContentProperty2content::className(), ['cms_content_property_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsContents() { return $this->hasMany(CmsContent::className(), ['id' => 'cms_content_id'])->viaTable('cms_content_property2content', ['cms_content_property_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsContentProperty2trees() { return $this->hasMany(CmsContentProperty2tree::className(), ['cms_content_property_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsSite() { return $this->hasOne(CmsSite::class, ['id' => 'cms_site_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsTrees() { return $this->hasMany(CmsTree::className(), ['id' => 'cms_tree_id'])->viaTable('cms_content_property2tree', ['cms_content_property_id' => 'id']); } public function asText() { return parent::asText(); return $result." ($this->code)"; } /** * @return CmsContentPropertyActiveQuery */ public static function find() { return (new CmsContentPropertyActiveQuery(get_called_class())); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsSiteAddressEmail.php
src/models/CmsSiteAddressEmail.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\helpers\StringHelper; use skeeks\cms\validators\PhoneValidator; use skeeks\modules\cms\user\models\User; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_site_phone". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property int $cms_site_id * @property string $value * @property string|null $name * @property int $priority * * @property CmsSiteAddress $cmsSiteAddress */ class CmsSiteAddressEmail extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%cms_site_address_email}}'; } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'value' => 'Email', 'name' => 'Название', 'priority' => 'Сортировка', ]); } /** * @inheritdoc */ public function attributeHints() { return array_merge(parent::attributeHints(), [ 'name' => 'Необязтельное поле, можно дать название этому email', 'priority' => 'Чем ниже цифра тем выше email', ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_address_id', 'priority'], 'integer'], [['cms_site_address_id', 'value'], 'required'], [['value', 'name'], 'string', 'max' => 255], [['value'], 'email'], [['cms_site_address_id', 'value'], 'unique', 'targetAttribute' => ['cms_site_address_id', 'value']], [['cms_site_address_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSiteAddress::class, 'targetAttribute' => ['cms_site_address_id' => 'id']], ]); } /** * Gets query for [[CmsSite]]. * * @return \yii\db\ActiveQuery */ public function getCmsSiteAddress() { return $this->hasOne(CmsSiteAddress::className(), ['id' => 'cms_site_address_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsDepartment.php
src/models/CmsDepartment.php
<?php namespace skeeks\cms\models; use paulzi\adjacencyList\AdjacencyListBehavior; use paulzi\autotree\AutoTreeTrait; use skeeks\cms\base\ActiveRecord; use skeeks\cms\behaviors\RelationalBehavior; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_contractor". * * @property int $id * @property int|null $created_by * @property int|null $created_at * @property string $name Название * @property int|null $worker_id Руководитель отдела * @property int $sort * * @property CmsUser $supervisor Руководитель отдела * @property CmsUser[] $workers Сотрудники отдела * * @property string $fullName * * @property CmsDepartment $parent * @property CmsDepartment[] $parents * @property CmsDepartment[] $children * @property CmsDepartment[] $activeChildren * @property CmsDepartment $root * @property CmsDepartment $prev * @property CmsDepartment $next * @property CmsDepartment[] $descendants * */ class CmsDepartment extends ActiveRecord { use AutoTreeTrait; /** * {@inheritdoc} */ public static function tableName() { return 'cms_department'; } /*public function init() { $this->on(self::EVENT_BEFORE_INSERT, [$this, '_beforeInsert']); }*/ public function behaviors() { $behaviors = parent::behaviors(); return ArrayHelper::merge(parent::behaviors(), [ [ 'class' => RelationalBehavior::class, ], [ 'class' => AdjacencyListBehavior::class, 'parentAttribute' => 'pid', 'sortable' => [ 'sortAttribute' => 'sort', ], ], ]); } /*public function _beforeInsert() { if ($this->pid) { $this->appendTo($this->parent); } }*/ /** * {@inheritdoc} */ public function rules() { return array_merge(parent::rules(), [ [['created_by', 'created_at'], 'integer'], [['name'], 'string', 'max' => 255], [['name'], 'required'], [['worker_id'], 'integer'], [['sort'], 'integer'], [['sort'], 'default', 'value' => 100], [['pid'], 'integer'], [['workers'], 'safe'], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'name' => 'Название', 'worker_id' => 'Руководитель отдела', 'pid' => 'Родительский отдел', 'sort' => 'Сортировка', 'workers' => 'Сотрудники', ]); } /** * @return \yii\db\ActiveQuery */ public function getSupervisor() { return $this->hasOne(CmsUser::class, ['id' => 'worker_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsDepartment2workers() { return $this->hasMany(CmsDepartment2worker::class, ['cms_department_id' => 'id']) ->from(['cmsDepartment2workers' => CmsDepartment2worker::tableName()]); } /** * @return \yii\db\ActiveQuery */ public function getWorkers() { return $this->hasMany(CmsUser::class, ['id' => 'worker_id']) ->via('cmsDepartment2workers');; } /** * @param string $glue * * @return string */ public function getFullName($glue = " / ") { $paths = []; if ($this->parents) { foreach ($this->parents as $parent) { $paths[] = $parent->name; } } $paths[] = $this->name; return implode($glue, $paths); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsUser2manager.php
src/models/CmsUser2manager.php
<?php namespace skeeks\cms\models; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "crm_client_map". * * @property int $id * @property int $created_by * @property int $updated_by * @property int $created_at * @property int $updated_at * @property int $client_id Клиент * @property int $worker_id Сотрудник * * @property CmsUser $client * @property CmsUser $worker */ class CmsUser2manager extends \skeeks\cms\base\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return '{{%cms_user2manager}}'; } /** * {@inheritdoc} */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['client_id', 'worker_id'], 'integer'], [['client_id', 'worker_id'], 'required'], [['client_id', 'worker_id'], 'unique', 'targetAttribute' => ['client_id', 'worker_id']], ]); } /** * {@inheritdoc} */ public function attributeLabels() { return ArrayHelper::merge(parent::attributeLabels(), [ 'worker_id' => Yii::t('app', 'Сотрудник'), 'client_id' => Yii::t('app', 'Клиент'), ]); } /** * {@inheritdoc} */ public function attributeHints() { return ArrayHelper::merge(parent::attributeHints(), [ ]); } /** * @return \yii\db\ActiveQuery */ public function getWorker() { $userClass = \Yii::$app->user->identityClass; return $this->hasOne($userClass, ['id' => 'worker_id']); } /** * @return \yii\db\ActiveQuery */ public function getClient() { $userClass = \Yii::$app->user->identityClass; return $this->hasOne($userClass, ['id' => 'client_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsTheme.php
src/models/CmsTheme.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 20.05.2015 */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\base\Theme; use skeeks\cms\models\behaviors\HasStorageFile; use skeeks\cms\models\behaviors\Serialize; use skeeks\modules\cms\user\models\User; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_site_theme". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property int $cms_site_id * @property string $code Уникальный код темы * * @property string|null $config Настройки темы * * @property string|null $name Название темы * @property string|null $description Описание темы * * @property int|null $cms_image_id Фото * @property int $priority * @property int|null $is_active Активирована? * * *** * * @property string $themeName * @property string $themeDescription * @property string $themeImageSrc * * @property Theme $objectTheme * @property CmsStorageFile $cmsImage * @property CmsSite $cmsSite */ class CmsTheme extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%cms_theme}}'; } public function init() { $this->on(static::EVENT_BEFORE_UPDATE, [$this, '_beforeUpdate']); return parent::init(); } public function _beforeUpdate() { //Перед обновлением активности шаблона, нужно деактивировать другие у этого сайта. if ($this->is_active == 1 && $this->isAttributeChanged("is_active")) { static::updateAll(['is_active' => null], ['cms_site_id' => $this->cms_site_id]); } } public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ HasStorageFile::className() => [ 'class' => HasStorageFile::className(), 'fields' => ['cms_image_id'], ], Serialize::class => [ 'class' => Serialize::class, 'fields' => ['config'], ], ]); } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'id' => Yii::t('skeeks/cms', 'ID'), ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'cms_image_id', 'priority', 'is_active'], 'integer'], [['code'], 'required'], [['config'], 'safe'], [['code', 'name', 'description'], 'string', 'max' => 255], [['cms_site_id', 'code'], 'unique', 'targetAttribute' => ['cms_site_id', 'code']], //[['cms_site_id', 'is_active'], 'unique', 'targetAttribute' => ['cms_site_id', 'is_active']], [['cms_image_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsStorageFile::className(), 'targetAttribute' => ['cms_image_id' => 'id']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::className(), 'targetAttribute' => ['cms_site_id' => 'id']], [['created_by'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::className(), 'targetAttribute' => ['created_by' => 'id']], [['updated_by'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::className(), 'targetAttribute' => ['updated_by' => 'id']], [['is_active'], 'default', 'value' => null], //TODO: добавить для null [['is_main', 'cms_site_id'], 'unique', 'targetAttribute' => ['is_main', 'cms_site_id']], [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsSite() { $class = \Yii::$app->skeeks->siteClass; return $this->hasOne($class, ['id' => 'cms_site_id']); } /** * @return string */ public function getCmsImage() { return $this->hasOne(CmsStorageFile::class, ['id' => 'cms_image_id']); } protected $_themeObject = null; /** * @return false|\skeeks\cms\base\Theme * @throws \yii\base\InvalidConfigException */ public function getObjectTheme() { if ($this->_themeObject === null) { $themes = \Yii::$app->view->availableThemes; $themeData = \yii\helpers\ArrayHelper::getValue($themes, $this->code); $theme = false; if ($themeData) { /** * @var $theme \skeeks\cms\base\Theme */ $theme = \Yii::createObject($themeData); $this->loadConfigToTheme($theme); } $this->_themeObject = $theme; } return $this->_themeObject; } /** * @return string|null */ public function getThemeName() { return $this->name ? $this->name : $this->objectTheme->descriptor->name; } /** * @return string|null */ public function getThemeDescription() { return $this->description ? $this->description : $this->objectTheme->descriptor->description; } /** * @return string|null */ public function getThemeImageSrc() { return $this->cmsImage ? $this->cmsImage->src : $this->objectTheme->descriptor->image; } /** * @param Theme $theme * @return $this */ public function loadConfigToTheme(Theme $theme) { if ($this->config) { foreach ($this->config as $key => $value) { if ($theme->canSetProperty($key)) { $theme->{$key} = $value; } } } return $this; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/Tree.php
src/models/Tree.php
<?php /** * Publication * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 31.10.2014 * @since 1.0.0 */ namespace skeeks\cms\models; use paulzi\adjacencyList\AdjacencyListBehavior; use paulzi\autotree\AutoTreeTrait; use paulzi\materializedPath\MaterializedPathBehavior; use skeeks\cms\base\ActiveRecord; use skeeks\cms\behaviors\CmsLogBehavior; use skeeks\cms\components\Cms; use skeeks\cms\components\urlRules\UrlRuleTree; use skeeks\cms\models\behaviors\CanBeLinkedToTree; use skeeks\cms\models\behaviors\HasRelatedProperties; use skeeks\cms\models\behaviors\HasStorageFile; use skeeks\cms\models\behaviors\HasStorageFileMulti; use skeeks\cms\models\behaviors\traits\HasLogTrait; use skeeks\cms\models\behaviors\traits\HasRelatedPropertiesTrait; use skeeks\cms\models\behaviors\traits\TreeBehaviorTrait; use skeeks\cms\models\behaviors\TreeBehavior; use skeeks\cms\query\CmsTreeActiveQuery; use skeeks\yii2\slug\SlugRuleProvider; use skeeks\yii2\yaslug\YaSlugHelper; use Yii; use yii\base\Event; use yii\base\Exception; use yii\db\ActiveQuery; use yii\db\AfterSaveEvent; use yii\helpers\ArrayHelper; use yii\helpers\Url; /** * This is the model class for table "{{%cms_tree}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property string $name * @property string $description_short * @property string $description_full * @property string $code * @property integer $pid * @property string $pids * @property integer $level * @property string $dir * @property integer $priority * @property string $tree_type_id * @property integer $published_at * @property string $active * @property string $meta_title * @property string $meta_description * @property string $meta_keywords * @property string $cms_site_id * @property string $description_short_type * @property string $description_full_type * @property integer $image_full_id * @property integer $image_id * @property string $name_hidden * @property string $view_file * @property string $seo_h1 * @property string|null $external_id * @property integer|null $main_cms_tree_id * @property integer|null $sx_id * * @property bool $shop_has_collections Раздел содержит товарные коллекции? * @property bool $shop_show_collections Показывать коллекции по умолчанию? * * @property integer $is_adult Содержит контент для взрослых? * @property integer $is_index Страница индексируется? * * @property string|null $canonical_link Canonical на другую страницу * @property integer|null $canonical_tree_id Canonical раздел сайта * @property integer|null $canonical_content_element_id Canonical на раздел сайта * @property integer|null $canonical_saved_filter_id Canonical на сохраненный фильтр сайта * * @property integer|null $redirect_content_element_id Перенаправление на элемент * @property integer|null $redirect_saved_filter_id Перенаправление на сохраненный фильтр * @property integer|null $redirect_tree_id Перенаправление на другой раздела * @property integer|null $redirect_code Код перенаправления * @property string|null $redirect Перенаправление на свободную ссылку * * *** * * @property string $fullName * * @property bool $isRedirect Страница является редирректом? * @property bool $isCanonical Страница явялется канонической? * * @property string $absoluteUrl * @property string $url * @property string $canonicalUrl Ссылка на каноническую страницу * * @property CmsStorageFile|null $mainImage * @property CmsStorageFile|null $image * @property CmsStorageFile|null $fullImage * * @property CmsTreeFile[] $cmsTreeFiles * @property CmsTreeImage[] $cmsTreeImages * @property CmsTree $redirectTree * @property CmsTree $canonicalTree * @property CmsTree $mainCmsTree * * @property CmsStorageFile[] $files * @property CmsStorageFile[] $images * * @property CmsContentElement[] $cmsContentElements * @property CmsContentElementTree[] $cmsContentElementTrees * @property CmsSite $site * @property CmsSite $cmsSiteRelation * @property CmsTreeType $cmsTreeType * @property CmsTreeProperty[] $cmsTreeProperties * * @property CmsContentProperty2tree[] $cmsContentProperty2trees * @property CmsContentProperty[] $cmsContentProperties * * @property CmsFaq[] $cmsFaqs * * @property string $seoName * @property bool $isAllowIndex * * @property Tree $parent * @property Tree[] $parents * @property Tree[] $children * @property Tree[] $activeChildren * @property Tree $root * @property Tree $prev * @property Tree $next * @property Tree[] $descendants * @property bool $isActive * @property CmsSavedFilter[] $cmsSavedFilters * @property static[] $cmsTreeChildsByPid * @property static $cmsTreeByPid * * @depricated */ class Tree extends ActiveRecord { use HasRelatedPropertiesTrait; use AutoTreeTrait; use HasLogTrait; /** * @inheritdoc */ public static function tableName() { return '{{%cms_tree}}'; } /** * @return string */ public function getSkeeksModelCode() { return CmsTree::class; } const PRIORITY_STEP = 100; //Шаг приоритета public function behaviors() { $behaviors = parent::behaviors(); return ArrayHelper::merge(parent::behaviors(), [ HasStorageFile::className() => [ 'class' => HasStorageFile::className(), 'fields' => ['image_id', 'image_full_id'], ], HasStorageFileMulti::className() => [ 'class' => HasStorageFileMulti::className(), 'relations' => [ [ 'relation' => 'images', 'property' => 'imageIds', ], [ 'relation' => 'files', 'property' => 'fileIds', ], ], ], HasRelatedProperties::className() => [ 'class' => HasRelatedProperties::className(), 'relatedElementPropertyClassName' => CmsTreeProperty::className(), 'relatedPropertyClassName' => CmsTreeTypeProperty::className(), ], [ 'class' => AdjacencyListBehavior::className(), 'parentAttribute' => 'pid', 'sortable' => [ 'sortAttribute' => 'priority', ], /*'parentsJoinLevels' => 0, 'childrenJoinLevels' => 0, 'sortable' => false,*/ ], [ 'class' => MaterializedPathBehavior::className(), 'pathAttribute' => 'pids', 'depthAttribute' => 'level', 'sortable' => [ 'sortAttribute' => 'priority', ], ], CmsLogBehavior::class => [ 'class' => CmsLogBehavior::class, 'no_log_fields' => [ 'description_short_type', 'description_full_type', ], 'relation_map' => [ 'tree_type_id' => 'treeType', ], ], ]); } public function init() { parent::init(); $this->on(self::EVENT_BEFORE_INSERT, [$this, '_updateCode']); $this->on(self::EVENT_BEFORE_UPDATE, [$this, '_updateCode']); $this->on(self::EVENT_AFTER_UPDATE, [$this, 'afterUpdateTree']); $this->on(self::EVENT_BEFORE_DELETE, [$this, 'beforeDeleteTree']); } /** * Если есть дети для начала нужно удалить их всех * @param Event $event * @throws \Exception */ public function beforeDeleteTree(Event $event) { if ($children = $this->getChildren()->all()) { foreach ($children as $childNode) { $childNode->delete(); } } } public function _updateCode(Event $event) { $parent = $this->getParent()->one(); //У корневой ноды всегда нет кода if ($this->isRoot()) { $this->code = null; $this->dir = null; } else { if (!$this->code) { $this->_generateCode(); } $this->dir = $this->code; if ($this->level > 1) { $parent = $this->getParent()->one(); $this->dir = $parent->dir."/".$this->code; } } //site code if ($parent) { $this->cms_site_id = $parent->cms_site_id; } elseif (!$this->cms_site_id) { if ($site = \Yii::$app->skeeks->site) { $this->cms_site_id = $site->code; } } //tree type if (!$this->tree_type_id) { if ($this->parent && $this->parent->treeType) { if ($this->parent->treeType->defaultChildrenTreeType) { $this->tree_type_id = $this->parent->treeType->defaultChildrenTreeType->id; } else { $this->tree_type_id = $this->parent->tree_type_id; } } else { if ($treeType = CmsTreeType::find()->orderBy(['priority' => SORT_ASC])->one()) { $this->tree_type_id = $treeType->id; } } } } /** * Изменился код * @param AfterSaveEvent $event */ public function afterUpdateTree(AfterSaveEvent $event) { if ($event->changedAttributes) { //Если изменилось название seo_page_name if (isset($event->changedAttributes['code'])) { $event->sender->processNormalize(); } //Если изменилось название seo_page_name if (isset($event->changedAttributes['pid'])) { $event->sender->processNormalize(); } } } /** * @inheritdoc */ public function attributeHints() { return array_merge(parent::attributeHints(), [ 'seo_h1' => 'Заголовок будет показан на детальной странице, в случае если его использование задано в шаблоне.', 'external_id' => 'Это поле чаще всего задействуют программисты, для интеграций со сторонними системами', 'active' => 'Если стоит галочка, то раздел показывается везде на сайте. Если галочка не стоит — раздел скрыт! Но при этому он индексируется и доступен по прямой ссылке!', 'is_adult' => 'Если эта страница содержит контент для взрослых, то есть имеет возрастные ограничения 18+ нужно поставить эту галочку!', 'is_index' => 'Необходимо поставить эту галочку, чтобы страница была доступна поисковым системам и попадала в карту сайта!', 'shop_has_collections' => Yii::t('skeeks/cms', 'Включив эту опцию, добавляя товар в этот раздел, необходим будет заполнять поле "Коллекции"'), 'shop_show_collections' => Yii::t('skeeks/cms', 'Если включен функционал коллекций (опция выше) то по умолчанию в этом разделе можно отображать коллекции или товары. Эта опция отвечает за это.'), ]); } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'shop_has_collections' => Yii::t('skeeks/cms', 'Раздел содержит товарные коллекции'), 'shop_show_collections' => Yii::t('skeeks/cms', 'Показывать коллекции по умолчанию'), 'published_at' => Yii::t('skeeks/cms', 'Published At'), 'published_to' => Yii::t('skeeks/cms', 'Published To'), 'priority' => Yii::t('skeeks/cms', 'Priority'), 'active' => Yii::t('skeeks/cms', 'Показывается на сайте?'), 'name' => Yii::t('skeeks/cms', 'Name'), 'tree_type_id' => Yii::t('skeeks/cms', 'Type'), 'redirect' => Yii::t('skeeks/cms', 'Redirect'), 'priority' => Yii::t('skeeks/cms', 'Priority'), 'code' => Yii::t('skeeks/cms', 'Code'), 'meta_title' => Yii::t('skeeks/cms', 'Meta Title'), 'meta_keywords' => Yii::t('skeeks/cms', 'Meta Keywords'), 'meta_description' => Yii::t('skeeks/cms', 'Meta Description'), 'description_short' => Yii::t('skeeks/cms', 'Description Short'), 'description_full' => Yii::t('skeeks/cms', 'Description Full'), 'description_short_type' => Yii::t('skeeks/cms', 'Description Short Type'), 'description_full_type' => Yii::t('skeeks/cms', 'Description Full Type'), 'image_id' => Yii::t('skeeks/cms', 'Image'), 'image_full_id' => Yii::t('skeeks/cms', 'Main Image'), 'images' => Yii::t('skeeks/cms', 'Images'), 'imageIds' => Yii::t('skeeks/cms', 'Images'), 'files' => Yii::t('skeeks/cms', 'Files'), 'fileIds' => Yii::t('skeeks/cms', 'Files'), 'redirect_tree_id' => Yii::t('skeeks/cms', 'Redirect Section'), 'redirect_code' => Yii::t('skeeks/cms', 'Redirect Code'), 'name_hidden' => Yii::t('skeeks/cms', 'Hidden Name'), 'view_file' => Yii::t('skeeks/cms', 'Template'), 'seo_h1' => Yii::t('skeeks/cms', 'SEO заголовок h1'), 'external_id' => Yii::t('skeeks/cms', 'ID из внешней системы'), 'sx_id' => Yii::t('skeeks/cms', 'SkeekS Suppliers ID'), 'is_adult' => Yii::t('skeeks/cms', 'Контент для взрослых?'), 'is_index' => Yii::t('skeeks/cms', 'Страница индексируется?'), 'dir' => Yii::t('skeeks/cms', 'Дирректория'), 'level' => Yii::t('skeeks/cms', 'Уровень вложенности'), 'pids' => Yii::t('skeeks/cms', 'Родительские разделы'), 'pid' => Yii::t('skeeks/cms', 'Родительский раздел'), ]); } /** * @inheritdoc */ public function rules() { return array_merge(parent::rules(), [ [['description_short', 'description_full'], 'string'], ['active', 'default', 'value' => Cms::BOOL_Y], ['sx_id', 'default', 'value' => null], [['redirect_code'], 'default', 'value' => 301], [['redirect_code'], 'in', 'range' => [301, 302]], [['redirect'], 'string'], [['redirect_content_element_id'], 'integer'], [['redirect_saved_filter_id'], 'integer'], [['redirect_tree_id'], 'integer'], [['redirect_code'], 'integer'], [['sx_id'], 'integer'], [ [ 'redirect', 'redirect_content_element_id', 'redirect_tree_id', 'canonical_saved_filter_id', ], 'default', 'value' => null, ], [['canonical_link'], 'string'], [['canonical_tree_id'], 'integer'], [['canonical_content_element_id'], 'integer'], [['canonical_saved_filter_id'], 'integer'], [ [ 'shop_has_collections', 'shop_show_collections', ], 'integer', ], [ [ 'shop_has_collections', ], 'default', 'value' => 0, ], [ [ 'shop_show_collections', ], 'default', 'value' => 1, ], [ [ 'canonical_saved_filter_id', 'canonical_tree_id', 'canonical_content_element_id', 'canonical_saved_filter_id', ], 'default', 'value' => null, ], [['is_adult'], 'integer'], [['is_adult'], 'default', 'value' => 0], [['is_adult'], 'in', 'range' => [1, 0]], [['is_index'], 'integer'], [['is_index'], 'default', 'value' => 1], [['is_index'], 'in', 'range' => [1, 0]], [['name_hidden'], 'string'], [['priority', 'tree_type_id'], 'integer'], [['code'], 'string', 'max' => 64], [['name'], 'string', 'max' => 255], [['seo_h1'], 'string', 'max' => 255], [['external_id'], 'string', 'max' => 255], [['external_id'], 'default', 'value' => null], [['seo_h1'], 'default', 'value' => ''], [['meta_title', 'meta_description', 'meta_keywords'], 'string'], [['meta_title'], 'string', 'max' => 500], [['cms_site_id'], 'integer'], [['main_cms_tree_id'], 'integer'], [ ['pid', 'code'], 'unique', 'targetAttribute' => ['pid', 'code'], 'message' => \Yii::t('skeeks/cms', 'For this subsection of the code is already in use.'), ], [ ['pid', 'code'], 'unique', 'targetAttribute' => ['pid', 'code'], 'message' => \Yii::t('skeeks/cms', 'The combination of Code and Pid has already been taken.'), ], ['description_short_type', 'string'], ['description_full_type', 'string'], ['description_short_type', 'default', 'value' => "text"], ['description_full_type', 'default', 'value' => "text"], ['view_file', 'string', 'max' => 128], [['image_id', 'image_full_id'], 'safe'], [ ['image_id', 'image_full_id'], \skeeks\cms\validators\FileValidator::class, 'skipOnEmpty' => false, 'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'], 'maxFiles' => 1, 'maxSize' => 1024 * 1024 * 15, 'minSize' => 1024, ], [['imageIds', 'fileIds'], 'safe'], [ ['imageIds'], \skeeks\cms\validators\FileValidator::class, 'skipOnEmpty' => false, 'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'], 'maxFiles' => 40, 'maxSize' => 1024 * 1024 * 15, 'minSize' => 1024, ], [ ['fileIds'], \skeeks\cms\validators\FileValidator::class, 'skipOnEmpty' => false, //'extensions' => [''], 'maxFiles' => 40, 'maxSize' => 1024 * 1024 * 50, 'minSize' => 1024, ], [ ['name'], 'default', 'value' => function (self $model) { $lastTree = static::find()->orderBy(["id" => SORT_DESC])->one(); if ($lastTree) { return "pk-".$lastTree->primaryKey; } return 'root'; }, ], [ ['main_cms_tree_id'], 'default', 'value' => null, ], [['code'], "trim"], [ ['code'], function ($attribute) { $string = $this->{$attribute}; if (!preg_match('/^[a-z]{1}[a-z0-9_-]+$/', $string)) { $this->addError($attribute, \Yii::t('skeeks/cms', "Используйте буквы латинского алфавита, так же допустимо использование символов _-")); return false; } }, ], ]); } /** * @return \yii\db\ActiveQuery */ public function getRedirectTree() { return $this->hasOne(CmsTree::className(), ['id' => 'redirect_tree_id']); } /** * @return \yii\db\ActiveQuery */ public function getCanonicalTree() { return $this->hasOne(static::class, ['id' => 'canonical_tree_id']); } /** * @return \yii\db\ActiveQuery */ public function getMainCmsTree() { return $this->hasOne(CmsTree::className(), ['id' => 'main_cms_tree_id']); } /** * @return \skeeks\cms\query\CmsActiveQuery */ public static function findRoots() { return static::find()->where(['level' => 0])->orderBy(["priority" => SORT_ASC]); } /** * @param null $cmsSite * @return ActiveQuery */ public static function findRootsForSite($cmsSite = null) { if ($cmsSite === null) { $cmsSite = \Yii::$app->skeeks->site; } return static::findRoots()->andWhere(['cms_site_id' => $cmsSite->id]); } /** * @return string */ public function getUrl($scheme = false, $params = []) { UrlRuleTree::$models[$this->id] = $this; if ($params) { $params = ArrayHelper::merge(['/cms/tree/view', 'id' => $this->id], $params); } else { $params = ['/cms/tree/view', 'id' => $this->id]; } return Url::to($params, $scheme); } /** * @return string */ public function getCanonicalUrl() { if ($this->canonical_link) { return (string)$this->canonical_link; } if ($this->canonical_tree_id) { return (string)$this->canonicalTree->url; } return ""; } /** * @return string */ public function getAbsoluteUrl($params = []) { return $this->getUrl(true, $params); } /** * @return CmsSite */ public function getSite() { //return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_id']); $siteClass = \Yii::$app->skeeks->siteClass; return $siteClass::getById($this->cms_site_id); } /** * @return ActiveQuery */ public function getCmsSiteRelation() { return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsContentElements() { return $this->hasMany(CmsContentElement::className(), ['tree_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsContentElementTrees() { return $this->hasMany(CmsContentElementTree::className(), ['tree_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsTreeProperties() { return $this->hasMany(CmsTreeProperty::className(), ['element_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsTreeByPid() { return $this->hasOne(static::class, ['id' => 'pid']); } /** * @return \yii\db\ActiveQuery */ public function getCmsTreeChildsByPid() { return $this->hasMany(static::class, ['pid' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getTreeType() { return $this->getCmsTreeType(); } /** * @return \yii\db\ActiveQuery */ public function getCmsTreeType() { return $this->hasOne(CmsTreeType::className(), ['id' => 'tree_type_id']); } static protected $_treeTypes = []; /** * Все возможные свойства связанные с моделью * * @return array|\yii\db\ActiveRecord[] */ public function getRelatedProperties() { //return $this->treeType->getCmsTreeTypeProperties(); if (isset(self::$_treeTypes[$this->tree_type_id])) { $treeType = self::$_treeTypes[$this->tree_type_id]; } else { self::$_treeTypes[$this->tree_type_id] = $this->treeType; $treeType = self::$_treeTypes[$this->tree_type_id]; } if (!$treeType) { return CmsTreeTypeProperty::find()->where(['id' => null]); } //return $this->treeType->getCmsTreeTypeProperties(); return $treeType->getCmsTreeTypeProperties(); } /** * @return \yii\db\ActiveQuery */ public function getImage() { return $this->hasOne(StorageFile::className(), ['id' => 'image_id']); } /** * @return \yii\db\ActiveQuery */ public function getFullImage() { return $this->hasOne(StorageFile::className(), ['id' => 'image_full_id']); } protected $_image_ids = null; /** * @return \yii\db\ActiveQuery */ public function setImageIds($ids) { $this->_image_ids = $ids; return $this; } /** * @return array */ public function getImageIds() { if ($this->_image_ids !== null) { return $this->_image_ids; } if ($this->images) { return ArrayHelper::map($this->images, 'id', 'id'); } return []; } protected $_file_ids = null; /** * @return \yii\db\ActiveQuery */ public function setFileIds($ids) { $this->_file_ids = $ids; return $this; } /** * @return array */ public function getFileIds() { if ($this->_file_ids !== null) { return $this->_file_ids; } if ($this->files) { return ArrayHelper::map($this->files, 'id', 'id'); } return []; } /** * @return \yii\db\ActiveQuery */ public function getImages() { return $this->hasMany(StorageFile::className(), ['id' => 'storage_file_id']) ->via('cmsTreeImages') ->orderBy(['priority' => SORT_ASC]); } /** * @return \yii\db\ActiveQuery */ public function getFiles() { return $this->hasMany(StorageFile::className(), ['id' => 'storage_file_id']) ->via('cmsTreeFiles') ->orderBy(['priority' => SORT_ASC]); } /** * @return \yii\db\ActiveQuery */ public function getCmsTreeFiles() { return $this->hasMany(CmsTreeFile::className(), ['tree_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsTreeImages() { return $this->hasMany(CmsTreeImage::className(), ['tree_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsContentProperty2trees() { return $this->hasMany(CmsContentProperty2tree::className(), ['cms_tree_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCmsContentProperties() { return $this->hasMany(CmsContentProperty::class, ['id' => 'cms_content_property_id'])->viaTable('cms_content_property2tree', ['cms_tree_id' => 'id']) ->orderBy([CmsContentProperty::tableName().".priority" => SORT_ASC]); } /** * @return $this */ protected function _generateCode() { if ($this->isRoot()) { $this->code = null; return $this; } $this->code = YaSlugHelper::slugify($this->name); if (strlen($this->code) < 2) { $this->code = $this->code."-".md5(microtime()); } if (strlen($this->code) > \Yii::$app->cms->tree_max_code_length) { $this->code = substr($this->code, 0, \Yii::$app->cms->tree_max_code_length); } $matches = []; //Роутинг элементов нужно исключить if (preg_match('/(?<id>\d+)\-(?<code>\S+)$/i', $this->code, $matches)) { $this->code = "s".$this->code; } if (!$this->_isValidCode()) { $this->code = YaSlugHelper::slugify($this->code."-".substr(md5(uniqid().time()), 0, 4)); if (!$this->_isValidCode()) { return $this->_generateCode(); } } return $this; } /** * @return bool */ protected function _isValidCode() { if (!$this->parent) { return true; } $find = $this->parent->getChildren() ->where([ "code" => $this->code, 'pid' => $this->pid, ]); if (!$this->isNewRecord) { $find->andWhere([ "!=", 'id', $this->id, ]); } if ($find->one()) { return false; } return true; } /** * * Обновление всего дерева ниже, и самого элемента. * Если найти всех рутов дерева и запустить этот метод, то дерево починиться в случае поломки * правильно переустановятся все dir, pids и т.д. * * @return $this */ public function processNormalize() { if ($this->isRoot()) { $this->setAttribute("dir", null); $this->save(false); } else { $this->setAttribute('dir', $this->code); if ($this->level > 1) { $parent = $this->getParent()->one();
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
true
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/Core.php
src/models/Core.php
<?php /** * Базовая модель содержит поведения пользователей, кто когда обновил, и создал сущьность * * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 31.10.2014 * @since 1.0.0 */ namespace skeeks\cms\models; /** * @deprecated */ abstract class Core extends \skeeks\cms\base\ActiveRecord { }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsSiteSocial.php
src/models/CmsSiteSocial.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\modules\cms\user\models\User; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_site_phone". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property int $cms_site_id * @property string $url * @property string|null $name * @property string $social_type * @property int $priority * * @property CmsSite $cmsSite * @property string $iconCode * @property string $iconHtml */ class CmsSiteSocial extends ActiveRecord { const SOCIAL_INSTAGRAM = 'instagram'; const SOCIAL_FACEBOOK = 'facebook'; const SOCIAL_VK = 'vk'; const SOCIAL_OK = 'odnoklassniki'; const SOCIAL_YOUTUBE = 'youtube'; const SOCIAL_WHATSAPP = 'whatsapp'; const SOCIAL_TELEGRAM = 'telegram'; const SOCIAL_OTHER = 'other'; const SOCIAL_PINTEREST = 'pinterest'; const SOCIAL_YANDEX = 'yandex'; const SOCIAL_RUTUBE = 'rutube'; const SOCIAL_DZEN = 'dzen'; /** * @inheritdoc */ public static function tableName() { return '{{%cms_site_social}}'; } /** * @return array */ static public function getSocialTypes() { return [ self::SOCIAL_TELEGRAM => 'Telegram', self::SOCIAL_WHATSAPP => 'WatsApp', self::SOCIAL_YANDEX => 'Yandex', self::SOCIAL_DZEN => 'Dzen', self::SOCIAL_FACEBOOK => 'Facebook', self::SOCIAL_INSTAGRAM => 'Instagram', self::SOCIAL_YOUTUBE => 'Youtube', self::SOCIAL_VK => 'Вконтакте', self::SOCIAL_OK => 'Одноклассники', self::SOCIAL_RUTUBE => 'Rutube', self::SOCIAL_PINTEREST => 'Pinterest', self::SOCIAL_OTHER => 'Другое', ]; } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'url' => 'Ссылка на профиль или сайт', 'social_type' => 'Социальная сеть или сайт', 'name' => 'Название', 'priority' => 'Сортировка', ]); } /** * @inheritdoc */ public function attributeHints() { return array_merge(parent::attributeHints(), [ 'name' => 'Необязтельное поле', 'priority' => 'Чем ниже цифра тем выше ссылка', ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'priority'], 'integer'], [['social_type'], 'string'], [['social_type'], 'required'], [['url'], 'required'], [['url', 'name'], 'string', 'max' => 255], [['cms_site_id', 'url'], 'unique', 'targetAttribute' => ['cms_site_id', 'url']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::className(), 'targetAttribute' => ['cms_site_id' => 'id']], [['url'], 'string', 'max' => 64], [['url'], 'url'], ]); } /** * Gets query for [[CmsSite]]. * * @return \yii\db\ActiveQuery */ public function getCmsSite() { return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_id']); } public function getIconCode() { return in_array($this->social_type, [self::SOCIAL_OTHER]) ? 'fas fa-external-link-alt' : "fab fa-".$this->social_type; } public function getIconHtml() { return "<i class='{$this->iconCode}'></i>"; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsContentElementImage.php
src/models/CmsContentElementImage.php
<?php namespace skeeks\cms\models; use Yii; /** * This is the model class for table "{{%cms_content_element_image}}". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property integer $storage_file_id * @property integer $content_element_id * @property integer $priority * * @property CmsContentElement $contentElement * @property CmsStorageFile $storageFile */ class CmsContentElementImage extends \skeeks\cms\models\Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_content_element_image}}'; } /** * @inheritdoc */ public function rules() { return [ [ [ 'created_by', 'updated_by', 'created_at', 'updated_at', 'storage_file_id', 'content_element_id', 'priority' ], 'integer' ], [['storage_file_id', 'content_element_id'], 'required'], [ ['storage_file_id', 'content_element_id'], 'unique', 'targetAttribute' => ['storage_file_id', 'content_element_id'], 'message' => \Yii::t('skeeks/cms', 'The combination of Storage File ID and Content Element ID has already been taken.') ] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('skeeks/cms', 'ID'), 'created_by' => Yii::t('skeeks/cms', 'Created By'), 'updated_by' => Yii::t('skeeks/cms', 'Updated By'), 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'storage_file_id' => Yii::t('skeeks/cms', 'Storage File ID'), 'content_element_id' => Yii::t('skeeks/cms', 'Content Element ID'), 'priority' => Yii::t('skeeks/cms', 'Priority'), ]; } /** * @return \yii\db\ActiveQuery */ public function getContentElement() { return $this->hasOne(CmsContentElement::className(), ['id' => 'content_element_id']); } /** * @return \yii\db\ActiveQuery */ public function getStorageFile() { return $this->hasOne(CmsStorageFile::className(), ['id' => 'storage_file_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsContentType.php
src/models/CmsContentType.php
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010-2014 SkeekS (Sx) * @date 09.11.2014 * @since 1.0.0 */ namespace skeeks\cms\models; use skeeks\cms\components\Cms; use skeeks\cms\models\behaviors\HasMultiLangAndSiteFields; use skeeks\cms\models\behaviors\HasStatus; use Yii; use yii\base\Exception; /** * This is the model class for table "cms_content_type". * * @property integer $id * @property integer $created_by * @property integer $updated_by * @property integer $created_at * @property integer $updated_at * @property integer $priority * @property string $name * @property string $code * * @property CmsContent[] $cmsContents */ class CmsContentType extends Core { /** * @inheritdoc */ public static function tableName() { return '{{%cms_content_type}}'; } /** * @return array */ public function behaviors() { return array_merge(parent::behaviors(), []); } /*public function init() { parent::init(); $this->on(self::EVENT_BEFORE_DELETE, [$this, '_actionBeforeDelete']); } public function _actionBeforeDelete($e) { if ($this->cmsContents) { throw new Exception(\Yii::t('skeeks/cms', "Before you delete this type of content you want to delete the contents invested in it")); } }*/ /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'id' => Yii::t('skeeks/cms', 'ID'), 'created_by' => Yii::t('skeeks/cms', 'Created By'), 'updated_by' => Yii::t('skeeks/cms', 'Updated By'), 'created_at' => Yii::t('skeeks/cms', 'Created At'), 'updated_at' => Yii::t('skeeks/cms', 'Updated At'), 'priority' => Yii::t('skeeks/cms', 'Priority'), 'name' => Yii::t('skeeks/cms', 'Name'), 'code' => Yii::t('skeeks/cms', 'Code'), ]); } public function attributeHints() { return array_merge(parent::attributeLabels(), [ 'priority' => Yii::t('skeeks/cms', 'Влияет на расположение группы контента в списке'), 'code' => Yii::t('skeeks/cms', 'Это поле не обязательно к заполнению и будет сгенерировано автоматически если оставить его пустым'), ]); } /** * @inheritdoc */ public function rules() { return array_merge(parent::rules(), [ [['created_by', 'updated_by', 'created_at', 'updated_at', 'priority'], 'integer'], [['name'], 'required'], [['name'], 'string', 'max' => 255], [['code'], 'string', 'max' => 32], [['code'], 'unique'], [ 'code', 'default', 'value' => function($model, $attribute) { return "auto" . \Yii::$app->security->generateRandomString(10); } ], [ 'priority', 'default', 'value' => function($model, $attribute) { return 500; } ], ]); } /** * @return \yii\db\ActiveQuery */ public function getCmsContents() { return $this->hasMany(CmsContent::className(), ['content_type' => 'code'])->orderBy("priority ASC")->andWhere(['is_active' => 1]); } public function asText() { $result = parent::asText(); return $result . " ($this->code)"; } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false
skeeks-cms/cms
https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/models/CmsSiteEmail.php
src/models/CmsSiteEmail.php
<?php /** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ namespace skeeks\cms\models; use skeeks\cms\base\ActiveRecord; use skeeks\cms\helpers\StringHelper; use skeeks\cms\validators\PhoneValidator; use skeeks\modules\cms\user\models\User; use Yii; use yii\helpers\ArrayHelper; /** * This is the model class for table "cms_site_phone". * * @property int $id * @property int|null $created_by * @property int|null $updated_by * @property int|null $created_at * @property int|null $updated_at * @property int $cms_site_id * @property string $value * @property string|null $name * @property int $priority * * @property CmsSite $cmsSite */ class CmsSiteEmail extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%cms_site_email}}'; } /** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), [ 'value' => 'Email', 'name' => 'Название', 'priority' => 'Сортировка', ]); } /** * @inheritdoc */ public function attributeHints() { return array_merge(parent::attributeHints(), [ 'name' => 'Необязтельное поле, можно дать название этому email', 'priority' => 'Чем ниже цифра тем выше email', ]); } /** * @inheritdoc */ public function rules() { return ArrayHelper::merge(parent::rules(), [ [ 'cms_site_id', 'default', 'value' => function () { if (\Yii::$app->skeeks->site) { return \Yii::$app->skeeks->site->id; } }, ], [['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'priority'], 'integer'], [['value'], 'required'], [['value', 'name'], 'string', 'max' => 255], [['cms_site_id', 'value'], 'unique', 'targetAttribute' => ['cms_site_id', 'value']], [['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::class, 'targetAttribute' => ['cms_site_id' => 'id']], [['value'], 'string', 'max' => 64], [['value'], "email", 'enableIDN' => true], ]); } /** * Gets query for [[CmsSite]]. * * @return \yii\db\ActiveQuery */ public function getCmsSite() { return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_id']); } }
php
BSD-3-Clause
c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf
2026-01-05T04:50:22.405425Z
false