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/models/CmsUserUniversalPropertyEnum.php | src/models/CmsUserUniversalPropertyEnum.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\RelatedPropertyEnumModel;
/**
* This is the model class for table "{{%cms_content_property_enum}}".
*
* @property CmsUserUniversalProperty $property
*/
class CmsUserUniversalPropertyEnum extends RelatedPropertyEnumModel
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_user_universal_property_enum}}';
}
/**
* @return array
*/
public function behaviors()
{
return array_merge(parent::behaviors(), []);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProperty()
{
return $this->hasOne(CmsUserUniversalProperty::className(), ['id' => 'property_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/CmsCompareElement.php | src/models/CmsCompareElement.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\shop\models\ShopCmsContentElement;
use skeeks\cms\shop\models\ShopUser;
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 $shop_user_id
* @property int $cms_content_element_id
*
* @property ShopUser $shopUser
* @property CmsContentElement $cmsContentElement
* @property ShopCmsContentElement $shopCmsContentElement
*/
class CmsCompareElement extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_compare_element}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['created_at', 'shop_user_id', 'cms_content_element_id'], 'integer'],
[['shop_user_id', 'cms_content_element_id'], 'required'],
[['shop_user_id', 'cms_content_element_id'], 'unique', 'targetAttribute' => ['shop_user_id', 'cms_content_element_id']],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'shop_user_id' => 'Пользователь',
'cms_content_element_id' => 'Товар',
]);
}
/**
* Gets query for [[ShopCart]].
*
* @return \yii\db\ActiveQuery
*/
public function getShopUser()
{
return $this->hasOne(ShopUser::className(), ['id' => 'shop_user_id']);
}
/**
* Gets query for [[ShopProduct]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsContentElement()
{
return $this->hasOne(CmsContentElement::className(), ['id' => 'cms_content_element_id']);
}
/**
* Gets query for [[ShopProduct]].
*
* @return \yii\db\ActiveQuery
*/
public function getShopCmsContentElement()
{
return $this->hasOne(ShopCmsContentElement::className(), ['id' => 'cms_content_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/CmsDealType.php | src/models/CmsDealType.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use yii\helpers\ArrayHelper;
/**
* @property int $id
* @property int $created_by
* @property int $updated_by
* @property int $created_at
* @property int $updated_at
* @property string $name
* @property string $description
* @property string $period
* @property int $is_periodic Конечная или периодичная услуга?
*
* @property string $periodAsText
* @property CmsDeal[] $deals
*/
class CmsDealType extends ActiveRecord
{
const PERIOD_MONTH = 'month';
const PERIOD_YEAR = 'year';
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_deal_type}}';
}
/**
* @return string
*/
public function getPeriodAsText()
{
return (string)ArrayHelper::getValue(self::optionsForPeriod(), $this->period);
}
static public function optionsForPeriod()
{
return [
self::PERIOD_MONTH => 'Мес',
self::PERIOD_YEAR => 'Год',
];
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['created_by', 'created_at', 'is_periodic'], 'integer'],
[['name'], 'required'],
[['description'], 'string'],
[['period'], 'string'],
[['name'], 'string', 'max' => 255],
[
'period',
function ($attribute) {
if ($this->is_periodic && !$this->period) {
$this->addError($attribute, 'Нужно заполнять для периодических сделок');
}
if (!$this->is_periodic && $this->period) {
$this->addError($attribute, 'Для разовых сделок заполнять не нужно');
}
},
],
[
'period',
'default',
'value' => function () {
if ($this->is_periodic) {
return self::PERIOD_MONTH;
} else {
return null;
}
},
],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'is_periodic' => 'Периодическая сделка?',
'period' => 'Период',
'name' => 'Название',
'description' => 'Комментарий',
]);
}
/**
* {@inheritdoc}
*/
public function attributeHints()
{
return ArrayHelper::merge(parent::attributeHints(), [
'is_periodic' => 'Сделки бывают разовые или постоянные',
'period' => 'Период действия сделки',
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCrmDeals()
{
return $this->hasMany(CrmDeal::class, ['cms_deal_type_id' => 'id']);
}
/**
* @return string
*/
public function asText()
{
return $this->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/CmsCompany2category.php | src/models/CmsCompany2category.php | <?php
namespace skeeks\cms\models;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "crm_client_map".
*
* @property int $id
* @property int $cms_company_id Компания
* @property int $cms_company_category_id Пользователь
*
* @property CmsCompany $cmsCompany
* @property CmsCompanyCategory $cmsCompanyCategory
*/
class CmsCompany2category extends \skeeks\cms\base\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_company2category}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['cms_company_id', 'cms_company_category_id'], 'integer'],
[['cms_company_id', 'cms_company_category_id'], 'required'],
[['cms_company_id', 'cms_company_category_id'], 'unique', 'targetAttribute' => ['cms_company_id', 'cms_company_category_id']],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'cms_company_category_id' => "Категория",
'cms_company_id' => "Компания",
]);
}
/**
* {@inheritdoc}
*/
public function attributeHints()
{
return ArrayHelper::merge(parent::attributeHints(), [
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsCompanyCategory()
{
return $this->hasOne(CmsCompanyCategory::class, ['id' => 'cms_company_category_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/CmsContentElementTree.php | src/models/CmsContentElementTree.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;
/**
* This is the model class for table "{{%cms_content_element_tree}}".
*
* @property integer $id
* @property integer $created_by
* @property integer $updated_by
* @property integer $created_at
* @property integer $updated_at
* @property integer $element_id
* @property integer $tree_id
*
* @property CmsContentElement $element
* @property CmsTree $tree
*/
class CmsContentElementTree extends Core
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_content_element_tree}}';
}
/**
* @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'),
'element_id' => Yii::t('skeeks/cms', 'Element ID'),
'tree_id' => Yii::t('skeeks/cms', 'Tree ID'),
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[['created_by', 'updated_by', 'created_at', 'updated_at', 'element_id', 'tree_id'], 'integer'],
[['element_id', 'tree_id'], 'required'],
[
['element_id', 'tree_id'],
'unique',
'targetAttribute' => ['element_id', 'tree_id'],
'message' => \Yii::t('skeeks/cms', 'The combination of Element ID and Tree ID has already been taken.')
]
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getElement()
{
return $this->hasOne(CmsContentElement::className(), ['id' => 'element_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTree()
{
return $this->hasOne(Tree::className(), ['id' => '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/CmsCallcheckMessage.php | src/models/CmsCallcheckMessage.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\models\behaviors\Serialize;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "cms_callcheck_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_callcheck_provider_id
* @property string $phone
* @property string $status
* @property string|null $code
* @property string|null $error_message
* @property string|null $provider_status
* @property string|null $provider_call_id
* @property string|null $provider_response_data
*
* @property CmsCallcheckProvider $cmsCallcheckProvider
* @property CmsSite $cmsSite
*/
class CmsCallcheckMessage extends \skeeks\cms\base\ActiveRecord
{
const STATUS_ERROR = "error";
const STATUS_OK = "ok";
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'cms_callcheck_message';
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
Serialize::class => [
'class' => Serialize::class,
'fields' => ['provider_response_data'],
],
]);
}
public function statuses()
{
return [
self::STATUS_OK => "Успешно",
self::STATUS_ERROR => "Ошибка",
];
}
/**
* @return bool
*/
public function getIsOk()
{
return $this->status == self::STATUS_OK;
}
/**
* @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_callcheck_provider_id'], 'integer'],
[['phone'], 'required'],
[['provider_response_data'], 'safe'],
[['user_ip'], 'string', 'max' => 255],
[['phone', 'status', 'code', 'error_message', 'provider_status', 'provider_call_id'], 'string', 'max' => 255],
[['cms_callcheck_provider_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsCallcheckProvider::className(), 'targetAttribute' => ['cms_callcheck_provider_id' => 'id']],
[['cms_site_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsSite::className(), 'targetAttribute' => ['cms_site_id' => 'id']],
[
['error_message', 'provider_status', 'provider_call_id'],
'default',
'value' => null,
],
[
'status',
'default',
'value' => self::STATUS_OK,
],
[
'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 [[CmsCallcheckProvider]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsCallcheckProvider()
{
return $this->hasOne(CmsCallcheckProvider::className(), ['id' => 'cms_callcheck_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/CmsSmsProvider.php | src/models/CmsSmsProvider.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\models\behaviors\Serialize;
use skeeks\cms\sms\SmsHandler;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "cms_sms_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 CmsSite $cmsSite
* @property SmsHandler $handler
*/
class CmsSmsProvider extends \skeeks\cms\base\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'cms_sms_provider';
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
Serialize::class => [
'class' => Serialize::class,
'fields' => ['component_config'],
],
]);
}
protected $_handler = null;
/**
* @return SmsHandler
*/
public function getHandler()
{
if ($this->_handler !== null) {
return $this->_handler;
}
if ($this->component) {
try {
$componentConfig = ArrayHelper::getValue(\Yii::$app->cms->smsHandlers, $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);
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']],
[['is_main'], 'default', 'value' => 0],
[['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 send($phone, $text)
{
$provider_message_id = '';
$cmsSmsMessage = new CmsSmsMessage();
$cmsSmsMessage->phone = $phone;
$cmsSmsMessage->message = $text;
$cmsSmsMessage->cms_sms_provider_id = $this->id;
try {
$this->handler->sendMessage($cmsSmsMessage);
if (!$cmsSmsMessage->save()) {
throw new Exception(print_r($cmsSmsMessage->errors, true));
}
} catch (\Exception $exception) {
$cmsSmsMessage->status = CmsSmsMessage::STATUS_ERROR;
$cmsSmsMessage->error_message = $exception->getMessage();
if (!$cmsSmsMessage->save()) {
throw new Exception(print_r($cmsSmsMessage->errors, true));
}
//throw $exception;
}
return $cmsSmsMessage;
}
}
| 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/CmsContent.php | src/models/CmsContent.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\models\behaviors\HasJsonFieldsBehavior;
use skeeks\cms\models\queries\CmsContentQuery;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%cms_content}}".
*
* @property integer $id
* @property integer|null $created_by
* @property integer|null $updated_by
* @property integer|null $created_at
* @property integer|null $updated_at
*
* @property string $name
* @property string $code
* @property integer $priority
* @property string $description
* @property string $content_type
*
* @property bool $is_tree_only_max_level Разрешено привязывать только к разделам, без подразделов
* @property bool $is_tree_only_no_redirect Разрешено привязывать только к разделам, не редирректам
* @property bool $is_tree_required Раздел необходимо выбирать обязательно
* @property bool $is_tree_allow_change Разраешено менять раздел при редактировании
*
* @property string $index_for_search
* @property string $tree_chooser
* @property string $list_mode
* @property string $name_meny
* @property string $name_one
* @property integer $default_tree_id
* @property integer $is_allow_change_tree
* @property integer $is_active
* @property integer $is_count_views
* @property integer $root_tree_id
* @property string $view_file
* @property integer $is_access_check_element
* @property array $editable_fields
* @property integer $cms_tree_type_id
* @property integer $saved_filter_tree_type_id
* @property string|null $base_role
*
* @property string $meta_title_template
* @property string $meta_description_template
* @property string $meta_keywords_template
*
* @property integer $parent_content_id
* @property integer $is_visible
* @property string $parent_content_on_delete
* @property integer $is_parent_content_required
* @property integer $is_have_page
* @property integer $is_show_on_all_sites
*
* ***
*
* @property string $adminPermissionName
*
* @property CmsTree $rootTree
* @property CmsTree $defaultTree
* @property CmsContentType $contentType
* @property CmsContentElement[] $cmsContentElements
* @property CmsContentProperty[] $cmsContentProperties
*
* @property CmsContent $parentContent
* @property CmsContent[] $childrenContents
* @property CmsTreeType $savedFilterTreeType
* @property CmsTreeType $cmsTreeType
*/
class CmsContent extends Core
{
const CASCADE = 'CASCADE';
const RESTRICT = 'RESTRICT';
const SET_NULL = 'SET_NULL';
const ROLE_PRODUCTS = "products";
/**
* @param string|null $code
* @return string|string[]
*/
static public function baseRoles(string $code = null)
{
$roles = [
self::ROLE_PRODUCTS => "Товары",
];
if ($code === null) {
return $roles;
}
return (string)ArrayHelper::getValue($roles, $code);
}
/**
* @return array
*/
public static function getOnDeleteOptions()
{
return [
self::CASCADE => "CASCADE (".\Yii::t('skeeks/cms', 'Remove all items of that content').")",
self::RESTRICT => "RESTRICT (".\Yii::t('skeeks/cms',
'Deny delete parent is not removed, these elements').")",
self::SET_NULL => "SET NULL (".\Yii::t('skeeks/cms', 'Remove the connection to a remote parent').")",
];
}
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_content}}';
}
public function behaviors()
{
return array_merge(parent::behaviors(), [
HasJsonFieldsBehavior::class => [
'class' => HasJsonFieldsBehavior::class,
'fields' => ['editable_fields'],
],
]);
}
/**
* @inheritdoc
*/
public function attributeHints()
{
return array_merge(parent::attributeHints(), [
'is_show_on_all_sites' => Yii::t('skeeks/cms', 'Если эта опция включена, то страница элемента этого контента, может отображаться на любом из сайтов.'),
'is_have_page' => Yii::t('skeeks/cms', 'Если эта опция включена, то показываются настройки SEO и URL'),
'code' => Yii::t('skeeks/cms', 'The name of the template to draw the elements of this type will be the same as the name of the code.'),
'view_file' => Yii::t('skeeks/cms', 'The path to the template. If not specified, the pattern will be the same code.'),
'root_tree_id' => Yii::t('skeeks/cms', 'If it is set to the root partition, the elements can be tied to him and his sub.'),
'editable_fields' => Yii::t('skeeks/cms', 'Поля которые отображаются при редактировании. Если ничего не выбрано, то показываются все!'),
'cms_tree_type_id' => Yii::t('skeeks/cms', 'Этот параметр ограничевает возможность привязки элементов этого контента к разделам только этого типа'),
'saved_filter_tree_type_id' => Yii::t('skeeks/cms', 'Элементы этого контента не имеют самостоятельной страницы а создают посадочную на корневой раздел этого типа'),
'base_role' => Yii::t('skeeks/cms', 'Базовый сценарий определяет поведение этого контента'),
'is_tree_only_max_level' => Yii::t('skeeks/cms', 'То есть разрешено привязывать элементы к разделам у которых нет подразделов'),
'is_tree_only_no_redirect' => Yii::t('skeeks/cms', 'Если раздел является редирректом на другой раздел или ссылку, то к такому разделу нельзя привязывать элементы'),
'is_tree_required' => Yii::t('skeeks/cms', 'Нельзя просто создать элемент, не выбрав его категорию-раздел'),
'is_tree_allow_change' => Yii::t('skeeks/cms', 'Эта настройка касается только редактирования. По хорошему, раздел должен выбираться у элемента только в момент создания! Потому что от этого зависят и характеристики элемента.'),
]);
}
/**
* @return array
*/
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'cms_tree_type_id' => Yii::t('skeeks/cms', 'Привязывать только к разделам этого типа'),
'saved_filter_tree_type_id' => Yii::t('skeeks/cms', 'Тип раздела для посадочной страницы'),
'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'),
'code' => Yii::t('skeeks/cms', 'Code'),
'is_active' => Yii::t('skeeks/cms', 'Active'),
'priority' => Yii::t('skeeks/cms', 'Priority'),
'description' => Yii::t('skeeks/cms', 'Description'),
'content_type' => Yii::t('skeeks/cms', 'Меню'),
'index_for_search' => Yii::t('skeeks/cms', 'To index for search module'),
'tree_chooser' => Yii::t('skeeks/cms', 'The Interface Binding Element to Sections'),
'list_mode' => Yii::t('skeeks/cms', 'View Mode Sections And Elements'),
'name_meny' => Yii::t('skeeks/cms', 'The Name Of The Elements (Plural)'),
'name_one' => Yii::t('skeeks/cms', 'The Name One Element'),
'is_tree_only_max_level' => Yii::t('skeeks/cms', 'Привязывать элементы только к разделам максимального уровня?'),
'is_tree_only_no_redirect' => Yii::t('skeeks/cms', 'Разрешено привязывать только к разделам - не редирректам'),
'is_tree_required' => Yii::t('skeeks/cms', 'Раздел выбирать обязательно'),
'is_tree_allow_change' => Yii::t('skeeks/cms', 'Разраешено менять раздел при редактировании'),
'base_role' => Yii::t('skeeks/cms', 'Базовый сценарий'),
'default_tree_id' => Yii::t('skeeks/cms', 'Default Section'),
'is_allow_change_tree' => Yii::t('skeeks/cms', 'Is Allow Change Default Section'),
'is_count_views' => Yii::t('skeeks/cms', 'Считать количество просмотров?'),
'root_tree_id' => Yii::t('skeeks/cms', 'Root Section'),
'view_file' => Yii::t('skeeks/cms', 'Template'),
'meta_title_template' => Yii::t('skeeks/cms', 'Шаблон META TITLE'),
'meta_description_template' => Yii::t('skeeks/cms', 'Шаблон META KEYWORDS'),
'meta_keywords_template' => Yii::t('skeeks/cms', 'Шаблон META DESCRIPTION'),
'is_access_check_element' => Yii::t('skeeks/cms', 'Включить управление доступом к элементам'),
'parent_content_id' => Yii::t('skeeks/cms', 'Parent content'),
'is_visible' => Yii::t('skeeks/cms', 'Show in menu'),
'parent_content_on_delete' => Yii::t('skeeks/cms', 'At the time of removal of the parent element'),
'is_parent_content_required' => Yii::t('skeeks/cms', 'Parent element is required to be filled'),
'is_have_page' => Yii::t('skeeks/cms', 'У элементов есть страница на сайте.'),
'editable_fields' => Yii::t('skeeks/cms', 'Редактируемые поля'),
'is_show_on_all_sites' => Yii::t('skeeks/cms', 'Показывать элементы на всех сайтах?'),
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[
['created_by', 'updated_by', 'created_at', 'updated_at', 'priority', 'default_tree_id', 'root_tree_id', 'is_count_views', 'is_allow_change_tree', 'is_active'],
'integer',
],
[['is_visible'], 'integer'],
[['cms_tree_type_id'], 'integer'],
[['saved_filter_tree_type_id'], 'integer'],
[['is_parent_content_required'], 'integer'],
[['is_have_page'], 'integer'],
[['is_show_on_all_sites'], 'integer'],
[['name'], 'required'],
[['description'], 'string'],
[['meta_title_template'], 'string'],
[['meta_description_template'], 'string'],
[['meta_keywords_template'], 'string'],
[['name', 'view_file'], 'string', 'max' => 255],
[['code'], 'string', 'max' => 50],
[['code'], 'unique'],
[['base_role'], 'unique'],
[['base_role'], 'string'],
[['base_role'], 'default', 'value' => null],
[['is_access_check_element'], 'integer'],
[['code'], 'validateCode'],
[['index_for_search', 'tree_chooser', 'list_mode'], 'string', 'max' => 1],
[['content_type'], 'string', 'max' => 32],
[['name_meny', 'name_one'], 'string', 'max' => 100],
['priority', 'default', 'value' => 500],
['is_active', 'default', 'value' => 1],
['is_allow_change_tree', 'default', 'value' => 1],
['is_access_check_element', 'default', 'value' => 0],
['name_meny', 'default', 'value' => function () {
return $this->name;
}],
['name_one', 'default', 'value' => function () {
return $this->name;
}],
[
[
'is_tree_only_max_level',
'is_tree_only_no_redirect',
'is_tree_required',
'is_tree_allow_change'
]
, 'integer'],
['is_visible', 'default', 'value' => 1],
['is_have_page', 'default', 'value' => 1],
['is_parent_content_required', 'default', 'value' => 0],
[[
'is_tree_only_no_redirect',
'is_tree_only_max_level',
'is_tree_allow_change',
], 'default', 'value' => 1],
[[
'is_tree_required',
], 'default', 'value' => 0],
['parent_content_on_delete', 'default', 'value' => self::CASCADE],
['parent_content_id', 'integer'],
[
'code',
'default',
'value' => function ($model, $attribute) {
return "sxauto".md5(rand(1, 10).time());
},
],
[['editable_fields'], 'safe'],
[['content_type'], 'default', 'value' => null],
//[['editable_fields'], 'default', 'value' => null],
]);
}
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']));
}
}
static protected $_selectData = [];
/**
* Данные для мультиселекта с группами типов
*
* @param bool|false $refetch
* @return array
*/
public static function getDataForSelect($refetch = false, $contentQueryCallback = null)
{
if ($refetch === false && static::$_selectData) {
return static::$_selectData;
}
static::$_selectData = [];
if ($cmsContentTypes = CmsContentType::find()->orderBy("priority ASC")->all()) {
/**
* @var $cmsContentType CmsContentType
*/
foreach ($cmsContentTypes as $cmsContentType) {
$query = $cmsContentType->getCmsContents();
if ($contentQueryCallback && is_callable($contentQueryCallback)) {
$contentQueryCallback($query);
}
static::$_selectData[$cmsContentType->name] = ArrayHelper::map($query->all(), 'id', 'name');
}
}
$query = CmsContent::find()->andWhere(['code' => null]);
if ($contentQueryCallback && is_callable($contentQueryCallback)) {
$contentQueryCallback($query);
}
static::$_selectData["Прочее"] = ArrayHelper::map($query->all(), 'id', 'name');
$otherContents = CmsContent::find()->andWhere(['content_type' => null])->all();
if ($otherContents) {
static::$_selectData = ArrayHelper::merge(static::$_selectData, ArrayHelper::map($otherContents, 'id', 'name'));
}
return static::$_selectData;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRootTree()
{
return $this->hasOne(CmsTree::class, ['id' => 'root_tree_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getDefaultTree()
{
return $this->hasOne(CmsTree::class, ['id' => 'default_tree_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getContentType()
{
return $this->hasOne(CmsContentType::class, ['code' => 'content_type']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSavedFilterTreeType()
{
return $this->hasOne(CmsTreeType::class, ['id' => 'saved_filter_tree_type_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTreeType()
{
return $this->hasOne(CmsTreeType::class, ['id' => 'cms_tree_type_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentElements()
{
return $this->hasMany(CmsContentElement::class, ['content_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
/*public function getCmsContentProperties()
{
return $this->hasMany(CmsContentProperty::class, ['content_id' => 'id'])->orderBy(['priority' => SORT_ASC]);
}*/
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentProperty2contents()
{
return $this->hasMany(CmsContentProperty2content::class, ['cms_content_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentProperties()
{
$q = CmsContentProperty::find();
$q->innerJoinWith("cmsContentProperty2contents as cmsContentProperty2contents");
$q->andWhere(["cmsContentProperty2contents.cms_content_id" => $this->id]);
$q->orderBy("priority");
$q->multiple = true;
return $q;
/*return $this
->hasMany(CmsContentProperty::class, ['id' => 'cms_content_property_id'])
->via('cmsContentProperty2contents')
->orderBy('priority');*/
}
/**
* @return string
*/
public function getAdminPermissionName()
{
return 'cms/admin-cms-content-element__'.$this->id;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getParentContent()
{
return $this->hasOne(CmsContent::class, ['id' => 'parent_content_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getChildrenContents()
{
return $this->hasMany(CmsContent::class, ['parent_content_id' => 'id']);
}
/**
* @return CmsContentElement
*/
public function createElement()
{
return new CmsContentElement([
'content_id' => $this->id,
'cms_site_id' => \Yii::$app->skeeks->site->id,
]);
}
/**
* Разрешено редактировать поле?
*
* @param $code
* @return bool
*/
public function isAllowEdit($code)
{
if (!$this->editable_fields) {
return true;
}
return (bool)in_array((string)$code, (array)$this->editable_fields);
}
/**
* @return CmsContentQuery
*/
public static function find()
{
return (new CmsContentQuery(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/CmsDepartment2worker.php | src/models/CmsDepartment2worker.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_department_id Отдел
* @property int $worker_id Сотрудник
*
* @property CmsUser $worker
* @property CmsDepartment $department
*/
class CmsDepartment2worker extends \skeeks\cms\base\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_department2worker}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['cms_department_id', 'worker_id'], 'integer'],
[['cms_department_id', 'worker_id'], 'required'],
[['cms_department_id', 'worker_id'], 'unique', 'targetAttribute' => ['cms_department_id', 'worker_id']],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'cms_department_id' => Yii::t('app', 'Отдел'),
'worker_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 getDepartment()
{
return $this->hasOne(CmsDepartment::class, ['id' => 'cms_department_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/CmsContentElementFile.php | src/models/CmsContentElementFile.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 $content_element_id
* @property integer $priority
*
* @property CmsContentElement $contentElement
* @property CmsStorageFile $storageFile
*/
class CmsContentElementFile extends \skeeks\cms\models\Core
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_content_element_file}}';
}
/**
* @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/CmsCompanyLink.php | src/models/CmsCompanyLink.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\behaviors\CmsLogBehavior;
use skeeks\cms\helpers\StringHelper;
use skeeks\cms\models\behaviors\traits\HasLogTrait;
use skeeks\cms\validators\PhoneValidator;
use yii\helpers\ArrayHelper;
/**
* @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_company_id
* @property string $url
* @property string|null $name
* @property string $link_type
* @property int $sort
*
* @property CmsCompany $cmsCompany
*/
class CmsCompanyLink extends ActiveRecord
{
use HasLogTrait;
const TYPE_INSTAGRAM = 'instagram';
const TYPE_FACEBOOK = 'facebook';
const TYPE_VK = 'vk';
const TYPE_OK = 'odnoklassniki';
const TYPE_YOUTUBE = 'youtube';
const TYPE_WHATSAPP = 'whatsapp';
const TYPE_TELEGRAM = 'telegram';
const TYPE_OTHER = 'other';
const TYPE_PINTEREST = 'pinterest';
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
CmsLogBehavior::class => [
'class' => CmsLogBehavior::class,
'parent_relation' => 'cmsCompany',
'relation_map' => [
'link_type' => 'linkTypeAsText',
],
],
]);
}
public function getLinkTypeAsText()
{
return (string) ArrayHelper::getValue(self::getLinkTypes(), $this->link_type);
}
/**
* @return array
*/
static public function getLinkTypes()
{
return [
self::TYPE_FACEBOOK => 'Facebook',
self::TYPE_INSTAGRAM => 'Instagram',
self::TYPE_YOUTUBE => 'Youtube',
self::TYPE_VK => 'Вконтакте',
self::TYPE_OK => 'Одноклассники',
self::TYPE_TELEGRAM => 'Telegram',
self::TYPE_WHATSAPP => 'WatsApp',
self::TYPE_PINTEREST => 'Pinterest',
self::TYPE_OTHER => 'Другое',
];
}
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_company_link}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_company_id', 'sort'], 'integer'],
[['cms_company_id', 'url'], 'required'],
[['name'], 'string', 'max' => 255],
[
['cms_company_id', 'url'],
'unique',
'targetAttribute' => ['cms_company_id', 'url'],
//'message' => 'Этот email уже занят'
],
[['name'], 'default', 'value' => null],
[['url'], 'required'],
[['url', 'name'], 'string', 'max' => 255],
[['url'], 'string', 'max' => 255],
[['url'], 'url'],
[['link_type'], 'string'],
[['link_type'], 'default', 'value' => self::TYPE_OTHER],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'url' => 'Ссылка на соцсеть или сайт',
'link_type' => 'Социальная сеть или сайт',
'name' => 'Название',
'priority' => 'Сортировка',
'cms_company_id' => "Компания",
'sort' => "Сортировка",
]);
}
/**
* @inheritdoc
*/
public function attributeHints()
{
return array_merge(parent::attributeHints(), [
'name' => 'Необязтельное поле',
'sort' => 'Чем ниже цифра тем выше ссылка',
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsCompany()
{
return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_id']);
}
/**
* @return string
*/
public function asText()
{
return $this->url;
}
} | 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/CmsTreeFile.php | src/models/CmsTreeFile.php | <?php
namespace skeeks\cms\models;
use Yii;
/**
* This is the model class for table "{{%cms_tree_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 $tree_id
* @property integer $priority
*
* @property CmsTree $tree
* @property CmsStorageFile $storageFile
*/
class CmsTreeFile extends \skeeks\cms\models\Core
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_tree_file}}';
}
/**
* @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/CmsCompanyStatus.php | src/models/CmsCompanyStatus.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 CmsCompanyStatus extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_company_status}}';
}
/**
* @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/CmsContentProperty2content.php | src/models/CmsContentProperty2content.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_property2content".
*
* @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_content_id
*
* @property CmsContentProperty $cmsContentProperty
* @property CmsContent $cmsContent
*/
class CmsContentProperty2content extends Core
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_content_property2content}}';
}
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_content_id'],
'integer'
],
[['cms_content_property_id', 'cms_content_id'], 'required'],
[
['cms_content_property_id', 'cms_content_id'],
'unique',
'targetAttribute' => ['cms_content_property_id', 'cms_content_id'],
'message' => 'The combination of Cms Content Property ID and Cms Content ID has already been taken.'
],
[
['cms_content_property_id'],
'exist',
'skipOnError' => true,
'targetClass' => CmsContentProperty::className(),
'targetAttribute' => ['cms_content_property_id' => 'id']
],
[
['cms_content_id'],
'exist',
'skipOnError' => true,
'targetClass' => CmsContent::className(),
'targetAttribute' => ['cms_content_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 getCmsContent()
{
return $this->hasOne(CmsContent::className(), ['id' => 'cms_content_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/CmsProject2manager.php | src/models/CmsProject2manager.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_project_id Компания
* @property int $cms_user_id Пользователь
*
* @property CmsUser $cmsUser
* @property Cmsproject $cmsProject
*/
class CmsProject2manager extends \skeeks\cms\base\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_project2manager}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['cms_project_id', 'cms_user_id'], 'integer'],
[['cms_project_id', 'cms_user_id'], 'required'],
[['cms_project_id', 'cms_user_id'], 'unique', 'targetAttribute' => ['cms_project_id', 'cms_user_id']],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'cms_user_id' => Yii::t('app', 'Контрагент'),
'cms_project_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 getCmsProject()
{
return $this->hasOne(Cmsproject::class, ['id' => 'cms_project_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/CmsCompanyEmail.php | src/models/CmsCompanyEmail.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\behaviors\CmsLogBehavior;
use skeeks\cms\helpers\StringHelper;
use skeeks\cms\models\behaviors\traits\HasLogTrait;
use yii\helpers\ArrayHelper;
/**
* @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_company_id
* @property string $value Email
* @property string|null $name Примечание к Email
* @property int $sort
*
* @property CmsCompany $cmsCompany
*/
class CmsCompanyEmail extends ActiveRecord
{
use HasLogTrait;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_company_email}}';
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
CmsLogBehavior::class => [
'class' => CmsLogBehavior::class,
'parent_relation' => 'cmsCompany',
],
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_company_id', 'sort'], 'integer'],
[['cms_company_id', 'value'], 'required'],
[['value', 'name'], 'string', 'max' => 255],
[
['cms_company_id', 'value'],
'unique',
'targetAttribute' => ['cms_company_id', 'value'],
//'message' => 'Этот email уже занят'
],
[['name'], '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_company_id' => "Компания",
'name' => "Описание",
'value' => "Email",
'sort' => "Сортировка",
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsCompany()
{
return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_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/CmsProject2user.php | src/models/CmsProject2user.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_project_id Компания
* @property int $cms_user_id Пользователь
*
* @property CmsUser $cmsUser
* @property Cmsproject $cmsProject
*/
class CmsProject2user extends \skeeks\cms\base\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_project2user}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['cms_project_id', 'cms_user_id'], 'integer'],
[['cms_project_id', 'cms_user_id'], 'required'],
[['cms_project_id', 'cms_user_id'], 'unique', 'targetAttribute' => ['cms_project_id', 'cms_user_id']],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'cms_user_id' => Yii::t('app', 'Контрагент'),
'cms_project_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 getCmsProject()
{
return $this->hasOne(Cmsproject::class, ['id' => 'cms_project_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/CmsUserUniversalProperty.php | src/models/CmsUserUniversalProperty.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\helpers\ArrayHelper;
/**
* @property CmsSite $cmsSite
*
* @property CmsUserUniversalPropertyEnum[] $enums
* @property CmsUserProperty[] $elementProperties
*/
class CmsUserUniversalProperty extends RelatedPropertyModel
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_user_universal_property}}';
}
/**
* @inheritdoc
*/
public function rules()
{
$rules = ArrayHelper::merge(parent::rules(), [
[['cms_site_id'], 'integer'],
[['cms_site_id'], 'default', 'value' => function() {
if (\Yii::$app->skeeks->site) {
return \Yii::$app->skeeks->site->id;
}
}],
[['code', 'cms_site_id'], 'unique', 'targetAttribute' => ['code', 'cms_site_id']],
]);
return $rules;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getElementProperties()
{
return $this->hasMany(CmsUserProperty::className(), ['property_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getEnums()
{
return $this->hasMany(CmsUserUniversalPropertyEnum::className(), ['property_id' => 'id']);
}
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsSite()
{
$class = \Yii::$app->skeeks->siteClass;
return $this->hasOne($class, ['id' => 'cms_site_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/CmsComponentSettings.php | src/models/CmsComponentSettings.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 21.05.2015
*/
namespace skeeks\cms\models;
use skeeks\cms\base\Component;
use skeeks\cms\models\behaviors\HasJsonFieldsBehavior;
use Yii;
use yii\db\ActiveQuery;
/**
* This is the model class for table "{{%cms_component_settings}}".
*
* @property integer $id
* @property integer $created_by
* @property integer $updated_by
* @property integer $created_at
* @property integer $updated_at
* @property string $component
* @property string $value
* @property integer $cms_site_id
* @property integer $user_id
* @property string $namespace
*
* @property CmsLang $lang
* @property CmsSite $site
* @property User $user
*/
class CmsComponentSettings extends Core
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_component_settings}}';
}
/**
* @return array
*/
public function behaviors()
{
return array_merge(parent::behaviors(), [
HasJsonFieldsBehavior::className() =>
[
'class' => HasJsonFieldsBehavior::className(),
'fields' => ['value']
]
]);
}
/**
* @return array
*/
public function rules()
{
return array_merge(parent::rules(), [
[['created_by', 'updated_by', 'created_at', 'updated_at', 'user_id'], 'integer'],
[['value'], 'safe'],
[['component'], 'string', 'max' => 255],
[['cms_site_id'], 'integer'],
[['namespace'], 'string', 'max' => 50]
]);
}
/**
* @return array
*/
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'id' => Yii::t('skeeks/cms', 'ID'),
'value' => Yii::t('skeeks/cms', 'Value'),
'component' => Yii::t('skeeks/cms', 'Component'),
'cms_site_id' => Yii::t('skeeks/cms', 'Site Code'),
'user_id' => Yii::t('skeeks/cms', 'User ID'),
'namespace' => Yii::t('skeeks/cms', 'Namespace'),
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSite()
{
return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(CmsUser::className(), ['id' => 'user_id']);
}
/**
* @param $component
* @return ActiveQuery
*/
public static function findByComponent(Component $component)
{
$query = static::find()->where([
'component' => $component->className(),
]);
if ($component->namespace) {
$query->andWhere(['namespace' => $component->namespace]);
}
return $query;
}
/**
* Overrides
*/
/**
* @param Component $component
* @return ActiveQuery
*/
public static function findByComponentDefault(Component $component)
{
return static::findByComponent($component)
->andWhere(['cms_site_id' => null])
->andWhere(['user_id' => null]);
}
/**
* @param Component $component
* @param CmsUser $user
* @return ActiveQuery
*/
public static function findByComponentUser(Component $component, $user)
{
return static::findByComponent($component)->andWhere(['user_id' => (int)$user->id]);
}
/**
* @param Component $component
* @param CmsUser $user
* @return ActiveQuery
*/
public static function findByComponentSite(Component $component, CmsSite $cmsSite)
{
return static::findByComponent($component)->andWhere(['cms_site_id' => (int)$cmsSite->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/CmsCompanyPhone.php | src/models/CmsCompanyPhone.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\behaviors\CmsLogBehavior;
use skeeks\cms\helpers\StringHelper;
use skeeks\cms\models\behaviors\traits\HasLogTrait;
use skeeks\cms\validators\PhoneValidator;
use yii\helpers\ArrayHelper;
/**
* @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_company_id
* @property string $value Телефон
* @property string|null $name Примечание к телефону
* @property int $sort
*
* @property CmsCompany $cmsCompany
*/
class CmsCompanyPhone extends ActiveRecord
{
use HasLogTrait;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_company_phone}}';
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
CmsLogBehavior::class => [
'class' => CmsLogBehavior::class,
'parent_relation' => 'cmsCompany',
],
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_company_id', 'sort'], 'integer'],
[['cms_company_id', 'value'], 'required'],
[['value', 'name'], 'string', 'max' => 255],
[
['cms_company_id', 'value'],
'unique',
'targetAttribute' => ['cms_company_id', 'value'],
//'message' => 'Этот email уже занят'
],
[['name'], '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_company_id' => "Компания",
'name' => "Описание",
'value' => "Телефон",
'sort' => "Сортировка",
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsCompany()
{
return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_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/CmsDeal2payment.php | src/models/CmsDeal2payment.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\shop\models\ShopPayment;
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_payment_id Платеж
*
* @property CmsDeal $deal
* @property ShopPayment $payment
*/
class CmsDeal2payment extends \skeeks\cms\base\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_deal2payment}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['cms_deal_id', 'shop_payment_id'], 'integer'],
[['cms_deal_id', 'shop_payment_id'], 'required'],
[['cms_deal_id', 'shop_payment_id'], 'unique', 'targetAttribute' => ['cms_deal_id', 'shop_payment_id']],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'shop_payment_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 getPayment()
{
return $this->hasOne(ShopPayment::class, ['id' => 'shop_payment_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/CmsCompanyAddress.php | src/models/CmsCompanyAddress.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\behaviors\CmsLogBehavior;
use skeeks\cms\models\behaviors\HasStorageFile;
use skeeks\cms\models\behaviors\traits\HasLogTrait;
use yii\helpers\ArrayHelper;
/**
* @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_company_id
* @property string|null $name Название адреса (необязательное)
* @property string $value Полный адрес
* @property float $latitude
* @property float $longitude
* @property string $entrance Подъезд
* @property string $floor Этаж
* @property string $apartment_number Номер квартиры
* @property string $comment
* @property string $postcode
* @property int|null $cms_image_id
* @property int $sort
*
* @property CmsCompany $cmsCompany
*/
class CmsCompanyAddress extends ActiveRecord
{
use HasLogTrait;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_company_address}}';
}
/**
* @return array
*/
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
CmsLogBehavior::class => [
'class' => CmsLogBehavior::class,
'parent_relation' => 'cmsCompany',
],
HasStorageFile::class => [
'class' => HasStorageFile::class,
'fields' => ['cms_image_id'],
],
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[
[
'created_by',
'updated_by',
'created_at',
'updated_at',
'cms_company_id',
'sort',
],
'integer',
],
[['cms_company_id', 'value'], 'required'],
//[['name'], 'default', 'value' => null],
[['latitude', 'longitude'], 'number'],
[
[
'floor',
'apartment_number',
'entrance',
'postcode',
'name',
],
'string',
],
[['comment', 'name', 'value'], 'string', 'max' => 255],
/*[
[
'value',
'floor',
'apartment_number',
'entrance',
'postcode',
'name',
],
"filter",
'filter' => 'trim',
],*/
[['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,
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'cms_company_id' => \Yii::t('skeeks/cms', 'User'),
'name' => "Название",
'value' => "Адрес",
'latitude' => "Широта",
'longitude' => "Долгота",
'entrance' => "Подъезд",
'floor' => "Этаж",
'apartment_number' => "Номер квартиры",
'comment' => "Комментарий",
'cms_image_id' => "Фото",
'priority' => "Сортировка",
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsCompany()
{
return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_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/CmsSavedFilter.php | src/models/CmsSavedFilter.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 19.05.2015
*/
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\components\urlRules\UrlRuleContentElement;
use skeeks\cms\eavqueryfilter\CmsEavQueryFilterHandler;
use skeeks\cms\helpers\StringHelper;
use skeeks\cms\models\behaviors\HasMultiLangAndSiteFields;
use skeeks\cms\models\behaviors\HasStatus;
use skeeks\cms\models\behaviors\HasStorageFile;
use skeeks\cms\models\behaviors\traits\HasUrlTrait;
use skeeks\cms\models\queries\CmsSavedFilterQuery;
use skeeks\cms\shop\models\ShopBrand;
use skeeks\cms\shop\queryFilter\ShopDataFiltersHandler;
use skeeks\yii2\yaslug\YaSlugBehavior;
use Yii;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Application;
/**
*
* @property integer $id
* @property integer $created_by
* @property integer $updated_by
* @property integer $created_at
* @property integer $updated_at
* @property integer $priority
* @property string|null $short_name
* @property string $code
* @property string $description_short
* @property string $description_full
* @property integer|null $cms_image_id
* @property integer $cms_tree_id
* @property string $meta_title
* @property string $meta_description
* @property string $meta_keywords
* @property string $seo_h1
* @property integer|null $cms_site_id
* @property integer|null $value_content_element_id
* @property integer|null $value_content_property_enum_id
* @property integer|null $cms_content_property_id
* @property string|null $country_alpha2
* @property integer|null $shop_brand_id
* @property string $description_short_type
* @property string $description_full_type
*
* ***
*
* @property string $absoluteUrl
* @property string $url
* @property bool $isAllowIndex
*
* @property string $propertyIdForFilter
* @property string $propertyValueForFilter
* @property CmsTree $cmsTree
* @property CmsSite $cmsSite
* @property CmsStorageFile $cmsImage
* @property CmsContentElement $valueContentElement
* @property CmsContentPropertyEnum $valueContentPropertyEnum
* @property CmsContentProperty $cmsContentProperty
* @property ShopBrand $brand
* @property CmsCountry $country
*
* @property string $seoName Полное seo название фильтра. Seo название раздела + склоненное название опции. Например (Строительные краски зеленого цвета).
* @property string $shortSeoName Короткое название фильтра. Название раздела + склоненное название опции. Например (Краски зеленого цвета).
* @property string $propertyValueName Название выбранной опции фильтра. Например цвет (Зеленый)
* @property string $propertyValueNameInflected Склоненное название выбранной опции фильтра. Например цвет (Зеленого цвета)
*
* @property string $name
* @property CmsStorageFile|null $image
*
*/
class CmsSavedFilter extends ActiveRecord
{
use HasUrlTrait;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_saved_filter}}';
}
/**
* @return array
*/
public function behaviors()
{
return array_merge(parent::behaviors(), [
HasStorageFile::className() => [
'class' => HasStorageFile::className(),
'fields' => ['cms_image_id'],
],
YaSlugBehavior::class => [
'class' => YaSlugBehavior::class,
'attribute' => 'seoName',
'slugAttribute' => 'code',
'ensureUnique' => false,
'maxLength' => \Yii::$app->cms->element_max_code_length,
],
]);
}
/**
* @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'),
'short_name' => Yii::t('skeeks/cms', 'Name'),
'code' => Yii::t('skeeks/cms', 'Code'),
'description_short' => Yii::t('skeeks/cms', 'Description Short'),
'description_full' => Yii::t('skeeks/cms', 'Description Full'),
'cms_tree_id' => Yii::t('skeeks/cms', 'The main section'),
'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_type' => Yii::t('skeeks/cms', 'Description Short Type'),
'description_full_type' => Yii::t('skeeks/cms', 'Description Full Type'),
'cms_image_id' => Yii::t('skeeks/cms', 'Main Image'),
'seo_h1' => Yii::t('skeeks/cms', 'SEO заголовок h1'),
'country_alpha2' => Yii::t('skeeks/cms', 'Страна'),
'shop_brand_id' => Yii::t('skeeks/cms', 'Бренд'),
'cms_content_property_id' => Yii::t('skeeks/cms', 'Характеристика'),
'value_content_element_id' => Yii::t('skeeks/cms', 'Значение'),
'value_content_property_enum_id' => Yii::t('skeeks/cms', 'Значение'),
]);
}
/**
* @inheritdoc
*/
public function attributeHints()
{
return array_merge(parent::attributeHints(), [
'seo_h1' => 'Заголовок будет показан на детальной странице, в случае если его использование задано в шаблоне.',
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[
[
'created_by',
'updated_by',
'created_at',
'updated_at',
'priority',
'cms_tree_id',
'cms_site_id',
'cms_content_property_id',
'value_content_element_id',
'value_content_property_enum_id',
'shop_brand_id',
],
'integer',
],
[
[
'cms_content_property_id',
'value_content_element_id',
'value_content_property_enum_id',
'country_alpha2',
'shop_brand_id',
],
'default',
'value' => null,
],
[['short_name'], 'trim'],
[['country_alpha2'], 'string'],
[['description_short', 'description_full'], 'string'],
[['short_name', 'code'], 'string', 'max' => 255],
[['seo_h1'], 'string', 'max' => 255],
['priority', 'default', 'value' => 500],
[['meta_title', 'meta_description', 'meta_keywords'], 'string'],
[['meta_title'], 'string', 'max' => 500],
['description_short_type', 'string'],
['description_full_type', 'string'],
['description_short_type', 'default', 'value' => "text"],
['description_full_type', 'default', 'value' => "text"],
[
'cms_site_id',
'default',
'value' => function () {
if (\Yii::$app->skeeks->site) {
return \Yii::$app->skeeks->site->id;
}
},
],
[['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,
],
[
['cms_tree_id', 'cms_site_id'],
function ($attribute) {
if ($this->cmsTree && $this->cmsSite) {
if ($this->cmsSite->id != $this->cmsTree->cms_site_id) {
$this->addError($attribute, "Раздел к которому привязывается элемент должен относится к тому же сайту");
}
}
},
],
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTree()
{
return $this->hasOne(CmsTree::className(), ['id' => 'cms_tree_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 getAbsoluteUrl($scheme = false, $params = [])
{
return $this->getUrl(true, $params);
}
/**
* @return string
*/
public function getUrl($scheme = false, $params = [])
{
//Это можно использовать только в коротких сценариях, иначе произойдет переполнение памяти
if (\Yii::$app instanceof Application) {
UrlRuleContentElement::$models[$this->id] = $this;
}
if ($params) {
$params = ArrayHelper::merge(['/cms/saved-filter/view', 'model' => $this], $params);
} else {
$params = ['/cms/saved-filter/view', 'model' => $this];
}
return Url::to($params, $scheme);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsImage()
{
return $this->hasOne(StorageFile::className(), ['id' => 'cms_image_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getValueContentElement()
{
return $this->hasOne(CmsContentElement::className(), ['id' => 'value_content_element_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentProperty()
{
return $this->hasOne(CmsContentProperty::className(), ['id' => 'cms_content_property_id']);
}
/**
* @return ShopBrand
*/
public function getBrand()
{
return $this->hasOne(ShopBrand::class, ['id' => 'shop_brand_id'])->from(['shopBrand' => ShopBrand::tableName()]);
}
/**
* @return CmsCountry|null
*/
public function getCountry()
{
return $this->hasOne(CmsCountry::class, ['alpha2' => 'country_alpha2']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getValueContentPropertyEnum()
{
return $this->hasOne(CmsContentPropertyEnum::className(), ['id' => 'value_content_property_enum_id']);
}
/**
* @return CmsStorageFile|null
*/
public function getImage()
{
if ($this->cmsImage) {
return $this->cmsImage;
}
if ($this->cmsTree && $this->cmsTree->image) {
return $this->cmsTree->image;
}
return null;
}
/**
* @return string|null
*/
public function getName()
{
if ($this->_name === null) {
if ($this->short_name) {
$this->_name = $this->short_name;
} else {
$this->_name = $this->propertyValueName;
}
}
return $this->_name;
}
protected $_name = null;
protected $_seoName = null;
protected $_shortSeoName = null;
/**
* @param $value
* @return $this
*/
public function setSeoName($value)
{
$this->_seoName = $value;
return $this;
}
/**
* @var CmsCountry
*/
protected $_country = null;
/**
* @var null|ShopBrand
*/
protected $_brand = null;
/**
* @var null|CmsContentPropertyEnum
*/
protected $_enum = null;
/**
* @var null|CmsContentElement
*/
protected $_element = null;
/**
* @var null подгтовлены все названия?
*/
protected $_initNames = null;
protected function _initNames()
{
$last = '';
if ($this->_initNames === null) {
if ($this->value_content_element_id) {
if ($this->isNewRecord) {
$this->_element = CmsContentElement::findOne($this->value_content_element_id);
if ($this->_element) {
$last = $this->_element->name;
}
} else {
$this->_element = $this->valueContentElement;
if ($this->_element) {
$last = $this->_element->name;
}
}
} elseif ($this->value_content_property_enum_id) {
//преобразуем вторую часть в нижний регистр
if ($this->isNewRecord) {
$this->_enum = CmsContentPropertyEnum::findOne($this->value_content_property_enum_id);
if ($this->_enum) {
$last = StringHelper::lcfirst($this->_enum->value_for_saved_filter ? $this->_enum->value_for_saved_filter : $this->_enum->value);
}
} else {
$this->_enum = $this->valueContentPropertyEnum;
if ($this->_enum) {
$last = StringHelper::lcfirst($this->_enum->value_for_saved_filter ? $this->_enum->value_for_saved_filter : $this->_enum->value);
}
}
} elseif ($this->shop_brand_id) {
//преобразуем вторую часть в нижний регистр
if ($this->isNewRecord) {
$this->_brand = ShopBrand::findOne($this->shop_brand_id);
if ($this->_brand) {
$last = $this->_brand->name;
}
} else {
$this->_brand = $this->brand;
if ($this->_brand) {
$last = $this->_brand->name;
}
}
} elseif ($this->country_alpha2) {
//преобразуем вторую часть в нижний регистр
if ($this->isNewRecord) {
$this->_country = CmsCountry::find()->alpha2($this->country_alpha2)->one();
if ($this->_country) {
$last = $this->_country->name;
}
} else {
$this->_country = $this->country;
if ($this->_country) {
$last = $this->_country->name;
}
}
}
}
return $this;
}
/**
* Название выбранной опции фильтра
*
* @return string
*/
public function getPropertyValueName()
{
$this->_initNames();
if ($this->_enum) {
return StringHelper::ucfirst($this->_enum->value);
} elseif ($this->_element) {
return StringHelper::ucfirst($this->_element->name);
} elseif ($this->_brand) {
return StringHelper::ucfirst($this->_brand->name);
} elseif ($this->_country) {
return StringHelper::ucfirst($this->_country->name);
}
return '';
}
/**
* Название выбранной опции фильтра
*
* @return string
*/
public function getPropertyValueNameInflected()
{
$this->_initNames();
if ($this->_enum) {
return StringHelper::ucfirst($this->_enum->value_for_saved_filter ? $this->_enum->value_for_saved_filter : $this->_enum->value);
} elseif ($this->_element) {
//todo: доработать склонение тут
return StringHelper::ucfirst($this->_element->name);
} elseif ($this->_country) {
//todo: доработать склонение тут
return $this->_country->name;
} elseif ($this->_brand) {
//todo: доработать склонение тут
return $this->_brand->name;
}
return '';
}
/**
* Полное название
*
* @return string
*/
public function getSeoName()
{
$result = "";
if ($this->_seoName === null) {
if ($this->seo_h1) {
$this->_seoName = $this->seo_h1;
} elseif ($this->short_name) {
$this->_seoName = $this->name;
} else {
$this->_initNames();
if ($this->_brand || $this->_country) {
$this->_seoName = $this->cmsTree->seoName." ".$this->propertyValueNameInflected;
} else {
$this->_seoName = $this->cmsTree->seoName." ".StringHelper::lcfirst($this->propertyValueNameInflected);
}
}
}
return $this->_seoName;
}
/**
* Полное название
*
* @return string
*/
public function getShortSeoName()
{
$result = "";
$this->_initNames();
if ($this->_brand || $this->_country) {
$this->_shortSeoName = $this->cmsTree->name." ".$this->propertyValueNameInflected;
} else {
$this->_shortSeoName = $this->cmsTree->name." ".StringHelper::lcfirst($this->propertyValueNameInflected);
}
return $this->_shortSeoName;
}
public function asText()
{
$result = [];
$result[] = "#".$this->id;
$result[] = $this->seoName;
return implode("", $result);
}
/**
* @param array $savedFilters
* @return array
*/
static public function formatFilters(array $savedFilters)
{
$savedFiltersData = [];
foreach ($savedFilters as $sf) {
/**
* @var $sf \skeeks\cms\models\CmsSavedFilter
*/
$pr_id = "";
$n = "";
if ($sf->cms_content_property_id) {
$pr_id = $sf->cms_content_property_id;
$n = $sf->cmsContentProperty->name;
} elseif ($sf->shop_brand_id) {
$pr_id = "shop_brand_id";
$n = "Бренд";
} elseif ($sf->country_alpha2) {
$pr_id = "country";
$n = "Страна";
}
$savedFiltersData[$pr_id]['savedFilters'][$sf->id] = $sf;
$savedFiltersData[$pr_id]['name'] = $n;
}
return $savedFiltersData;
}
/**
* @return CmsContentQuery
*/
public static function find()
{
return (new CmsSavedFilterQuery(get_called_class()));
}
/**
* @return bool
*/
public function getIsAllowIndex()
{
//Если страница 18+, и не разрешено индексировать такой контент, то не индексируем!
if ($this->cmsTree && $this->cmsTree->is_adult && !\Yii::$app->seo->is_allow_index_adult_content) {
return false;
}
return true;
}
public function getPropertyIdForFilter()
{
$baseQuery = CmsCompareElement::find();
if ($this->shop_brand_id) {
$f = new ShopDataFiltersHandler([
'baseQuery' => $baseQuery,
]);
return "field-{$f->formName()}-brand_id";
}
if ($this->cms_content_property_id) {
$f = new CmsEavQueryFilterHandler([
'baseQuery' => $baseQuery,
]);
return "field-{$f->formName()}-" . $this->cms_content_property_id;
}
return "";
}
public function getPropertyValueForFilter()
{
if ($this->value_content_element_id) {
return $this->value_content_element_id;
}
if ($this->value_content_property_enum_id) {
return $this->value_content_property_enum_id;
}
if ($this->shop_brand_id) {
return $this->shop_brand_id;
}
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/models/CmsSiteAddressPhone.php | src/models/CmsSiteAddressPhone.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 CmsSiteAddressPhone extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_site_address_phone}}';
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'value' => 'Телефон',
'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],
[['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']],
[['value'], 'string', 'max' => 64],
[['value'], PhoneValidator::class],
]);
}
/**
* 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/CmsContractor.php | src/models/CmsContractor.php | <?php
namespace skeeks\cms\models;
use http\Exception\InvalidArgumentException;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\helpers\StringHelper;
use skeeks\cms\models\behaviors\HasStorageFile;
use skeeks\cms\models\queries\CmsContractorQuery;
use skeeks\cms\shop\models\ShopBill;
use skeeks\cms\validators\PhoneValidator;
use skeeks\yii2\dadataClient\models\PartyModel;
use yii\helpers\ArrayHelper;
use yii\validators\EmailValidator;
/**
* This is the model class for table "cms_contractor".
*
* @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 $contractor_type Тип контрагента (Ип, Юр, Физ лицо)
* @property string|null $name Название
* @property string|null $full_name Полное название
* @property string|null $international_name Интернациональное название
* @property string|null $first_name
* @property string|null $last_name
* @property string|null $patronymic
* @property string $inn ИНН
* @property string|null $ogrn ОГРН
* @property string|null $kpp КПП
* @property string|null $okpo ОКПО
* @property string|null $address Адрес организации
* @property string|null $mailing_address Почтовый адрес (для отправки писем)
* @property string|null $mailing_postcode Почтовый индекс
* @property int|null $cms_image_id Фото
* @property int|null $stamp_id Печать
* @property int|null $director_signature_id Подпись директора
* @property int|null $signature_accountant_id Подпись гл. бухгалтера
* @property int $is_our Это наш контрагент?
* @property string $description Описание
* @property string $phone Телефон
* @property string $email Email
*
* @property string $asShortText
*
* @property CmsStorageFile $cmsImage
* @property CmsSite $cmsSite
* @property CmsStorageFile $directorSignature
* @property CmsStorageFile $signatureAccountant
* @property CmsStorageFile $stamp
* @property CmsCompany[] $companies
* @property CmsUser[] $users
* @property CmsContractorBank[] $banks
*
* @property ShopBill[] $receiverBills
* @property ShopBill[] $senderBills
*/
class CmsContractor extends ActiveRecord
{
const TYPE_LEGAL = 'legal';
const TYPE_INDIVIDUAL = 'individual';
const TYPE_SELFEMPLOYED = 'selfemployed';
const TYPE_HUMAN = 'human';
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'cms_contractor';
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
HasStorageFile::class => [
'class' => HasStorageFile::class,
'fields' => [
'cms_image_id',
'stamp_id',
'director_signature_id',
'signature_accountant_id',
],
],
/*HasJsonFieldsBehavior::class => [
'class' => HasJsonFieldsBehavior::class,
'fields' => [
'dadata',
],
],*/
]);
}
/**
* {@inheritdoc}
*/
public function rules()
{
return array_merge(parent::rules(), [
[['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_site_id', 'is_our'], 'integer'],
[['contractor_type'], 'required'],
[
['description', 'contractor_type', 'name', 'full_name', 'international_name', 'first_name', 'last_name', 'patronymic', 'inn', 'ogrn', 'kpp', 'okpo', 'address', 'mailing_address', 'mailing_postcode'],
'string',
'max' => 255,
],
[['cms_image_id'], 'safe'],
[['stamp_id'], 'safe'],
[['director_signature_id'], 'safe'],
[['signature_accountant_id'], 'safe'],
/*[
[
'inn',
'ogrn',
'kpp',
'okpo',
],
"filter",
'filter' => 'trim',
],*/
[
'cms_site_id',
'default',
'value' => function () {
if (\Yii::$app->skeeks->site) {
return \Yii::$app->skeeks->site->id;
}
},
],
[
[
'name',
'international_name',
'full_name',
'first_name',
'last_name',
'patronymic',
'description',
'inn',
],
'default',
'value' => null,
],
[['cms_site_id', 'inn'], 'unique', 'when' => function() {
return $this->inn;
}, 'targetAttribute' => ['cms_site_id', 'inn'], 'message' => 'Этот ИНН уже используется'],
[['inn'], 'unique', 'when' => function() {
return $this->inn;
}, 'targetAttribute' => ['inn'], 'message' => 'Этот ИНН уже используется'],
[
['inn'],
'required',
'when' => function () {
return (bool)(in_array($this->contractor_type, [self::TYPE_INDIVIDUAL, self::TYPE_SELFEMPLOYED, self::TYPE_LEGAL]));
},
],
[
['name'],
'required',
'when' => function () {
return (bool)(in_array($this->contractor_type, [self::TYPE_LEGAL]));
},
],
[
['first_name'],
'required',
'when' => function () {
return (bool)(!in_array($this->contractor_type, [self::TYPE_LEGAL]));
},
],
[
['name'],
function () {
if (!in_array($this->contractor_type, [self::TYPE_LEGAL])) {
$this->name = null;
}
},
],
[
['first_name', 'last_name', 'patronymic'],
function () {
if (in_array($this->contractor_type, [self::TYPE_LEGAL])) {
$this->first_name = null;
$this->last_name = null;
$this->patronymic = null;
}
},
],
[['phone'], 'string', 'max' => 64],
[['phone'], PhoneValidator::class],
//[['phone'], "filter", 'filter' => 'trim'],
[
['phone'],
"filter",
'filter' => function ($value) {
return StringHelper::strtolower($value);
},
],
[['email'], 'string', 'max' => 64],
[['email'], EmailValidator::class],
//[['email'], "filter", 'filter' => 'trim'],
[
['email'],
"filter",
'filter' => function ($value) {
return StringHelper::strtolower($value);
},
],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'cms_site_id' => 'Cms Site ID',
'contractor_type' => 'Тип контрагента',
'name' => 'Название',
'full_name' => 'Полное название',
'international_name' => 'Интернациональное название',
'first_name' => 'Имя',
'last_name' => 'Фамилия',
'patronymic' => 'Отчество',
'inn' => 'ИНН',
'ogrn' => 'ОГРН',
'kpp' => 'КПП',
'okpo' => 'ОКПО',
'address' => 'Адрес',
'mailing_address' => 'Почтовый адрес',
'mailing_postcode' => 'Индекс',
'cms_image_id' => 'Фото или логотип',
'stamp_id' => 'Печать',
'director_signature_id' => 'Подпись директора',
'signature_accountant_id' => 'Подпись бухгалтера',
'is_our' => 'Контрагент нашей компании',
'phone' => 'Телефон',
'email' => 'Email',
'description' => 'Описание',
]);
}
/**
* {@inheritdoc}
*/
public function attributeHints()
{
return array_merge(parent::attributeLabels(), [
'stamp_id' => 'Используется при формировании счетов',
'director_signature_id' => 'Используется при формировании счетов',
'signature_accountant_id' => 'Используется при формировании счетов',
]);
}
/**
* @return array
*/
static public function optionsForType()
{
return [
self::TYPE_LEGAL => 'Компания',
self::TYPE_INDIVIDUAL => 'ИП',
self::TYPE_SELFEMPLOYED => 'Самозанятый',
self::TYPE_HUMAN => 'Физическое лицо',
//self::TYPE_INDIVIDUAL => 'Физическое лицо',
];
}
public function asText()
{
//$parent = parent::asText();
$parent = '';
if (in_array($this->contractor_type, [
self::TYPE_INDIVIDUAL,
self::TYPE_SELFEMPLOYED,
self::TYPE_HUMAN,
])) {
$parent .= $this->typeAsText." ";
}
if (!in_array($this->contractor_type, [self::TYPE_LEGAL])) {
$parent .= implode(" ", [
$this->last_name,
$this->first_name,
]);
} else {
$parent .= $this->name;
}
if ($this->international_name) {
$parent .= " / ".$this->international_name;
}
//return "#" . $this->id . " " . $parent;
return $parent;
}
/**
* @return string
*/
public function getTypeAsText()
{
return (string)ArrayHelper::getValue(self::optionsForType(), $this->contractor_type);
}
/**
* Gets query for [[CmsImage]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsImage()
{
return $this->hasOne(CmsStorageFile::className(), ['id' => 'cms_image_id']);
}
/**
* Gets query for [[CmsSite]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSite()
{
return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_id']);
}
/**
* Gets query for [[DirectorSignature]].
*
* @return \yii\db\ActiveQuery
*/
public function getDirectorSignature()
{
return $this->hasOne(CmsStorageFile::className(), ['id' => 'director_signature_id']);
}
/**
* Gets query for [[SignatureAccountant]].
*
* @return \yii\db\ActiveQuery
*/
public function getSignatureAccountant()
{
return $this->hasOne(CmsStorageFile::className(), ['id' => 'signature_accountant_id']);
}
/**
* Gets query for [[Stamp]].
*
* @return \yii\db\ActiveQuery
*/
public function getStamp()
{
return $this->hasOne(CmsStorageFile::className(), ['id' => 'stamp_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContractorMap()
{
return $this->hasMany(CmsContractorMap::class, ['cms_contractor_id' => 'id'])
->from(['cmsContractorMap' => CmsContractorMap::tableName()]);
}
/**
* @return \yii\db\ActiveQuery|CrmContractorQuery
*/
/*public function getCmsUsers()
{
return $this->hasMany(CrmContractor::class, ['id' => 'crm_child_contractor_id'])->via('crmContractorMapCompanies');
}*/
/**
* {@inheritdoc}
* @return CmsContractorQuery the active query used by this AR class.
*/
public static function find()
{
return new CmsContractorQuery(get_called_class());
}
/**
* @param PartyModel $party
* @return $this
*/
public function setAttributesFromDadata(PartyModel $party)
{
$this->name = $party->unrestricted_value;
$this->full_name = $party->unrestricted_value;
$this->kpp = $party->kpp;
$this->ogrn = $party->ogrn;
$this->okpo = $party->getDataValue("okpo");
$this->address = (string)$party->address;
$this->mailing_address = (string)$party->address;
$this->mailing_postcode = $party->getDataValue("address.data.postal_code");
$this->inn = $party->inn;
//$this->dadata = $party->toArray();
if ($party->type == "LEGAL") {
$this->contractor_type = self::TYPE_LEGAL;
} elseif ($party->type == "INDIVIDUAL") {
$this->contractor_type = self::TYPE_INDIVIDUAL;
[$this->last_name, $this->first_name, $this->patronymic] = explode(" ", $party->name->full);
} else {
throw new InvalidArgumentException("Тип {$party->type} не предусмотрен");
}
return $this;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsCompany2contractors()
{
return $this->hasMany(CmsCompany2contractor::class, ['cms_contractor_id' => 'id'])
->from(['cmsCompany2contractors' => CmsCompany2contractor::tableName()]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCompanies()
{
return $this->hasMany(CmsCompany::class, ['id' => 'cms_company_id'])
->via('cmsCompany2contractors');;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBanks()
{
return $this->hasMany(CmsContractorBank::class, ['cms_contractor_id' => 'id'])->orderBy(['sort' => SORT_ASC]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUsers()
{
return $this->hasMany(CmsUser::class, ['id' => 'cms_user_id'])
->via('cmsContractorMap');;
}
/**
* @return null|string
*/
public function getAsShortText()
{
$parent = "";
if (!in_array($this->contractor_type, [self::TYPE_LEGAL])) {
$parent = implode(" ", [
$this->last_name,
$this->first_name,
$this->patronymic,
]);
if ($this->contractor_type == self::TYPE_INDIVIDUAL) {
$parent = "ИП ".$parent;
}
if ($this->contractor_type == self::TYPE_SELFEMPLOYED) {
$parent = "Самозанятый ".$parent;
}
} else {
$parent = $this->name;
}
return $parent;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSenderBills()
{
return $this->hasMany(ShopBill::class, ['sender_contractor_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getReceiverBills()
{
return $this->hasMany(ShopBill::class, ['receiver_contractor_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/CmsSite.php | src/models/CmsSite.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\assets\CmsAsset;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\models\behaviors\HasJsonFieldsBehavior;
use skeeks\cms\models\behaviors\HasStorageFile;
use skeeks\cms\rbac\models\CmsAuthAssignment;
use skeeks\modules\cms\user\models\User;
use Yii;
use yii\base\Event;
use yii\base\Exception;
use yii\db\BaseActiveRecord;
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 $is_active
* @property integer $is_default
* @property integer $priority
* @property string $name
* @property string $internal_name
* @property string $description
* @property integer $image_id
* @property integer $favicon_storage_file_id
* @property array $work_time
*
* @property string $url
*
* @property string $internalName
* @property CmsAuthAssignment[] $authAssignments
* @property CmsTree $rootCmsTree
* @property CmsLang $cmsLang
* @property CmsSiteDomain[] $cmsSiteDomains
* @property CmsSiteDomain $cmsSiteMainDomain
* @property CmsTree[] $cmsTrees
* @property CmsContentElement[] $cmsContentElements
* @property CmsStorageFile $image
* @property CmsStorageFile $favicon
* @property CmsComponentSettings[] $cmsComponentSettings
* @property CmsSiteEmail|null $cmsSiteEmail
* @property CmsSitePhone|null $cmsSitePhone
* @property CmsSiteAddress|null $cmsSiteAddress
* @property CmsSiteEmail[] $cmsSiteEmails
* @property CmsSiteAddress[] $cmsSiteAddresses
* @property CmsSitePhone[] $cmsSitePhones
* @property CmsSiteSocial[] $cmsSiteSocials
* @property CmsSmsProvider[] $cmsSmsProviders
* @property CmsSmsProvider|null $cmsSmsProvider
*
* @property string $faviconRootSrc
* @property string $faviconUrl всегда вернет какую нибудь фавиконку, не важно задана она для сайта или нет
* @property string $faviconType полный тип фивикон https://yandex.ru/support/webmaster/search-results/create-favicon.html
*/
class CmsSite extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_site}}';
}
public function init()
{
parent::init();
$this->on(BaseActiveRecord::EVENT_AFTER_INSERT, [$this, 'createTreeAfterInsert']);
$this->on(BaseActiveRecord::EVENT_BEFORE_INSERT, [$this, 'beforeInsertChecks']);
$this->on(BaseActiveRecord::EVENT_BEFORE_UPDATE, [$this, 'beforeUpdateChecks']);
$this->on(BaseActiveRecord::EVENT_BEFORE_DELETE, [$this, 'beforeDeleteRemoveTree']);
}
/**
* @throws Exception
* @throws \Exception
*/
public function beforeDeleteRemoveTree()
{
//Before delete site delete all tree
foreach ($this->cmsTrees as $tree) {
//$tree->delete();
/*if (!$tree->deleteWithChildren())
{
throw new Exception('Not deleted tree');
}*/
}
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
HasStorageFile::className() => [
'class' => HasStorageFile::className(),
'fields' => ['image_id', 'favicon_storage_file_id'],
],
HasJsonFieldsBehavior::className() => [
'class' => HasJsonFieldsBehavior::className(),
'fields' => ['work_time'],
],
]);
}
/**
* @param Event $e
* @throws Exception
*/
public function beforeUpdateChecks(Event $e)
{
//Если этот элемент по умолчанию выбран, то все остальны нужно сбросить.
if ($this->is_default) {
static::updateAll(
[
'is_default' => null,
],
['!=', 'id', $this->id]
);
$this->is_active = 1; //сайт по умолчанию всегда активный
}
}
/**
* @param Event $e
* @throws Exception
*/
public function beforeInsertChecks(Event $e)
{
//Если этот элемент по умолчанию выбран, то все остальны нужно сбросить.
if ($this->is_default) {
static::updateAll([
'is_default' => null,
]);
$this->is_active = 1; //сайт по умолчанию всегда активный
}
}
public function createTreeAfterInsert(Event $e)
{
$tree = new CmsTree([
'name' => 'Главная страница',
]);
$tree->makeRoot();
$tree->cms_site_id = $this->id;
try {
if (!$tree->save()) {
throw new Exception('Failed to create a section of the tree');
}
} catch (\Exception $e) {
var_dump($e->getMessage());
die;
throw $e;
}
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'is_active' => Yii::t('skeeks/cms', 'Active'),
'is_default' => Yii::t('skeeks/cms', 'Default'),
'priority' => Yii::t('skeeks/cms', 'Priority'),
'name' => Yii::t('skeeks/cms', 'Name'),
'internal_name' => Yii::t('skeeks/cms', 'Внутреннее название'),
'description' => Yii::t('skeeks/cms', 'Description'),
'image_id' => Yii::t('skeeks/cms', 'Логотип'),
'favicon_storage_file_id' => Yii::t('skeeks/cms', 'Favicon'),
'work_time' => Yii::t('skeeks/cms', 'Рабочее время'),
]);
}
/**
* @inheritdoc
*/
public function attributeHints()
{
return array_merge(parent::attributeHints(), [
'name' => Yii::t('skeeks/cms', 'Основное название сайта, отображается в разных местах шаблона, в заголовках писем и других местах.'),
'internal_name' => Yii::t('skeeks/cms', 'Название сайта, чаще всего невидимое для клиента, но видимое администраторам и менеджерам.'),
'favicon_storage_file_id' => Yii::t('skeeks/cms',
'Формат: ICO (рекомендуемый), Размер: 16 × 16, 32 × 32 или 120 × 120 пикселей. Иконка сайта отображаемая в браузере, а так же в различных поисковиках. <br />Подробная документация <a href="https://yandex.ru/support/webmaster/search-results/favicon.html" target="_blank" data-pjax="0">https://yandex.ru/support/webmaster/search-results/favicon.html</a>'),
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[['created_by', 'updated_by', 'created_at', 'updated_at', 'priority'], 'integer'],
[['is_active'], 'integer'],
[['is_default'], 'integer'],
[['name', 'description'], 'string', 'max' => 255],
[['internal_name'], 'string', 'max' => 255],
['priority', 'default', 'value' => 500],
['is_active', 'default', 'value' => 1],
['internal_name', 'default', 'value' => null],
['is_default', 'default', 'value' => null],
/*[['is_default'], 'unique'],*/
[['image_id'], 'safe'],
[['work_time'], 'safe'],
[['favicon_storage_file_id'], 'safe'],
[
['image_id'],
\skeeks\cms\validators\FileValidator::class,
'skipOnEmpty' => false,
'mimeTypes' => [
'image/*',
],
//'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'svg'],
'maxFiles' => 1,
'maxSize' => 1024 * 1024 * 2,
'minSize' => 1024,
],
[
['favicon_storage_file_id'],
\skeeks\cms\validators\FileValidator::class,
'skipOnEmpty' => false,
//'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'ico', 'svg'],
'mimeTypes' => [
'image/*',
],
'maxFiles' => 1,
'maxSize' => 1024 * 1024 * 2,
//'minSize' => 1024,
],
]);
}
static public $sites = [];
/**
* @param (integer) $id
* @return static
*/
public static function getById($id)
{
if (!array_key_exists($id, static::$sites)) {
static::$sites[$id] = static::find()->where(['id' => (integer)$id])->one();
}
return static::$sites[$id];
}
static public $sites_by_code = [];
/**
* @param (integer) $id
* @return static
*/
public static function getByCode($code)
{
if (!array_key_exists($code, static::$sites_by_code)) {
static::$sites_by_code[$code] = static::find()->where(['code' => (string)$code])->one();
}
return static::$sites_by_code[$code];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsSiteDomains()
{
return $this->hasMany(CmsSiteDomain::class, ['cms_site_id' => 'id']);
}
/**
* Gets query for [[CmsSiteEmails]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSmsProviders()
{
return $this->hasMany(CmsSmsProvider::className(), ['cms_site_id' => 'id'])->orderBy(['priority' => SORT_ASC]);
}
/**
* Gets query for [[CmsSiteEmails]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSmsProvider()
{
return $this->getCmsSmsProviders()->andWhere(['is_main' => 1])->one();
}
/**
* Gets query for [[CmsSiteEmails]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSiteEmails()
{
return $this->hasMany(CmsSiteEmail::className(), ['cms_site_id' => 'id'])->orderBy(['priority' => SORT_ASC]);
}
/**
* Gets query for [[CmsSiteEmails]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSiteAddresses()
{
return $this->hasMany(CmsSiteAddress::className(), ['cms_site_id' => 'id'])->orderBy(['priority' => SORT_ASC]);
}
/**
* Gets query for [[CmsSitePhones]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSitePhones()
{
return $this->hasMany(CmsSitePhone::className(), ['cms_site_id' => 'id'])->orderBy(['priority' => SORT_ASC]);
}
/**
* Главный телефон сайта
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSitePhone()
{
$q = $this->getCmsSitePhones()->limit(1);
$q->multiple = false;
return $q;
}
/**
* Главный адрес сайта
* @return \yii\db\ActiveQuery
*/
public function getCmsSiteAddress()
{
$q = $this->getCmsSiteAddresses()->limit(1);
$q->multiple = false;
return $q;
}
/**
* Главный email сайта
* @return \yii\db\ActiveQuery
*/
public function getCmsSiteEmail()
{
$q = $this->getCmsSiteEmails()->limit(1);
$q->multiple = false;
return $q;
}
/**
* Gets query for [[CmsSiteSocials]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSiteSocials()
{
return $this->hasMany(CmsSiteSocial::className(), ['cms_site_id' => 'id'])->orderBy(['priority' => SORT_ASC]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsSiteMainDomain()
{
//return null;
$query = $this->getCmsSiteDomains()->andWhere(['is_main' => 1]);
$query->multiple = false;
return $query;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTrees()
{
return $this->hasMany(CmsTree::class, ['cms_site_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentElements()
{
return $this->hasMany(CmsContentElement::class, ['cms_site_id' => 'id']);
}
/**
* @return string
*/
public function getUrl()
{
if ($this->cmsSiteMainDomain) {
return (($this->cmsSiteMainDomain->is_https ? "https:" : "http:")."//".$this->cmsSiteMainDomain->domain);
}
return \Yii::$app->urlManager->hostInfo;
}
/**
* @return CmsTree
*/
public function getRootCmsTree()
{
return $this->getCmsTrees()->andWhere(['level' => 0])->limit(1)->one();
}
/**
* @return \yii\db\ActiveQuery
*/
public function getImage()
{
return $this->hasOne(CmsStorageFile::className(), ['id' => 'image_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getFavicon()
{
return $this->hasOne(CmsStorageFile::className(), ['id' => 'favicon_storage_file_id']);
}
/**
* Gets query for [[CmsComponentSettings]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsComponentSettings()
{
return $this->hasMany(CmsComponentSettings::className(), ['cms_site_id' => 'id']);
}
/**
* @return string
* @throws \yii\base\InvalidConfigException
*/
public function getFaviconUrl()
{
if ($this->favicon) {
return $this->favicon->absoluteSrc;
} else {
return CmsAsset::getAssetUrl('favicon.ico');
}
}
/**
* @return string
*/
public function getFaviconRootSrc()
{
if ($this->favicon) {
return $this->favicon->getRootSrc();
} else {
return \Yii::getAlias('@skeeks/cms/assets/src/favicon.ico');
}
}
/**
* @return string
* @see https://yandex.ru/support/webmaster/search-results/create-favicon.html
*/
public function getFaviconType()
{
$data = pathinfo($this->faviconUrl);
$extension = strtolower((string) ArrayHelper::getValue($data, "extension"));
$last = 'x-icon';
if (in_array($extension, ["png", "jpeg", "gif", "bmp"])) {
$last = $extension;
}
if (in_array($extension, ["svg"])) {
$last = "svg+xml";
}
return "image/".$last;
}
/**
* Gets query for [[AuthAssignments]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsAuthAssignments()
{
return $this->hasMany(CmsAuthAssignment::className(), ['cms_site_id' => 'id']);
}
/**
* Внутреннее название сайта используемое в административной части
* @return string
*/
public function getInternalName()
{
if ($this->internal_name) {
return $this->internal_name;
}
return $this->name;
}
/**
* @return string
*/
public function asText()
{
$name = $this->name;
$this->name = $this->internalName;
$result = parent::asText();
$this->name = $name;
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/models/CmsContractorBank.php | src/models/CmsContractorBank.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use yii\helpers\ArrayHelper;
/**
* @property int $id
* @property int $created_by
* @property int $created_at
* @property int $cms_contractor_id
* @property string $bank_name Банк
* @property string $bic БИК
* @property string|null $correspondent_account Корреспондентский счёт
* @property string $checking_account Расчетный счет
* @property string $bank_address Адрес банка
* @property string $comment Комментарий
* @property int $is_active
* @property int $sort
*
* @property CmsContractor $contractor
*/
class CmsContractorBank extends ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'cms_contractor_bank';
}
/**
* @inheritdoc
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['created_by', 'created_at', 'cms_contractor_id'], 'integer'],
[['cms_contractor_id', 'bank_name', 'bic', 'checking_account'], 'required'],
[['checking_account', 'correspondent_account'], 'string', 'max' => 20],
[['bic'], 'string', 'max' => 12],
[['comment'], 'string'],
[['bank_name'], 'string', 'max' => 255],
[['cms_contractor_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsContractor::class, 'targetAttribute' => ['cms_contractor_id' => 'id']],
[['checking_account'], 'unique', 'targetAttribute' => ['checking_account', 'cms_contractor_id', 'bic']],
[['is_active'], 'integer'],
[['sort'], 'integer'],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'id' => 'ID',
'cms_contractor_id' => 'Контрагент',
'bank_name' => 'Банк',
'bic' => 'БИК',
'correspondent_account' => 'Корреспондентский счёт',
'checking_account' => 'Расчетный счет',
'bank_address' => 'Адрес банка',
'comment' => 'Комментарий',
'sort' => 'Сортировка',
'is_active' => 'Активность',
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getContractor()
{
return $this->hasOne(CmsContractor::class, ['id' => 'cms_contractor_id']);
}
public function asText()
{
return "{$this->bank_name} / БИК {$this->bic} / Счет: {$this->checking_account}";
}
} | 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/CmsTask.php | src/models/CmsTask.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\behaviors\CmsLogBehavior;
use skeeks\cms\helpers\CmsScheduleHelper;
use skeeks\cms\models\behaviors\HasStorageFileMulti;
use skeeks\cms\models\behaviors\traits\HasLogTrait;
use skeeks\cms\models\queries\CmsTaskQuery;
use yii\base\Exception;
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 $description Описание задачи
*
* @property int|null $executor_id Исполнитель
* @property int|null $cms_project_id Проект
* @property int|null $cms_company_id Компания
* @property int|null $cms_user_id Клиент
*
* @property int|null $plan_start_at Планируемое начало
* @property int|null $plan_end_at Планируемое завершение
*
* @property int|null $plan_duration Длительность по плану в секундах
* @property int|null $fact_duration Фактическая длительность в секундах
*
* @property string $status Статус задачи
*
* @property int $executor_sort Сортировка у исполнителя
* @property int|null $executor_end_at Ориентировочная дата исполнения задачи исполнителем
*
* @property CmsProject $cmsProject
* @property CmsCompany $cmsCompany
* @property CmsUser $cmsUser
* @property CmsUser $executor
*
* @property CrmTaskSchedule[] $schedules
*
* @property CrmSchedule|null $notEndSchedule Не закрытый временной промежуток
* @property CrmSchedule|null $notEndScheduleByDate Не закрытый временной промежуток за сегодня
* @property CrmSchedules[]|null $schedulesByDate Рабочие промежутки за сегодняшний день
*
*
* @property string $statusAsText
* @property string $statusAsIcon
* @property string $statusAsColor
* @property string $statusAsFeatureHint
* @property string $statusAsHint
*/
class CmsTask extends ActiveRecord
{
use HasLogTrait;
const STATUS_NEW = 'new';
const STATUS_ACCEPTED = 'accepted';
const STATUS_IN_WORK = 'in_work';
const STATUS_ON_PAUSE = 'on_pouse';
const STATUS_ON_CHECK = 'on_check';
const STATUS_CANCELED = 'canceled';
const STATUS_READY = 'ready';
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'cms_task';
}
public function init()
{
//Уведомить исполнителя
/*$this->on(self::EVENT_AFTER_INSERT, function($e) {
if ($this->executor_id) {
$notify = new CmsWebNotify();
$notify->cms_user_id = $this->executor_id;
$notify->name = "Вам поставлена новая задача";
$notify->model_id = $this->id;
$notify->model_code = $this->skeeksModelCode;
$notify->save();
}
});*/
$this->on(self::EVENT_BEFORE_DELETE, function () {
if ($this->schedules) {
throw new Exception("Нельзя удалить эту задачу, потому что по ней есть отработанное время.");
}
});
return parent::init();
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
HasStorageFileMulti::class => [
'class' => HasStorageFileMulti::class,
'relations' => [
[
'relation' => 'files',
'property' => 'fileIds',
],
],
],
CmsLogBehavior::class => [
'class' => CmsLogBehavior::class,
'no_log_fields' => [
'executor_sort',
'executor_end_at',
],
'relation_map' => [
'cms_project_id' => 'cmsProject',
'cms_company_id' => 'cmsCompany',
'cms_user_id' => 'cmsUser',
'executor_id' => 'executor',
'status' => 'statusAsText',
],
],
]);
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['created_by', 'created_at', 'cms_project_id', 'executor_id', 'plan_start_at', 'plan_end_at'], 'integer'],
[['executor_sort'], 'integer'],
[['cms_company_id'], 'integer'],
[['cms_user_id'], 'integer'],
[['executor_end_at'], 'integer'],
[['name', 'executor_id'], 'required'],
[['description'], 'string'],
[['status'], 'string'],
[['plan_duration', 'fact_duration'], 'integer'],
[['name'], 'string', 'max' => 255],
['plan_duration', 'default', 'value' => 60 * 5], //5 минут
[
'status',
'default',
'value' => function () {
//Если задавча ставится себе, то она сразу подтверждена
if ($this->executor_id == $this->created_by || !$this->created_by) {
return self::STATUS_ACCEPTED;
} else {
return self::STATUS_NEW;
}
},
],
[
'status',
function () {
if ($this->isNewRecord) {
if ($this->executor_id == $this->created_by || (!$this->created_by && $this->executor_id == \Yii::$app->user->identity->id)) {
$this->status = self::STATUS_ACCEPTED;
} else {
$this->status = self::STATUS_NEW;
}
return true;
}
//Если статус меняется
if (!$this->isNewRecord && $this->isAttributeChanged('status')) {
//Если принимается задача
if ($this->status == self::STATUS_ACCEPTED) {
if (!in_array($this->getOldAttribute('status'), [self::STATUS_NEW])) {
$this->addError('status', "Для того чтобы принять задачу, она должна быть в статусе новая");
return false;
}
if (\Yii::$app->user->id != $this->executor_id) {
$this->addError('status', "Принять задачу может только исполнитель");
return false;
}
return true;
} elseif ($this->status == self::STATUS_CANCELED) {
if (!in_array($this->getOldAttribute('status'), [self::STATUS_NEW, self::STATUS_ACCEPTED])) {
$this->addError('status', "Для того чтобы отменить задачу, она должна быть в статусе (новая, принята)");
return false;
}
if (\Yii::$app->user->id == $this->executor_id) {
return true;
}
if (\Yii::$app->user->id == $this->created_by) {
return true;
}
$this->addError('status', "Отменить задачу может только исполнитель или автор.");
return false;
} elseif ($this->status == self::STATUS_IN_WORK) {
if (!in_array($this->getOldAttribute('status'), [self::STATUS_ACCEPTED, self::STATUS_ON_PAUSE])) {
$this->addError('status', "Для того чтобы включить задачу, она должна быть в статусе (принята или на паузе)");
return false;
}
if (\Yii::$app->user->id != $this->executor_id) {
$this->addError('status', "Взять в работу задачу может только исполнитель.");
return false;
}
//Если пользователь сейчас не работает
if (!\Yii::$app->user->identity->isWorkingNow) {
$this->addError('status', "Для начала необходимо включить работу.");
return false;
}
if (\Yii::$app->user->identity->getExecutorTasks()->statusInWork()->one()) {
$this->addError('status', "У вас уже запущена другая задача.");
return false;
}
return true;
} elseif ($this->status == self::STATUS_ON_PAUSE) {
if (!in_array($this->getOldAttribute('status'), [self::STATUS_IN_WORK, self::STATUS_ON_CHECK, self::STATUS_READY, self::STATUS_CANCELED])) {
$this->addError('status', "Для того чтобы включить задачу, она должна быть в статусе (в работе)");
return false;
}
if (\Yii::$app->user->id != $this->executor_id && $this->getOldAttribute('status') == self::STATUS_IN_WORK) {
$this->addError('status', "Остановить задачу может только исполнитель.");
return false;
}
return true;
} elseif ($this->status == self::STATUS_ON_CHECK) {
if (!in_array($this->getOldAttribute('status'), [
self::STATUS_IN_WORK
//, self::STATUS_ON_PAUSE
])) {
$this->addError('status', "Для того чтобы отправить задачу на проверку, она должна быть в статусе (в работе)");
return false;
}
if (\Yii::$app->user->id != $this->executor_id) {
$this->addError('status', "Может только исполнитель.");
return false;
}
return true;
} elseif ($this->status == self::STATUS_READY) {
if ($this->executor_id == $this->created_by) {
if (!in_array($this->getOldAttribute('status'), [self::STATUS_IN_WORK])) {
$this->addError('status', "Для того чтобы сделать задачу готовой, она должна быть в статусе (в работе)");
return false;
}
} else {
if (!in_array($this->getOldAttribute('status'), [self::STATUS_ON_CHECK])) {
$this->addError('status', "Для того чтобы сделать задачу готовой, она должна быть в статусе (на проверке)");
return false;
}
}
/*if (\Yii::$app->user->id != $this->executor_id) {
$this->addError('status', "Может только исполнитель.");
return false;
}*/
return true;
}
}
return true;
},
],
[['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_project_id' => 'Проект',
'name' => 'Название',
'description' => 'Описание задачи',
'description' => 'Описание задачи',
'cms_company_id' => 'Компания',
'cms_user_id' => 'Клиент',
'plan_start_at' => 'Планируемое начало',
'plan_end_at' => 'Планируемое завершение',
'plan_duration' => 'Длительность по плану',
'fact_duration' => 'Фактическая длительность',
'status' => 'Статус',
'executor_id' => 'Исполнитель',
'executor_sort' => 'Приоритет исполнителя по задаче',
'executor_end_at' => 'Ориентировочная дата исполнения задачи исполнителем',
'fileIds' => "Файлы",
]);
}
protected $_file_ids = null;
/**
* @return \yii\db\ActiveQuery
*/
public function getFiles()
{
return $this->hasMany(CmsStorageFile::class, ['id' => 'storage_file_id'])
->via('cmsTaskFiles')
->orderBy(['priority' => SORT_ASC]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTaskFiles()
{
return $this->hasMany(CmsTaskFile::className(), ['cms_task_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;
}
static public function statuses($status = null)
{
$data = [
self::STATUS_NEW => "Новая",
self::STATUS_ACCEPTED => "Принята",
self::STATUS_CANCELED => "Отменена",
self::STATUS_READY => "Готова",
self::STATUS_IN_WORK => "В работе",
self::STATUS_ON_CHECK => "На проверке",
self::STATUS_ON_PAUSE => "На паузе",
];
return ArrayHelper::getValue($data, $status, $data);
}
static public function statusesIcons($status = null)
{
$data = [
self::STATUS_NEW => "fas fa-plus",
self::STATUS_ACCEPTED => "fas fa-anchor",
self::STATUS_CANCELED => "fas fa-times-circle",
self::STATUS_READY => "fas fa-check",
self::STATUS_IN_WORK => "fas fa-play",
self::STATUS_ON_CHECK => "fas fa-user-check",
self::STATUS_ON_PAUSE => "fas fa-pause",
];
return ArrayHelper::getValue($data, $status, $data);
}
/**
* @param null $status
* @return string|array
*/
static public function statusesHints($status = null)
{
$data = [
self::STATUS_NEW => "Новая задача",
self::STATUS_ACCEPTED => "Задача закреплена за исполнителем",
self::STATUS_CANCELED => "Задача отменена",
self::STATUS_READY => "Задача готова",
self::STATUS_IN_WORK => "Задача сейчас в работе",
self::STATUS_ON_CHECK => "Задача на проверке у автора или ответственного менеджера",
self::STATUS_ON_PAUSE => "Задача на паузе",
];
return ArrayHelper::getValue($data, $status, $data);
}
/**
* @param null $status
* @return string|array
*/
static public function statusesFeatureHints($status = null)
{
$data = [
self::STATUS_NEW => "Новая задача",
self::STATUS_ACCEPTED => "Задача будет закреплена за исполнителем, и он сможет взять ее в работу",
self::STATUS_CANCELED => "Задача будет отменена",
self::STATUS_READY => "Задача будет готова",
self::STATUS_IN_WORK => "Начать работу по этой задаче. <br />Для этого вы должны быть включены в работу и у вас не должно быть запущено других задач",
self::STATUS_ON_CHECK => "Отправить задачу на проверку автору или ответственному менеджеру",
self::STATUS_ON_PAUSE => "Поставить задачу на паузу",
];
return ArrayHelper::getValue($data, $status, $data);
}
/**
* @return string
*/
public function getStatusAsFeatureHint()
{
return (string)self::statusesFeatureHints($this->status);
}
/**
* @return string
*/
public function getStatusAsHint()
{
return (string)self::statusesHints($this->status);
}
/**
* @param null $status
* @return string|array
*/
static public function statusesColors($status = null)
{
$data = [
self::STATUS_NEW => "g-bg-gray-light-v1",
self::STATUS_ACCEPTED => "u-btn-purple",
self::STATUS_CANCELED => "u-btn-darkred",
self::STATUS_READY => "u-btn-green",
self::STATUS_IN_WORK => "u-btn-teal",
self::STATUS_ON_CHECK => "u-btn-cyan",
self::STATUS_ON_PAUSE => "u-btn-orange",
];
return ArrayHelper::getValue($data, $status, $data);
}
/**
* @param null $status
* @return string|array
*/
static public function statusesSourceColors($status = null)
{
$data = [
self::STATUS_NEW => "#bbb",
self::STATUS_ACCEPTED => "#9a69cb",
self::STATUS_CANCELED => "u-btn-darkred",
self::STATUS_READY => "green",
self::STATUS_IN_WORK => "#18ba9b",
self::STATUS_ON_CHECK => "#00bed6",
self::STATUS_ON_PAUSE => "#e57d20",
];
return ArrayHelper::getValue($data, $status, $data);
}
/**
* @return string
*/
public function getStatusAsText()
{
return ArrayHelper::getValue(self::statuses(), $this->status);
}
/**
* @return string
*/
public function getStatusAsIcon()
{
return (string)ArrayHelper::getValue(self::statusesIcons(), $this->status);
}
/**
* @return string
*/
public function getStatusAsColor()
{
return (string)ArrayHelper::getValue(self::statusesColors(), $this->status);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsProject()
{
return $this->hasOne(CmsProject::class, ['id' => 'cms_project_id']);
}
/**
* @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(CmsCompany::class, ['id' => 'cms_user_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getExecutor()
{
return $this->hasOne(\Yii::$app->user->identityClass, ['id' => 'executor_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSchedules()
{
return $this->hasMany(CmsTaskSchedule::class, ['cms_task_id' => 'id'])->from(['schedules' => CmsTaskSchedule::tableName()]);;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSchedulesByDate($date = null)
{
if ($date === null) {
$date = \Yii::$app->formatter->asDate(time(), "php:Y-m-d");
}
return $this->getSchedules()->andWhere(['date' => $date]);
}
/**
* Не закрытый временной промежуток
*
* @return \yii\db\ActiveQuery
*/
public function getNotEndSchedule()
{
$query = $this->getSchedules()->andWhere(['end_time' => null]);
$query->multiple = false;
return $query;
}
/**
* Не закрытый временной промежуток сегодня
*
* @return \yii\db\ActiveQuery
*/
public function getNotEndScheduleByDate($date = null)
{
if ($date === null) {
$date = \Yii::$app->formatter->asDate(time(), "php:Y-m-d");
}
$query = $this->getSchedules()->andWhere(['end_time' => null])->andWhere(['date' => $date]);
$query->multiple = false;
return $query;
}
/**
* @return float|int
*/
public function getPlanDurationSeconds()
{
return $this->plan_duration * 60 * 60;
}
static public function recalculateTasksPriority(CmsUser $user, $sortTaskIds)
{
$currentUser = \Yii::$app->user->identity;
/**
* @var $task \skeeks\crm\models\CrmTask
*/
$scheduleTotalTime = CmsTaskSchedule::find()->select([
'SUM(end_at - start_at) as total_timestamp',
])->where([
'cms_task_id' => new \yii\db\Expression(CmsTask::tableName().".id"),
]);
$tasks = CmsTask::find()->select([
CmsTask::tableName().'.*',
'scheduleTotalTime' => $scheduleTotalTime,
'planTotalTime' => new \yii\db\Expression(CmsTask::tableName().".plan_duration"),
])->where([
'executor_id' => $user->id,
])->andWhere([
'status' => [
CmsTask::STATUS_NEW,
CmsTask::STATUS_IN_WORK,
CmsTask::STATUS_ON_PAUSE,
CmsTask::STATUS_ACCEPTED,
],
])->orderBy([
'executor_sort' => SORT_ASC,
'id' => SORT_DESC,
])
->all();
if ($sortTaskIds) {
$tasksTmp = [];
$tasks = ArrayHelper::map($tasks, 'id', function ($model) {
return $model;
});
foreach ($sortTaskIds as $id) {
if (isset($tasks[$id])) {
$tasksTmp[$id] = $tasks[$id];
unset($tasks[$id]);
}
}
$resultTasks = ArrayHelper::merge((array)$tasksTmp, (array)$tasks);
$tasks = $resultTasks;
/*print_r(array_keys($tasks));die;*/
}
$priority = 0;
$elseDayTime = 0;
for ($i = 0; $i <= 1000; $i++) {
$workShedule = $user->work_shedule;
$date = date("Y-m-d", strtotime("+{$i} day"));
$times = \skeeks\cms\helpers\CmsScheduleHelper::getSchedulesByWorktimeForDate($workShedule, $date);
if (!$times) {
continue;
}
$todayDate = \Yii::$app->formatter->asDate(time(), "php:Y-m-d");
//Тут отфильтровать время согласно текущему времени
if ($todayDate == $date) {
//$times = CrmScheduleHelper::getFilteredSchedulesByStartTime($times, \Yii::$app->formatter->asTime(time(), "php:H:i:s"));
$times = \skeeks\cms\helpers\CmsScheduleHelper::getFilteredSchedulesByStartTime($times);
}
if (!$times) {
continue;
}
if (!$tasks) {
break;
}
foreach ($times as $period)
{
$periodDuration = CmsScheduleHelper::durationBySchedules([$period]);
$peroidTime = $periodDuration + $elseDayTime;
if ($tasks) {
$elseTime = 0;
foreach ($tasks as $key => $task) {
$priority++;
//время по плану на задачу минус то что уже отработано по задаче
$time = $task->raw_row['planTotalTime'] - $task->raw_row['scheduleTotalTime'];
if ($time < 0) {
$time = 0;
}
$elseTime = $time + $elseTime;
$peroidTime = $peroidTime - $time;
$task->executor_sort = $priority;
$task->executor_end_at = $period->start_at + $elseTime;
$task->save();
/*echo "$key\n";*/
unset($tasks[$key]);
if ($peroidTime <= 0) {
$elseDayTime = $peroidTime;
break;
}
}
} else {
break;
}
}
}
//Если приоритет задач обновил другой пользователь, то уведомим исполнителя
if ($currentUser != $user) {
$notify = new CmsWebNotify();
$notify->cms_user_id = $user->id;
$notify->name = $currentUser->asText . " поменял(а) порядок ваших задач.";
$notify->model_id = $user->id;
$notify->model_code = $user->skeeksModelCode;
$notify->save();
}
return true;
}
/**
* @return CmsTaskQuery
*/
public static function find()
{
return new CmsTaskQuery(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/CmsDashboardWidget.php | src/models/CmsDashboardWidget.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\models\behaviors\Serialize;
use skeeks\cms\modules\admin\base\AdminDashboardWidget;
use Yii;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%cms_dashboard_widget}}".
*
* @property integer $id
* @property integer $created_by
* @property integer $updated_by
* @property integer $created_at
* @property integer $updated_at
* @property integer $cms_dashboard_id
* @property integer $priority
* @property string $component
* @property string $component_settings
* @property string $cms_dashboard_column
*
*
* @property string $name
*
* @property CmsDashboard $cmsDashboard
*
* @property AdminDashboardWidget $widget
*/
class CmsDashboardWidget extends \skeeks\cms\models\Core
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_dashboard_widget}}';
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
Serialize::className() =>
[
'class' => Serialize::className(),
'fields' => ['component_settings']
]
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['created_by', 'updated_by', 'created_at', 'updated_at', 'cms_dashboard_id', 'priority'], 'integer'],
[['cms_dashboard_id', 'component'], 'required'],
[['component_settings'], 'safe'],
[['component'], 'string', 'max' => 255],
[['cms_dashboard_column'], 'integer', 'max' => 6, 'min' => 1],
[['cms_dashboard_column'], 'default', 'value' => 1],
[['priority'], 'default', 'value' => 50],
];
}
/**
* @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'),
'cms_dashboard_id' => Yii::t('skeeks/cms', 'Cms Dashboard ID'),
'priority' => Yii::t('skeeks/cms', 'Priority'),
'component' => Yii::t('skeeks/cms', 'Component'),
'component_settings' => Yii::t('skeeks/cms', 'Component Settings'),
'cms_dashboard_column' => Yii::t('skeeks/cms', 'cms_dashboard_column'),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsDashboard()
{
return $this->hasOne(CmsDashboard::className(), ['id' => 'cms_dashboard_id']);
}
/**
* @return AdminDashboardWidget
* @throws \yii\base\InvalidConfigException
*/
public function getWidget()
{
if ($this->component) {
if (class_exists($this->component)) {
/**
* @var $component AdminDashboardWidget
*/
$component = \Yii::createObject($this->component);
$component->load($this->component_settings, "");
return $component;
}
}
return null;
}
/**
* @return string
*/
public function getName()
{
if ($this->widget) {
if ($this->widget->getAttributes(['name'])) {
return (string)$this->widget->name;
}
}
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/models/CmsUserAddress.php | src/models/CmsUserAddress.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\models\behaviors\HasStorageFile;
use skeeks\cms\models\behaviors\traits\HasLogTrait;
use Yii;
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|null $name Название адреса (необязательное)
* @property string $value Полный адрес
* @property float $latitude
* @property float $longitude
* @property string $entrance Подъезд
* @property string $floor Этаж
* @property string $apartment_number Номер квартиры
* @property string $comment
* @property int|null $cms_image_id
* @property int $priority
*
* @property CmsSite $cmsSite
* @property CmsUser $cmsUser
*/
class CmsUserAddress extends ActiveRecord
{
use HasLogTrait;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_user_address}}';
}
/**
* @return array
*/
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
HasStorageFile::class => [
'class' => HasStorageFile::class,
'fields' => ['cms_image_id'],
],
CmsLogBehavior::class => [
'class' => CmsLogBehavior::class,
'parent_relation' => 'cmsUser',
],
]);
}
/**
* @return \skeeks\cms\query\CmsActiveQuery
*/
/*public static function find()
{
return parent::find()->cmsSite();
}*/
/**
* @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;
}
},
],
[['name'], 'default', 'value' => null],
[['latitude', 'longitude'], 'number'],
[
[
'created_by',
'updated_by',
'created_at',
'updated_at',
'cms_site_id',
'cms_user_id',
'priority',
],
'integer',
],
[
[
'floor',
'apartment_number',
'entrance',
],
'string',
],
[['cms_user_id', 'value'], 'required'],
[['comment', 'name', 'value'], 'string', 'max' => 255],
[['cms_image_id'], 'safe'],
[['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']],
[['cms_user_id', 'name'], 'unique', 'targetAttribute' => ['cms_user_id', 'value'], 'message' => 'Уже есть адрес с таким названием'],
//[['cms_user_id', 'value'], 'unique', 'targetAttribute' => ['cms_user_id', 'value'], 'message' => 'Этот телефон уже занят'],
[
[
'value',
'floor',
'apartment_number',
'entrance',
],
"filter",
'filter' => 'trim',
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'cms_user_id' => Yii::t('skeeks/cms', 'User'),
'name' => "Название",
'value' => "Адрес",
'latitude' => "Широта",
'longitude' => "Долгота",
'entrance' => "Подъезд",
'floor' => "Этаж",
'apartment_number' => "Номер квартиры",
'comment' => "Комментарий",
'cms_image_id' => "Фото",
'priority' => "Сортировка",
]);
}
/**
* @return string
*/
public function getCoordinates()
{
if (!$this->latitude || !$this->longitude) {
return '';
}
return $this->latitude.",".$this->longitude;
}
/**
* @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']);
}
/**
* Gets query for [[CmsSite]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsSite()
{
return $this->hasOne(CmsSite::className(), ['id' => 'cms_site_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/CmsUserSchedule.php | src/models/CmsUserSchedule.php | <?php
namespace skeeks\cms\models;
use common\models\User;
use skeeks\cms\helpers\CmsScheduleHelper;
use skeeks\cms\models\queries\CmsUserScheduleQuery;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%crm_schedule}}".
*
* @property int $id
* @property int $cms_user_id Пользователь
* @property int $start_at Начало работы
* @property int|null $end_at Завершение работы
*
* @property CmsUser|User $cmsUser
*
* @property int $duration Продолжительность промежутка в понятном написании
* @property string $durationAsText Продолжительность промежутка в понятном написании
*/
class CmsUserSchedule extends \skeeks\cms\base\ActiveRecord
//implements CrmScheduleInterface
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_user_schedule}}';
}
public function init()
{
parent::init();
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['cms_user_id', 'start_at'], 'required'],
[['cms_user_id'], 'integer'],
[['end_at'], 'safe'],
[['cms_user_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::class, 'targetAttribute' => ['cms_user_id' => 'id']],
[
['end_at'],
function () {
if ($this->end_at && $this->start_at >= $this->end_at) {
$this->addError('end_at', 'Время начала работы должно быть меньше времени завершения.');
return false;
}
if ($this->cmsUser->getExecutorTasks()->statusInWork()->one()) {
$this->addError('end_at', 'Для завершения работы, необходимо остановить задачу.');
return false;
}
//Ищем логи рабочего времени по задачам
/*if ($crmSchedules = static::find()->user($this->user)
->andWhere(['>=', 'end_at', $this->end_at])
->all()
) {
$this->addError('end_at', 'В этом временном промежутке у вас были запущены задачи: '.
implode(",", ArrayHelper::map($crmSchedules, 'crm_task_id', 'crm_task_id'))
);
return false;
}*/
},
],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'cms_user_id' => 'Пользователь',
'start_at' => 'Начало работы',
'end_at' => 'Завершение работы',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsUser()
{
return $this->hasOne(\Yii::$app->user->identityClass, ['id' => 'cms_user_id']);
}
/**
* @return CmsUserScheduleQuery
*/
public static function find()
{
return new CmsUserScheduleQuery(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/CmsContentElement.php | src/models/CmsContentElement.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 19.05.2015
*/
namespace skeeks\cms\models;
use skeeks\cms\behaviors\CmsLogBehavior;
use skeeks\cms\components\Cms;
use skeeks\cms\components\urlRules\UrlRuleContentElement;
use skeeks\cms\models\behaviors\HasMultiLangAndSiteFields;
use skeeks\cms\models\behaviors\HasRelatedProperties;
use skeeks\cms\models\behaviors\HasStatus;
use skeeks\cms\models\behaviors\HasStorageFile;
use skeeks\cms\models\behaviors\HasStorageFileMulti;
use skeeks\cms\models\behaviors\HasTrees;
use skeeks\cms\models\behaviors\TimestampPublishedBehavior;
use skeeks\cms\models\behaviors\traits\HasLogTrait;
use skeeks\cms\models\behaviors\traits\HasRelatedPropertiesTrait;
use skeeks\cms\models\behaviors\traits\HasTreesTrait;
use skeeks\cms\models\behaviors\traits\HasUrlTrait;
use skeeks\cms\query\CmsContentElementActiveQuery;
use skeeks\cms\relatedProperties\models\RelatedElementModel;
use skeeks\yii2\yaslug\YaSlugBehavior;
use Yii;
use yii\base\Exception;
use yii\caching\TagDependency;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Application;
/**
* This is the model class for table "{{%cms_content_element}}".
*
* @property integer $id
* @property integer $created_by
* @property integer $updated_by
* @property integer $created_at
* @property integer $updated_at
* @property integer $published_at
* @property integer $published_to
* @property integer $priority
* @property string $active
* @property string $name
* @property string $code
* @property string $description_short
* @property string $description_full
* @property integer $content_id
* @property integer $image_id
* @property integer $image_full_id
* @property integer $tree_id
* @property integer $show_counter
* @property integer $show_counter_start
* @property string $meta_title
* @property string $meta_description
* @property string $meta_keywords
* @property string $seo_h1
* @property integer|null $cms_site_id
*
* @property string|null $external_id
* @property integer|null $main_cce_id
* @property integer|null $main_cce_at
* @property integer|null $main_cce_by
*
* @property integer|null $sx_id
*
* @property integer|null $shop_is_brand
* @property integer|null $shop_is_collection
* @property integer|null $shop_is_ccountry
*
* @property bool $is_active
* @property bool $is_adult
*
* @property integer $parent_content_element_id version > 2.4.8
*
*
* @property string $permissionName
*
* @property string $description_short_type
* @property string $description_full_type
*
* @property string $absoluteUrl
* @property string $url
*
* @property CmsContent $cmsContent
* @property Tree $cmsTree
* @property CmsSite $cmsSite
* @property CmsContentElementProperty[] $relatedElementProperties
* @property CmsContentProperty[] $relatedProperties
* @property CmsContentElementTree[] $cmsContentElementTrees
* @property CmsContentElementProperty[] $cmsContentElementProperties
* @property CmsContentElementProperty[] $cmsContentElementPropertyValues
* @property CmsContentProperty[] $cmsContentProperties
* @property CmsFaq[] $cmsFaqs
*
* @property CmsStorageFile $image
* @property CmsStorageFile $fullImage
*
* @property CmsContentElementFile[] $cmsContentElementFiles
* @property CmsContentElementImage[] $cmsContentElementImages
*
* @property CmsStorageFile[] $files
* @property CmsStorageFile[] $images
*
* @property bool $isAllowIndex
* @version > 2.4.8
* @property CmsContentElement $parentContentElement
* @property CmsContentElement[] $childrenContentElements
*
* @property CmsContentElement2cmsUser[] $cmsContentElement2cmsUsers
* @property CmsUser[] $usersToFavorites
* @property string $seoName
*
* @property CmsContentElement $mainCmsContentElement
*
*/
class CmsContentElement extends RelatedElementModel
{
use HasRelatedPropertiesTrait;
use HasTreesTrait;
use HasUrlTrait;
use HasLogTrait;
protected $_image_ids = null;
protected $_file_ids = null;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_content_element}}';
}
public function init()
{
parent::init();
if (\Yii::$app->skeeks->site) {
$this->cms_site_id = \Yii::$app->skeeks->site->id;
}
$this->on(self::EVENT_BEFORE_DELETE, [$this, '_beforeDeleteE']);
$this->on(self::EVENT_AFTER_DELETE, [$this, '_afterDeleteE']);
$this->on(self::EVENT_BEFORE_INSERT, [$this, "_beforeSaveEvent"]);
$this->on(self::EVENT_BEFORE_UPDATE, [$this, "_beforeSaveEvent"]);
}
/**
* Перед сохранением модели, всегда следим за типом товара
* @param $event
*/
public function _beforeSaveEvent($event)
{
if ($this->isAttributeChanged('main_cce_id')) {
if ($this->main_cce_id) {
$this->main_cce_at = time();
if (isset(\Yii::$app->user) && !\Yii::$app->user->isGuest) {
$this->main_cce_by = \Yii::$app->user->id;
} else {
$this->main_cce_by = null;
}
} else {
$this->main_cce_id = null;
$this->main_cce_by = null;
}
}
}
public function _beforeDeleteE($e)
{
//Если есть дочерние элементы
if ($this->childrenContentElements) {
//Удалить все дочерние элементы
if ($this->cmsContent->parent_content_on_delete == CmsContent::CASCADE) {
foreach ($this->childrenContentElements as $childrenElement) {
$childrenElement->delete();
}
}
if ($this->cmsContent->parent_content_on_delete == CmsContent::RESTRICT) {
throw new Exception("Для начала необходимо удалить вложенные элементы");
}
if ($this->cmsContent->parent_content_on_delete == CmsContent::SET_NULL) {
foreach ($this->childrenContentElements as $childrenElement) {
$childrenElement->parent_content_element_id = null;
$childrenElement->save();
}
}
}
}
public function _afterDeleteE($e)
{
if ($permission = \Yii::$app->authManager->getPermission($this->permissionName)) {
\Yii::$app->authManager->remove($permission);
}
}
/**
* @return array
*/
public function behaviors()
{
return array_merge(parent::behaviors(), [
TimestampPublishedBehavior::className() => TimestampPublishedBehavior::className(),
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' => CmsContentElementProperty::className(),
'relatedPropertyClassName' => CmsContentProperty::className(),
],
HasTrees::className() => [
'class' => HasTrees::className(),
],
YaSlugBehavior::class => [
'class' => YaSlugBehavior::class,
'attribute' => 'seoName',
'slugAttribute' => 'code',
'ensureUnique' => false,
'maxLength' => \Yii::$app->cms->element_max_code_length,
],
CmsLogBehavior::class => [
'class' => CmsLogBehavior::class,
'no_log_fields' => [
'description_short_type',
'description_full_type',
'show_counter',
],
'relation_map' => [
'content_id' => 'cmsContent',
'tree_id' => 'cmsTree',
],
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'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'),
'code' => Yii::t('skeeks/cms', 'Code'),
'description_short' => Yii::t('skeeks/cms', 'Description Short'),
'description_full' => Yii::t('skeeks/cms', 'Description Full'),
'content_id' => Yii::t('skeeks/cms', 'Content'),
'tree_id' => Yii::t('skeeks/cms', 'The main section'),
'show_counter' => Yii::t('skeeks/cms', 'Количество просмотров'),
'show_counter_start' => Yii::t('skeeks/cms', 'Show Counter Start'),
'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_type' => Yii::t('skeeks/cms', 'Description Short Type'),
'description_full_type' => Yii::t('skeeks/cms', 'Description Full Type'),
'image_id' => Yii::t('skeeks/cms', 'Main Image'),
'image_full_id' => Yii::t('skeeks/cms', 'Main Image'),
'imageIds' => Yii::t('skeeks/cms', 'Images'),
'fileIds' => Yii::t('skeeks/cms', 'Files'),
'images' => Yii::t('skeeks/cms', 'Images'),
'files' => Yii::t('skeeks/cms', 'Files'),
'treeIds' => Yii::t('skeeks/cms', 'Additional sections'),
'parent_content_element_id' => Yii::t('skeeks/cms', 'Parent element'),
'show_counter' => Yii::t('skeeks/cms', 'Количество просмотров'),
'seo_h1' => Yii::t('skeeks/cms', 'SEO заголовок h1'),
'external_id' => Yii::t('skeeks/cms', 'Уникальный код'),
'main_cce_id' => Yii::t('skeeks/cms', 'Инфо карточка'),
'sx_id' => Yii::t('skeeks/cms', 'SkeekS Suppliers ID'),
'is_adult' => Yii::t('skeeks/cms', 'Контент для взрослых?'),
]);
}
/**
* @inheritdoc
*/
public function attributeHints()
{
return array_merge(parent::attributeHints(), [
'treeIds' => Yii::t('skeeks/cms', 'You can specify some additional sections that will show your records.'),
'seo_h1' => 'Заголовок будет показан на детальной странице, в случае если его использование задано в шаблоне.',
'external_id' => Yii::t('skeeks/cms', 'Обычно заполняется если этот элемент выгружается из какой-либо внешней системы'),
'is_adult' => Yii::t('skeeks/cms', 'Если эта страница содержит контент для взрослых, то есть имеет возрастные ограничения 18+ нужно поставить эту галочку!'),
'active' => Yii::t('skeeks/cms', 'Если эта галочка не стоит, то контент не показывается и не индексируется поисковыми системами'),
'priority' => Yii::t('skeeks/cms', 'В некоторых блоках сортировка товаров производится согласно значению в этмо поле'),
'show_counter' => Yii::t('skeeks/cms', 'Количество просмотров, от этого зависит популярность товара. По умолчанию чем популярнее товар, тем он выше в списке, в разделе.'),
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[
[
'created_by',
'updated_by',
'created_at',
'updated_at',
'published_at',
'published_to',
'priority',
'content_id',
'tree_id',
'show_counter',
'cms_site_id',
'show_counter_start',
'main_cce_id',
'main_cce_at',
'main_cce_by',
'is_adult',
'sx_id',
],
'integer',
],
[['name'], 'required'],
[['name'], 'trim'],
[['description_short', 'description_full'], 'string'],
[['active'], 'string', 'max' => 1],
[['name', 'code'], 'string', 'max' => 255],
[['seo_h1'], 'string', 'max' => 255],
[['external_id'], 'trim'],
[['external_id'], 'string', 'max' => 255],
[['external_id'], 'default', 'value' => null],
/*[
['content_id', 'code'],
'unique',
'targetAttribute' => ['content_id', 'code'],
'message' => \Yii::t('skeeks/cms', 'For the content of this code is already in use.'),
],
[
['tree_id', 'code'],
'unique',
'targetAttribute' => ['tree_id', 'code'],
'message' => \Yii::t('skeeks/cms', 'For this section of the code is already in use.'),
],*/
[['treeIds'], 'safe'],
['priority', 'default', 'value' => 500],
['active', 'default', 'value' => Cms::BOOL_Y],
[['meta_title', 'meta_description', 'meta_keywords'], 'string'],
[['meta_title', 'meta_description', 'meta_keywords', 'seo_h1'], 'default', 'value' => ''],
[['meta_title'], 'string', 'max' => 500],
['description_short_type', 'string'],
['description_full_type', 'string'],
['description_short_type', 'default', 'value' => "text"],
['description_full_type', 'default', 'value' => "text"],
['main_cce_id', 'default', 'value' => null],
['sx_id', 'default', 'value' => null],
[
['main_cce_at'],
'default',
'value' => function () {
if ($this->main_cce_id) {
return time();
}
return null;
},
],
[
['main_cce_by'],
'default',
'value' => function () {
if ($this->main_cce_id) {
if (isset(\Yii::$app->user) && !\Yii::$app->user->isGuest) {
return \Yii::$app->user->id;
}
}
return null;
},
],
[
'tree_id',
'default',
'value' => function () {
if ($this->cmsContent->defaultTree) {
return $this->cmsContent->defaultTree->id;
}
},
],
[
'cms_site_id',
'default',
'value' => function () {
if (\Yii::$app->skeeks->site) {
return \Yii::$app->skeeks->site->id;
}
},
],
[['image_id', 'image_full_id'], 'safe'],
[
['image_id', 'image_full_id'],
\skeeks\cms\validators\FileValidator::class,
'skipOnEmpty' => true,
'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'],
'maxFiles' => 1,
'maxSize' => 1024 * 1024 * 15,
'minSize' => 256,
],
[['imageIds', 'fileIds'], 'safe'],
[
['imageIds'],
\skeeks\cms\validators\FileValidator::class,
'skipOnEmpty' => false,
'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'],
'maxFiles' => 100,
'maxSize' => 1024 * 1024 * 15,
'minSize' => 256,
],
[
['fileIds'],
\skeeks\cms\validators\FileValidator::class,
'skipOnEmpty' => false,
//'extensions' => [''],
'maxFiles' => 50,
'maxSize' => 1024 * 1024 * 50,
'minSize' => 256,
],
['parent_content_element_id', 'integer'],
['parent_content_element_id', 'validateParentContentElement'],
[
'parent_content_element_id',
'required',
'when' => function (CmsContentElement $model) {
if ($model->cmsContent && $model->cmsContent->parentContent) {
return (bool)($model->cmsContent->is_parent_content_required);
}
return false;
},
'whenClient' => "function (attribute, value) {
return $('#cmscontent-is_parent_content_required').val() == '1';
}",
],
[
['cms_site_id', 'external_id', 'content_id'],
'unique',
'targetAttribute' => ['cms_site_id', 'external_id', 'content_id'],
'when' => function (CmsContentElement $model) {
return (bool)$model->external_id;
},
],
[
['tree_id', 'cms_site_id'],
function ($attribute) {
if ($this->cmsTree && $this->cmsSite) {
if ($this->cmsSite->id != $this->cmsTree->cms_site_id) {
$this->addError($attribute, "Раздел к которому привязывается элемент должен относится к тому же сайту");
}
}
},
],
[
['tree_id'],
function ($attribute) {
if ($this->cmsTree && $this->cmsContent->cms_tree_type_id) {
if ($this->cmsTree->tree_type_id != $this->cmsContent->cms_tree_type_id) {
$typeName = $this->cmsContent->cmsTreeType->asText;
$this->addError($attribute, "Нельзя привязать к этому разделу. Разрешено привязывать к разделам у которых тип '{$typeName}'");
return false;
}
}
},
],
[
"tree_id",
"required",
'when' => function (self $model) {
if ($model->cmsContent && $model->cmsContent->is_tree_required) {
return true;
}
return false;
},
],
]);
}
/**
* Валидация родительского элемента
*
* @param $attribute
* @return bool
*/
public function validateParentContentElement($attribute)
{
if (!$this->cmsContent) {
return false;
}
if (!$this->cmsContent->parentContent) {
return false;
}
if ($this->$attribute) {
$contentElement = static::findOne($this->$attribute);
if ($contentElement->cmsContent->id != $this->cmsContent->parentContent->id) {
$this->addError($attribute,
\Yii::t('skeeks/cms', 'The parent must be a content element: «{contentName}».',
['contentName' => $this->cmsContent->parentContent->name]));
}
}
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContent()
{
return $this->hasOne(CmsContent::className(), ['id' => 'content_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTree()
{
return $this->hasOne(CmsTree::className(), ['id' => 'tree_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsSite()
{
$class = \Yii::$app->skeeks->siteClass;
return $this->hasOne($class, ['id' => 'cms_site_id']);
}
static public $_contents = [];
static public $_relatedProperties = [];
/**
* Все возможные свойства связанные с моделью
* @return CmsContentProperty[]
*/
public function getRelatedProperties()
{
$siteId = $this->cms_site_id ? $this->cms_site_id : 0;
$contentId = $this->content_id ? $this->content_id : 0;
$treeId = $this->tree_id ? $this->tree_id : 0;
$cacheKey = "{$siteId}-{$contentId}-{$treeId}";
/*if (\Yii::$app->request->post()) {
print_r($cacheKey);
}*/
/*echo $cacheKey;
echo "<br>";*/
if (isset(self::$_relatedProperties[$cacheKey])) {
/*print_r(self::$_relatedProperties[$cacheKey]);die;*/
return self::$_relatedProperties[$cacheKey];
}
/**
* @var $cmsContent CmsContent
*/
//return $this->treeType->getCmsTreeTypeProperties();
if (isset(self::$_contents[$this->content_id])) {
$cmsContent = self::$_contents[$this->content_id];
} else {
self::$_contents[$this->content_id] = $this->cmsContent;
$cmsContent = self::$_contents[$this->content_id];
}
$q = $cmsContent->getCmsContentProperties()
->groupBy(\skeeks\cms\models\CmsContentProperty::tableName().".id");
if ($treeId) {
$q->joinWith('cmsContentProperty2trees as map2trees');
$q->andWhere([
'or',
['map2trees.cms_tree_id' => $treeId],
['map2trees.cms_tree_id' => null],
]);
} else {
$q->joinWith('cmsContentProperty2trees as map2trees');
$q->andWhere(
['map2trees.cms_tree_id' => null]
);
}
if ($this->cms_site_id) {
$q->andWhere([
'or',
[CmsContentProperty::tableName().'.cms_site_id' => null],
[CmsContentProperty::tableName().'.cms_site_id' => $this->cms_site_id],
]);
}
$q->orderBy(['priority' => SORT_ASC]);
/*if (\Yii::$app->request->post()) {
print_r($q->createCommand()->rawSql);
}*/
/*if (YII_ENV_DEV) {
print_r($this->toArray());die;
var_dump($treeId);die;
print_r($q->createCommand()->rawSql);die;
}*/
$result = $q->all();
self::$_relatedProperties[$cacheKey] = $result;
/*print_r(self::$_relatedProperties[$cacheKey]);
echo count(self::$_relatedProperties[$cacheKey]);
echo "------<br>";*/
//Память может переполниться...
if (count(self::$_relatedProperties[$cacheKey]) > 20) {
self::$_relatedProperties = [];
}
return $result;
return $q;
//return $this->cmsContent->getCmsContentProperties();
//return $this->cmsContent->getCmsContentProperties();
/*$query = $this->cmsContent->getCmsContentProperties();
$query->joinWith('cmsContentProperty2trees as map2trees')
->andWhere(['map2trees.cms_tree_id' => $this->treeIds])
;
$query->groupBy(CmsContentProperty::tableName() . ".id");
return $query;
$query = CmsContentProperty::find()
->from(CmsContentProperty::tableName() . ' AS property')
->joinWith('cmsContentProperty2contents as map2contents')
->joinWith('cmsContentProperty2trees as map2trees')
->andWhere(['map2contents.cms_content_id' => $this->content_id])
->all()
;*/
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentElementTrees()
{
return $this->hasMany(CmsContentElementTree::className(), ['element_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentElementProperties()
{
return $this->hasMany(CmsContentElementProperty::className(), ['element_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentProperties()
{
return $this->hasMany(CmsContentProperty::className(), ['id' => 'property_id'])
->via('cmsContentElementProperties');
}
/**
* Значения свойств
*
* @return \yii\db\ActiveQuery
*/
public function getCmsContentElementPropertyValues()
{
return $this->hasMany(CmsContentElementProperty::className(), ['value_element_id' => 'id'])->from(['values' => CmsContentElementProperty::tableName()]);
}
/**
* @return string
*/
public function getAbsoluteUrl($scheme = false, $params = [])
{
return $this->getUrl(true, $params);
}
/**
* @return string
*/
public function getUrl($scheme = false, $params = [])
{
//Это можно использовать только в коротких сценариях, иначе произойдет переполнение памяти
if (\Yii::$app instanceof Application) {
UrlRuleContentElement::$models[$this->id] = $this;
}
$isSavedFilter = false;
if ($savedFilterCmsTree = static::getContentMainTreeForSavedFilter($this->content_id)) {
$savedFilter = CmsSavedFilter::find()->cmsSite()
->andWhere([
'cms_tree_id' => $savedFilterCmsTree->id,
])
->andWhere([
'value_content_element_id' => $this->id,
])
->one();
if ($savedFilter) {
$isSavedFilter = true;
if ($params) {
$params = ArrayHelper::merge([
'/cms/saved-filter/view',
'model' => $savedFilter,
], $params);
} else {
$params = [
'/cms/saved-filter/view',
'model' => $savedFilter,
];
}
}
}
if ($isSavedFilter === false) {
if ($params) {
$params = ArrayHelper::merge(['/cms/content-element/view', 'id' => $this->id], $params);
} else {
$params = ['/cms/content-element/view', 'id' => $this->id];
}
}
return Url::to($params, $scheme);
}
static protected $_contentSavedFilter = [];
/**
* Главный раздел для посадочной страницы
* @param $content_id
* @return null|CmsTree
*/
static public function getContentMainTreeForSavedFilter($content_id)
{
$mainCmsTree = ArrayHelper::getValue(static::$_contentSavedFilter, $content_id, false);
if ($mainCmsTree === false) {
static::$_contentSavedFilter[$content_id] = null;
$dependencyContent = new TagDependency([
'tags' => [
(new CmsContent())->getTableCacheTag(),
],
]);
$cmsContent = CmsContent::getDb()->cache(function ($db) use ($content_id) {
return CmsContent::findOne($content_id);
}, null, $dependencyContent);
if ($cmsContent) {
if ($cmsContent->saved_filter_tree_type_id) {
$mainCmsTree = CmsTree::find()
->cmsSite()
->andWhere(['tree_type_id' => $cmsContent->saved_filter_tree_type_id])
->orderBy(['level' => SORT_ASC, 'priority' => SORT_ASC])
->limit(1)
->one();
static::$_contentSavedFilter[$content_id] = $mainCmsTree;
}
}
}
return static::$_contentSavedFilter[$content_id];
}
/**
* @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']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentElementFiles()
{
return $this->hasMany(CmsContentElementFile::className(), ['content_element_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsContentElementImages()
{
return $this->hasMany(CmsContentElementImage::className(), ['content_element_id' => 'id']);
}
/**
* @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 [];
}
/**
* @return \yii\db\ActiveQuery
*/
public function setImageIds($ids)
{
$this->_image_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 setFileIds($ids)
{
$this->_file_ids = $ids;
return $this;
}
/**
| 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/CmsUserProperty.php | src/models/CmsUserProperty.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 CmsContentProperty $property
* @property CmsContentElement $element
*/
class CmsUserProperty extends RelatedElementPropertyModel
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_user_property}}';
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProperty()
{
return $this->hasOne(CmsUserUniversalProperty::className(), ['id' => 'property_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getElement()
{
return $this->hasOne(CmsUser::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/CmsTreeType.php | src/models/CmsTreeType.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 22.05.2015
*/
namespace skeeks\cms\models;
use Yii;
/**
* This is the model class for table "{{%cms_tree_type}}".
*
* @property integer $id
* @property integer $created_by
* @property integer $updated_by
* @property integer $created_at
* @property integer $updated_at
* @property string $name
* @property string $code
* @property integer $is_active
* @property integer $priority
* @property string $description
*
* @property string|null $meta_title_template
* @property string|null $meta_description_template
* @property string|null $meta_keywords_template
*
* @property string $name_meny
* @property string $name_one
* @property string $viewFile
* @property integer $default_children_tree_type
*
* ***
*
* @property CmsTree[] $cmsTrees
* @property CmsTreeType $defaultChildrenTreeType
*
* @property CmsTreeType[] $cmsTreeTypes
* @property CmsTreeTypeProperty2type[] $cmsTreeTypeProperty2types
* @property CmsTreeTypeProperty[] $cmsTreeTypeProperties
*/
class CmsTreeType extends Core
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_tree_type}}';
}
/**
* @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'),
'name' => Yii::t('skeeks/cms', 'Name'),
'code' => Yii::t('skeeks/cms', 'Code'),
'is_active' => Yii::t('skeeks/cms', 'Active'),
'priority' => Yii::t('skeeks/cms', 'Priority'),
'description' => Yii::t('skeeks/cms', 'Description'),
'name_meny' => Yii::t('skeeks/cms', 'Name of many sections'),
'name_one' => Yii::t('skeeks/cms', 'Name of one section'),
'view_file' => Yii::t('skeeks/cms', 'Template'),
'default_children_tree_type' => Yii::t('skeeks/cms', 'Type of child partitions by default'),
'meta_title_template' => Yii::t('skeeks/cms', 'Шаблон meta title'),
'meta_description_template' => Yii::t('skeeks/cms', 'Шаблон meta description'),
'meta_keywords_template' => Yii::t('skeeks/cms', 'Шаблон meta keywords'),
]);
}
/**
* @inheritdoc
*/
public function attributeHints()
{
return array_merge(parent::attributeHints(), [
'code' => \Yii::t('skeeks/cms', 'The name of the template to draw the elements of this type will be the same as the name of the code.'),
'view_file' => \Yii::t('skeeks/cms', 'The path to the template. If not specified, the pattern will be the same code.'),
'default_children_tree_type' => \Yii::t('skeeks/cms', 'If this parameter is not specified, the child partition is created of the same type as the current one.'),
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[
['created_by', 'updated_by', 'created_at', 'updated_at', 'priority', 'default_children_tree_type', 'is_active'],
'integer',
],
[['name', 'code'], 'required'],
[['meta_title_template'], 'string'],
[['meta_description_template'], 'string'],
[['meta_keywords_template'], 'string'],
[[
'meta_title_template',
'meta_description_template',
'meta_keywords_template',
], 'default', 'value' => null],
[['description'], 'string'],
[['name', 'view_file'], 'string', 'max' => 255],
[['code'], 'string', 'max' => 50],
[['name_meny', 'name_one'], 'string', 'max' => 100],
[['code'], 'unique'],
[['code'], 'validateCode'],
['priority', 'default', 'value' => 500],
['name_meny', 'default', 'value' => \Yii::t('skeeks/cms', 'Sections')],
['name_one', 'default', 'value' => \Yii::t('skeeks/cms', 'Section')],
]);
}
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 getCmsTrees()
{
return $this->hasMany(CmsTree::className(), ['tree_type_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTreeTypeProperties()
{
/*$query = CmsTreeTypeProperty::find()->joinWith('cmsTreeTypeProperty2types as cmsTreeTypeProperty2types')->andWhere(['cmsTreeTypeProperty2types.cms_tree_type_id' => $this->id]);
$query->multiple = true;
return $query;*/
return $this->hasMany(CmsTreeTypeProperty::className(),
['id' => 'cms_tree_type_property_id'])->via('cmsTreeTypeProperty2types');
//return $this->hasMany(CmsTreeTypeProperty::className(), ['tree_type_id' => 'id'])->orderBy(['priority' => SORT_ASC]);;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getDefaultChildrenTreeType()
{
return $this->hasOne(CmsTreeType::className(), ['id' => 'default_children_tree_type']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTreeTypes()
{
return $this->hasMany(CmsTreeType::className(), ['default_children_tree_type' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTreeTypeProperty2types()
{
return $this->hasMany(CmsTreeTypeProperty2type::className(), ['cms_tree_type_id' => 'id']);
}
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/CmsCompany2user.php | src/models/CmsCompany2user.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 string|null $comment
* @property int $sort
* @property int $is_root
* @property int $is_notify
*
* @property CmsUser $cmsUser
* @property CmsCompany $cmsCompany
*/
class CmsCompany2user extends \skeeks\cms\base\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_company2user}}';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[['comment'], 'string'],
[['sort'], 'integer'],
[['is_root'], 'integer'],
[['is_notify'], 'integer'],
[['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(), [
'comment' => Yii::t('app', 'Комментарий'),
'cms_user_id' => Yii::t('app', 'Контрагент'),
'cms_company_id' => Yii::t('app', 'Компания'),
'is_root' => Yii::t('app', 'Есть доступ к компании'),
'is_notify' => Yii::t('app', 'Получать уведомления по компании'),
'sort' => Yii::t('app', 'Сортировка'),
]);
}
/**
* {@inheritdoc}
*/
public function attributeHints()
{
return ArrayHelper::merge(parent::attributeHints(), [
'comment' => Yii::t('app', 'Должность в компании или прочяя информация о клиенте'),
'is_root' => Yii::t('app', 'Опция открывает доступ к сделкам, документам, оплатам и услугам по этой компании'),
'is_notify' => Yii::t('app', 'Этот контакт участвует в получении уведомлений по данной компании'),
'sort' => Yii::t('app', 'Порядок сортировки контакта в компании, чем меньше цифра тем выше человек'),
]);
}
/**
* @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']);
}
public function asText()
{
return $this->cmsUser->shortDisplayName;
}
} | 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/CmsDeal.php | src/models/CmsDeal.php | <?php
namespace skeeks\cms\models;
use skeeks\cms\base\ActiveRecord;
use skeeks\cms\behaviors\CmsLogBehavior;
use skeeks\cms\models\behaviors\traits\HasLogTrait;
use skeeks\cms\models\queries\CmsDealQuery;
use skeeks\cms\money\models\MoneyCurrency;
use skeeks\cms\money\Money;
use skeeks\cms\shop\models\ShopBill;
use skeeks\cms\shop\models\ShopPayment;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "{{%crm_pact}}".
*
* @property int $id
* @property int $created_by
* @property int $created_at
* @property int $start_at Дата начала сделки
* @property int $end_at Дата завершения сделки
* @property int $cms_deal_type_id Тип сделки
* @property int $cms_company_id Компания
* @property int $cms_user_id Контакт
* @property string $name Название
* @property string $description
* @property string $amount Значение цены
* @property string $currency_code Валюта
* @property string $period Период действия для периодического договора
* @property int $is_active Активность
* @property int $is_periodic Конечная или периодичная услуга?
* @property int $is_auto Авто продление + уведомления
*
* @property MoneyCurrency $currencyCode
* @property CmsDealType $dealType
* @property CmsCompany $company
* @property CmsUser $user
* @property Money $money
*
* @property string $moneyAsText
* @property string $asShortText
*
* @property ShopPayment[] $payments
* @property ShopBill[] $bills
*
* @property bool $isEnded
*/
class CmsDeal extends ActiveRecord
{
use HasLogTrait;
/**
* @return string
*/
public function getAsShortText()
{
return "Сделка №{$this->id} «".$this->name."»";
}
/**
* Уведомить после создания?
* @var bool
*/
public $isCreateNotify = 0;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return '{{%cms_deal}}';
}
public function init()
{
parent::init();
$this->on(self::EVENT_AFTER_FIND, [$this, '_normalizeData']);
$this->on(self::EVENT_AFTER_INSERT, [$this, '_notifyCreate']);
$this->on(self::EVENT_BEFORE_DELETE, [$this, '_beforeDelete']);
}
public function _beforeDelete()
{
return true;
//TODO::доработать
if ($this->getCmsDeal2bills()->joinWith('bill as bill')->andWhere(['is not', 'bill.paid_at', null])->exists()) {
throw new Exception("Нельзя удалить эту сделку, потому что по ней есть оплаченные счета");
}
if ($bill2Deals = $this->getCmsDeal2bills()->all()) {
foreach ($bill2Deals as $bill2Deal) {
$bill2Deal->delete();
}
}
}
public function _normalizeData()
{
$this->amount = (float)$this->amount;
}
/**
* Уведомление о создании счета на оплату заказчику услуги
*/
public function _notifyCreate()
{
return true;
//TODO::доработать
if (!$this->isCreateNotify) {
return false;
}
$emails = [];
if ($this->executorCrmContractor->email) {
$emails[] = $this->executorCrmContractor->email;
}
if ($this->customerCrmContractor->email) {
$emails[] = $this->customerCrmContractor->email;
}
if ($emails) {
\Yii::$app->mailer->view->theme->pathMap['@app/mail'][] = '@skeeks/crm/mail';
\Yii::$app->mailer->compose('pact/created', [
'model' => $this,
])
->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName.''])
->setTo($emails)
->setSubject('Договор №'.$this->id." от ".\Yii::$app->formatter->asDate($this->created_at)." «{$this->name}»")
->send();
}
}
/**
* @return array
*/
public function behaviors()
{
return array_merge(parent::behaviors(), [
\skeeks\cms\behaviors\RelationalBehavior::class,
CmsLogBehavior::class => [
'class' => CmsLogBehavior::class,
'relation_map' => [
'cms_deal_type_id' => 'dealType',
],
],
]);
}
/**
* {@inheritdoc}
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[
[
'is_periodic',
'is_auto',
'created_by',
'created_at',
'start_at',
'end_at',
'cms_deal_type_id',
'cms_user_id',
'cms_company_id',
'is_active',
],
'integer',
],
[['cms_deal_type_id', 'name'], 'required'],
[['description'], 'string'],
[['amount'], 'number'],
[['name'], 'string', 'max' => 255],
[['currency_code'], 'string', 'max' => 3],
[['period'], 'string', 'max' => 10],
[['cms_deal_type_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsDealType::class, 'targetAttribute' => ['cms_deal_type_id' => 'id']],
[['currency_code'], 'exist', 'skipOnError' => true, 'targetClass' => MoneyCurrency::class, 'targetAttribute' => ['currency_code' => 'code']],
[['cms_company_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsCompany::class, 'targetAttribute' => ['cms_company_id' => 'id']],
[['cms_user_id'], 'exist', 'skipOnError' => true, 'targetClass' => CmsUser::class, 'targetAttribute' => ['cms_user_id' => 'id']],
[['period'], 'string'],
[['isCreateNotify'], 'integer'],
['start_at', 'default', 'value' => \Yii::$app->formatter->asTimestamp(time())],
[
'period',
function ($attribute) {
if ($this->is_periodic && !$this->period) {
$this->addError($attribute, 'Нужно заполнять для периодических сделок');
}
if (!$this->is_periodic && $this->period) {
$this->addError($attribute, 'Для разовых сделок заполнять не нужно: '.$this->period);
}
},
],
[
['cms_company_id'],
'required',
'when' => function () {
return !$this->cms_user_id;
},
],
[
['cms_user_id'],
'required',
'when' => function () {
return !$this->cms_company_id;
},
],
[
'is_periodic',
'default',
'value' => 0,
],
[
'period',
'default',
'value' => null,
],
[
['period'],
'required',
'when' => function () {
return $this->is_periodic;
},
],
[['bills'], 'safe'],
[['payments'], 'safe'],
]);
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'start_at' => 'Дата начала сделки',
'end_at' => 'Дата завершения сделки',
'cms_deal_type_id' => 'Тип сделки',
'cms_user_id' => "Клиент",
'cms_company_id' => 'Компания',
'name' => 'Название',
'description' => 'Комментарий',
'amount' => 'Сумма',
'currency_code' => 'Валюта',
'period' => 'Период действия для периодической сделки',
'is_active' => 'Активность',
'is_periodic' => 'Периодическая сделка?',
'payments' => 'Платежи',
'bills' => 'Счета',
'is_auto' => 'Авто продление + уведомления',
'isCreateNotify' => 'Уведомить после создания сделки?',
]);
}
/**
* @return string
*/
public function getPeriodAsText()
{
return (string)ArrayHelper::getValue(CmsDealType::optionsForPeriod(), $this->period);
}
/**
* {@inheritdoc}
*/
public function attributeHints()
{
return ArrayHelper::merge(parent::attributeHints(), [
'is_periodic' => 'Сделки бывают разовые или постоянные',
'period' => 'Период действия сделки',
'is_auto' => 'Если выбрано "да", то клиент будет получать уведомления перед завершением действия сделки.',
'start_at' => 'Если не заполнить, то поле будет заполнено текущим временем автоматически.',
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCurrencyCode()
{
return $this->hasOne(MoneyCurrency::class, ['code' => 'currency_code']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCompany()
{
return $this->hasOne(CmsCompany::class, ['id' => 'cms_company_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(CmsUser::class, ['id' => 'cms_user_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getDealType()
{
return $this->hasOne(CmsDealType::class, ['id' => 'cms_deal_type_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsDealType()
{
return $this->hasOne(CmsDealType::class, ['id' => 'cms_deal_type_id']);
}
/**
* @return Money
*/
public function getMoney()
{
return new Money($this->amount, $this->currency_code);
}
/**
* @return string
*/
public function asText()
{
$name = '';
if ($this->company) {
$name = $this->company->name;
} elseif ($this->user) {
$name = $this->user->shortDisplayName;
}
return $this->asShortText." ({$name})";
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCrmPayment2pacts()
{
return $this->hasMany(CrmPayment2pact::class, ['crm_deal_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCrmPayments()
{
return $this->hasMany(CrmPayment::class, ['id' => 'crm_payment_id'])
->viaTable(CrmPayment2pact::tableName(), ['crm_deal_id' => 'id']);
}
/**
* Услуга закончилась?
*
* @return bool
*/
public function getIsEnded()
{
return (\Yii::$app->formatter->asTimestamp(time()) > $this->end_at);
}
/**
*
* Создать счет для оплаты услуги
*
* @param null $period
* @return CrmBill
*/
public function createBill($period = null, $amount = null)
{
$bill = new CrmBill();
//$bill->description = "Оплата по договору: «" . $this->asText . "»";
$bill->crmDeals = [$this->id];
//$bill->sender_crm_contractor_id = $this->cms_company_id;
//Если заказчик Физ лицо то оплата через интернет-реквайринг
/*if ($this->customerCrmContractor->isIndividual) {
$bill->type = CrmBill::TYPE_INTERNET_ACQUIRING;
$bill->receiver_crm_contractor_id = CrmContractor::ID_TINKOFF;
} else {
throw new Exception('Не готово!');
//Если не физ лицо тогда банковский перевод
//$bill->type = CrmBill::TYPE_BANK_TRANSFER;
//$bill->receiver_crm_contractor_id = CrmContractor::ID_SEMENOV_IP;
$bill->type = CrmBill::TYPE_INTERNET_ACQUIRING;
$bill->receiver_crm_contractor_id = CrmContractor::ID_TINKOFF;
}*/
//Если услуга периодичная
if ($this->is_periodic) {
$period = (int)$period;
if (!$period) {
$period = 1;
}
if ($this->period == CrmService::PERIOD_MONTH) {
$bill->extend_pact_to = $this->end_at + (60 * 60 * 24 * 30 * $period);
}
if ($this->period == CrmService::PERIOD_YEAR) {
$bill->extend_pact_to = $this->end_at + (60 * 60 * 24 * 365 * $period);
}
$bill->amount = $this->amount * $period;
} else {
$bill->extend_pact_to = null;
$bill->amount = $this->amount;
}
return $bill;
}
public function notifyEnd($days = 15)
{
}
/**
* @return string
*/
public function getMoneyAsText()
{
return (string)$this->money.($this->is_periodic ? "/".\skeeks\cms\helpers\StringHelper::strtolower($this->periodAsText) : "");
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsDeal2bills()
{
return $this->hasMany(CmsDeal2bill::className(), ['shop_bill_id' => 'id']);
}
/**
* Gets query for [[CrmPayment2deals]].
*
* @return \yii\db\ActiveQuery
*/
public function getCmsDeal2payments()
{
return $this->hasMany(CmsDeal2payment::className(), ['shop_payment_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPayments()
{
return $this->hasMany(ShopPayment::class, ['id' => 'shop_payment_id'])
->viaTable(CmsDeal2payment::tableName(), ['cms_deal_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBills()
{
return $this->hasMany(ShopBill::class, ['id' => 'shop_bill_id'])
->viaTable(CmsDeal2bill::tableName(), ['cms_deal_id' => 'id']);
}
/**
* @return CmsUserQuery|\skeeks\cms\query\CmsActiveQuery
*/
public static function find()
{
return (new CmsDealQuery(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/CmsTreeTypePropertyEnum.php | src/models/CmsTreeTypePropertyEnum.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\RelatedPropertyEnumModel;
/**
* This is the model class for table "{{%cms_tree_type_property_enum}}".
* @property CmsTreeTypeProperty $property
*/
class CmsTreeTypePropertyEnum extends RelatedPropertyEnumModel
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_tree_type_property_enum}}';
}
/**
* @return array
*/
public function behaviors()
{
return array_merge(parent::behaviors(), []);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProperty()
{
return $this->hasOne(CmsTreeTypeProperty::className(), ['id' => 'property_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/CmsCountry.php | src/models/CmsCountry.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\models\behaviors\HasStorageFile;
use skeeks\cms\models\queries\CmsCountryQuery;
use Yii;
use yii\helpers\ArrayHelper;
/**
* @property integer $id
* @property string $name
* @property string $alpha2
* @property string $alpha3
* @property string $iso
* @property string|null $phone_code
* @property string|null $domain
* @property int|null $flag_image_id
*
* @property CmsStorageFile $flag
*/
class CmsCountry extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_country}}';
}
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
HasStorageFile::class => [
'class' => HasStorageFile::class,
'fields' => ['flag_image_id'],
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'name' => Yii::t('skeeks/cms', 'Name'),
'alpha2' => Yii::t('skeeks/cms', 'Код страны в двухбуквенном формате'),
'alpha3' => Yii::t('skeeks/cms', 'Код страны в трехбуквенном формате'),
'iso' => Yii::t('skeeks/cms', 'Цифровой код страны'),
'phone_code' => Yii::t('skeeks/cms', 'Телефонный код'),
'domain' => Yii::t('skeeks/cms', 'Главное доменное имя'),
'flag_image_id' => Yii::t('skeeks/cms', 'Флаг'),
]);
}
public function attributeHints()
{
return array_merge(parent::attributeLabels(), [
'alpha2' => "Код страны в формате ISO 3166-1 alpha-2. Пример RU",
'alpha3' => "Код страны в формате ISO 3166-1 alpha-3. Пример RUS",
'iso' => "Цифровой код. Пример 643",
'domain' => "Корневое доменное имя страны. Пример .ru",
'phone_code' => "Код телефона. Пример +7",
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[['flag_image_id'], 'safe'],
[
[
'name',
'alpha2',
'alpha3',
'iso',
],
'required',
],
[['name'], 'string', 'max' => 255],
[['alpha2'], 'string', 'max' => 2],
[['alpha3'], 'string', 'max' => 3],
[['iso'], 'string', 'max' => 3],
[['domain'], 'string', 'max' => 16],
[['phone_code'], 'string', 'max' => 16],
[
['flag_image_id'],
\skeeks\cms\validators\FileValidator::class,
'skipOnEmpty' => false,
'extensions' => ['jpg', 'jpeg', 'gif', 'png', 'webp'],
'maxFiles' => 1,
'maxSize' => 1024 * 1024 * 2,
'minSize' => 100,
],
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getFlag()
{
return $this->hasOne(CmsStorageFile::className(), ['id' => 'flag_image_id']);
}
/**
* @return CmsCountryQuery
*/
public static function find()
{
return (new CmsCountryQuery(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/CmsTreeTypeProperty2type.php | src/models/CmsTreeTypeProperty2type.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link https://skeeks.com/
* @copyright (c) 2010 SkeekS
* @date 15.05.2017
*/
namespace skeeks\cms\models;
/**
* This is the model class for table "cms_tree_type_property2type".
*
* @property integer $id
* @property integer $created_by
* @property integer $updated_by
* @property integer $created_at
* @property integer $updated_at
* @property integer $cms_tree_type_property_id
* @property integer $cms_tree_type_id
*
* @property CmsTreeTypeProperty $cmsTreeTypeProperty
* @property CmsTreeType $cmsTreeType
*/
class CmsTreeTypeProperty2type extends Core
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_tree_type_property2type}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
[
[
'created_by',
'updated_by',
'created_at',
'updated_at',
'cms_tree_type_property_id',
'cms_tree_type_id'
],
'integer'
],
[['cms_tree_type_property_id', 'cms_tree_type_id'], 'required'],
[
['cms_tree_type_property_id', 'cms_tree_type_id'],
'unique',
'targetAttribute' => ['cms_tree_type_property_id', 'cms_tree_type_id'],
'message' => 'The combination of Cms Tree Type Property ID and Cms Tree Type ID has already been taken.'
],
[
['cms_tree_type_property_id'],
'exist',
'skipOnError' => true,
'targetClass' => CmsTreeTypeProperty::className(),
'targetAttribute' => ['cms_tree_type_property_id' => 'id']
],
[
['cms_tree_type_id'],
'exist',
'skipOnError' => true,
'targetClass' => CmsTreeType::className(),
'targetAttribute' => ['cms_tree_type_id' => 'id']
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'id' => 'ID',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'cms_tree_type_property_id' => 'Cms Tree Type Property ID',
'cms_tree_type_id' => 'Cms Tree Type ID',
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTreeTypeProperty()
{
return $this->hasOne(CmsTreeTypeProperty::className(), ['id' => 'cms_tree_type_property_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTreeType()
{
return $this->hasOne(CmsTreeType::className(), ['id' => 'cms_tree_type_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/Search.php | src/models/Search.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 20.04.2015
*/
namespace skeeks\cms\models;
use yii\base\Component;
use yii\data\ActiveDataProvider;
use yii\db\ActiveRecord;
/**
* @property ActiveRecord $loadedModel
* @property ActiveDataProvider $dataProvider
*
* Class Search
* @package skeeks\cms\models
*/
class Search extends Component
{
/**
* @var null|string
*/
public $modelClassName = null;
/**
* @param array $modelClassName
*/
public function __construct($modelClassName)
{
$this->modelClassName = $modelClassName;
}
protected $_loadedModel = null;
protected $_dataProvider = null;
/**
* @return ActiveRecord
*/
public function getLoadedModel()
{
if ($this->_loadedModel === null) {
$className = $this->modelClassName;
$this->_loadedModel = new $className();
}
return $this->_loadedModel;
}
/**
* @return ActiveDataProvider
*/
public function getDataProvider()
{
if ($this->_dataProvider === null) {
$className = $this->modelClassName;
$this->_dataProvider = new ActiveDataProvider([
'query' => $className::find(),
]);
}
return $this->_dataProvider;
}
/**
* @param $params
* @return ActiveDataProvider
* @throws \yii\base\InvalidConfigException
*/
public function search($params)
{
if (!($this->loadedModel->load($params))) {
return $this->dataProvider;
}
$query = $this->dataProvider->query;
if ($columns = $this->loadedModel->getTableSchema()->columns) {
/**
* @var \yii\db\ColumnSchema $column
*/
foreach ($columns as $column) {
if ($column->phpType == "integer") {
$query->andFilterWhere([$this->loadedModel->tableName() . '.' . $column->name => $this->loadedModel->{$column->name}]);
} else {
if ($column->phpType == "string") {
$query->andFilterWhere([
'like',
$this->loadedModel->tableName() . '.' . $column->name,
$this->loadedModel->{$column->name}
]);
}
}
}
}
return $this->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/models/CmsContentPropertyEnum.php | src/models/CmsContentPropertyEnum.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (�����)
* @date 29.07.2016
*/
namespace skeeks\cms\models;
use skeeks\cms\models\behaviors\HasStorageFile;
use skeeks\cms\relatedProperties\models\RelatedPropertyEnumModel;
/**
* This is the model class for table "{{%cms_content_property_enum}}".
*
* @property string|null $value_for_saved_filter Название (для сохраненных фильтров)
* @property string|null $description Описание
* @property int|null $cms_image_id Фото/Изображение
* @property string|null $color цвет
* @property int|null $sx_id
*
* @property CmsStorageFile $cmsImage
*
* @property CmsContentProperty $property
*/
class CmsContentPropertyEnum extends RelatedPropertyEnumModel
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%cms_content_property_enum}}';
}
/**
* @return array
*/
public function behaviors()
{
return array_merge(parent::behaviors(), [
HasStorageFile::className() => [
'class' => HasStorageFile::className(),
'fields' => ['cms_image_id'],
],
]);
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'value_for_saved_filter' => 'Название (для сохраненных фильтров)',
'description' => 'Описание',
'cms_image_id' => 'Фото/Изображение',
'color' => 'Цвет',
'sx_id' => \Yii::t('skeeks/cms', 'SkeekS Suppliers ID'),
]);
}
/**
* @inheritdoc
*/
public function attributeHints()
{
return array_merge(parent::attributeHints(), [
'value_for_saved_filter' => 'Как будет склонятся или изменяться название в сохраненном фильтре.<br />Например:<br /> Если опция "зеленый", то фильтр "товары {зеленого цвета}"',
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[['color'], 'string'],
[['value_for_saved_filter'], 'string'],
[['sx_id'], 'integer'],
[['sx_id'], 'default', 'value' => null],
[['color'], 'default', 'value' => null],
[['description'], 'string'],
[['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,
],
]);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsImage()
{
return $this->hasOne(CmsStorageFile::className(), ['id' => 'cms_image_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProperty()
{
return $this->hasOne(CmsContentProperty::className(), ['id' => 'property_id']);
}
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/searchs/SearchRelatedPropertiesModel.php | src/models/searchs/SearchRelatedPropertiesModel.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 25.05.2015
*/
namespace skeeks\cms\models\searchs;
use skeeks\cms\models\CmsContent;
use skeeks\cms\models\CmsContentElement;
use skeeks\cms\models\CmsContentElementProperty;
use skeeks\cms\models\CmsContentProperty;
use skeeks\cms\relatedProperties\models\RelatedPropertyModel;
use yii\base\DynamicModel;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use yii\db\ActiveQueryInterface;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
/**
* Class SearchRelatedPropertiesModel
* @package skeeks\cms\models\searchs
*/
class SearchRelatedPropertiesModel extends DynamicModel
{
/**
* TODO: IS DEPRECATED > 3.0
* @var CmsContent
*/
public $cmsContent = null;
/**
* @var CmsContentProperty[]
*/
public $properties = [];
/**
* @var string
*/
public $propertyElementClassName = '\skeeks\cms\models\CmsContentElementProperty';
/**
* TODO: IS DEPRECATED > 3.0
* @param CmsContent $cmsContent
*/
public function initCmsContent(CmsContent $cmsContent)
{
$this->cmsContent = $cmsContent;
/**
* @var $prop CmsContentProperty
*/
if ($props = $this->cmsContent->cmsContentProperties) {
$this->initProperties($props);
}
}
public function initProperties($props = [])
{
foreach ($props as $prop) {
if ($prop->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_NUMBER) {
$this->defineAttribute($this->getAttributeNameRangeFrom($prop->code), '');
$this->defineAttribute($this->getAttributeNameRangeTo($prop->code), '');
$this->addRule([
$this->getAttributeNameRangeFrom($prop->code),
$this->getAttributeNameRangeTo($prop->code)
], "safe");
}
$this->defineAttribute($prop->code, "");
$this->addRule([$prop->code], "safe");
$this->properties[$prop->code] = $prop;
}
}
/**
* @param $code
* @return CmsContentProperty
*/
public function getProperty($code)
{
return ArrayHelper::getValue($this->properties, $code);
}
/**
* @return array
*/
public function attributeLabels()
{
$result = [];
foreach ($this->attributes() as $code) {
if ($property = $this->getProperty($code)) {
$result[$code] = $property->name;
} else {
$result[$code] = $code;
}
}
return $result;
}
public $prefixRange = "Sxrange";
/**
* @param $propertyCode
* @return string
*/
public function getAttributeNameRangeFrom($propertyCode)
{
return $propertyCode . $this->prefixRange . "From";
}
/**
* @param $propertyCode
* @return string
*/
public function getAttributeNameRangeTo($propertyCode)
{
return $propertyCode . $this->prefixRange . "To";
}
/**
* @param $propertyCode
* @return bool
*/
public function isAttributeRange($propertyCode)
{
if (strpos($propertyCode, $this->prefixRange)) {
return true;
}
return false;
}
/**
* @param ActiveDataProvider $activeDataProvider
*/
public function search(ActiveDataProvider $activeDataProvider, $tableName = 'cms_content_element')
{
$classSearch = $this->propertyElementClassName;
/**
* @var $activeQuery ActiveQuery
*/
$activeQuery = $activeDataProvider->query;
$elementIdsGlobal = [];
$applyFilters = false;
$unionQueries = [];
foreach ($this->toArray() as $propertyCode => $value) {
//TODO: add to validator related properties
if ($propertyCode == 'properties') {
continue;
}
if ($property = $this->getProperty($propertyCode)) {
if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_NUMBER) {
$elementIds = [];
$query = $classSearch::find()->select(['element_id as id'])->where([
"property_id" => $property->id
])->indexBy('element_id');
if ($fromValue = $this->{$this->getAttributeNameRangeFrom($propertyCode)}) {
$applyFilters = true;
$query->andWhere(['>=', 'value_num', (float)$fromValue]);
}
if ($toValue = $this->{$this->getAttributeNameRangeTo($propertyCode)}) {
$applyFilters = true;
$query->andWhere(['<=', 'value_num', (float)$toValue]);
}
if (!$fromValue && !$toValue) {
continue;
}
$unionQueries[] = $query;
//$elementIds = $query->all();
} else {
if (!$value) {
continue;
}
$applyFilters = true;
if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_STRING) {
$query = $classSearch::find()->select(['element_id as id'])
->where([
"property_id" => $property->id
])
->andWhere([
'like',
'value',
$value
]);
/*->indexBy('element_id')
->all();*/
$unionQueries[] = $query;
} else {
if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_BOOL) {
$query = $classSearch::find()->select(['element_id as id'])->where([
"value_bool" => $value,
"property_id" => $property->id
]);
//print_r($query->createCommand()->rawSql);die;
//$elementIds = $query->indexBy('element_id')->all();
$unionQueries[] = $query;
} else {
if (in_array($property->property_type, [
\skeeks\cms\relatedProperties\PropertyType::CODE_ELEMENT
,
\skeeks\cms\relatedProperties\PropertyType::CODE_LIST
,
\skeeks\cms\relatedProperties\PropertyType::CODE_TREE
])) {
$query = $classSearch::find()->select(['element_id as id'])->where([
"value_enum" => $value,
"property_id" => $property->id
]);
//print_r($query->createCommand()->rawSql);die;
//$elementIds = $query->indexBy('element_id')->all();
$unionQueries[] = $query;
} else {
$query = $classSearch::find()->select(['element_id as id'])->where([
"value" => $value,
"property_id" => $property->id
]);
//print_r($query->createCommand()->rawSql);die;
//$elementIds = $query->indexBy('element_id')->all();
$unionQueries[] = $query;
}
}
}
}
/*$elementIds = array_keys($elementIds);
\Yii::beginProfile('array_intersect');
if (!$elementIds)
{
$elementIdsGlobal = [];
}
if ($elementIdsGlobal)
{
$elementIdsGlobal = array_intersect($elementIds, $elementIdsGlobal);
} else
{
$elementIdsGlobal = $elementIds;
}
\Yii::endProfile('array_intersect');*/
}
}
if ($applyFilters) {
if ($unionQueries) {
/**
* @var $unionQuery ActiveQuery
*/
$lastQuery = null;
$unionQuery = null;
$unionQueriesStings = [];
foreach ($unionQueries as $query) {
if ($lastQuery) {
$lastQuery->andWhere(['in', 'element_id', $query]);
$lastQuery = $query;
continue;
}
if ($unionQuery === null) {
$unionQuery = $query;
} else {
$unionQuery->andWhere(['in', 'element_id', $query]);
$lastQuery = $query;
}
//$unionQueriesStings[] = $query->createCommand()->rawSql;
}
}
//print_r($unionQuery->createCommand()->rawSql);die;
//$activeQuery->andWhere(['in', $tableName . '.id', $unionQuery]);
//$activeQuery->union()
/*if ($unionQueriesStings)
{
$unionQueryStings = implode(" MINUS ", $unionQueriesStings);
}*/
$activeQuery->andWhere(['in', $tableName . '.id', $unionQuery]);
//print_r($unionQuery->createCommand()->rawSql);die;
//$activeQuery->andWhere($tableName . '.id in (' . new Expression($unionQuery) . ')');
//print_r($activeQuery->createCommand()->rawSql);die;
}
}
} | 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/searchs/SearchChildrenRelatedPropertiesModel.php | src/models/searchs/SearchChildrenRelatedPropertiesModel.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 25.05.2015
*/
namespace skeeks\cms\models\searchs;
use skeeks\cms\models\CmsContent;
use skeeks\cms\models\CmsContentElement;
use skeeks\cms\models\CmsContentElementProperty;
use skeeks\cms\models\CmsContentProperty;
use skeeks\cms\relatedProperties\models\RelatedPropertyModel;
use yii\base\DynamicModel;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use yii\db\ActiveQueryInterface;
use yii\helpers\ArrayHelper;
/**
* Class SearchRelatedPropertiesModel
* @package skeeks\cms\models\searchs
*/
class SearchChildrenRelatedPropertiesModel extends SearchRelatedPropertiesModel
{
/**
* @param ActiveDataProvider $activeDataProvider
*/
public function search(ActiveDataProvider $activeDataProvider, $tableName = 'cms_content_element')
{
$classSearch = $this->propertyElementClassName;
/**
* @var $activeQuery ActiveQuery
*/
$activeQuery = $activeDataProvider->query;
$elementIdsGlobal = [];
$applyFilters = false;
foreach ($this->toArray() as $propertyCode => $value) {
//TODO: add to validator related properties
if ($propertyCode == 'properties') {
continue;
}
if ($property = $this->getProperty($propertyCode)) {
if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_NUMBER) {
$elementIds = [];
$query = $classSearch::find()->select(['element_id'])->where([
"property_id" => $property->id
])->indexBy('element_id');
if ($fromValue = $this->{$this->getAttributeNameRangeFrom($propertyCode)}) {
$applyFilters = true;
$query->andWhere(['>=', 'value_num', (float)$fromValue]);
}
if ($toValue = $this->{$this->getAttributeNameRangeTo($propertyCode)}) {
$applyFilters = true;
$query->andWhere(['<=', 'value_num', (float)$toValue]);
}
if (!$fromValue && !$toValue) {
continue;
}
$elementIds = $query->all();
} else {
if (!$value) {
continue;
}
$applyFilters = true;
$elementIds = $classSearch::find()->select(['element_id'])->where([
"value" => $value,
"property_id" => $property->id
])->indexBy('element_id')->all();
}
$elementIds = array_keys($elementIds);
if ($elementIds) {
$realElements = CmsContentElement::find()->where(['id' => $elementIds])->select([
'id',
'parent_content_element_id'
])->indexBy('parent_content_element_id')->groupBy(['parent_content_element_id'])->asArray()->all();
$elementIds = array_keys($realElements);
}
if (!$elementIds) {
$elementIdsGlobal = [];
}
if ($elementIdsGlobal) {
$elementIdsGlobal = array_intersect($elementIds, $elementIdsGlobal);
} else {
$elementIdsGlobal = $elementIds;
}
}
}
if ($applyFilters) {
//$activeQuery->andWhere(['cms_content_element.id' => $elementIdsGlobal]);
$activeQuery->andWhere([$tableName . '.id' => $elementIdsGlobal]);
}
}
} | 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/searchs/CmsContentElementSearch.php | src/models/searchs/CmsContentElementSearch.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 19.05.2015
*/
namespace skeeks\cms\models\searchs;
use skeeks\cms\models\CmsContentElement;
use skeeks\cms\models\CmsContentElementTree;
use yii\data\ActiveDataProvider;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
class CmsContentElementSearch extends CmsContentElement
{
public $section;
public $created_at_from;
public $created_at_to;
public $updated_at_from;
public $updated_at_to;
public $published_at_from;
public $published_at_to;
public $has_image;
public $has_full_image;
public $q;
public function rules()
{
return ArrayHelper::merge(parent::rules(), [
['section', 'integer'],
['created_at_from', 'integer'],
['created_at_to', 'integer'],
['updated_at_from', 'integer'],
['updated_at_to', 'integer'],
['published_at_from', 'integer'],
['published_at_to', 'integer'],
['has_image', 'integer'],
['has_full_image', 'integer'],
['q', 'string'],
]);
}
public function attributeLabels()
{
return ArrayHelper::merge(parent::attributeLabels(), [
'section' => \Yii::t('skeeks/cms', 'Section'),
'created_at_from' => \Yii::t('skeeks/cms', 'Created date (from)'),
'created_at_to' => \Yii::t('skeeks/cms', 'Created (up to)'),
'updated_at_from' => \Yii::t('skeeks/cms', 'Updated time (from)'),
'updated_at_to' => \Yii::t('skeeks/cms', 'Updated time (up to)'),
'published_at_from' => \Yii::t('skeeks/cms', 'Time of publication (from)'),
'published_at_to' => \Yii::t('skeeks/cms', 'Time of publication (up to)'),
'has_image' => \Yii::t('skeeks/cms', 'Image'),
'has_full_image' => \Yii::t('skeeks/cms', 'The presence of such images'),
'q' => \Yii::t('skeeks/cms', 'Search'),
]);
}
public function search($params)
{
$tableName = $this->tableName();
$activeDataProvider = new ActiveDataProvider([
'query' => static::find()
]);
if (!($this->load($params))) {
return $activeDataProvider;
}
$query = $activeDataProvider->query;
//Standart
if ($columns = $this->getTableSchema()->columns) {
/**
* @var \yii\db\ColumnSchema $column
*/
foreach ($columns as $column) {
if ($column->phpType == "integer") {
$query->andFilterWhere([$this->tableName() . '.' . $column->name => $this->{$column->name}]);
} else {
if ($column->phpType == "string") {
$query->andFilterWhere([
'like',
$this->tableName() . '.' . $column->name,
$this->{$column->name}
]);
}
}
}
}
if ($this->section) {
$query->joinWith('cmsContentElementTrees');
$query->andFilterWhere([
'or',
[$this->tableName() . '.tree_id' => $this->section],
[CmsContentElementTree::tableName() . '.tree_id' => $this->section]
]);
}
if ($this->created_at_from) {
$query->andFilterWhere([
'>=',
$this->tableName() . '.created_at',
\Yii::$app->formatter->asTimestamp(strtotime($this->created_at_from))
]);
}
if ($this->created_at_to) {
$query->andFilterWhere([
'<=',
$this->tableName() . '.created_at',
\Yii::$app->formatter->asTimestamp(strtotime($this->created_at_to))
]);
}
if ($this->updated_at_from) {
$query->andFilterWhere([
'>=',
$this->tableName() . '.updated_at',
\Yii::$app->formatter->asTimestamp(strtotime($this->updated_at_from))
]);
}
if ($this->updated_at_to) {
$query->andFilterWhere([
'<=',
$this->tableName() . '.created_at',
\Yii::$app->formatter->asTimestamp(strtotime($this->updated_at_to))
]);
}
if ($this->published_at_from) {
$query->andFilterWhere([
'>=',
$this->tableName() . '.published_at',
\Yii::$app->formatter->asTimestamp(strtotime($this->published_at_from))
]);
}
if ($this->published_at_to) {
$query->andFilterWhere([
'<=',
$this->tableName() . '.published_at',
\Yii::$app->formatter->asTimestamp(strtotime($this->published_at_to))
]);
}
if ($this->has_image) {
$query->andFilterWhere([
'>',
$this->tableName() . '.image_id',
0
]);
}
if ($this->has_full_image) {
$query->andFilterWhere([
'>',
$this->tableName() . '.image_full_id',
0
]);
}
if ($this->q) {
$query->andFilterWhere([
'or',
['like', $this->tableName() . '.name', $this->q],
['like', $this->tableName() . '.description_full', $this->q],
['like', $this->tableName() . '.description_short', $this->q],
]);
}
return $activeDataProvider;
}
/**
* Returns the list of attribute names.
* By default, this method returns all public non-static properties of the class.
* You may override this method to change the default behavior.
* @return array list of attribute names.
*/
public function attributes()
{
$class = new \ReflectionClass($this);
$names = [];
foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
if (!$property->isStatic()) {
$names[] = $property->getName();
}
}
return ArrayHelper::merge(parent::attributes(), $names);
}
}
| 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/behaviors/HasRelatedProperties.php | src/models/behaviors/HasRelatedProperties.php | <?php
/**
* Наличие свойств в связанных таблицах
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 18.05.2015
*/
namespace skeeks\cms\models\behaviors;
use skeeks\cms\models\CmsContentPropertyEnum;
use skeeks\cms\relatedProperties\models\RelatedPropertiesModel;
use skeeks\cms\relatedProperties\models\RelatedPropertyModel;
use yii\base\Behavior;
use yii\base\Exception;
use yii\db\ActiveQuery;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\web\ErrorHandler;
/**
* Class HasRelatedProperties
* @package skeeks\cms\models\behaviors
*/
class HasRelatedProperties extends Behavior
{
/**
* @var string связующая модель ( например CmsContentElementProperty::className() )
*/
public $relatedElementPropertyClassName;
/**
* @var string модель свойства ( например CmsContentProperty::className() )
*/
public $relatedPropertyClassName;
/**
* @var string модель свойства ( например CmsContentPropertyEnum::class )
*/
//public $relatedPropertyEnumClassName;
/**
* Значения связанных свойств.
* Вернуться только заданные значения свойств.
*
* @return ActiveQuery
*/
public function getRelatedElementProperties()
{
return $this->owner->hasMany($this->relatedElementPropertyClassName, ['element_id' => 'id']);
}
/**
* @return array
*/
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_DELETE => "_deleteRelatedProperties",
];
}
/**
* before removal of the model you want to delete related properties
*/
public function _deleteRelatedProperties()
{
$rpm = $this->owner->relatedPropertiesModel;
$rpm->delete();
}
/**
*
* Все возможные свойства, для модели.
* Это может зависеть от группы элемента, или от его типа, например.
* Для разных групп пользователей можно задать свои свойства, а у пользователя можно заполнять только те поля котоыре заданы для группы к которой он относиться.
*
* @return ActiveQuery
*/
public function getRelatedProperties()
{
$className = $this->relatedPropertyClassName;
$find = $className::find()->orderBy(['priority' => SORT_ASC]); ;
$find->multiple = true;
return $find;
}
/**
* @return RelatedPropertiesModel
*/
public function createRelatedPropertiesModel()
{
return new RelatedPropertiesModel([], [
'relatedElementModel' => $this->owner
]);
}
/**
* @var RelatedPropertiesModel
*/
public $_relatedPropertiesModel = null;
/**
* @return RelatedPropertiesModel
*/
public function getRelatedPropertiesModel()
{
if ($this->_relatedPropertiesModel === null) {
$this->_relatedPropertiesModel = $this->createRelatedPropertiesModel();
}
return $this->_relatedPropertiesModel;
}
} | 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/behaviors/HasTableCache.php | src/models/behaviors/HasTableCache.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 28.05.2015
*/
namespace skeeks\cms\models\behaviors;
use skeeks\cms\models\CmsTheme;
use yii\base\Behavior;
use yii\caching\Cache;
use yii\caching\TagDependency;
use yii\db\BaseActiveRecord;
/**
* Class HasTableCache
* @package skeeks\cms\models\behaviors
*/
class HasTableCache extends Behavior
{
/**
* @var Cache
*/
public $cache;
/**
* @return array
*/
public function events()
{
return [
BaseActiveRecord::EVENT_AFTER_UPDATE => "invalidateTableCache",
BaseActiveRecord::EVENT_AFTER_INSERT => "invalidateTableCache",
BaseActiveRecord::EVENT_BEFORE_DELETE => "invalidateTableCache",
];
}
/**
* При любом обновлении, сохранении, удалении записей в эту таблицу, инвалидируется тэг кэша таблицы
* @return $this
*/
public function invalidateTableCache()
{
TagDependency::invalidate($this->cache, [
$this->getTableCacheTag(),
]);
$owner = $this->owner;
/*if ($owner instanceof CmsTheme) {
print_r($this->getTableCacheTagCmsSite($owner->cms_site_id));
die(111);
}*/
if (isset($owner->cms_site_id) && $owner->cms_site_id) {
//\Yii::info("Invalidate: " . $this->getTableCacheTagCmsSite($owner->cms_site_id));
TagDependency::invalidate($this->cache, [
$this->getTableCacheTagCmsSite($owner->cms_site_id),
]);
}
if (isset($owner->site_id) && $owner->site_id) {
//die('111');
TagDependency::invalidate($this->cache, [
$this->getTableCacheTagCmsSite($owner->site_id),
]);
}
return $this;
}
/**
* @return string
*/
public function getTableCacheTag()
{
return 'sx-table-' . $this->owner->tableName();
}
/**
* @return string
*/
public function getTableCacheTagCmsSite($cms_site_id = null)
{
if ($cms_site_id === null) {
$cms_site_id = \Yii::$app->skeeks->site->id;
}
return 'sx-table-' . $this->owner->tableName() . "-" . $cms_site_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/behaviors/HasStorageFileMulti.php | src/models/behaviors/HasStorageFileMulti.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\behaviors;
use skeeks\cms\models\CmsStorageFile;
use skeeks\cms\models\StorageFile;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
/**
* @property ActiveRecord $owner
*
* Class HasStorageFileMulti
* @package skeeks\cms\models\behaviors
*/
class HasStorageFileMulti extends Behavior
{
/**
* Набор полей модели к которым будут привязываться id файлов
* @var array
*/
public $relations = [
/*[
'relation' => 'images',
'property' => 'imageIds',
],*/
];
public $fields = [
];
/**
* При удалении сущьности удалять все привязанные файлы?
*
* @var string
*/
public $onDeleteCascade = true;
/**
* @var array
*/
public $nameAttribute = 'name';
/**
* @var array
*/
protected $_removeFiles = [];
protected $_linkFiles = [];
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_DELETE => "deleteStorgaFile",
BaseActiveRecord::EVENT_BEFORE_INSERT => [$this, "saveStorgaFile"],
BaseActiveRecord::EVENT_BEFORE_UPDATE => "saveStorgaFile",
BaseActiveRecord::EVENT_AFTER_INSERT => "afterSaveStorgaFile",
BaseActiveRecord::EVENT_AFTER_UPDATE => "afterSaveStorgaFile",
];
}
/**
* Загрузка файлов в хранилище и их сохранение со связанной сущьностью
*
* @param $e
*/
public function saveStorgaFile($e)
{
if ($this->fields) {
foreach ($this->fields as $fieldCode) {
$oldIds = $this->owner->getOldAttribute($fieldCode);
//$oldIds = $this->owner->{$fieldCode};
$oldIdsStatic = $oldIds;
$files = [];
if ($this->owner->{$fieldCode} && is_array($this->owner->{$fieldCode})) {
foreach ($this->owner->{$fieldCode} as $fileId) {
if (is_string($fileId) && ((string)(int)$fileId != (string)$fileId)) {
try {
$data = [];
if (isset($this->owner->{$this->nameAttribute})) {
if ($name = $this->owner->{$this->nameAttribute}) {
$data['name'] = $name;
}
}
$file = \Yii::$app->storage->upload($fileId, $data);
if ($file) {
$files[] = $file->id;
}
} catch (\Exception $e) {
}
} else {
$files[] = $fileId;
ArrayHelper::removeValue($oldIds, $fileId);
}
}
$this->owner->{$fieldCode} = $files;
}
if ($oldIdsStatic && $this->owner->{$fieldCode}) {
if (implode(',', $oldIdsStatic) != implode(',', $this->owner->{$fieldCode})) {
$count = 100;
//$this->owner->unlinkAll($relation, true);
foreach ($this->owner->{$fieldCode} as $id) {
/**
* @var CmsStorageFile $file
*/
$file = CmsStorageFile::findOne($id);
$file->priority = $count;
$file->save();
$count = $count + 100;
}
}
}
/**
* Удалить старые файлы
*/
if ($oldIds) {
$this->_removeFiles = $oldIds;
}
}
}
if ($this->relations) {
foreach ($this->relations as $data) {
$fieldCode = ArrayHelper::getValue($data, 'property');
$relation = ArrayHelper::getValue($data, 'relation');
if (!isset($this->owner->{$relation})) {
continue;
}
$oldFiles = $this->owner->{$relation};
$oldIds = [];
$oldIdsStatic = [];
if ($oldFiles) {
$oldIds = ArrayHelper::map($oldFiles, 'id', 'id');
$oldIdsStatic = ArrayHelper::map($oldFiles, 'id', 'id');
}
$files = [];
if ($this->owner->{$fieldCode} && is_array($this->owner->{$fieldCode})) {
foreach ($this->owner->{$fieldCode} as $fileId) {
if (is_string($fileId) && ((string)(int)$fileId != (string)$fileId)) {
try {
$data = [];
if (isset($this->owner->{$this->nameAttribute})) {
if ($name = $this->owner->{$this->nameAttribute}) {
$data['name'] = $name;
}
}
$file = \Yii::$app->storage->upload($fileId, $data);
if ($file) {
if ($this->owner->isNewRecord) {
$this->_linkFiles[$relation][] = $file;
} else {
$this->owner->link($relation, $file);
}
$files[] = $file->id;
}
} catch (\Exception $e) {
}
} else {
//Если файл не существует, то будет удален
if (!$storageFile = CmsStorageFile::findOne($fileId)) {
continue;
}
if ($this->owner->isNewRecord) {
$this->_linkFiles[$relation][] = $storageFile;
} else {
//Если файл еще не был привязан, то нужно привязать
if (!in_array($fileId, $oldIds)) {
$this->owner->link($relation, $storageFile);
}
}
//Файл попадает в перечень файлов
$files[] = $fileId;
//Удаляется ID из претендентов на удаление
ArrayHelper::remove($oldIds, $fileId);
}
}
$this->owner->{$fieldCode} = $files;
}
if ($oldIdsStatic && $this->owner->{$fieldCode}) {
if (implode(',', $oldIdsStatic) != implode(',', $this->owner->{$fieldCode})) {
$count = 100;
//$this->owner->unlinkAll($relation, true);
foreach ($this->owner->{$fieldCode} as $id) {
/**
* @var CmsStorageFile $file
*/
$file = CmsStorageFile::findOne($id);
$file->priority = $count;
$file->save();
$count = $count + 100;
}
}
}
/**
* Удалить старые файлы
*/
if ($oldIds) {
$this->_removeFiles = $oldIds;
}
}
}
}
/**
* @throws \Exception
* @throws \Throwable
*/
public function afterSaveStorgaFile()
{
if ($this->_linkFiles) {
foreach ($this->_linkFiles as $relation => $files) {
foreach ($files as $file) {
$this->owner->link($relation, $file);
}
}
}
if ($this->_removeFiles) {
if ($files = StorageFile::find()->where(['id' => $this->_removeFiles])->all()) {
foreach ($files as $file) {
$file->delete();
}
}
}
}
/**
* До удаления сущьности, текущей необходим проверить все описанные модели, и сделать операции с ними (удалить, убрать привязку или ничего не делать кинуть Exception)
* @throws Exception
*/
public function deleteStorgaFile()
{
if (!$this->onDeleteCascade) {
return $this;
}
if ($this->relations) {
foreach ($this->relations as $data) {
$fieldName = ArrayHelper::getValue($data, 'property');
if ($fileIds = $this->owner->{$fieldName}) {
if ($storageFiles = CmsStorageFile::find()->where(['id' => $fileIds])->all()) {
foreach ($storageFiles as $file) {
$file->delete();
}
}
}
}
}
if ($this->fields) {
foreach ($this->fields as $fieldName) {
if ($fileIds = $this->owner->{$fieldName}) {
if ($storageFiles = CmsStorageFile::find()->where(['id' => $fileIds])->all()) {
foreach ($storageFiles as $file) {
$file->delete();
}
}
}
}
}
}
} | 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/behaviors/HasJsonFieldsBehavior.php | src/models/behaviors/HasJsonFieldsBehavior.php | <?php
/**
* HasJsonFieldsBehavior
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 19.11.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\behaviors;
use yii\db\BaseActiveRecord;
use \yii\base\Behavior;
use yii\base\Event;
use yii\helpers\Json;
/**
* Class Serialize
* @package skeeks\cms\models\behaviors
*/
class HasJsonFieldsBehavior extends Behavior
{
/**
* @var array
*/
public $fields = [];
/**
* @return array
*/
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_INSERT => "jsonEncodeFields",
BaseActiveRecord::EVENT_BEFORE_UPDATE => "jsonEncodeFields",
BaseActiveRecord::EVENT_AFTER_FIND => "jsonDecodeFields",
BaseActiveRecord::EVENT_AFTER_UPDATE => "jsonDecodeFields",
BaseActiveRecord::EVENT_AFTER_INSERT => "jsonDecodeFields",
];
}
/**
* @param Event $event
*/
public function jsonEncodeFields($event)
{
foreach ($this->fields as $fielName) {
if ($this->owner->hasAttribute($fielName) && $this->owner->{$fielName}) {
if (is_array($this->owner->{$fielName})) {
$this->owner->{$fielName} = Json::encode((array)$this->owner->{$fielName});
}
} else {
if ($this->owner->hasAttribute($fielName)) {
$this->owner->{$fielName} = "";
}
}
}
}
/**
* @param Event $event
*/
public function jsonDecodeFields($event)
{
foreach ($this->fields as $fielName) {
if ($this->owner->hasAttribute($fielName) && $this->owner->{$fielName}) {
if (is_string($this->owner->{$fielName})) {
try {
$this->owner->{$fielName} = Json::decode($this->owner->{$fielName});
} catch (\Exception $e) {
$r = new \ReflectionClass($this->owner);
\Yii::warning("Json::decode error — {$e->getMessage()} value for decode={$this->owner->{$fielName}} model={$r->getName()} modeldata=" . print_r($this->owner->toArray(), true), self::class);
$this->owner->{$fielName} = [];
}
}
} else {
if ($this->owner->hasAttribute($fielName)) {
$this->owner->{$fielName} = [];
}
}
}
}
}
| 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/behaviors/HasTrees.php | src/models/behaviors/HasTrees.php | <?php
/**
* Может привязываться к разделам через связующую таблицу
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 18.05.2015
*/
namespace skeeks\cms\models\behaviors;
use yii\base\Behavior;
use yii\db\ActiveQuery;
use yii\db\AfterSaveEvent;
use yii\db\BaseActiveRecord;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\web\ErrorHandler;
/**
* @property ActiveRecord $owner
*
* Class HasTrees
* @package skeeks\cms\models\behaviors
*/
class HasTrees extends Behavior
{
public $_tree_ids = null;
/**
* @var string названием модели таблицы через которую связаны элементы и разделы.
*/
public $elementTreesClassName = '\skeeks\cms\models\CmsContentElementTree';
/**
* @var string класс разделов
*/
public $treesClassName = '\skeeks\cms\models\CmsTree';
/**
* @var string
*/
public $attributeElementName = 'element_id';
/**
* @var string
*/
public $attributeTreeName = 'tree_id';
/**
* @return array
*/
public function events()
{
return [
BaseActiveRecord::EVENT_AFTER_UPDATE => "afterSaveTree",
BaseActiveRecord::EVENT_AFTER_INSERT => "afterSaveTree",
];
}
/**
* @param AfterSaveEvent $event
*/
public function afterSaveTree($event)
{
if ($this->owner->_tree_ids === null) {
return $this;
}
//Старые атрибуты
$oldIds = (array)ArrayHelper::map($this->owner->elementTrees, $this->attributeTreeName,
$this->attributeTreeName);
$newIds = (array)$this->owner->treeIds; //Новые
//Если старых не было, просто записать новые
$writeIds = [];
$deleteIds = [];
if (!$oldIds) {
$writeIds = $newIds;
} else {
foreach ($oldIds as $oldId) {
//Старый элемент есть в новом массиве, его не трогаем он остается
if (in_array($oldId, $newIds)) {
} else {
$deleteIds[] = $oldId; //Иначе его надо удалить.
}
}
foreach ($newIds as $newId) {
//Если новый элемент уже был, то ничего не делаем
if (in_array($newId, $oldIds)) {
} else {
$writeIds[] = $newId; //Иначе запишем
}
}
}
//Есть элементы на удаление
if ($deleteIds) {
$elementTrees = $this->owner->getElementTrees()->andWhere([
$this->attributeTreeName => $deleteIds
])->limit(count($deleteIds))->all();
foreach ($elementTrees as $elementTree) {
$elementTree->delete();
}
}
//Есть элементы на запись
if ($writeIds) {
$className = $this->elementTreesClassName;
foreach ($writeIds as $treeId) {
if ($treeId) {
$elementTree = new $className([
$this->attributeElementName => $this->owner->id,
$this->attributeTreeName => $treeId,
]);
$elementTree->save(false);
}
}
}
$this->owner->_tree_ids = null;
}
/**
* @return int[]
*/
public function getTreeIds()
{
if ($this->owner->_tree_ids === null) {
$this->owner->_tree_ids = [];
if ($this->owner->elementTrees) {
$this->_tree_ids = (array)ArrayHelper::map($this->owner->elementTrees, $this->attributeTreeName,
$this->attributeTreeName);
}
return $this->_tree_ids;
}
return (array)$this->_tree_ids;
}
/**
* @param $ids
* @return $this
*/
public function setTreeIds($ids)
{
$this->owner->_tree_ids = $ids;
return $this;
}
/**
* @return \yii\db\ActiveQuery
*/
public function getElementTrees()
{
$className = $this->elementTreesClassName;
return $this->owner->hasMany($className::className(), [$this->attributeElementName => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCmsTrees()
{
$className = $this->elementTreesClassName;
$treesClassName = $this->treesClassName;
return $this->owner->hasMany($treesClassName::className(), ['id' => 'tree_id'])
->via('elementTrees');
}
} | 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/behaviors/Implode.php | src/models/behaviors/Implode.php | <?php
/**
* implode / explode before after save
*
* @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\behaviors;
use yii\db\BaseActiveRecord;
use \yii\base\Behavior;
use yii\base\Event;
/**
* Class Implode
* @package skeeks\cms\models\behaviors
*/
class Implode extends Behavior
{
/**
* @var array
*/
public $fields = [];
/**
* @var string
*/
public $delimetr = ',';
/**
* @return array
*/
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_INSERT => "implodeFields",
BaseActiveRecord::EVENT_BEFORE_UPDATE => "implodeFields",
BaseActiveRecord::EVENT_AFTER_FIND => "explodeFields",
BaseActiveRecord::EVENT_AFTER_UPDATE => "explodeFields",
BaseActiveRecord::EVENT_AFTER_INSERT => "explodeFields",
];
}
/**
* @param Event $event
*/
public function implodeFields($event)
{
foreach ($this->fields as $fielName) {
if ($this->owner->{$fielName}) {
if (is_array($this->owner->{$fielName})) {
$this->owner->{$fielName} = implode($this->delimetr, $this->owner->{$fielName});
}
} else {
$this->owner->{$fielName} = "";
}
}
}
/**
* @param Event $event
*/
public function explodeFields($event)
{
foreach ($this->fields as $fielName) {
if ($this->owner->{$fielName}) {
if (is_string($this->owner->{$fielName})) {
$this->owner->{$fielName} = explode($this->delimetr, $this->owner->{$fielName});
}
} else {
$this->owner->{$fielName} = [];
}
}
}
}
| 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/behaviors/Serialize.php | src/models/behaviors/Serialize.php | <?php
/**
* Serialize
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 10.11.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\behaviors;
use yii\db\BaseActiveRecord;
use \yii\base\Behavior;
use yii\base\Event;
/**
* Class Serialize
* @package skeeks\cms\models\behaviors
*/
class Serialize extends Behavior
{
/**
* @var array
*/
public $fields = [];
/**
* @return array
*/
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_INSERT => "serializeFields",
BaseActiveRecord::EVENT_BEFORE_UPDATE => "serializeFields",
BaseActiveRecord::EVENT_AFTER_FIND => "unserializeFields",
BaseActiveRecord::EVENT_AFTER_UPDATE => "unserializeFields",
BaseActiveRecord::EVENT_AFTER_INSERT => "unserializeFields",
];
}
/**
* @param Event $event
*/
public function serializeFields($event)
{
foreach ($this->fields as $fielName) {
if ($this->owner->{$fielName}) {
if (is_array($this->owner->{$fielName})) {
$this->owner->{$fielName} = serialize($this->owner->{$fielName});
}
} else {
$this->owner->{$fielName} = "";
}
}
}
/**
* @param Event $event
*/
public function unserializeFields($event)
{
foreach ($this->fields as $fielName) {
if ($this->owner->{$fielName}) {
if (is_string($this->owner->{$fielName})) {
$this->owner->{$fielName} = @unserialize($this->owner->{$fielName});
}
} else {
$this->owner->{$fielName} = [];
}
}
}
}
| 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/behaviors/TimestampPublishedBehavior.php | src/models/behaviors/TimestampPublishedBehavior.php | <?php
/**
* TimestampPublishedBehavior
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 09.12.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\behaviors;
use yii\behaviors\AttributeBehavior;
use yii\db\BaseActiveRecord;
use yii\db\Expression;
class TimestampPublishedBehavior extends AttributeBehavior
{
/**
* @var string the attribute that will receive timestamp value
* Set this property to false if you do not want to record the creation time.
*/
public $publishedAtAttribute = 'published_at';
/**
* @var callable|Expression The expression that will be used for generating the timestamp.
* This can be either an anonymous function that returns the timestamp value,
* or an [[Expression]] object representing a DB expression (e.g. `new Expression('NOW()')`).
* If not set, it will use the value of `time()` to set the attributes.
*/
public $value;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->publishedAtAttribute],
];
}
}
/**
* @inheritdoc
*/
protected function getValue($event)
{
if ($this->value instanceof Expression) {
return $this->value;
} else {
return $this->value !== null ? call_user_func($this->value, $event) : 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/behaviors/HasStorageFile.php | src/models/behaviors/HasStorageFile.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\behaviors;
use common\models\User;
use skeeks\cms\models\CmsStorageFile;
use skeeks\cms\models\StorageFile;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\db\BaseActiveRecord;
/**
* @property ActiveRecord|User $owner
*
* Class HasStorageFile
* @package skeeks\cms\models\behaviors
*/
class HasStorageFile extends Behavior
{
/**
* Набор полей модели к которым будут привязываться id файлов
* @var array
*/
public $fields = ['image_id'];
/**
* @var array
*/
public $nameAttribute = 'name';
/**
* При удалении сущьности удалять все привязанные файлы?
*
* @var string
*/
public $onDeleteCascade = true;
/**
* @var array
*/
protected $_removeFiles = [];
/**
* @return array
*/
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_DELETE => "deleteStorgaFile",
BaseActiveRecord::EVENT_BEFORE_INSERT => "saveStorgaFile",
BaseActiveRecord::EVENT_BEFORE_UPDATE => "saveStorgaFile",
BaseActiveRecord::EVENT_AFTER_INSERT => "afterSaveStorgaFile",
BaseActiveRecord::EVENT_AFTER_UPDATE => "afterSaveStorgaFile",
];
}
/**
* Загрузка файлов в хранилище и их сохранение со связанной сущьностью
*
* @param $e
*/
public function saveStorgaFile($e)
{
foreach ($this->fields as $fieldCode) {
/**
* Удалить старые файлы
*/
if ($this->owner->isAttributeChanged($fieldCode)) {
if ($this->owner->getOldAttribute($fieldCode) && $this->owner->getOldAttribute($fieldCode) != $this->owner->{$fieldCode}) {
$this->_removeFiles[] = $this->owner->getOldAttribute($fieldCode);
}
}
if ($this->owner->{$fieldCode} && is_string($this->owner->{$fieldCode}) && ((string)(int)$this->owner->{$fieldCode} != (string)$this->owner->{$fieldCode})) {
try {
$data = [];
if (isset($this->owner->{$this->nameAttribute})) {
if ($name = $this->owner->{$this->nameAttribute}) {
$data['name'] = $name;
}
}
$file = \Yii::$app->storage->upload($this->owner->{$fieldCode}, $data);
if ($file) {
$this->owner->{$fieldCode} = $file->id;
} else {
$this->owner->{$fieldCode} = null;
}
} catch (\Exception $e) {
\Yii::error($e->getMessage());
$this->owner->{$fieldCode} = null;
}
}
}
}
/**
* @throws \Exception
* @throws \Throwable
*/
public function afterSaveStorgaFile()
{
if ($this->_removeFiles) {
if ($files = StorageFile::find()->where(['id' => $this->_removeFiles])->all()) {
foreach ($files as $file) {
$file->delete();
}
}
}
}
/**
* До удаления сущьности, текущей необходим проверить все описанные модели, и сделать операции с ними (удалить, убрать привязку или ничего не делать кинуть Exception)
* @throws Exception
*/
public function deleteStorgaFile()
{
if (!$this->onDeleteCascade) {
return $this;
}
foreach ($this->fields as $fieldValue) {
if ($fileId = $this->owner->{$fieldValue}) {
if ($storageFile = CmsStorageFile::findOne($fileId)) {
$storageFile->delete();
}
}
}
}
} | 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/behaviors/traits/HasUrlTrait.php | src/models/behaviors/traits/HasUrlTrait.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 24.05.2015
*/
namespace skeeks\cms\models\behaviors\traits;
use skeeks\cms\models\CmsContentElementTree;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
/**
* @method string getAbsoluteUrl()
* @method string getUrl()
*
* @property string absoluteUrl
* @property string url
*/
trait HasUrlTrait
{
/**
* @return string
*/
public function getAbsoluteUrl()
{
return $this->url;
}
/**
* @return string
*/
public function getUrl()
{
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/models/behaviors/traits/HasTreesTrait.php | src/models/behaviors/traits/HasTreesTrait.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 18.05.2015
*/
namespace skeeks\cms\models\behaviors\traits;
use skeeks\cms\models\CmsContentElementTree;
use skeeks\cms\models\CmsTree;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
/**
* @method ActiveQuery getElementTrees()
* @method ActiveQuery getCmsTrees()
* @method int[] getTreeIds()
*
* @property CmsContentElementTree[] $elementTrees
* @property int[] $treeIds
* @property CmsTree[] $cmsTrees
*/
trait HasTreesTrait
{
} | 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/behaviors/traits/HasRelatedPropertiesTrait.php | src/models/behaviors/traits/HasRelatedPropertiesTrait.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 18.05.2015
*/
namespace skeeks\cms\models\behaviors\traits;
use skeeks\cms\relatedProperties\models\RelatedElementPropertyModel;
use skeeks\cms\relatedProperties\models\RelatedPropertiesModel;
use skeeks\cms\relatedProperties\models\RelatedPropertyModel;
use skeeks\cms\relatedProperties\PropertyType;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
/**
* @method ActiveQuery getRelatedElementProperties()
* @method ActiveQuery getRelatedProperties()
* @method RelatedPropertiesModel getRelatedPropertiesModel()
*
* @property RelatedElementPropertyModel[] relatedElementProperties
* @property RelatedPropertyModel[] relatedProperties
* @property RelatedPropertiesModel relatedPropertiesModel
*/
trait HasRelatedPropertiesTrait
{
/**
*
* @param ActiveQuery $activeQuery
* @param RelatedPropertyModel|null $relatedPropertyModel
* @param $value
* @return null
*/
public static function filterByProperty(
ActiveQuery $activeQuery,
RelatedPropertyModel $relatedPropertyModel = null,
$value
) {
if (!$relatedPropertyModel) {
return null;
}
$activeQuery->joinWith('relatedElementProperties map');
if (in_array($relatedPropertyModel->property_type, [PropertyType::CODE_STRING])) {
$activeQuery
->andWhere(['map.property_id' => $relatedPropertyModel->id])
->andWhere(['map.value_string' => $value]);
} else {
if (in_array($relatedPropertyModel->property_type, [
PropertyType::CODE_ELEMENT
,
PropertyType::CODE_TREE
,
PropertyType::CODE_LIST
,
PropertyType::CODE_NUMBER
])) {
$activeQuery
->andWhere(['map.property_id' => $relatedPropertyModel->id])
->andWhere(['map.value_enum' => $value]);
} else {
//TODO: медленно
$activeQuery
->andWhere(['map.property_id' => $relatedPropertyModel->id])
->andWhere(['map.value' => $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/behaviors/traits/HasLogTrait.php | src/models/behaviors/traits/HasLogTrait.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 24.05.2015
*/
namespace skeeks\cms\models\behaviors\traits;
use skeeks\cms\models\CmsLog;
use skeeks\cms\models\queries\CmsLogQuery;
use yii\helpers\ArrayHelper;
/**
* @property CmsLog[] $logs
*
* @property string $skeeksModelCode
* @property string $skeeksModelName
* @property string $skeeksModelClass
*/
trait HasLogTrait
{
/**
* @return string
*/
public function getSkeeksModelCode()
{
return static::class;
}
/**
* @param CmsLog $cmsLog
* @return string
*/
public function renderLog(CmsLog $cmsLog)
{
return (string)$cmsLog->render();
}
/**
* @return CmsLogQuery
*/
public function getLogs()
{
$q = CmsLog::find()
->andWhere(['model_code' => $this->skeeksModelCode])
->andWhere(['model_id' => $this->id])
->orderBy(['created_at' => SORT_DESC]);
$q->multiple = true;
return $q;
}
/*static public function findLogs()
{
$q = CmsLog::find()
->andWhere(['model_code' => self::getSkeeksModelCode()])
->orderBy(['created_at' => SORT_DESC]);
}*/
} | 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/forms/ResetPasswordForm.php | src/models/forms/ResetPasswordForm.php | <?php
/**
* ResetPasswordForm
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 28.10.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\forms;
use yii\base\InvalidParamException;
use yii\base\Model;
use Yii;
/**
* Class ResetPasswordForm
* @package skeeks\module\cms\user\model
*/
class ResetPasswordForm extends Model
{
public $password;
/**
* @var User
*/
private $_user;
/**
* Creates a form model given a token.
*
* @param string $token
* @param array $config name-value pairs that will be used to initialize the object properties
* @throws \yii\base\InvalidParamException if token is empty or not valid
*/
public function __construct($token, $config = [])
{
if (empty($token) || !is_string($token)) {
throw new InvalidParamException(\Yii::t('skeeks/cms', 'Password reset token cannot be blank.'));
}
$this->_user = User::findByPasswordResetToken($token);
if (!$this->_user) {
throw new InvalidParamException(\Yii::t('skeeks/cms', 'Wrong password reset token.'));
}
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Resets password.
*
* @return boolean if password was reset.
*/
public function resetPassword()
{
$user = $this->_user;
$user->password = $this->password;
$user->removePasswordResetToken();
return $user->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/models/forms/LoginFormUsernameOrEmail.php | src/models/forms/LoginFormUsernameOrEmail.php | <?php
/**
* Форма позволяющая авторизовываться использую логин или email
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 26.02.2015
* @since 1.0.0
*/
namespace skeeks\cms\models\forms;
use skeeks\cms\models\User;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginFormUsernameOrEmail extends Model
{
public $identifier;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['identifier', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
['identifier', 'validateEmailIsApproved'],
];
}
/**
* @return array
*/
public function attributeLabels()
{
return [
'identifier' => \Yii::t('skeeks/cms', 'Username or Email'),
'password' => \Yii::t('skeeks/cms', 'Password'),
'rememberMe' => \Yii::t('skeeks/cms', 'Remember me'),
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validateEmailIsApproved($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (\Yii::$app->cms->auth_only_email_is_approved && !$user->email_is_approved) {
$this->addError($attribute, \Yii::t('skeeks/cms', 'Вам необходимо подтвердить ваш email. Для этого перейдите по ссылке из письма.'));
}
}
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, \Yii::t('skeeks/cms', 'Incorrect username or password.'));
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$identityClass = \Yii::$app->user->identityClass;
$this->_user = $identityClass::findByUsernameOrEmail($this->identifier);
}
return $this->_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/forms/BlockedUserForm.php | src/models/forms/BlockedUserForm.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 02.07.2015
*/
namespace skeeks\cms\models\forms;
use skeeks\cms\models\User;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class BlockedUserForm extends Model
{
public $password;
private $_user = false;
/**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['password'], 'required'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, \Yii::t('skeeks/cms', 'Incorrect password.'));
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
$this->getUser()->updateLastAdminActivity();
return true;
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = \Yii::$app->user->identity;
}
return $this->_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/forms/PasswordResetRequestForm.php | src/models/forms/PasswordResetRequestForm.php | <?php
/**
* PasswordResetRequestForm
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 28.10.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\forms;
use yii\base\Model;
use yii\helpers\ArrayHelper;
/**
* Class PasswordResetRequestForm
*/
class PasswordResetRequestForm extends Model
{
public $email;
/**
* @inheritdoc
*/
public function rules()
{
$identityClassName = \Yii::$app->user->identityClass;
return [
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
[
'email',
'exist',
'targetClass' => $identityClassName,
'filter' => ['status' => $identityClassName::STATUS_ACTIVE],
'message' => \Yii::t('skeeks/cms', 'There is no user with such email.')
],
];
}
/**
* Sends an email with a link, for resetting the password.
*
* @return boolean whether the email was send
*/
public function sendEmail()
{
/* @var $user User */
$user = User::findOne([
'status' => User::STATUS_ACTIVE,
'email' => $this->email,
]);
if ($user) {
if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
$user->generatePasswordResetToken();
}
if ($user->save()) {
\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/password-reset-token', ['user' => $user])
->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName . ' robot'])
->setTo($this->email)
->setSubject(\Yii::t('skeeks/cms', 'Password reset for ') . \Yii::$app->cms->appName)
->send();
}
}
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/models/forms/LoginForm.php | src/models/forms/LoginForm.php | <?php
/**
* LoginForm
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 28.10.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\forms;
use skeeks\cms\models\User;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, \Yii::t('skeeks/cms', 'Incorrect username or password.'));
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_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/forms/PasswordResetRequestFormEmailOrLogin.php | src/models/forms/PasswordResetRequestFormEmailOrLogin.php | <?php
/**
* PasswordResetRequestFormEmailOrLogin
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 26.02.2015
*/
namespace skeeks\cms\models\forms;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\web\User;
/**
* Class PasswordResetRequestFormEmailOrLogin
* @package skeeks\cms\models\forms
*/
class PasswordResetRequestFormEmailOrLogin extends Model
{
public $identifier;
/**
* На какой контроллер формировать ссылку на сброс пароля, админский или сайтовый.
* @var bool
*/
public $isAdmin = true;
/**
* @inheritdoc
*/
public function rules()
{
$identityClassName = \Yii::$app->user->identityClass;
return [
['identifier', 'filter', 'filter' => 'trim'],
['identifier', 'required'],
['identifier', 'validateEdentifier'],
/*['email', 'exist',
'targetClass' => $identityClassName,
'filter' => ['status' => $identityClassName::STATUS_ACTIVE],
'message' => 'There is no user with such email.'
],*/
];
}
/**
* @return array
*/
public function attributeLabels()
{
return [
'identifier' => \Yii::t('skeeks/cms', 'Email'),
];
}
public function validateEdentifier($attr)
{
$identityClassName = \Yii::$app->user->identityClass;
$user = $identityClassName::findByUsernameOrEmail($this->identifier);
if (!$user) {
$this->addError($attr, \Yii::t('skeeks/cms', 'User not found'));
}
}
/**
* Sends an email with a link, for resetting the password.
*
* @return boolean whether the email was send
*/
public function sendEmail()
{
/* @var $user \common\models\User */
$identityClassName = \Yii::$app->user->identityClass;
$user = $identityClassName::findByUsernameOrEmail($this->identifier);
//$user = $identityClassName::
if ($user) {
if (!$identityClassName::isPasswordResetTokenValid($user->password_reset_token)) {
$user->generatePasswordResetToken();
}
if ($user->save()) {
if (!$user->email) {
return false;
}
if ($this->isAdmin) {
$resetLink = \skeeks\cms\helpers\UrlHelper::construct('/admin/auth/reset-password',
['token' => $user->password_reset_token])->enableAbsolute()->enableAdmin();
} else {
$resetLink = \skeeks\cms\helpers\UrlHelper::construct('/cms/auth/reset-password',
['token' => $user->password_reset_token])->enableAbsolute();
}
\Yii::$app->mailer->view->theme->pathMap = ArrayHelper::merge(\Yii::$app->mailer->view->theme->pathMap,
[
'@app/mail' =>
[
'@skeeks/cms/mail-templates'
]
]);
$message = \Yii::$app->mailer->compose('@app/mail/password-reset-token', [
'user' => $user,
'resetLink' => $resetLink
])
->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName])
->setTo($user->email)
->setSubject(\Yii::t('skeeks/cms',
'The request to change the password for') . \Yii::$app->cms->appName);
return $message->send();
}
}
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/models/forms/PasswordChangeForm.php | src/models/forms/PasswordChangeForm.php | <?php
/**
* LoginForm
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 28.10.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\forms;
use skeeks\cms\models\User;
use Yii;
use yii\base\Model;
use yii\helpers\ArrayHelper;
/**
* Login form
*/
class PasswordChangeForm extends Model
{
/**
* @var User
*/
public $user;
/**
* @var string
*/
public $new_password;
/**
* @var
*/
public $new_password_confirm;
const SCENARION_NOT_REQUIRED = 'notRequired';
public function scenarios()
{
$scenarios = parent::scenarios();
return ArrayHelper::merge(parent::scenarios(), [
self::SCENARION_NOT_REQUIRED => $scenarios[self::SCENARIO_DEFAULT],
]);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
// password is validated by validatePassword()
/*[['new_password_confirm', 'new_password'], 'required'/*, 'when' => function(self $model)
{
return $model->scenario != self::SCENARION_NOT_REQUIRED;
}],*/
/*],*/
[['new_password_confirm', 'new_password'], 'required'],
[['new_password_confirm', 'new_password'], 'string', 'min' => 6],
[['new_password_confirm'], 'validateNewPassword'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'new_password' => \Yii::t('skeeks/cms', 'New password'),
'new_password_confirm' => \Yii::t('skeeks/cms', 'New Password Confirm'),
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validateNewPassword($attribute, $params)
{
if ($this->new_password_confirm != $this->new_password) {
$this->addError($attribute, \Yii::t('skeeks/cms', 'New passwords do not match'));
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function changePassword()
{
if ($this->validate() && $this->new_password == $this->new_password_confirm && $this->new_password) {
$this->user->setPassword($this->new_password);
return $this->user->save(false);
} 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/models/forms/ViewFileEditModel.php | src/models/forms/ViewFileEditModel.php | <?php
/**
* SignupForm
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 28.10.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\forms;
use skeeks\cms\models\CmsUserEmail;
use skeeks\cms\models\User;
use yii\base\Model;
use Yii;
/**
* Class ViewFileEditModel
* @package skeeks\cms\models\forms
*/
class ViewFileEditModel extends Model
{
public $rootViewFile;
public $error;
public $source;
public function init()
{
parent::init();
if (is_readable($this->rootViewFile) && file_exists($this->rootViewFile)) {
$fp = fopen($this->rootViewFile, 'a+');
if ($fp) {
$content = fread($fp, filesize($this->rootViewFile));
fclose($fp);
$this->source = $content;
} else {
$this->error = "file is not exist or is not readable";
}
}
}
/**
* @return array
*/
public function attributeLabels()
{
return [
'source' => \Yii::t('skeeks/cms', 'Code'),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['rootViewFile', 'string'],
['source', 'string'],
];
}
/**
* @return bool
*/
public function saveFile()
{
if (is_writable($this->rootViewFile) && file_exists($this->rootViewFile)) {
$file = fopen($this->rootViewFile, 'w');
fwrite($file, $this->source);
fclose($file);
return true;
}
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/models/forms/PasswordChangeFormV2.php | src/models/forms/PasswordChangeFormV2.php | <?php
/**
* LoginForm
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 28.10.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\forms;
use skeeks\cms\helpers\StringHelper;
use skeeks\cms\models\User;
use Yii;
use yii\base\Model;
use yii\helpers\ArrayHelper;
/**
* Login form
*/
class PasswordChangeFormV2 extends Model
{
/**
* @var User
*/
public $user;
/**
* @var string
*/
public $password;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['password'], 'required'],
[['password'], function ($attribute) {
$password = $this->{$attribute};
$password = trim($password);
$number = preg_match('@[0-9]@', $password);
$uppercase = preg_match('@[A-Z]@', $password);
$lowercase = preg_match('@[a-z]@', $password);
$specialChars = preg_match('@[^\w]@', $password);
$passLength = StringHelper::strlen($password);
if ($passLength < \Yii::$app->cms->pass_required_length) {
$this->addError($attribute, "Пароль слишком короткий! Необходимо минимум " . \Yii::$app->cms->pass_required_length . " символов.");
return false;
}
if (!$number && \Yii::$app->cms->pass_required_need_number) {
$this->addError($attribute, "Пароль должен содержать как минимум одну цифру");
return false;
}
if (!$uppercase && \Yii::$app->cms->pass_required_need_uppercase) {
$this->addError($attribute, "Пароль должен хоть одну заглавную английскую букву");
return false;
}
if (!$lowercase && \Yii::$app->cms->pass_required_need_lowercase) {
$this->addError($attribute, "Пароль должен хоть одну строчную английскую букву");
return false;
}
if (!$specialChars && \Yii::$app->cms->pass_required_need_specialChars ) {
$this->addError($attribute, "Пароль должен содержать хоть один специальный символ");
return false;
}
}],
];
}
public function attributeLabels()
{
return [
'password' => 'Пароль'
];
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function changePassword()
{
if ($this->validate()) {
$this->user->setPassword($this->password);
return $this->user->save(false);
} 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/models/forms/SignupForm.php | src/models/forms/SignupForm.php | <?php
/**
* SignupForm
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 28.10.2014
* @since 1.0.0
*/
namespace skeeks\cms\models\forms;
use skeeks\cms\models\CmsUserEmail;
use skeeks\cms\models\CmsUserPhone;
use skeeks\cms\models\User;
use skeeks\cms\validators\PhoneValidator;
use Yii;
use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
/**
* Class SignupForm
* @package skeeks\cms\models\forms
*/
class SignupForm extends Model
{
const SCENARION_FULLINFO = 'fullInfo';
const SCENARION_ONLYEMAIL = 'onlyEmail';
const SCENARION_SHORTINFO = 'shortInfo';
public $username;
public $email;
public $password;
public $first_name;
public $last_name;
public $patronymic;
public $phone;
/**
* @return array
*/
public function attributeLabels()
{
return [
'username' => \Yii::t('skeeks/cms', 'Login'),
'email' => \Yii::t('skeeks/cms', 'Email'),
'password' => \Yii::t('skeeks/cms', 'Password'),
'first_name' => \Yii::t('skeeks/cms', 'First name'),
'last_name' => \Yii::t('skeeks/cms', 'Last name'),
'patronymic' => \Yii::t('skeeks/cms', 'Patronymic'),
'email' => Yii::t('skeeks/cms', 'Email'),
'phone' => Yii::t('skeeks/cms', 'Phone'),
];
}
public function scenarios()
{
$scenarions = parent::scenarios();
$scenarions[self::SCENARION_FULLINFO] = [
'username',
'email',
'password',
'first_name',
'last_name',
'patronymic',
];
$scenarions[self::SCENARION_SHORTINFO] = [
'email',
'password',
'phone',
'first_name',
'last_name',
'patronymic',
];
$scenarions[self::SCENARION_ONLYEMAIL] = [
'email',
];
return $scenarions;
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
[
'username',
'unique',
'targetClass' => \Yii::$app->user->identityClass,
'message' => \Yii::t('skeeks/cms', 'This login is already in use by another user.'),
],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
[
'email',
'unique',
'targetAttribute' => 'value',
'targetClass' => CmsUserEmail::class,
'message' => \Yii::t('skeeks/cms', 'This Email is already in use by another user'),
],
//[['email'], 'unique', 'targetClass' => CmsUserEmail::className(), 'targetAttribute' => 'value'],
['password', 'required'],
['password', 'string', 'min' => 6],
[
['first_name', 'last_name', 'patronymic'],
'string',
'max' => 255,
],
[['phone'], 'string', 'max' => 64],
[['phone'], PhoneValidator::class],
[
['phone'],
'unique',
'targetClass' => CmsUserPhone::class,
'targetAttribute' => 'value',
],
[['phone'], 'default', 'value' => null],
];
}
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function signup()
{
if ($this->validate()) {
/**
* @var User $user
*/
$userClassName = \Yii::$app->user->identityClass;
$user = new $userClassName();
if ($this->scenario == self::SCENARION_FULLINFO) {
$user->username = $this->username;
$user->email = $this->email;
$user->last_name = $this->last_name;
$user->first_name = $this->first_name;
$user->patronymic = $this->patronymic;
$user->phone = $this->phone;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->save();
return $user;
} elseif ($this->scenario == self::SCENARION_SHORTINFO) {
//$user->generateUsername();
$user->email = $this->email;
$user->last_name = $this->last_name;
$user->first_name = $this->first_name;
$user->patronymic = $this->patronymic;
$user->phone = $this->phone;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->save();
return $user;
} else {
if ($this->scenario == self::SCENARION_ONLYEMAIL) {
$password = \Yii::$app->security->generateRandomString(6);
//$user->generateUsername();
$user->setPassword($password);
$user->email = $this->email;
$user->generateAuthKey();
if ($user->save()) {
\Yii::$app->mailer->view->theme->pathMap = ArrayHelper::merge(\Yii::$app->mailer->view->theme->pathMap,
[
'@app/mail' =>
[
'@skeeks/cms/mail-templates',
],
]);
\Yii::$app->mailer->compose('@app/mail/register-by-email', [
'user' => $user,
'password' => $password,
])
->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName.''])
->setTo($user->email)
->setSubject(\Yii::t('skeeks/cms', 'Sign up at site').\Yii::$app->cms->appName)
->send();
return $user;
} else {
\Yii::error("User rgister by email error: {$user->username} ".Json::encode($user->getFirstErrors()),
'RegisterError');
return null;
}
}
}
}
return null;
}
/**
* Sends an email with a link, for resetting the password.
*
* @return boolean whether the email was send
*/
public function sendEmail()
{
/* @var $user User */
if ($user = User::findByEmail($this->email)) {
if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
$user->generatePasswordResetToken();
}
if ($user->save()) {
\Yii::$app->mailer->view->theme->pathMap = ArrayHelper::merge(\Yii::$app->mailer->view->theme->pathMap,
[
'@app/mail' =>
[
'@skeeks/cms/mail',
],
]);
return \Yii::$app->mailer->compose('@app/mail/password-reset-token', ['user' => $user])
->setFrom([\Yii::$app->cms->adminEmail => \Yii::$app->cms->appName.' robot'])
->setTo($this->email)
->setSubject(\Yii::t('skeeks/cms', 'Password reset for ').\Yii::$app->cms->appName)
->send();
}
}
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/models/queries/CmsWebNotifyQuery.php | src/models/queries/CmsWebNotifyQuery.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\queries;
use skeeks\cms\models\User;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
use yii\helpers\ArrayHelper;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsWebNotifyQuery extends CmsActiveQuery
{
/**
* @param string|array $types
* @return $this
*/
public function notRead()
{
$this->andWhere(['is_read' => 0]);
return $this;
}
/**
* @param string|array $types
* @return $this
*/
public function notPopup()
{
$this->andWhere(['is_popup' => 0]);
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/queries/CmsUserQuery.php | src/models/queries/CmsUserQuery.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\queries;
use skeeks\cms\models\CmsCompany;
use skeeks\cms\models\User;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
use yii\helpers\ArrayHelper;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsUserQuery extends CmsActiveQuery
{
/**
* @param string $username
* @return $this
*/
public function username(string $username)
{
return $this->andWhere([$this->getPrimaryTableName().'.username' => $username]);
}
/**
* @param string $username
* @return $this
*/
public function isWorker(bool $value = true)
{
return $this->andWhere([$this->getPrimaryTableName().'.is_worker' => (int) $value]);
}
/**
* @param string $username
* @return $this
*/
public function email(string $email)
{
$this->joinWith("cmsUserEmails as cmsUserEmails");
$this->groupBy($this->getPrimaryTableName().'.id');
return $this->andWhere(['cmsUserEmails.value' => trim($email)]);
}
/**
* @param string $username
* @return $this
*/
public function phone(string $phone)
{
$this->joinWith("cmsUserPhones as cmsUserPhones");
$this->groupBy($this->getPrimaryTableName().'.id');
return $this->andWhere(['cmsUserPhones.value' => $phone]);
}
/**
* @param string $username
* @return $this
*/
public function search($word = '')
{
$this->joinWith("cmsUserPhones as cmsUserPhones");
$this->joinWith("cmsUserEmails as cmsUserEmails");
$this->groupBy($this->getPrimaryTableName().'.id');
return $this->andWhere([
'or',
['like', 'cmsUserPhones.value', $word],
['like', 'cmsUserEmails.value', $word],
['like', $this->getPrimaryTableName() . '.first_name', $word],
['like', $this->getPrimaryTableName() . '.last_name', $word],
['like', $this->getPrimaryTableName() . '.patronymic', $word],
['like', $this->getPrimaryTableName() . '.company_name', $word],
]);
}
/**
* Поиск компаний доступных пользователю
*
* @param User|null $user
* @return $this
*/
public function forManager(User $user = null)
{
if ($user === null) {
$user = \Yii::$app->user->identity;
$isCanAdmin = \Yii::$app->user->can(CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
} else {
$isCanAdmin = \Yii::$app->authManager->checkAccess($user->id, CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
}
if (!$user) {
return $this;
}
//Если нет прав админа, нужно показать только доступные компании
if (!$isCanAdmin) {
$managers = [];
$managers[] = $user->id;
if ($subordinates = $user->subordinates) {
$managers = ArrayHelper::merge($managers, ArrayHelper::map($subordinates, "id", "id"));
}
$cmsCompanyQuery = CmsCompany::find()->forManager()->select(CmsCompany::tableName() . '.id');
$this->joinWith("companiesAll as companies");
$this->joinWith("managers as managers");
//Поиск клиентов с которыми связан сотрудник + все дочерние сотрудники
$this->andWhere([
'or',
//Связь клиентов с менеджерами
["managers.id" => $managers],
//Искать конткты по всем доступным компаниям
["companies.id" => $cmsCompanyQuery],
]);
}
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/queries/CmsCompanyQuery.php | src/models/queries/CmsCompanyQuery.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\queries;
use skeeks\cms\models\User;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
use yii\helpers\ArrayHelper;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsCompanyQuery extends CmsActiveQuery
{
/**
* Поиск компаний доступных сотруднику
*
* @param User|null $user
* @return $this
*/
public function forManager(User $user = null)
{
if ($user === null) {
$user = \Yii::$app->user->identity;
$isCanAdmin = \Yii::$app->user->can(CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
} else {
$isCanAdmin = \Yii::$app->authManager->checkAccess($user->id, CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
}
if (!$user) {
return $this;
}
//Если нет прав админа, нужно показать только доступные компании
if (!$isCanAdmin) {
$managers = [];
$managers[] = $user->id;
if ($subordinates = $user->subordinates) {
$managers = ArrayHelper::merge($managers, ArrayHelper::map($subordinates, "id", "id"));
}
$this->joinWith("managers as managers");
$this->andWhere(["managers.id" => $managers]);
}
return $this;
}
/**
* Поиск компаний доступных клиенту
*
* @param User|null $user
* @return $this
*/
public function forClient(User $user = null)
{
if ($user === null) {
$user = \Yii::$app->user->identity;
}
if (!$user) {
return $this;
}
$this->andWhere([$this->getPrimaryTableName() . ".id" => $user->getCompanies()->select('id')]);
return $this;
}
/**
* @param string $username
* @return $this
*/
public function search($word = '')
{
/*$this->joinWith("cmsUserPhones as cmsUserPhones");
$this->joinWith("cmsUserEmails as cmsUserEmails");*/
$this->groupBy($this->getPrimaryTableName().'.id');
$this->joinWith('addresses as addresses');
$this->joinWith('emails as emails');
$this->joinWith('phones as phones');
$this->joinWith('links as links');
$this->joinWith('contractors as contractors');
$this->joinWith('users as users');
return $this->andWhere([
'or',
['like', $this->getPrimaryTableName().'.name', $word],
['like', $this->getPrimaryTableName().'.description', $word],
['like', 'emails.value', $word],
['like', 'phones.value', $word],
['like', 'addresses.name', $word],
['like', 'addresses.value', $word],
['like', 'links.url', $word],
['like', 'contractors.name', $word],
['like', 'contractors.first_name', $word],
['like', 'contractors.last_name', $word],
['like', 'contractors.patronymic', $word],
['like', 'contractors.inn', $word],
['like', 'users.first_name', $word],
['like', 'users.last_name', $word],
['like', 'users.patronymic', $word],
]);
}
} | 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/queries/CmsContentElementQuery.php | src/models/queries/CmsContentElementQuery.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\queries;
use skeeks\cms\query\CmsActiveQuery;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsContentElementQuery extends CmsActiveQuery
{
} | 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/queries/CmsTaskQuery.php | src/models/queries/CmsTaskQuery.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\queries;
use skeeks\cms\models\CmsCompany;
use skeeks\cms\models\CmsContractor;
use skeeks\cms\models\CmsLog;
use skeeks\cms\models\CmsProject;
use skeeks\cms\models\CmsTask;
use skeeks\cms\models\CmsUser;
use skeeks\cms\models\User;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsTaskQuery extends CmsActiveQuery
{
/**
* Поиск компаний доступных сотруднику
*
* @param User|null $user
* @return $this
*/
public function forManager(User $user = null)
{
if ($user === null) {
$user = \Yii::$app->user->identity;
$isCanAdmin = \Yii::$app->user->can(CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
} else {
$isCanAdmin = \Yii::$app->authManager->checkAccess($user->id, CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
}
if (!$user) {
return $this;
}
//Если нет прав админа, нужно показать только доступные компании
if (!$isCanAdmin) {
$managers = [];
$managers[] = $user->id;
if ($subordinates = $user->subordinates) {
$managers = ArrayHelper::merge($managers, ArrayHelper::map($subordinates, "id", "id"));
}
$this->andWhere([
"or",
[self::getPrimaryTableName() . ".cms_project_id" => CmsProject::find()->forManager()->select(CmsProject::tableName() . '.id')],
[self::getPrimaryTableName() . ".cms_company_id" => CmsCompany::find()->forManager()->select(CmsCompany::tableName() . '.id')],
[self::getPrimaryTableName() . ".cms_user_id" => CmsUser::find()->forManager()->select(CmsUser::tableName() . '.id')],
[self::getPrimaryTableName() . ".executor_id" => $user->id],
[self::getPrimaryTableName() . ".created_by" => $user->id],
]);
}
return $this;
}
/**
* @param string|array $types
* @return $this
*/
public function executor($user)
{
$user_id = null;
if ($user instanceof CmsUser) {
$user_id = $user->id;
} else {
$user_id = (int) $user;
}
$this->andWhere(['executor_id' => $user_id]);
return $this;
}
/**
* @return CmsUserScheduleQuery
* @throws \yii\base\InvalidConfigException
*/
public function status($status)
{
return $this->andWhere([
"status" => $status,
]);
}
/**
* @return CmsUserScheduleQuery
* @throws \yii\base\InvalidConfigException
*/
public function statusInWork()
{
return $this->status(CmsTask::STATUS_IN_WORK);
}
/**
* Просроченные задачи
*
* @return CmsTaskQuery
*/
public function expired()
{
return $this->andWhere([
'<', $this->getPrimaryTableName() . '.plan_start_at', time()
]);
}
/**
* @param $sort
* @return CmsTaskQuery
*/
public function orderPlanStartAt($sort = SORT_ASC)
{
return $this->orderBy([$this->getPrimaryTableName() . '.plan_start_at' => $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/queries/CmsCountryQuery.php | src/models/queries/CmsCountryQuery.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\queries;
use skeeks\cms\query\CmsActiveQuery;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsCountryQuery extends CmsActiveQuery
{
/**
* @param string $alpha2
* @return CmsCountryQuery
*/
public function alpha2(string $alpha2)
{
return $this->andWhere(['alpha2' => strtoupper($alpha2)]);
}
/**
* @param string $alpha3
* @return CmsCountryQuery
*/
public function alpha3(string $alpha3)
{
return $this->andWhere(['alpha3' => strtoupper($alpha3)]);
}
/**
* @param string $alpha3
* @return CmsCountryQuery
*/
public function iso(string $iso)
{
return $this->andWhere(['iso' => $iso]);
}
/**
* @param string $name
* @return CmsCountryQuery
*/
public function name(string $name)
{
return $this->andWhere(['name' => $name]);
}
/**
* @param mixed $phone_code
* @return CmsCountryQuery
*/
public function phoneCode(mixed $phone_code)
{
$phone_code = (string) $phone_code;
if (strpos($phone_code, "+") === false) {
$phone_code = "+" . $phone_code;
}
return $this->andWhere(['phone_code' => $phone_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/queries/CmsTaskScheduleQuery.php | src/models/queries/CmsTaskScheduleQuery.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\queries;
use skeeks\cms\models\CmsCompany;
use skeeks\cms\models\CmsContractor;
use skeeks\cms\models\CmsLog;
use skeeks\cms\models\CmsUser;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
use yii\db\ActiveRecord;
use yii\db\Expression;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsTaskScheduleQuery extends CmsActiveQuery
{
/**
* @param $task
* @return $this
*/
public function task($model)
{
$model_id = null;
if ($model instanceof ActiveRecord) {
$model_id = $model->id;
} else {
$model_id = (int) $model;
}
$this->andWhere(['cms_task_id' => $model_id]);
return $this;
}
/**
* @return $this
*/
public function notEnd()
{
$this->andWhere(['end_at' => null]);
return $this;
}
/**
* @return CmsUserScheduleQuery
* @throws \yii\base\InvalidConfigException
*/
public function today()
{
$date = \Yii::$app->formatter->asDate(time(), "php:Y-m-d");
return $this->andWhere([
'or',
new Expression("FROM_UNIXTIME(start_at, '%Y-%m-%d') = '{$date}'"),
new Expression("FROM_UNIXTIME(end_at, '%Y-%m-%d') = '{$date}'"),
]);
}
} | 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/queries/CmsContractorQuery.php | src/models/queries/CmsContractorQuery.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\queries;
use skeeks\cms\models\CmsCompany;
use skeeks\cms\models\CmsContractor;
use skeeks\cms\models\CmsUser;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsContractorQuery extends CmsActiveQuery
{
/*public function active()
{
return $this->andWhere('[[status]]=1');
}*/
/**
* {@inheritdoc}
* @return CmsContractor[]|array
*/
public function all($db = null)
{
return parent::all($db);
}
/**
* {@inheritdoc}
* @return CmsContractor|array|null
*/
public function one($db = null)
{
return parent::one($db);
}
/**
* @param $type
* @return CmsContractorQuery
*/
public function type($type)
{
return $this->andWhere(['contractor_type' => $type]);
}
/**
* @return CmsContractorQuery
*/
public function typeLegal()
{
return $this->type(CmsContractor::TYPE_LEGAL);
}
/**
* @return CmsContractorQuery
*/
public function typeIndividual()
{
return $this->type(CmsContractor::TYPE_INDIVIDUAL);
}
/**
* @return CmsContractorQuery
*/
public function typeIndividualAndLegal()
{
return $this->type([
CmsContractor::TYPE_INDIVIDUAL,
CmsContractor::TYPE_LEGAL,
]);
}
/**
* @param string $q
* @return CmsContractorQuery
*/
public function search($q = '')
{
return $this->andWhere([
'or',
['like', 'first_name', $q],
['like', 'last_name', $q],
['like', 'email', $q],
['like', 'phone', $q],
['like', 'name', $q],
['like', 'inn', $q],
]);
}
/**
* @param string $inn
* @return CmsContractorQuery
*/
public function inn($inn)
{
return $this->andWhere([
'inn' => $inn
]);
}
/**
* @param $value
* @return CrmContractorQuery
*/
public function our($value = 1)
{
return $this->andWhere(['is_our' => (int) $value]);
}
/**
* Поиск компаний доступных пользователю
*
* @param User|null $user
* @return $this
*/
public function forManager(User $user = null)
{
if ($user === null) {
$user = \Yii::$app->user->identity;
$isCanAdmin = \Yii::$app->user->can(CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
} else {
$isCanAdmin = \Yii::$app->authManager->checkAccess($user->id, CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
}
if (!$user) {
return $this;
}
//Если нет прав админа, нужно показать только доступные сделки
if (!$isCanAdmin) {
$cmsCompanyQuery = CmsCompany::find()->forManager()->select(CmsCompany::tableName() . '.id');
$cmsUserQuery = CmsUser::find()->forManager()->select(CmsUser::tableName() . '.id');
$this->joinWith("users as users");
$this->joinWith("companies as companies");
//Поиск клиентов с которыми связан сотрудник + все дочерние сотрудники
$this->andWhere([
'or',
//Связь клиентов с менеджерами
["companies.id" => $cmsCompanyQuery],
//Искать конткты по всем доступным компаниям
["users.id" => $cmsUserQuery],
]);
}
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/queries/CmsDealQuery.php | src/models/queries/CmsDealQuery.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\queries;
use skeeks\cms\models\CmsCompany;
use skeeks\cms\models\CmsUser;
use skeeks\cms\models\User;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
use yii\helpers\ArrayHelper;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsDealQuery extends CmsActiveQuery
{
/**
* Поиск компаний доступных пользователю
*
* @param User|null $user
* @return $this
*/
public function forManager(User $user = null)
{
if ($user === null) {
$user = \Yii::$app->user->identity;
$isCanAdmin = \Yii::$app->user->can(CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
} else {
$isCanAdmin = \Yii::$app->authManager->checkAccess($user->id, CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
}
if (!$user) {
return $this;
}
//Если нет прав админа, нужно показать только доступные сделки
if (!$isCanAdmin) {
$cmsCompanyQuery = CmsCompany::find()->forManager()->select(CmsCompany::tableName() . '.id');
$cmsUserQuery = CmsUser::find()->forManager()->select(CmsUser::tableName() . '.id');
//Поиск клиентов с которыми связан сотрудник + все дочерние сотрудники
$this->andWhere([
'or',
//Связь клиентов с менеджерами
["cms_company_id" => $cmsCompanyQuery],
//Искать конткты по всем доступным компаниям
["cms_user_id" => $cmsUserQuery],
]);
}
return $this;
}
/**
* Поиск компаний доступных пользователю
*
* @param User|null $user
* @return $this
*/
public function forClient(User $user = null)
{
if ($user === null) {
$user = \Yii::$app->user->identity;
}
if (!$user) {
return $this;
}
$cmsCompanyQuery = CmsCompany::find()->forClient()->select(CmsCompany::tableName() . '.id');
//Поиск клиентов с которыми связан сотрудник + все дочерние сотрудники
$this->andWhere([
'or',
//Связь клиентов с менеджерами
["cms_company_id" => $cmsCompanyQuery],
//Искать конткты по всем доступным компаниям
["cms_user_id" => $user->id],
]);
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/queries/CmsLogQuery.php | src/models/queries/CmsLogQuery.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\queries;
use skeeks\cms\models\CmsCompany;
use skeeks\cms\models\CmsContractor;
use skeeks\cms\models\CmsLog;
use skeeks\cms\models\CmsUser;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsLogQuery extends CmsActiveQuery
{
/**
* @param string|array $types
* @return $this
*/
public function logType($types)
{
$this->andWhere(['log_type' => $types]);
return $this;
}
/**
* @return $this
*/
public function comments()
{
return $this->logType(CmsLog::LOG_TYPE_COMMENT);
}
} | 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/queries/CmsContentQuery.php | src/models/queries/CmsContentQuery.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\queries;
use skeeks\cms\models\CmsContent;
use skeeks\cms\query\CmsActiveQuery;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsContentQuery extends CmsActiveQuery
{
/**
* @param string $role
* @return CmsContentQuery
*/
public function baseRole(string $role)
{
return $this->andWhere(['base_role' => trim($role)]);
}
/**
* @return CmsContentQuery
*/
public function isProducts()
{
return $this->baseRole(CmsContent::ROLE_PRODUCTS);
}
} | 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/queries/CmsProjectQuery.php | src/models/queries/CmsProjectQuery.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\queries;
use skeeks\cms\models\User;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
use yii\helpers\ArrayHelper;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsProjectQuery extends CmsActiveQuery
{
/**
* Поиск компаний доступных сотруднику
*
* @param User|null $user
* @return $this
*/
public function forManager(User $user = null)
{
if ($user === null) {
$user = \Yii::$app->user->identity;
$isCanAdmin = \Yii::$app->user->can(CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
} else {
$isCanAdmin = \Yii::$app->authManager->checkAccess($user->id, CmsManager::PERMISSION_ROLE_ADMIN_ACCESS);
}
if (!$user) {
return $this;
}
//Если нет прав админа, нужно показать только доступные компании
if (!$isCanAdmin) {
$managers = [];
$managers[] = $user->id;
if ($subordinates = $user->subordinates) {
$managers = ArrayHelper::merge($managers, ArrayHelper::map($subordinates, "id", "id"));
}
$this->joinWith("managers as managers");
$this->andWhere([
"or",
[self::getPrimaryTableName() . ".is_private" => 0],
[
"and",
[self::getPrimaryTableName() . ".is_private" => 1],
["managers.id" => $managers]
],
]);
}
return $this;
}
/**
* @param string $username
* @return $this
*/
public function search($word = '')
{
/*$this->joinWith("cmsUserPhones as cmsUserPhones");
$this->joinWith("cmsUserEmails as cmsUserEmails");*/
$this->groupBy($this->getPrimaryTableName().'.id');
return $this->andWhere([
'or',
['like', $this->getPrimaryTableName().'.name', $word],
['like', $this->getPrimaryTableName().'.description', $word],
]);
}
} | 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/queries/CmsUserScheduleQuery.php | src/models/queries/CmsUserScheduleQuery.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\queries;
use skeeks\cms\models\CmsCompany;
use skeeks\cms\models\CmsContractor;
use skeeks\cms\models\CmsLog;
use skeeks\cms\models\CmsUser;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\rbac\CmsManager;
use yii\db\Expression;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsUserScheduleQuery extends CmsActiveQuery
{
/**
* @param string|array $types
* @return $this
*/
public function user($user)
{
$user_id = null;
if ($user instanceof CmsUser) {
$user_id = $user->id;
} else {
$user_id = (int) $user;
}
$this->andWhere(['cms_user_id' => $user_id]);
return $this;
}
/**
* @return $this
*/
public function notEnd()
{
$this->andWhere(['end_at' => null]);
return $this;
}
/**
* @return CmsUserScheduleQuery
* @throws \yii\base\InvalidConfigException
*/
public function today()
{
$date = \Yii::$app->formatter->asDate(time(), "php:Y-m-d");
return $this->andWhere([
'or',
new Expression("FROM_UNIXTIME(start_at, '%Y-%m-%d') = '{$date}'"),
new Expression("FROM_UNIXTIME(end_at, '%Y-%m-%d') = '{$date}'"),
]);
}
} | 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/queries/CmsSavedFilterQuery.php | src/models/queries/CmsSavedFilterQuery.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\queries;
use http\Exception\InvalidArgumentException;
use skeeks\cms\models\CmsContent;
use skeeks\cms\models\CmsTree;
use skeeks\cms\query\CmsActiveQuery;
use skeeks\cms\shop\models\ShopBrand;
/**
* @author Semenov Alexander <semenov@skeeks.com>
*/
class CmsSavedFilterQuery extends CmsActiveQuery
{
/**
* @param CmsTree|int|string|array $cmsTree
* @return CmsSavedFilterQuery
*/
public function tree(mixed $cmsTree)
{
$cms_tree_id = '';
if ($cmsTree instanceof CmsTree) {
$cms_tree_id = $cmsTree->id;
} elseif (is_int($cmsTree)) {
$cms_tree_id = $cmsTree;
} elseif(is_string($cmsTree)) {
$cms_tree_id = (int) $cmsTree;
} elseif(is_array($cmsTree)) {
$cms_tree_id = (array) $cmsTree;
} else {
throw new InvalidArgumentException("Ошибка");
}
return $this->andWhere(['cms_tree_id' => $cms_tree_id]);
}
/**
* @param CmsTree|int|string|array $value
* @return CmsSavedFilterQuery
*/
public function brand(mixed $value)
{
$brand_id = '';
if ($value instanceof ShopBrand) {
$brand_id = $value->id;
} elseif (is_int($value)) {
$brand_id = $value;
} elseif(is_string($value)) {
$brand_id = (int) $value;
} elseif(is_array($value)) {
$brand_id = (array) $value;
} else {
throw new InvalidArgumentException("Ошибка");
}
return $this->andWhere(['shop_brand_id' => $brand_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/callcheck/CallcheckHandler.php | src/callcheck/CallcheckHandler.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\callcheck;
use skeeks\cms\IHasConfigForm;
use skeeks\cms\models\CmsCallcheckMessage;
use skeeks\cms\traits\HasComponentDescriptorTrait;
use skeeks\cms\traits\TConfigForm;
use yii\base\Model;
/**
* @property Model $checkoutModel
*
* @author Semenov Alexander <semenov@skeeks.com>
*/
abstract class CallcheckHandler extends Model implements IHasConfigForm
{
use HasComponentDescriptorTrait;
use TConfigForm;
/**
* @param $phone
* @return mixed
*/
abstract public function callcheck($phone);
abstract public function callcheckMessage(CmsCallcheckMessage $callcheckMessage);
/**
* @return int
*/
public function balance()
{
return 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/views/admin-cms-project/view.php | src/views/admin-cms-project/view.php | <?php
/* @var $model \skeeks\cms\models\CmsUser */
/* @var $this yii\web\View */
/* @var $controller \skeeks\cms\backend\controllers\BackendModelController */
/* @var $action \skeeks\cms\backend\actions\BackendModelCreateAction|\skeeks\cms\backend\actions\IHasActiveForm */
/* @var $model \skeeks\cms\models\CmsProject */
$controller = $this->context;
$action = $controller->action;
$model = $action->model;
?>
<div class="sx-block">
<?php if ($model->description) : ?>
<div style="margin-bottom: 1rem;"><?php echo $model->description; ?></div>
<?php endif; ?>
<div class="sx-properties-wrapper sx-columns-1">
<ul class="sx-properties">
<!--<li>
<span class="sx-properties--name">
Создан
</span>
<span class="sx-properties--value">
<?php /*echo \Yii::$app->formatter->asDate($model->created_at) */ ?>
</span>
</li>-->
<li>
<span class="sx-properties--name">
Тип проекта
</span>
<span class="sx-properties--value">
<?php if ($model->is_private) : ?>
Закрытый
<?php else : ?>
Открытый
<?php endif; ?>
</span>
</li>
<?php if ($model->cms_company_id) : ?>
<li>
<span class="sx-properties--name">
Компания
</span>
<span class="sx-properties--value">
<?php $widget = \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::begin([
'controllerId' => '/cms/admin-cms-company',
'modelId' => $model->cmsCompany->id,
'isRunFirstActionOnClick' => true,
'options' => [
'class' => 'sx-dashed',
'style' => 'cursor: pointer; border-bottom: 1px dashed;',
],
]); ?>
<?php echo $model->cmsCompany->name; ?>
<?php $widget::end(); ?>
</span>
</li>
<?php endif; ?>
<?php if ($model->managers) : ?>
<li>
<span class="sx-properties--name">
Работают с проектом
</span>
<span class="sx-properties--value">
<?php foreach ($model->managers as $manager) : ?>
<?php echo \skeeks\cms\widgets\admin\CmsWorkerViewWidget::widget(['user' => $manager, "isSmall" => true]); ?>
<?php endforeach; ?>
</span>
</li>
<?php endif; ?>
<?php if ($model->users) : ?>
<li>
<span class="sx-properties--name">
Работают с проектом
</span>
<span class="sx-properties--value">
<?php foreach ($model->users as $user) : ?>
<?php echo \skeeks\cms\widgets\admin\CmsUserViewWidget::widget(['cmsUser' => $user, "isSmall" => true]); ?>
<?php endforeach; ?>
</span>
</li>
<?php endif; ?>
<li>
<span class="sx-properties--name">
Количество задач
</span>
<span class="sx-properties--value">
<?php
$count = $model->getTasks()->count();
if ($count) : ?>
<?php echo \Yii::$app->formatter->asInteger($count); ?>
<?php else : ?>
—
<?php endif; ?>
</span>
</li>
</ul>
</div>
</div>
<?php $pjax = \skeeks\cms\widgets\Pjax::begin([
'id' => 'sx-comments',
]); ?>
<div class="row">
<div class="col-12">
<div class="sx-block">
<?php echo \skeeks\cms\widgets\admin\CmsCommentWidget::widget([
'model' => $model,
]); ?>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<?php echo \skeeks\cms\widgets\admin\CmsLogListWidget::widget([
'query' => $model->getLogs()->comments(),
'is_show_model' => false,
]); ?>
</div>
</div>
<?php $pjax::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/views/admin-profile/password.php | src/views/admin-profile/password.php | <?
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 26.02.2017
*/
/* @var $this \yii\web\View */
/* @var \skeeks\cms\models\forms\PasswordChangeForm $model */
$this->registerCss(<<<CSS
.sx-view-pass {
position: absolute;
right: 2.75rem;
top: 2.85rem;
cursor: pointer;
}
.sx-generate-pass {
border-bottom: 1px dashed;
}
.sx-generate-pass:hover {
text-decoration: none;
}
CSS
);
$passId = \yii\helpers\Html::getInputId($model, "password");
$this->registerJs(<<<JS
$("body").on("click", ".sx-view-pass", function() {
var jInput = $("input#{$passId}");
var jIcon = $(this);
if (jInput.attr("type") == 'password') {
jInput.attr('type', 'text');
jIcon.addClass("fa-eye-slash");
jIcon.removeClass("fa-eye");
} else {
jInput.attr('type', 'password');
jIcon.addClass("fa-eye");
jIcon.removeClass("fa-eye-slash");
}
});
$("body").on("click", ".sx-generate-pass", function() {
var jInput = $("input#{$passId}");
var jIcon = $(".sx-view-pass");
var pass = password_generator(8);
jInput.attr('type', 'text');
jInput.val(pass);
jIcon.addClass("fa-eye-slash");
jIcon.removeClass("fa-eye");
return false;
});
function gen_password(len){
var password = "";
var symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!№;%:?*()_+=";
for (var i = 0; i < len; i++){
password += symbols.charAt(Math.floor(Math.random() * symbols.length));
}
return password;
}
function password_generator( len ) {
var length = (len)?(len):(10);
var string = "abcdefghijklmnopqrstuvwxyz"; //to upper
var numeric = '0123456789';
var punctuation = '!@#$%^&*()_+~`|}{[]\:;?><,./-=';
var password = "";
var character = "";
var crunch = true;
while( password.length<length ) {
entity1 = Math.ceil(string.length * Math.random()*Math.random());
entity2 = Math.ceil(numeric.length * Math.random()*Math.random());
entity3 = Math.ceil(punctuation.length * Math.random()*Math.random());
hold = string.charAt( entity1 );
hold = (password.length%2==0)?(hold.toUpperCase()):(hold);
character += hold;
character += numeric.charAt( entity2 );
character += punctuation.charAt( entity3 );
password = character;
}
password=password.split('').sort(function(){return 0.5-Math.random()}).join('');
return password.substr(0,len);
}
JS
);
?>
<!--<h1>Смена пароля</h1>-->
<div class="row">
<div class="col-12" style="max-width: 50rem;">
<?php if (!\Yii::$app->user->identity->password_hash && \Yii::$app->cms->pass_is_need_change) : ?>
<?php $alert = \yii\bootstrap\Alert::begin([
'closeButton' => false,
'id' => "no-pass",
'options' => [
'class' => 'alert-danger',
],
]); ?>
<b>Внимание!</b> <br/> Для продолжения работы, придумайте свой постоянный пароль, с которым вы будете входить в систему в дальнейшем.
<?php $alert::end(); ?>
<?php endif; ?>
<?php $form = \skeeks\cms\backend\widgets\ActiveFormAjaxBackend::begin([
'clientSuccess' => new \yii\web\JsExpression(<<<JS
function (ActiveFormAjaxSubmit) {
if ($("#no-pass").length) {
$("#no-pass").fadeOut();
}
}
JS
)
]); ?>
<div style="position:relative;">
<i class="far fa-eye sx-view-pass"></i>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<a href="#" class="sx-generate-pass">Сгенерировать пароль</a>
</div>
</div>
<?= $form->buttonsStandart($model) ?>
<?php $form::end(); ?>
</div>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/admin-profile/update.php | src/views/admin-profile/update.php | <?
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 26.02.2017
*/
/* @var $this \yii\web\View */
/* @var \yii\web\User $model */
?>
<!--<h1>Личные данные</h1>-->
<div class="row">
<div class="col-12" style="max-width: 50rem;">
<?php if (!$model->email || !$model->first_name || !$model->last_name
//|| !$model->image
) : ?>
<?php $alert = \yii\bootstrap\Alert::begin([
'closeButton' => false,
'id' => "no-info",
'options' => [
'class' => 'alert-danger',
],
]); ?>
<p><b>Внимание!</b></p>
<p>Для продолжения работы с системой управления сайта требуется указать ваши данные:</p>
<ul>
<li>Реальный email</li>
<li>Фамилия</li>
<li>Имя</li>
<!--<li>Фото</li>-->
</ul>
<?php $alert::end(); ?>
<?php endif; ?>
<?php $form = \skeeks\cms\backend\widgets\ActiveFormAjaxBackend::begin([
'clientSuccess' => new \yii\web\JsExpression(<<<JS
function (ActiveFormAjaxSubmit) {
if ($("#no-info").length) {
$("#no-info").fadeOut();
}
}
JS
)
]); ?>
<?
\skeeks\cms\admin\assets\JqueryMaskInputAsset::register($this);
$id = \yii\helpers\Html::getInputId($model, 'phone');
$this->registerJs(<<<JS
$("#{$id}").mask("+7 999 999-99-99");
JS
);
?>
<?php echo $form->field($model, "image_id")->widget(\skeeks\cms\widgets\AjaxFileUploadWidget::class, [
//'view_file' => '@skeeks/yii2/ajaxfileupload/widgets/views/default',
'accept' => 'image/*',
'multiple' => false,
]); ?>
<?= $form->field($model, 'gender')->widget(
\skeeks\cms\widgets\Select::class,
[
'options' => [
'placeholder' => "Пол не указан..."
],
'data' => [
'men' => \Yii::t('skeeks/cms', 'Male'),
'women' => \Yii::t('skeeks/cms', 'Female'),
]
]
); ?>
<?= $form->field($model, 'first_name') ?>
<?= $form->field($model, 'last_name') ?>
<?= $form->field($model, 'patronymic') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'phone') ?>
<?= $form->field($model, 'birthday_at')->widget(
\skeeks\cms\backend\widgets\forms\DateControlInputWidget::class,
[
'type' => \skeeks\cms\backend\widgets\forms\DateControlInputWidget::FORMAT_DATE
]
); ?>
<?= $form->buttonsStandart($model) ?>
<?= $form->errorSummary([$model]) ?>
<?php $form::end(); ?>
</div>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/admin-cms-department/copy-tree.php | src/views/admin-cms-department/copy-tree.php | <?php
use skeeks\cms\models\Tree;
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model Tree */
/* @var $this yii\web\View */
/* @var $controller \skeeks\cms\backend\controllers\BackendModelController */
/* @var $action \skeeks\cms\backend\actions\BackendModelCreateAction|\skeeks\cms\backend\actions\IHasActiveForm */
/* @var $model \skeeks\cms\models\CmsLang */
/* @var $relatedModel \skeeks\cms\relatedProperties\models\RelatedPropertiesModel */
$controller = $this->context;
$action = $controller->action;
?>
<? $form = \skeeks\cms\base\widgets\ActiveFormAjaxSubmit::begin([
'clientCallback' => new \yii\web\JsExpression(<<<JS
function (ActiveFormAjaxSubmit) {
ActiveFormAjaxSubmit.on('success', function(e, response) {
$("#sx-result").empty();
if (response.data.html) {
$("#sx-result").append(response.data.html);
}
});
}
JS
)
]); ?>
<?php echo $form->field($dm, 'is_copy_childs')->checkbox(); ?>
<?php echo $form->field($dm, 'is_copy_elements')->checkbox(); ?>
<div class="form-group">
<button type="submit" class="btn btn-primary">Запустить копирование</button>
</div>
<? $form::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/views/admin-cms-department/_form.php | src/views/admin-cms-department/_form.php | <?php
use skeeks\cms\models\Tree;
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model Tree */
/* @var $this yii\web\View */
/* @var $controller \skeeks\cms\backend\controllers\BackendModelController */
/* @var $action \skeeks\cms\backend\actions\BackendModelCreateAction|\skeeks\cms\backend\actions\IHasActiveForm */
/* @var $model \skeeks\cms\models\CmsLang */
/* @var $relatedModel \skeeks\cms\relatedProperties\models\RelatedPropertiesModel */
$controller = $this->context;
$action = $controller->action;
\skeeks\cms\themes\unify\admin\assets\UnifyAdminIframeAsset::register($this);
?>
<?php $pjax = \skeeks\cms\widgets\Pjax::begin(); ?>
<?php $form = $action->beginActiveForm(); ?>
<?php echo $form->errorSummary([$model, $model->relatedPropertiesModel]); ?>
<? $fieldSet = $form->fieldSet(\Yii::t('skeeks/cms', 'Main')); ?>
<div class="d-flex">
<div>
<?= $form->field($model, 'active')->checkbox([
'uncheck' => \skeeks\cms\components\Cms::BOOL_N,
'value' => \skeeks\cms\components\Cms::BOOL_Y,
]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>
<?php if ($model->level > 0) : ?>
<div data-listen="isLink" data-show="0" class="sx-hide">
<?php
$this->registerCss(<<<CSS
.sx-link-url .form-group {
padding: 0px !important;
}
.sx-link-url .form-control {
border: 0 !important;
padding: 0 !important;
}
CSS
);
?>
<div class="form-group sx-link-url">
<label class="control-label" for="tree-code">Адрес страницы</label>
<div class="d-flex no-fluid">
<div class="my-auto">
<?php if ($model->parent->level == 0) : ?>
<?php echo $model->parent->url; ?>
<?php else: ?>
<?php echo $model->parent->url; ?>/
<?php endif; ?>
</div>
<div style="width: 100%;">
<?= $form->field($model, 'code')
->textInput(['maxlength' => 255])
->label(false); ?>
</div>
<!--\Yii::t('skeeks/cms', 'This affects the address of the page, be careful when editing.')-->
</div>
</div>
</div>
<?php endif; ?>
<?= $form->field($model, 'tree_type_id')->widget(
\skeeks\cms\widgets\AjaxSelect::class,
[
'dataCallback' => function ($q = '') {
$query = \skeeks\cms\models\CmsTreeType::find()
->active();
if ($q) {
$query->andWhere(['like', 'name', $q]);
}
$data = $query->limit(100)
->all();
$result = [];
if ($data) {
foreach ($data as $model) {
$result[] = [
'id' => $model->id,
'text' => $model->name,
];
}
}
return $result;
},
'valueCallback' => function ($value) {
return \yii\helpers\ArrayHelper::map(\skeeks\cms\models\CmsTreeType::find()->where(['id' => $value])->all(), 'id', 'name');
},
/*'items' => \yii\helpers\ArrayHelper::map(
\skeeks\cms\models\CmsTreeType::find()->active()->all(),
"id",
"name"
),*/
'allowDeselect' => false,
'options' => [
'data-form-reload' => 'true',
],
])->label('Тип раздела')->hint(\Yii::t('skeeks/cms',
'On selected type of partition can depend how it will be displayed.'));
?>
</div>
<div>
<?= $form->field($model, 'image_id')->widget(
\skeeks\cms\widgets\AjaxFileUploadWidget::class,
[
'accept' => 'image/*',
'multiple' => false,
]
); ?>
</div>
</div>
<div class="form-group">
<?= Html::checkbox("isLink", (bool)($model->redirect || $model->redirect_tree_id), [
'value' => '1',
'label' => \Yii::t('skeeks/cms', 'Этот раздел является ссылкой (редирректом)'),
'class' => 'smartCheck',
'id' => 'isLink',
]); ?>
</div>
<div data-listen="isLink" data-show="1" class="sx-hide">
<?= \skeeks\cms\modules\admin\widgets\BlockTitleWidget::widget([
'content' => \Yii::t('skeeks/cms', 'Настройки перенаправления (редирректа)'),
]); ?>
<?= $form->field($model, 'redirect_code', [])->radioList([
301 => 'Постоянное перенаправление [301]',
302 => 'Временное перенаправление [302]',
])
->label(\Yii::t('skeeks/cms', 'Redirect Code')) ?>
<div class="d-flex">
<div style="min-width: 300px;" class="my-auto">
<? /*= $form->field($model, 'redirect_tree_id')->widget(
\skeeks\cms\backend\widgets\SelectModelDialogTreeWidget::class
) */ ?>
<?= $form->field($model, 'redirect_tree_id')->widget(
\skeeks\cms\widgets\formInputs\selectTree\SelectTreeInputWidget::class,
[
'multiple' => false,
]
)->label("Выбрать раздел")->hint("Выбрать существующий раздел"); ?>
</div>
<div class="my-auto">
или
</div>
<div style="width: 100%;">
<?= $form->field($model, 'redirect', [])->textInput(['maxlength' => 500])->label(\Yii::t('skeeks/cms',
'Redirect'))
->label("Ссылка в свободной форме")
->hint(\Yii::t('skeeks/cms',
'Specify an absolute or relative URL for redirection, in the free form.')) ?>
</div>
</div>
</div>
<?php $relatedModel->initAllProperties(); ?>
<?php if ($relatedModel->properties) : ?>
<?= \skeeks\cms\modules\admin\widgets\BlockTitleWidget::widget([
'content' => \Yii::t('skeeks/cms', 'Additional properties'),
]); ?>
<?php foreach ($relatedModel->properties as $property) : ?>
<?
if (in_array($property->property_type, [
\skeeks\cms\relatedProperties\PropertyType::CODE_LIST,
\skeeks\cms\relatedProperties\PropertyType::CODE_ELEMENT,
])) {
$property->handler->setAjaxSelectUrl(\yii\helpers\Url::to(['/cms/ajax/autocomplete-tree-eav-options', 'property_id' => $property->id, 'cms_site_id' => \Yii::$app->skeeks->site->id]));
$property->handler->setEnumClass(\skeeks\cms\models\CmsTreeTypePropertyEnum::class);
}
?>
<?= $property->renderActiveForm($form, $model); ?>
<?php endforeach; ?>
<?php else
: ?>
<?php /*= \Yii::t('skeeks/cms','Additional properties are not set')*/ ?>
<?php endif;
?>
<? $fieldSet::end(); ?>
<?php
$prodcutsContent = \skeeks\cms\models\CmsContent::find()->isProducts()->andWhere(['cms_tree_type_id' => $model->tree_type_id])->one();
if ($prodcutsContent) :
?>
<? $fieldSet = $form->fieldSet(\Yii::t('skeeks/cms', 'Настройки магазина'), ['isOpen' => true]); ?>
<?php
$this->registerJs(<<<JS
if ($(".field-tree-shop_has_collections input").is(":checked")) {
$(".field-tree-shop_show_collections").slideDown();
} else {
$(".field-tree-shop_show_collections").slideUp();
}
$(".field-tree-shop_has_collections input").on("change", function () {
if ($(this).is(":checked")) {
$(".field-tree-shop_show_collections").slideDown();
} else {
$(".field-tree-shop_show_collections").slideUp();
}
});
JS
);
?>
<?php echo $form->field($model, 'shop_has_collections')->checkbox(); ?>
<?php echo $form->field($model, 'shop_show_collections')->checkbox(); ?>
<? $fieldSet::end(); ?>
<?php endif; ?>
<? $fieldSet = $form->fieldSet(\Yii::t('skeeks/cms', 'Announcement'), ['isOpen' => false]); ?>
<?= $form->field($model, 'description_short')->label(false)->widget(
\skeeks\cms\widgets\formInputs\comboText\ComboTextInputWidget::className(),
[
'modelAttributeSaveType' => 'description_short_type',
]);
?>
<?php /*= $form->field($model, 'description_short')->widget(
\skeeks\cms\widgets\formInputs\comboText\ComboTextInputWidget::className(),
[
'modelAttributeSaveType' => 'description_short_type',
'ckeditorOptions' => [
'preset' => 'full',
'relatedModel' => $model,
],
'codemirrorOptions' =>
[
'preset' => 'php',
'assets' =>
[
\skeeks\widget\codemirror\CodemirrorAsset::THEME_NIGHT
],
'clientOptions' =>
[
'theme' => 'night',
],
]
])
*/ ?>
<? $fieldSet::end(); ?>
<div data-listen="isLink" data-show="0" class="sx-hide">
<? $fieldSet = $form->fieldSet(\Yii::t('skeeks/cms', 'In detal'), ['isOpen' => false]); ?>
<?= $form->field($model, 'image_full_id')->widget(
\skeeks\cms\widgets\AjaxFileUploadWidget::class,
[
'accept' => 'image/*',
'multiple' => false,
]
); ?>
<?= $form->field($model, 'description_full')->widget(
\skeeks\cms\widgets\formInputs\comboText\ComboTextInputWidget::className(),
[
'modelAttributeSaveType' => 'description_full_type',
]);
?>
<? $fieldSet::end(); ?>
</div>
<div data-listen="isLink" data-show="0" class="sx-hide">
<? $fieldSet = $form->fieldSet(\Yii::t('skeeks/cms', 'SEO'), ['isOpen' => false]); ?>
<?= $form->field($model, 'is_index')->checkbox(); ?>
<?= $form->field($model, 'seo_h1'); ?>
<?= $form->field($model, 'meta_title')->textarea(); ?>
<?= $form->field($model, 'meta_description')->textarea(); ?>
<?= $form->field($model, 'meta_keywords')->textarea(); ?>
<div class="form-group">
<?= Html::checkbox("isCanonical", (bool)($model->isCanonical), [
'value' => '1',
'label' => \Yii::t('skeeks/cms', 'Указать атрибут canonical'),
'class' => 'smartCheck',
'id' => 'isCanonical',
]); ?>
<div class="hint-block">Атрибут rel=canonical сообщает поисковой системе, что некоторые страницы сайта являются одинаковыми <a href='https://skeeks.com/atribut-rel-canonical-chto-ehto-i-dlya-chego-isp-501'
data-pjax='0' target='_blank'>подробнее</a></div>
</div>
<div data-listen="isCanonical" data-show="1" class="sx-hide">
<?= \skeeks\cms\modules\admin\widgets\BlockTitleWidget::widget([
'content' => \Yii::t('skeeks/cms', 'Настройки canonical'),
]); ?>
<div class="d-flex">
<div style="min-width: 300px;">
<? /*= $form->field($model, 'redirect_tree_id')->widget(
\skeeks\cms\backend\widgets\SelectModelDialogTreeWidget::class
) */ ?>
<?= $form->field($model, 'canonical_tree_id')->widget(
\skeeks\cms\widgets\formInputs\selectTree\SelectTreeInputWidget::class,
[
'multiple' => false,
]
)->label("Выбрать раздел"); ?>
</div>
<div class="my-auto">
или
</div>
<div style="width: 100%;">
<?= $form->field($model, 'canonical_link', [])->textInput(['maxlength' => 500])->label(\Yii::t('skeeks/cms',
'Redirect'))
->label("Ссылка в свободной форме")
->hint(\Yii::t('skeeks/cms',
'Укажите абсолютный или относительный адрес ссылки.')) ?>
</div>
</div>
</div>
<? $fieldSet::end(); ?>
</div>
<div data-listen="isLink" data-show="0" class="sx-hide">
<? $fieldSet = $form->fieldSet(\Yii::t('skeeks/cms', 'Оформление/Дизайн'), ['isOpen' => false]); ?>
<?
$currentTheme = \skeeks\cms\models\CmsTheme::find()->cmsSite()->active()->one();
$this->registerCss(<<<CSS
.btn-check .sx-title {
font-size: 16px;
font-weight: bold;
}
.btn-check .sx-other {
display: none;
}
.btn-check .sx-checked-icon {
font-size: 16px;
display: none;
margin-right: 5px;
}
.btn-check {
text-align: left;
padding: 20px;
background: #ececec;
border: 1px solid gray;
}
.sx-checked {
background: #6c757d;
color: white;
}
.sx-checked:hover {
background: #6c757d;
color: white;
}
.sx-checked .sx-title {
font-weight: bold;
}
.sx-checked .sx-checked-icon {
display: block;
}
.sx-checked .sx-other {
display: block;
}
.sx-other .form-group {
margin: 0 !important;;
padding: 0 !important;
}
.sx-other .form-group:hover {
background: transparent !important;
}
CSS
);
$this->registerJs(<<<JS
$(".sx-available-trees .btn-check").on("click", function() {
$(".sx-available-trees .btn-check").removeClass("sx-checked");
$(this).addClass("sx-checked");
var code = $(this).data("code");
$("#tree-view_file").val(code);
if (code == 'sx-other') {
$("#tree-view_file").val("");
}
return false;
});
if ($(".sx-available-trees .btn-check.sx-checked").length == 0) {
$(".sx-other-btn").addClass("sx-checked");
}
JS
);
?>
<div class="col-12" style="margin-top: 15px;">
<div class="alert alert-default">
<p>От этих настроек зависит как будет выглядеть раздел на сайте.</p>
По умолчанию страница оформляется согласно выбранному:
<ol>
<li>Общему шаблону сайта (задается в настройках сайта для всех страниц)</li>
<li>Типу раздела (выше у вас уже выбран тип, опрределяющий оформление этой страницы)</li>
</ol>
Если вы хотите чтобы этот раздел был оформлен иначе, нажмите опцию ниже <b>(Использовать персональный шаблон для страницы)</b>
</div>
<?
/**
* @var $currentTheme \skeeks\cms\models\CmsTheme
*/
$treeViews = [];
?>
<?php if ($currentTheme) : ?>
<?php
$treeViews = $currentTheme->objectTheme->treeViews;
?>
<div class="alert alert-default">
<div style="margin-bottom: 5px;">
<b>Общий шаблон подключенный к сайту:</b>
</div>
<div class="d-flex">
<?php if ($currentTheme->themeImageSrc) : ?>
<div class="my-auto" style="width: 60px;">
<img style="width: 50px; border-radius: 8px; border: 1px solid silver;" src="<?php echo $currentTheme->themeImageSrc; ?>"/>
</div>
<?php endif; ?>
<div class="my-auto">
<b><?php echo $currentTheme->themeName; ?></b>
</div>
<div class="my-auto" style="margin-left: 10px;">
<a href="<?php echo \skeeks\cms\backend\helpers\BackendUrlHelper::createByParams(['/cms/admin-cms-theme'])->disableEmptyLayout()->url; ?>" target="_blank" data-pjax="0"
class="btn btn-default btn-xs">Изменить</a>
</div>
</div>
<div style="color: gray; font-size: 10px;">От выбранного шаблона, будут зависеть доступные шаблоны страниц. <br/>
Разные шаблоны имеют разные наборы для оформления страниц.
</div>
</div>
<?php endif; ?>
</div>
<div class="form-group">
<?= Html::checkbox("isSelfTemplate", (bool)($model->view_file), [
'value' => '1',
'label' => \Yii::t('skeeks/cms', 'Использовать персональный шаблон для страницы'),
'class' => 'smartCheck',
'id' => 'isSelfTemplate',
]); ?>
</div>
<div data-listen="isSelfTemplate" data-show="0" class="sx-show">
<div class="col-md-6 col-12" style="margin-top: 15px; margin-bottom: 15px;">
<div class="btn btn-block btn-check sx-checked">
<div class="d-flex">
<span class="sx-checked-icon" data-icon="✓">
✓
</span>
<span class="sx-title">
<?php echo \yii\helpers\ArrayHelper::getValue($treeViews, [$model->cmsTreeType->code, 'name'], $model->cmsTreeType->code); ?>
</span>
</div>
<div class="sx-description">
<?php echo \yii\helpers\ArrayHelper::getValue($treeViews, [$model->cmsTreeType->code, 'description']); ?>
</div>
</div>
</div>
</div>
<div data-listen="isSelfTemplate" data-show="1" class="sx-hide">
<div class="sx-available-trees">
<?php if ($treeViews) : ?>
<?php foreach ($treeViews as $code => $treeView) : ?>
<div class="col-md-6 col-12" style="margin-top: 15px; margin-bottom: 15px;">
<div class="btn btn-block btn-check <?php echo $code == $model->view_file ? "sx-checked" : ""; ?>" data-code="<?php echo $code; ?>">
<div class="d-flex">
<span class="sx-checked-icon" data-icon="✓">
✓
</span>
<span class="sx-title">
<?php echo \yii\helpers\ArrayHelper::getValue($treeView, ['name'], $model->cmsTreeType->code); ?>
</span>
</div>
<div class="sx-description">
<?php echo \yii\helpers\ArrayHelper::getValue($treeView, ['description']); ?>
</div>
</div>
</div>
<?php endforeach; ?>
<div class="col-md-6 col-12" style="margin-top: 15px; margin-bottom: 15px;">
<div class="btn btn-block btn-check sx-other-btn" data-code="sx-other">
<div class="d-flex">
<span class="sx-checked-icon" data-icon="✓">
✓
</span>
<span class="sx-title">
Другое
</span>
</div>
<div class="sx-description">
Можно указать в свободной форме (обычно это используют разработчики)
</div>
<div class="sx-other">
<?= $form->field($model, 'view_file')->label("Укажите код шаблона")->textInput()
->hint('@app/views/template-name || template-name');
?>
</div>
</div>
</div>
<?php endif; ?>
</div>
</div>
<? $fieldSet::end(); ?>
</div>
<? $fieldSet = $form->fieldSet(\Yii::t('skeeks/cms', 'Дополнительно'), ['isOpen' => false]); ?>
<?= $form->field($model, 'name_hidden')->textInput(['maxlength' => 255])->hint(\Yii::t('skeeks/cms', 'Не отображается на сайте! Показывается только как пометка возле названия раздела в админ части сайта.')) ?>
<?= $form->field($model, 'is_adult')->checkbox(); ?>
<? $fieldSet::end(); ?>
<? $fieldSet = $form->fieldSet(\Yii::t('skeeks/cms', 'Images/Files'), ['isOpen' => false]); ?>
<?= $form->field($model, 'imageIds')->widget(
\skeeks\cms\widgets\AjaxFileUploadWidget::class,
[
'accept' => 'image/*',
'multiple' => true,
]
); ?>
<?= $form->field($model, 'fileIds')->widget(
\skeeks\cms\widgets\AjaxFileUploadWidget::class,
[
'multiple' => true,
]
); ?>
<? $fieldSet::end(); ?>
<?= $form->buttonsStandart($model); ?>
<?php $this->registerJs(<<<JS
(function(sx, $, _)
{
sx.createNamespace('classes', sx);
sx.classes.SmartCheck = sx.classes.Component.extend({
_init: function()
{},
_onDomReady: function()
{
var self = this;
$('.smartCheck').each(function() {
var jSmartCheck = $(this);
self.updateInstance(jSmartCheck);
jSmartCheck.on("change", function()
{
self.updateInstance($(this));
});
});
},
updateInstance: function(JsmartCheck)
{
if (!JsmartCheck instanceof jQuery)
{
throw new Error('1');
}
var id = JsmartCheck.attr('id');
var val = Number(JsmartCheck.is(":checked"));
console.log(id);
if (!id)
{
return false;
}
if (val == 0)
{
if (id == 'isCanonical') {
$('#tree-canonical_link').val('');
$('#tree-canonical_tree_id').val('');
} else if(id == 'isSelfTemplate') {
$('#tree-view_file').val('');
} else {
$('#tree-redirect').val('');
$('#tree-redirect_tree_id').val('');
}
}
$('[data-listen="' + id + '"]').hide();
$('[data-listen="' + id + '"][data-show="' + val + '"]').show();
},
});
new sx.classes.SmartCheck();
})(sx, sx.$, sx._);
JS
);
?>
<?php echo $form->errorSummary([$model, $model->relatedPropertiesModel]); ?>
<?php $form::end(); ?>
<?php $pjax::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/views/admin-cms-department/new-children.php | src/views/admin-cms-department/new-children.php | <?php
/**
* new-children
*
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010-2014 SkeekS (Sx)
* @date 15.11.2014
* @since 1.0.0
*/
?>
<?= $this->render('_form', [
'model' => $model
]); ?>
<hr/>
<?php /*= \yii\helpers\Html::a('Пересчитать приоритеты по алфавиту', '#', ['class' => 'btn btn-xs btn-primary']) ?> |
<?= \yii\helpers\Html::a('Пересчитать приоритеты по дате добавления', '#', ['class' => 'btn btn-xs btn-primary']) ?> |
<?= \yii\helpers\Html::a('Пересчитать приоритеты по дате обновления', '#', ['class' => 'btn btn-xs btn-primary']) */ ?>
<?= $this->render('_recalculate-children-priorities', [
'model' => $model
]); ?>
<?= $this->render('list', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'controller' => $controller,
]); ?> | php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/admin-cms-department/_model_header.php | src/views/admin-cms-department/_model_header.php | <?php
/**
* @link https://cms.skeeks.com/
* @copyright Copyright (c) 2010 SkeekS
* @license https://cms.skeeks.com/license/
* @author Semenov Alexander <semenov@skeeks.com>
*/
/**
* @var $this yii\web\View
* @var $model \skeeks\cms\models\CmsTree
*/
$controller = $this->context;
?>
<div class="row" style="margin-bottom: 5px;">
<? if ($model->image) : ?>
<div class="col my-auto" style="max-width: 60px">
<img style="border: 2px solid #ededed; border-radius: 5px;" src="<?php echo \Yii::$app->imaging->getImagingUrl($model->image->src,
new \skeeks\cms\components\imaging\filters\Thumbnail()); ?>" />
</div>
<? endif; ?>
<div class="col my-auto">
<div class="d-flex">
<div>
<h1 style="margin-bottom: 0px; line-height: 1.1;">
<?php echo $model->name; ?>
<? if ($model->is_adult) : ?>
<span style="font-size: 17px; color: red; font-weight: bold; color: #ff0000bd;">
<span data-toggle="tooltip" title="Этот раздел содержит информацию для взрослых. Имеет возрастные ограничения 18+">[18+]</span>
</span>
<? endif; ?>
<? if (!$model->isAllowIndex) : ?>
<span style="font-size: 17px; color: red; font-weight: bold; color: #ff0000bd;">
<span data-toggle="tooltip" title="Эта страница не индексируется поисковыми системами!">[no index]</span>
</span>
<? endif; ?>
<? if (isset($model->sx_id) && $model->sx_id) : ?>
<span style="font-size: 17px; font-weight: bold;">
<span data-toggle='tooltip' title='SkeekS Suppliers ID: <?php echo $model->sx_id; ?>'><i class='fas fa-link'></i></span>
</span>
<? endif; ?>
<?/* if ($model->is_index == 0 || $model->isRedirect || $model->isCanonical) : */?><!--
<span style="font-size: 17px; color: red; font-weight: bold; color: #ff0000bd;">
<span data-toggle="tooltip" title="Эта страница не попадает в карту сайта!">[no sitemap]</span>
</span>
--><?/* endif; */?>
<? if ($model->isCanonical) : ?>
<span style="font-size: 17px; color: red; font-weight: bold; color: #ff0000bd;">
<span data-toggle="tooltip" title="У этой страницы задана атрибут rel=canonical на сатраницу: <?php echo $model->canonicalUrl; ?>">[canonical]</span>
</span>
<? endif; ?>
<? if ($model->isRedirect) : ?>
<span style="font-size: 17px;">
<i class="fas fa-directions" data-toggle="tooltip" title="<?= $model->redirect_code ?> редиррект посетителя на страницу: <?= $model->url; ?>"></i>
</span>
<? endif; ?>
</h1>
<div class="sx-small-info" style="font-size: 10px; color: silver;">
<span title="ID записи - уникальный код записи в базе данных." data-toggle="tooltip"><i class="fas fa-key"></i> <?php echo $model->id; ?></span>
<? if ($model->created_at) : ?>
<span style="margin-left: 5px;" data-toggle="tooltip" title="Запись создана в базе: <?php echo \Yii::$app->formatter->asDatetime($model->created_at); ?>"><i class="far fa-clock"></i> <?php echo \Yii::$app->formatter->asDate($model->created_at); ?></span>
<? endif; ?>
<? if ($model->created_by) : ?>
<span style="margin-left: 5px;" data-toggle="tooltip" title="Запись создана пользователем с ID: <?php echo $model->createdBy->id; ?>"><i class="far fa-user"></i> <?php echo $model->createdBy->shortDisplayName; ?></span>
<? endif; ?>
<? if ($model->pid) : ?>
<span style="margin-left: 5px;" data-toggle="tooltip" title=""><i class="far fa-folder"></i>
<?php echo $model->fullName; ?>
</span>
<? endif; ?>
<?/* if ($model->tree_id) : */?><!--
<span style="margin-left: 5px;" data-toggle="tooltip" title="<?php /*echo $model->cmsTree->fullName; */?>"><i class="far fa-folder"></i> <?php /*echo $model->cmsTree->name; */?></span>
--><?/* endif; */?>
</div>
</div>
<div class="col my-auto" style="max-width: 70px; text-align: right;">
<a href="<?php echo $model->url; ?>" data-toggle="tooltip" class="btn btn-default" target="_blank" title="<?php echo \Yii::t('skeeks/cms', 'Watch to site (opens new window)'); ?>"><i class="fas fa-external-link-alt"></i></a>
</div>
</div>
</div>
<?php
$modelActions = $controller->modelActions;
$deleteAction = \yii\helpers\ArrayHelper::getValue($modelActions, "delete");
if ($deleteAction) : ?>
<?php
$actionData = [
"url" => $deleteAction->url,
//TODO:// is deprecated
"isOpenNewWindow" => true,
"confirm" => isset($deleteAction->confirm) ? $deleteAction->confirm : "",
"method" => isset($deleteAction->method) ? $deleteAction->method : "",
"request" => isset($deleteAction->request) ? $deleteAction->request : "",
"size" => isset($deleteAction->size) ? $deleteAction->size : "",
];
$actionData = \yii\helpers\Json::encode($actionData);
$href = \yii\helpers\Html::a('<i class="fa fa-trash sx-action-icon"></i>', "#", [
'onclick' => "new sx.classes.backend.widgets.Action({$actionData}).go(); return false;",
'class' => "btn btn-default",
'data-toggle' => "tooltip",
'title' => "Удалить",
]);
?>
<div class="col my-auto" style="text-align: right; max-width: 65px;">
<?php echo $href; ?>
</div>
<?php endif; ?>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/admin-cms-department/_node.php | src/views/admin-cms-department/_node.php | <?php
/**
* @link https://cms.skeeks.com/
* @copyright Copyright (c) 2010 SkeekS
* @license https://cms.skeeks.com/license/
* @author Semenov Alexander <semenov@skeeks.com>
*
* @var \skeeks\cms\models\CmsTree $model
*/
/* @var $this yii\web\View */
/* @var $widget \skeeks\cms\widgets\tree\CmsTreeWidget */
/* @var $model \skeeks\cms\models\CmsDepartment */
/* */
$widget = $this->context;
$result = $model->name;
$additionalName = '';
/*if ($model->level == 0) {
$site = \skeeks\cms\models\CmsSite::findOne(['id' => $model->cms_site_id]);
if ($site) {
$additionalName = $site->name;
}
} else {
if ($model->name_hidden) {
$additionalName = $model->name_hidden;
}
}*/
if ($additionalName) {
$result .= " [{$additionalName}]";
}
?>
<div class="sx-department">
<div class="sx-label-node">
<? /* if ($widget->isOpenNode($model)) : */ ?><!--
<i class="far fa-folder-open"></i>
<? /* else : */ ?>
<i class="far fa-folder"></i>
--><? /* endif; */ ?>
<!--<a href="<? /*= $widget->getOpenCloseLink($model); */ ?>">
<? /*= $result; */ ?>
</a>-->
<?php $widget = \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::begin([
'controllerId' => '/cms/admin-cms-department',
'modelId' => $model->id,
/*'rightClickSelectors' => ['.sx-tree-node-'.$model->id],*/
'isRunFirstActionOnClick' => true,
'options' => [
'tag' => false,
'class' => '',
'style' => 'cursor: pointer; font-size: 1.5rem;',
],
]); ?>
<?= $result; ?>
<?php $widget::end(); ?>
</div>
<?php if($model->supervisor) : ?>
<div>
Руководитель: <?php echo $model->supervisor->shortDisplayName; ?>
</div>
<?php endif; ?>
<?php if($model->workers) : ?>
<div>
Сотрудники: <?php echo implode(", ", \yii\helpers\ArrayHelper::map($model->workers, 'id', 'shortDisplayName')); ?>
</div>
<?php endif; ?>
<div class="">
<div>
<a href="#" class="btn btn-default btn-sm add-tree-child"
title="<?= \Yii::t('skeeks/cms', 'Create subsection'); ?>" data-id="<?= $model->id; ?>"><span
class="fa fa-plus"></span> Добавить отдел</a>
</div>
</div>
<? /*= \skeeks\cms\backend\widgets\DropdownControllerActionsWidget::widget([
"actions" => $controller->modelActions,
"renderFirstAction" => true,
"wrapperOptions" => ['class' => "dropdown pull-left"],
'clientOptions' =>
[
'pjax-id' => $widget->pjax->id
]
]); */ ?>
<?php if ($model->pid > 0) : ?>
<a href="#" class="btn btn-default sx-tree-move" style="cursor: move;"
title="<?= \Yii::t('skeeks/cms', "Change sorting"); ?>">
<span class="fas fa-arrows-alt-v"></span>
</a>
<?php endif; ?>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/admin-cms-department/properties.php | src/views/admin-cms-department/properties.php | <?php
use skeeks\cms\models\Tree;
/* @var $this yii\web\View */
/* @var $tree Tree */
/* @var $this yii\web\View */
/* @var $controller \skeeks\cms\backend\controllers\BackendModelController */
/* @var $action \skeeks\cms\backend\actions\BackendModelCreateAction|\skeeks\cms\backend\actions\IHasActiveForm */
/* @var $model \skeeks\cms\models\CmsLang */
/* @var $relatedModel \skeeks\cms\relatedProperties\models\RelatedPropertiesModel */
$controller = $this->context;
$action = $controller->action;
$tree = $action->model;
$contents = \skeeks\cms\models\CmsContent::find()->andWhere(['cms_tree_type_id' => $tree->tree_type_id])->all();
?>
<?php foreach ($contents as $content) : ?>
<div class="sx-cms-content">
<div style="text-transform: uppercase; font-weight: bold;">
<?php echo $content->name; ?>
</div>
<div style="color: gray; margin-bottom: 5px;">При добавлении элементов "<?php echo $content->name; ?>" в этот раздел, будет заполнять такие характеристики.</div>
<?php
$create = null;
if ($controllerProperty = \Yii::$app->createController('cms/admin-cms-content-property')[0]) {
/**
* @var \skeeks\cms\backend\BackendAction $actionIndex
* @var \skeeks\cms\backend\BackendAction $actionCreate
*/
$createAction = \yii\helpers\ArrayHelper::getValue($controllerProperty->actions, 'create');
if ($createAction) {
$r = new \ReflectionClass(\skeeks\cms\models\CmsContentProperty::class);
$createAction->url = \yii\helpers\ArrayHelper::merge($createAction->urlData, [
$r->getShortName() => [
'cmsContents' => [$content->id],
'cmsTrees' => [$tree->id],
],
]);
$createAction->name = \Yii::t("skeeks/cms", "Создать характеристику");
/*echo \skeeks\cms\backend\widgets\DropdownControllerActionsWidget::widget([
'actions' => ['create' => $actionCreate],
'isOpenNewWindow' => true
]);*/
$createProperty = \skeeks\cms\backend\widgets\ControllerActionsWidget::widget([
'actions' => ['create' => $createAction],
'clientOptions' => [
'updateSuccessCallback' => new \yii\web\JsExpression(<<<JS
function() {
window.location.reload();
}
JS
),
],
'isOpenNewWindow' => true,
'tag' => 'span',
'minViewCount' => 1,
'itemWrapperTag' => 'span',
'itemTag' => 'button',
'itemOptions' => ['class' => 'btn btn-default'],
'options' => ['class' => 'sx-controll-actions'],
]);
}
}
?>
<? if ($createProperty) : ?>
<div class="sx-controlls" style="margin-bottom: 10px;">
<?php echo $createProperty; ?>
<a href="#" class="btn btn-default sx-btn-search-property"><i class="fa fa-search"></i> Добавить существующую</a>
<div style="display: none;" class="sx-search-property-element-wrapper">
<?
$url = \yii\helpers\Url::to(['/cms/admin-cms-content-property/join-property']);
$this->registerJs(<<<JS
var propertyUrl = "{$url}";
$("#search-exist-property").on("change", function() {
var ajaxQuery = sx.ajax.preparePostQuery(propertyUrl + "&pk=" + $(this).val());
ajaxQuery.setData({
'tree_id': {$tree->id},
'content_id': {$content->id}
});
console.log(ajaxQuery.toArray());
var AjaxHandler = new sx.classes.AjaxHandlerStandartRespose(ajaxQuery);
AjaxHandler.on("success", function() {
window.location.reload();
});
ajaxQuery.execute();
return false;
});
$(".sx-btn-search-property").on("click", function() {
$(".sx-search-property-element-wrapper .sx-btn-create").click();
return false;
});
JS
);
echo \skeeks\cms\backend\widgets\SelectModelDialogWidget::widget([
'id' => 'search-exist-property',
'modelClassName' => \skeeks\cms\models\CmsContentProperty::class,
'name' => 'search-property',
'dialogRoute' => [
'/cms/admin-cms-content-property',
],
]);
?>
</div>
</div>
<? endif; ?>
<?php
$model = new \skeeks\cms\models\CmsContentElement([
'content_id' => $content->id,
'tree_id' => $tree->id,
]);
$model->relatedPropertiesModel->initAllProperties();
$form = \skeeks\cms\backend\widgets\ActiveFormBackend::begin();
$properties = \skeeks\cms\models\CmsContentProperty::find()
->cmsSite()
->joinWith('cmsContentProperty2trees as map')
->joinWith('cmsContentProperty2contents as cmap')
->andWhere([
'or',
['map.cms_tree_id' => $tree->id],
['map.cms_tree_id' => null],
])
->andWhere([
'cmap.cms_content_id' => $content->id,
])
->groupBy('code')
->orderBy([\skeeks\cms\models\CmsContentProperty::tableName().'.priority' => SORT_ASC])
->all();
?>
<?php if ($properties) : ?>
<?
$this->registerCss(<<<CSS
.form-group .sx-fast-edit {
opacity: 0;
}
.form-group:hover .sx-fast-edit {
opacity: 1;
cursor: pointer;
}
.form-group {
position: relative;
}
.form-group .sx-fast-edit {
transition: 1s;
color: gray;
position: absolute;
top: 50%;
transform: translateX(-50%) translateY(-50%);
left: 15px;
z-index: 999;
}
CSS
);
?>
<?php foreach ($properties as $property) : ?>
<?php if ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_LIST) : ?>
<?php /*$pjax = \skeeks\cms\modules\admin\widgets\Pjax::begin(); */ ?>
<div class="row">
<div class="col-md-12">
<?
$create = '';
?>
<?php if ($controllerProperty = \Yii::$app->createController('cms/admin-cms-content-property-enum')[0]) : ?>
<?
/**
* @var \skeeks\cms\backend\BackendAction $actionIndex
* @var \skeeks\cms\backend\BackendAction $actionCreate
*/
$actionCreate = \yii\helpers\ArrayHelper::getValue($controllerProperty->actions, 'create');
?>
<?
if ($actionCreate) {
$actionCreate->url = \yii\helpers\ArrayHelper::merge($actionCreate->urlData, [
'property_id' => $property->id,
]);
$actionCreate->name = \Yii::t("skeeks/cms", "Добавить опцию");
/*echo \skeeks\cms\backend\widgets\DropdownControllerActionsWidget::widget([
'actions' => ['create' => $actionCreate],
'isOpenNewWindow' => true
]);*/
$create = \skeeks\cms\backend\widgets\ControllerActionsWidget::widget([
'actions' => ['create' => $actionCreate],
'clientOptions' => [
'updateSuccessCallback' => new \yii\web\JsExpression(<<<JS
function() {
}
JS
),
],
'isOpenNewWindow' => true,
'tag' => 'div',
'minViewCount' => 1,
'itemWrapperTag' => 'span',
'itemTag' => 'button',
'itemOptions' => ['class' => 'btn btn-default btn-sm'],
'options' => ['class' => 'sx-controll-actions'],
]);
}
?>
<?php endif; ?>
<?
$field = $property->renderActiveForm($form, $model);
$editBtn = \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::widget([
'controllerId' => "/cms/admin-cms-content-property/",
'modelId' => $property->id,
'tag' => 'span',
'content' => '<i class="fas fa-pencil-alt"></i>',
'options' => [
'class' => 'sx-fast-edit',
'title' => 'Редактировать характеристику',
],
]);
$field->template = '<div class="row sx-inline-row">'.$editBtn.'<div class="col-md-3 text-md-right my-auto">{label}</div><div class="col-md-5">{input}{hint}{error}</div><div class="col-md-3 my-auto">'.$create.'</div></div>';
echo $field;
?>
</div>
</div>
<?php /*\skeeks\cms\modules\admin\widgets\Pjax::end(); */ ?>
<?php elseif ($property->property_type == \skeeks\cms\relatedProperties\PropertyType::CODE_ELEMENT): ?>
<?php /*$pjax = \skeeks\cms\modules\admin\widgets\Pjax::begin(); */ ?>
<div class="row">
<div class="col-md-12">
<?
$create = '';
?>
<?php if (1 == 1) : ?>
<?php if ($controllerProperty = \Yii::$app->createController('cms/admin-cms-content-element')[0]) : ?>
<?
$controllerProperty->content = \skeeks\cms\models\CmsContent::findOne($property->handler->content_id);
/**
* @var \skeeks\cms\backend\BackendAction $actionIndex
* @var \skeeks\cms\backend\BackendAction $actionCreate
*/
$actionCreate = \yii\helpers\ArrayHelper::getValue($controllerProperty->actions, 'create');
?>
<?
if ($actionCreate) {
$actionCreate->url = \yii\helpers\ArrayHelper::merge($actionCreate->urlData, [
'content_id' => $property->handler->content_id,
]);
$actionCreate->name = \Yii::t("skeeks/cms", "Добавить опцию");
/*echo \skeeks\cms\backend\widgets\DropdownControllerActionsWidget::widget([
'actions' => ['create' => $actionCreate],
'isOpenNewWindow' => true
]);*/
$create = \skeeks\cms\backend\widgets\ControllerActionsWidget::widget([
'actions' => ['create' => $actionCreate],
'clientOptions' => [
'updateSuccessCallback' => new \yii\web\JsExpression(<<<JS
function() {
}
JS
),
],
'isOpenNewWindow' => true,
'tag' => 'div',
'minViewCount' => 1,
'itemWrapperTag' => 'span',
'itemTag' => 'button',
'itemOptions' => ['class' => 'btn btn-default btn-sm'],
'options' => ['class' => 'sx-controll-actions'],
]);
}
?>
<?php endif; ?>
<?
$editBtn = \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::widget([
'controllerId' => "/cms/admin-cms-content-property/",
'modelId' => $property->id,
'tag' => 'span',
'content' => '<i class="fas fa-pencil-alt"></i>',
'options' => [
'class' => 'sx-fast-edit',
'title' => 'Редактировать характеристику',
],
]);
?>
<? $field = $property->renderActiveForm($form, $model);
$field->template = '<div class="row sx-inline-row">'.$editBtn.'<div class="col-md-3 text-md-right my-auto">{label}</div><div class="col-md-5">{input}{hint}{error}</div><div class="col-md-3 my-auto">'.$create.'</div></div>';
echo $field;
?>
<?php else: ?>
<?
$editBtn = \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::widget([
'controllerId' => "/cms/admin-cms-content-property/",
'modelId' => $property->id,
'tag' => 'span',
'content' => '<i class="fas fa-pencil-alt"></i>',
'options' => [
'class' => 'sx-fast-edit',
'title' => 'Редактировать характеристику',
],
]);
?>
<? $field = $property->renderActiveForm($form, $model);
$field->template = '<div class="row sx-inline-row">'.$editBtn.'<div class="col-md-3 text-md-right my-auto">{label}111</div><div class="col-md-8">{input}{hint}{error}</div></div>';
echo $field;
?>
<?php endif; ?>
</div>
</div>
<?php /*\skeeks\cms\modules\admin\widgets\Pjax::end(); */ ?>
<?php else
: ?>
<?
$editBtn = \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::widget([
'controllerId' => "/cms/admin-cms-content-property/",
'modelId' => $property->id,
'tag' => 'span',
'content' => '<i class="fas fa-pencil-alt"></i>',
'options' => [
'class' => 'sx-fast-edit',
'title' => 'Редактировать характеристику',
],
]);
?>
<? $field = $property->renderActiveForm($form, $model);
$field->template = '<div class="row sx-inline-row">'.$editBtn.'<div class="col-md-3 text-md-right my-auto">{label}</div><div class="col-md-8">{input}{hint}{error}</div></div>';
echo $field;
?>
<?php endif;
?>
<?php endforeach; ?>
<?php else : ?>
<?php /*= \Yii::t('skeeks/cms','Additional properties are not set')*/ ?>
<?php endif; ?>
<?
\skeeks\cms\backend\widgets\ActiveFormBackend::end();
?>
<? if (count($properties) > 10) : ?>
<? if ($createProperty) : ?>
<div class="sx-controlls" style="margin-bottom: 10px; margin-top: 10px;">
<?php echo $createProperty; ?>
<a href="#" class="btn btn-default sx-btn-search-property"><i class="fa fa-search"></i> Добавить существующую</a>
</div>
<? endif; ?>
<? endif; ?>
</div>
<?php endforeach; ?>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/admin-cms-department/index.php | src/views/admin-cms-department/index.php | <?
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 31.05.2015
*/
/* @var $this yii\web\View */
$this->registerJs(<<<JS
$("body").on("dblclick", ".sx-tree-node", function() {
$(".sx-first-action", $(this)).click();
return false;
});
$("body").on("click", ".sx-first-action-trigger", function() {
/*console.log($(".sx-first-action", $(this).closest('.sx-tree-node')));*/
$(".sx-first-action", $(this).closest('.sx-tree-node')).first().click();
return false;
});
JS
);
$this->registerCss(<<<CSS
.cms-tree-wrapper {
margin-left: 0;
}
.sx-department {
position: relative;
}
.sx-tree ul li.sx-tree-node .sx-node-open-close > a {
font-size: 12px;
}
.sx-department {
display: block;
min-width: 40rem;
}
.sx-department {
border: 1px solid silver;
border-radius: 1rem;
padding: 1rem;
}
.sx-tree ul li.sx-tree-node {
list-style-type: none;
padding-left: 3rem;
}
.sx-tree ul li.sx-tree-node .row:hover {
background: none;
}
.sx-tree ul li.sx-tree-node .row .sx-controll-node
{
display: flex;
float: left;
}
.sx-tree ul li.sx-tree-node .row .sx-controll-node .sx-btn-caret-action
{
width: 21px;
height: 22px;
}
.sx-tree ul li.sx-tree-node .row .sx-controll-node .btn
{
height: 22px;
}
.sx-tree ul li.sx-tree-node .row:hover .sx-controll-node
{
display: block;
}
.btn-tree-node-controll
{
font-size: 8px;
}
.sx-tree ul li.sx-tree-node .sx-controll-node
{
width: auto;
float: left;
margin-left: 10px;
padding-top: 0px;
}
.sx-tree ul li.sx-tree-node .sx-controll-node > .dropdown button
{
font-size: 6px;
color: #000000;
background: white;
padding: 2px 4px;
}
.sx-tree-move
{
cursor: move;
position: absolute;
right: 1rem;
top: 1rem;
}
CSS
);
if (!$models) {
$cmsDepartment = new \skeeks\cms\models\CmsDepartment();
$cmsDepartment->name = "Главный отдел";
$cmsDepartment->worker_id = \Yii::$app->user->id;
$cmsDepartment->makeRoot();
$cmsDepartment->save();
$models = [$cmsDepartment];
}
?>
<div class="h1">Структура компании</div>
<div class="col-md-12">
<?php $widget = \skeeks\cms\widgets\tree\CmsTreeWidget::begin([
"models" => $models,
"isSearchEnabled" => false,
"viewNodeContentFile" => '@skeeks/cms/views/admin-cms-department/_node',
'pjaxClass' => \skeeks\cms\modules\admin\widgets\Pjax::class,
/*'pjaxOptions' =>
[
'blockPjaxContainer' => false,
'blockContainer' => '.sx-panel',
]*/
]); ?>
<?
\yii\jui\Sortable::widget();
$options = \yii\helpers\Json::encode([
'id' => $widget->id,
'pjaxid' => $widget->pjax->id,
'backendNewChild' => \skeeks\cms\helpers\UrlHelper::construct(['/cms/admin-cms-department/new-children'])->enableAdmin()->toString(),
'backendResort' => \skeeks\cms\helpers\UrlHelper::construct(['/cms/admin-cms-department/resort'])->enableAdmin()->toString()
]);
$this->registerJs(<<<JS
(function(window, sx, $, _)
{
sx.createNamespace('classes.tree.admin', sx);
sx.classes.tree.admin.CmsTreeWidget = sx.classes.Component.extend({
_init: function()
{
var self = this;
},
_onDomReady: function()
{
var self = this;
/*$('.sx-tree-node').on('dblclick', function(event)
{
event.stopPropagation();
$(this).find(".sx-row-action:first").click();
});*/
$(".sx-tree ul").find("ul").sortable(
{
cursor: "move",
handle: ".sx-tree-move",
forceHelperSize: true,
forcePlaceholderSize: true,
opacity: 0.5,
placeholder: "ui-state-highlight",
out: function( event, ui )
{
var Jul = $(ui.item).closest("ul");
var newSort = [];
Jul.children("li").each(function(i, element)
{
newSort.push($(this).data("id"));
});
var blocker = sx.block(Jul);
var ajax = sx.ajax.preparePostQuery(
self.get('backendResort'),
{
"ids" : newSort,
"changeId" : $(ui.item).data("id")
}
);
//new sx.classes.AjaxHandlerNoLoader(ajax); //отключение глобального загрузчика
new sx.classes.AjaxHandlerNotify(ajax, {
'error': "Изменения не сохранились",
'success': "Изменения сохранены",
}); //отключение глобального загрузчика
ajax.onError(function(e, data)
{
sx.notify.info("Подождите сейчас страница будет перезагружена");
_.delay(function()
{
window.location.reload();
}, 2000);
})
.onSuccess(function(e, data)
{
blocker.unblock();
})
.execute();
}
});
var self = this;
$('.add-tree-child').on('click', function()
{
var jNode = $(this);
sx.prompt("Введите название нового отдела", {
'yes' : function(e, result)
{
var blocker = sx.block(jNode);
var ajax = sx.ajax.preparePostQuery(
self.get('backendNewChild'),
{
"pid" : jNode.data('id'),
"CmsDepartment" : {"name" : result},
}
);
//new sx.classes.AjaxHandlerNoLoader(ajax); //отключение глобального загрузчика
new sx.classes.AjaxHandlerNotify(ajax, {
'error': "Не удалось добавить новый отдел",
'success': "Новый отдел добавлен"
}); //отключение глобального загрузчика
ajax.onError(function(e, data)
{
$.pjax.reload('#' + self.get('pjaxid'), {});
/*sx.notify.info("Подождите сейчас страница будет перезагружена");
_.delay(function()
{
window.location.reload();
}, 2000);*/
})
.onSuccess(function(e, data)
{
blocker.unblock();
$.pjax.reload('#' + self.get('pjaxid'), {});
/*sx.notify.info("Подождите сейчас страница будет перезагружена");
_.delay(function()
{
window.location.reload();
}, 2000);*/
})
.execute();
}
});
return false;
});
$('.show-at-site').on('click', function()
{
window.open($(this).attr('href'));
return false;
});
},
});
new sx.classes.tree.admin.CmsTreeWidget({$options});
})(window, sx, sx.$, sx._);
JS
);
?>
<?php $widget::end(); ?>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/admin-cms-department/_search.php | src/views/admin-cms-department/_search.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 26.05.2016
*/
/**
* @var $query \yii\db\ActiveQuery
*/
$query = $dataProvider->query;
$filter = new \yii\base\DynamicModel([
'fill',
]);
$filter->addRule('fill', 'integer');
$filter->load(\Yii::$app->request->get());
if ($filter->fill) {
$query->joinWith('cmsTreeProperties as tp');
$query->andWhere(['!=', 'tp.value', '']);
$query->andWhere(['tp.property_id' => $filter->fill]);
$query->groupBy('id');
}
/*if ($filter->not_fill == 'not_fill')
{
$query->joinWith('elementProperties as ep');
$query->andWhere(['=', 'value', '']);
$query->groupBy('id');
}*/
?>
<?php $form = \skeeks\cms\modules\admin\widgets\filters\AdminFiltersForm::begin([
'action' => '/' . \Yii::$app->request->pathInfo,
]); ?>
<?= $form->field($searchModel, 'name')->setVisible(true)->textInput([
'placeholder' => \Yii::t('skeeks/cms', 'Search by name')
]) ?>
<?= $form->field($searchModel, 'id') ?>
<?= $form->field($searchModel, 'code'); ?>
<?= $form->field($searchModel, 'active')->listBox(\yii\helpers\ArrayHelper::merge([
'' => ' - '
], \Yii::$app->cms->booleanFormat()), [
'size' => 1
]); ?>
<?= $form->field($filter, 'fill')
->label(\Yii::t('skeeks/cms', 'Связь с разделами'))
->widget(
\skeeks\cms\widgets\Select::class,
[
'items' => \yii\helpers\ArrayHelper::map(
\skeeks\cms\models\CmsTreeTypeProperty::find()->all(), 'id', 'name'
)
]
); ?>
<?php $form::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/views/admin-cms-department/_recalculate-children-priorities.php | src/views/admin-cms-department/_recalculate-children-priorities.php | <?php
use skeeks\cms\models\Tree;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model Tree */
/* @var $form yii\widgets\ActiveForm */
?>
<?php $form = ActiveForm::begin(); ?>
<?= \Yii::t('skeeks/cms', 'Recalculate the priorities of childs') ?><br/>
По полю: <?= Html::dropDownList('column', null, [
'name' => \Yii::t('skeeks/cms', 'Name'),
'created_at' => \Yii::t('skeeks/cms', 'Created At'),
'updated_at' => \Yii::t('skeeks/cms', 'Updated At')
]) ?>
<br/>
Порядок: <?= Html::dropDownList('sort', null,
['desc' => \Yii::t('skeeks/cms', 'Descending'), 'asc' => \Yii::t('skeeks/cms', 'Ascending')]) ?>
<br/>
<?= Html::submitButton(\Yii::t('skeeks/cms', 'Recalculate'),
['class' => 'btn btn-xs btn-primary', 'name' => 'recalculate_children_priorities', 'value' => '1']) ?>
<br/><br/>
<?php 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/views/imaging/process.php | src/views/imaging/process.php | aasdasd | php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/auth/forget.php | src/views/auth/forget.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 25.03.2015
*/
/* @var $this yii\web\View */
/* @var $model \skeeks\cms\models\forms\PasswordResetRequestFormEmailOrLogin */
use yii\helpers\Html;
use skeeks\cms\base\widgets\ActiveFormAjaxSubmit as ActiveForm;
use \skeeks\cms\helpers\UrlHelper;
$this->title = \Yii::t('skeeks/cms', 'Request for password recovery');
\Yii::$app->breadcrumbs->createBase()->append($this->title);
?>
<div class="row">
<section id="sidebar-main" class="col-md-12">
<div id="content">
<div class="row">
<div class="col-lg-3">
</div>
<div class="col-lg-6">
<?php $form = ActiveForm::begin([
'validationUrl' => UrlHelper::construct('/cms/auth/forget')->setSystemParam(\skeeks\cms\helpers\RequestResponse::VALIDATION_AJAX_FORM_SYSTEM_NAME)->toString()
]); ?>
<?= $form->field($model, 'identifier') ?>
<div class="form-group">
<?= Html::submitButton(\Yii::t('skeeks/cms', "Send"),
['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?= Html::a(\Yii::t('skeeks/cms', 'Authorization'),
UrlHelper::constructCurrent()->setRoute('cms/auth/login')->toString()) ?> |
<?= Html::a(\Yii::t('skeeks/cms', 'Registration'),
UrlHelper::constructCurrent()->setRoute('cms/auth/register')->toString()) ?>
</div>
<div class="col-lg-3">
</div>
<!--Или социальные сети
--><?php /*= yii\authclient\widgets\AuthChoice::widget([
'baseAuthUrl' => ['site/auth']
]) */ ?>
</div>
</div>
</section>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/auth/login.php | src/views/auth/login.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 25.03.2015
*/
/* @var $this yii\web\View */
/* @var $model \skeeks\cms\models\forms\LoginFormUsernameOrEmail */
use yii\helpers\Html;
use skeeks\cms\base\widgets\ActiveFormAjaxSubmit as ActiveForm;
use \skeeks\cms\helpers\UrlHelper;
$this->title = \Yii::t('skeeks/cms', 'Authorization');
\Yii::$app->breadcrumbs->createBase()->append($this->title);
?>
<div class="row">
<section id="sidebar-main" class="col-md-12">
<div id="content">
<div class="row">
<div class="col-lg-3">
</div>
<div class="col-lg-6">
<?php $form = ActiveForm::begin([
'validationUrl' => UrlHelper::construct('/cms/auth/login')->setSystemParam(\skeeks\cms\helpers\RequestResponse::VALIDATION_AJAX_FORM_SYSTEM_NAME)->toString()
]); ?>
<?= $form->field($model, 'identifier') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div class="form-group">
<?= Html::submitButton("<i class=\"glyphicon glyphicon-off\"></i> " . \Yii::t('skeeks/cms',
'Log in'), ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?= Html::a(\Yii::t('skeeks/cms', 'Forgot your password?'),
UrlHelper::constructCurrent()->setRoute('cms/auth/forget')->toString()) ?> |
<?= Html::a(\Yii::t('skeeks/cms', 'Registration'),
UrlHelper::constructCurrent()->setRoute('cms/auth/register')->toString()) ?>
</div>
<div class="col-lg-3">
</div>
<!--Или социальные сети
--><?php /*= yii\authclient\widgets\AuthChoice::widget([
'baseAuthUrl' => ['site/auth']
]) */ ?>
</div>
</div>
</section>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/auth/register.php | src/views/auth/register.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 25.03.2015
*/
/* @var $this yii\web\View */
/* @var $model \skeeks\cms\models\forms\SignupForm */
use yii\helpers\Html;
use skeeks\cms\base\widgets\ActiveFormAjaxSubmit as ActiveForm;
use \skeeks\cms\helpers\UrlHelper;
$this->title = \Yii::t('skeeks/cms', 'Registration');
\Yii::$app->breadcrumbs->createBase()->append($this->title);
?>
<div class="row">
<section id="sidebar-main" class="col-md-12">
<div id="content">
<div class="row">
<div class="col-lg-3">
</div>
<div class="col-lg-6">
<?php $form = ActiveForm::begin([
'validationUrl' => UrlHelper::construct('/cms/auth/register')->setSystemParam(\skeeks\cms\helpers\RequestResponse::VALIDATION_AJAX_FORM_SYSTEM_NAME)->toString()
]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton("<i class=\"glyphicon glyphicon-off\"></i> " . \Yii::t('skeeks/cms',
'Sign up'), ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?= Html::a(\Yii::t('skeeks/cms', 'Authorization'),
UrlHelper::constructCurrent()->setRoute('cms/auth/login')->toString()) ?>
</div>
<div class="col-lg-3">
</div>
<!--Или социальные сети
--><?php /*= yii\authclient\widgets\AuthChoice::widget([
'baseAuthUrl' => ['site/auth']
]) */ ?>
</div>
</div>
</section>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/auth/reset-password.php | src/views/auth/reset-password.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 25.03.2015
*/
/* @var $this yii\web\View */
use yii\helpers\Html;
use skeeks\cms\base\widgets\ActiveFormAjaxSubmit as ActiveForm;
use \skeeks\cms\helpers\UrlHelper;
$this->title = \Yii::t('skeeks/cms', 'Getting a new password');
\Yii::$app->breadcrumbs->createBase()->append($this->title);
?>
<div class="row">
<section id="sidebar-main" class="col-md-12">
<div id="content">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<h1><?= $message; ?></h1>
<?= Html::a(\Yii::t('skeeks/cms', 'Request recovery again'),
UrlHelper::constructCurrent()->setRoute('cms/auth/forget')->toString()) ?> |
<?= Html::a(\Yii::t('skeeks/cms', 'Authorization'),
UrlHelper::constructCurrent()->setRoute('cms/auth/login')->toString()) ?> |
<?= Html::a(\Yii::t('skeeks/cms', 'Registration'),
UrlHelper::constructCurrent()->setRoute('cms/auth/register')->toString()) ?>
</div>
<div class="col-lg-3"></div>
</div>
</div>
</section>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
skeeks-cms/cms | https://github.com/skeeks-cms/cms/blob/c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf/src/views/auth/approve-email.php | src/views/auth/approve-email.php | <?php
/**
* @author Semenov Alexander <semenov@skeeks.com>
* @link http://skeeks.com/
* @copyright 2010 SkeekS (СкикС)
* @date 25.03.2015
*/
/* @var $this yii\web\View */
use yii\helpers\Html;
use skeeks\cms\base\widgets\ActiveFormAjaxSubmit as ActiveForm;
use \skeeks\cms\helpers\UrlHelper;
$this->title = \Yii::t('skeeks/cms', 'Getting a new password');
\Yii::$app->breadcrumbs->createBase()->append($this->title);
?>
<div class="row">
<section id="sidebar-main" class="col-md-12">
<div id="content">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<h1><?= $message; ?></h1>
<?= Html::a(\Yii::t('skeeks/cms', 'Authorization'),
UrlHelper::constructCurrent()->setRoute('cms/auth/login')->toString()) ?> |
<?= Html::a(\Yii::t('skeeks/cms', 'Registration'),
UrlHelper::constructCurrent()->setRoute('cms/auth/register')->toString()) ?>
</div>
<div class="col-lg-3"></div>
</div>
</div>
</section>
</div>
| php | BSD-3-Clause | c22dc84c6fc4da5f67815a3339bc10c6c4aa39cf | 2026-01-05T04:50:22.405425Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.