Inheritance: extends Core, use trait skeeks\cms\models\behaviors\traits\HasRelatedPropertiesTrait
Exemplo n.º 1
2
 /**
  * @inheritdoc
  */
 public function run()
 {
     try {
         $this->_initAndValidate();
         $valueArray = [];
         $trees = [];
         $valueSingle = "";
         $select = "";
         $singleInput = "";
         if (in_array($this->mode, [self::MOD_COMBO, self::MOD_MULTI])) {
             $valueArray = Html::getAttributeValue($this->model, $this->attribute);
             $select = Html::activeListBox($this->model, $this->attribute, ['16' => "16"], ['multiple' => true, 'class' => 'sx-controll-element', 'style' => 'display: none;']);
             $trees = Tree::find()->where(['id' => $valueArray])->all();
         }
         if (in_array($this->mode, [self::MOD_COMBO, self::MOD_SINGLE])) {
             $singleInput = Html::activeInput("hidden", $this->model, $this->attributeSingle, ['class' => 'sx-single']);
             $valueSingle = Html::getAttributeValue($this->model, $this->attributeSingle);
         }
         $src = UrlHelper::construct('/cms/admin-tree')->set('mode', $this->mode)->set('s', $valueArray)->setSystemParam(Module::SYSTEM_QUERY_EMPTY_LAYOUT, 'true')->setSystemParam(Module::SYSTEM_QUERY_NO_ACTIONS_MODEL, 'true')->enableAdmin()->toString();
         $id = "sx-id-" . md5(serialize([$this->clientOptions, $this->mode, $this->attributeMulti, $this->attributeSingle]));
         $selected = [];
         foreach ($trees as $tree) {
             $selected[] = $tree->id;
         }
         return $this->render('widget', ['widget' => $this, 'id' => $id, 'select' => $select, 'src' => $src, 'valueSingle' => $valueSingle, 'singleInput' => $singleInput, 'clientOptions' => Json::encode(['src' => $src, 'name' => $id, 'id' => $id, 'selected' => $selected, 'valueSingle' => $valueSingle])]);
         //$this->registerClientScript();
     } catch (Exception $e) {
         echo $e->getMessage();
     }
 }
Exemplo n.º 2
0
 /**
  * Стандартный sitemap
  */
 public function actionSitemap()
 {
     ini_set("memory_limit", "512M");
     $trees = Tree::find()->where(['site_code' => \Yii::$app->cms->site->code])->orderBy(['level' => SORT_ASC, 'priority' => SORT_ASC])->all();
     if ($trees) {
         /**
          * @var Tree $tree
          */
         foreach ($trees as $tree) {
             if (!$tree->redirect) {
                 $result[] = ["loc" => $tree->url, "lastmod" => $this->_lastMod($tree), "priority" => $this->_calculatePriority($tree), "changefreq" => "daily"];
             }
         }
     }
     $elements = CmsContentElement::find()->joinWith('cmsTree')->andWhere([Tree::tableName() . '.site_code' => \Yii::$app->cms->site->code])->orderBy(['updated_at' => SORT_DESC, 'priority' => SORT_ASC])->all();
     //Добавление элементов в карту
     if ($elements) {
         /**
          * @var CmsContentElement $model
          */
         foreach ($elements as $model) {
             $result[] = ["loc" => $model->absoluteUrl, "lastmod" => $this->_lastMod($model), "priority" => "0.3", "changefreq" => "daily"];
         }
     }
     \Yii::$app->response->format = Response::FORMAT_XML;
     $this->layout = false;
     //Генерация sitemap вручную, не используем XmlResponseFormatter
     \Yii::$app->response->content = $this->render($this->action->id, ['data' => $result]);
     return;
     /*return $this->render($this->action->id, [
           'data' => $result
       ]);;*/
 }
Exemplo n.º 3
0
 protected function _run()
 {
     $key = $this->getCacheKey() . 'run';
     $dependency = new TagDependency(['tags' => [$this->className() . (string) $this->namespace, (new Tree())->getTableCacheTag()]]);
     $result = \Yii::$app->cache->get($key);
     if ($result === false || $this->enabledRunCache == Cms::BOOL_N) {
         $this->activeQuery = Tree::find();
         if ($this->treePid) {
             $this->activeQuery->andWhere(['pid' => $this->treePid]);
         }
         if ($this->level) {
             $this->activeQuery->andWhere(['level' => $this->level]);
         }
         if ($this->active) {
             $this->activeQuery->andWhere(['active' => $this->active]);
         }
         if ($this->site_codes) {
             $this->activeQuery->andWhere(['site_code' => $this->site_codes]);
         }
         if ($this->enabledCurrentSite == Cms::BOOL_Y && ($currentSite = \Yii::$app->cms->site)) {
             $this->activeQuery->andWhere(['site_code' => $currentSite->code]);
         }
         if ($this->orderBy) {
             $this->activeQuery->orderBy([$this->orderBy => (int) $this->order]);
         }
         if ($this->tree_type_ids) {
             $this->activeQuery->andWhere(['tree_type_id' => $this->tree_type_ids]);
         }
         /**
          *
          */
         if ($this->with) {
             $this->activeQuery->with($this->with);
         }
         if ($this->activeQueryCallback && is_callable($this->activeQueryCallback)) {
             $callback = $this->activeQueryCallback;
             $callback($this->activeQuery);
         }
         $result = parent::_run();
         \Yii::$app->cache->set($key, $result, (int) $this->runCacheDuration, $dependency);
     }
     return $result;
 }
Exemplo n.º 4
0
 /**
  * @param $id
  * @return string
  * @throws InvalidConfigException
  * @throws \yii\web\HttpException
  */
 public function run($id)
 {
     $this->model = \Yii::$app->cms->getCurrentTree();
     if (!$this->model) {
         $treeNode = Tree::find()->where(['id' => $id])->one();
         \Yii::$app->cms->setCurrentTree($treeNode);
         $this->model = \Yii::$app->cms->getCurrentTree();
     }
     if ($this->model->redirect || $this->model->redirect_tree_id) {
         return \Yii::$app->response->redirect($this->model->url, $this->model->redirect_code);
     }
     //Пробуем рендерить view для текущего типа страницы
     if ($this->model) {
         if ($this->model->treeType) {
             if ($this->model->treeType->viewFile) {
                 $this->view = $this->model->treeType->viewFile;
             } else {
                 $this->view = $this->model->treeType->code;
             }
         }
     }
     return $this->_go();
 }
 public function safeUp()
 {
     if ($models = \skeeks\cms\models\Tree::find()->all()) {
         /**
          * @var $model \skeeks\cms\models\Tree
          */
         foreach ($models as $model) {
             if (!method_exists($model, 'getMainImageSrc')) {
                 continue;
             }
             //$user->getFiles()
             $imageSrc = $model->getMainImageSrcOld();
             if ($imageSrc) {
                 $storageFile = \skeeks\cms\models\CmsStorageFile::find()->where(['src' => $imageSrc])->one();
                 if ($storageFile) {
                     $model->image_id = $storageFile->id;
                     $model->image_full_id = $storageFile->id;
                     $model->save(false);
                 }
             }
         }
     }
 }
Exemplo n.º 6
0
Arquivo: Tree.php Projeto: Liv1020/cms
    public function registerAssets()
    {
        Sortable::widget();
        $models = \skeeks\cms\models\Tree::find()->where(["id" => $this->_getSelectedIds()])->all();
        $options = Json::encode(['selected' => $models]);
        Asset::register($this->getView());
        $this->getView()->registerJs(<<<JS

        (function(window, sx, \$, _)
        {
            sx.createNamespace('classes', sx);

            sx.classes.Tree = sx.classes.Component.extend({

                _init: function()
                {
                    var self = this;
                    if (sx.Window.openerWidget())
                    {
                        this._parentWidget = sx.Window.openerWidget();
                    }
                },

                _onDomReady: function()
                {

                    \$(".sx-tree ul").find("ul").sortable(
                    {
                        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(
                                "resort",
                                {
                                    "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;
                    \$('.sx-controll-btn-select').on('click', function()
                    {
                        self._parentWidget.trigger('selected', {
                            'selected': self.get('selected')
                        });

                        window.close();
                        return false;
                    });

                    \$('.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(
                                        "new-children",
                                        {
                                            "pid" : jNode.data('id'),
                                            "Tree" : {"name" : result},
                                            "no_redirect": true
                                        }
                                );

                                new sx.classes.AjaxHandlerNoLoader(ajax); //отключение глобального загрузчика

                                new sx.classes.AjaxHandlerNotify(ajax, {
                                    'error': "Не удалось добавить новый раздел",
                                    'success': "Новый раздел добавлен"
                                }); //отключение глобального загрузчика

                                ajax.onError(function(e, data)
                                {
                                    \$.pjax.reload('#sx-pjax-tree', {});
                                    /*sx.notify.info("Подождите сейчас страница будет перезагружена");
                                    _.delay(function()
                                    {
                                        window.location.reload();
                                    }, 2000);*/
                                })
                                .onSuccess(function(e, data)
                                {
                                    blocker.unblock();

                                    \$.pjax.reload('#sx-pjax-tree', {});
                                    /*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;
                    });
                },

                select: function(id, link)
                {
                    var selected = [];
                    \$("input[type='checkbox']:checked").each(function()
                    {
                        selected.push(\$(this).val());
                    });

                    this.trigger("select", {
                        'selected': selected,
                        'select': id
                    });

                    _.delay(function()
                    {
                        \$(".sx-tree").append();

                        \$("<a>", {
                            'href':link,
                            'style':'display:none;'
                        }).append("test").appendTo(\$(".sx-tree")).click();

                        //window.location.href = link;
                    }, 100);
                },

                selectSingle: function(id)
                {
                    this.trigger("selectSingle", {
                        'id': id
                    });
                },

                setSingle: function(id)
                {
                    console.log('setSingle' + id);
                    var Jelement = \$(".sx-tree .sx-readio[value='" + id + "']");
                    if (!Jelement.is(":checked"))
                    {
                        Jelement.click();
                    };
                },


            });

            sx.Tree = new sx.classes.Tree({$options});

        })(window, sx, sx.\$, sx._);
JS
);
        $this->getView()->registerCss(<<<CSS

.sx-tree
{
    margin-left: 15px;
}
.sx-tree ul
{
    padding-left: 0px;
}


    .sx-tree ul li.sx-tree-node
    {
        list-style-type: none;
        padding-left: 15px;
        margin: 2px 0px;
    }

        .sx-tree ul li .sx-tree-type
        {
            display: none;
            padding-top: 2px;
            padding-left: 20px;
            font-size: 11px;
        }

            .sx-tree ul li:hover>.row .sx-tree-type
            {
                display: block;
            }

        .sx-tree ul li.sx-tree-node .sx-controll-act
        {
            margin-left: 5px;
        }

    .sx-tree ul li.sx-tree-node.open
    {}

    .sx-tree ul li.sx-tree-node.active
    {}

        .sx-tree ul li.sx-tree-node .row
        {
            margin: 0 !important;
        }



    .sx-tree ul li.sx-tree-node .sx-node-open-close
    {
        float: left;
        width: 23px;
        margin-left: -23px;
    }

        .sx-tree ul li.sx-tree-node .sx-node-open-close > a
        {
            font-size: 6px;
            color: #000000;
            background: white;
            padding: 2px 4px;
            margin-top: 2px;
        }

.btn-tree-node-controll
{
    font-size: 8px;
}

    .sx-tree ul li.sx-tree-node .sx-controll-node
    {
        width: 80px;
        float: left;
        margin-left: 10px;
        padding-top: 2px;
    }

        .sx-tree ul li.sx-tree-node .sx-controll-node > .dropdown button
        {
            font-size: 6px;
            color: #000000;
            background: white;
            padding: 2px 4px;
        }



    .sx-tree ul li.sx-tree-node .sx-label-node
    {
        float: left;
        padding-left: 23px;
    }

        .sx-tree ul li.sx-tree-node .sx-label-node > a
        {
            font-size: 12px;
            font-weight: bold;
            color: #000000;
        }

/**
* Запись неактивна
**/
        .sx-tree ul li.sx-tree-node .sx-label-node.status-N  > a
        {
            color: silver;
        }

CSS
);
    }
Exemplo n.º 7
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getTree()
 {
     return $this->hasOne(Tree::className(), ['id' => 'tree_id']);
 }
Exemplo n.º 8
0
 public function actionResort()
 {
     $response = ['success' => false];
     Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
     if (\Yii::$app->request->isPost) {
         $tree = new Tree();
         $post = \Yii::$app->request->post();
         //$ids = array_reverse(array_filter($post['ids']));
         $ids = array_filter($post['ids']);
         $priority = 100;
         foreach ($ids as $id) {
             $node = $tree->find()->where(['id' => $id])->one();
             $node->priority = $priority;
             $node->save(false);
             $priority += 100;
         }
         $response['success'] = true;
     }
     /*
     if (\Yii::$app->request->isPost)
     {
         $tree = new Tree();
     
         $post = \Yii::$app->request->post();
     
         $resortIds = array_filter($post['ids']);
         $changeId = intval($post['changeId']);
     
         $changeNode = $tree->find()->where(['id' => $changeId])->one();
     
         $nodes = $tree->find()->where(['pid' =>$changeNode->pid])->orderBy(["priority" => SORT_DESC])->all();
         $origIds = [];
         foreach($nodes as $node)
         {
             $origIds[] = $node->id;
         }
     
         $origPos = array_search($changeId, $origIds);
         $resortPos = array_search($changeId, $resortIds);
     
         if($origPos > $resortPos)
         {
             $origIds = array_reverse($origIds);
             $offset = count($origIds) - 1;
             $origPos = $offset - $origPos;
             $resortPos = $offset - $resortPos;
         }
     
         for($i = $origPos+1; $i <= $resortPos; $i++)
         {
             $id = $origIds[$i];
             $node = $tree->find()->where(['id'=>$id])->one();
             $changeNode->swapPriorities($node);
         }
     
         $response['success'] = true;
     }
     */
     return $response;
 }
Exemplo n.º 9
0
 public function createTreeAfterInsert(Event $e)
 {
     $tree = new Tree(['name' => 'Главная страница', 'site_code' => $this->code]);
     if (!$tree->save(false)) {
         throw new Exception('Failed to create a section of the tree');
     }
 }
Exemplo n.º 10
0
 protected function _go($normalizeDir = null)
 {
     if (\Yii::$app->seo->useLastDelimetrTree) {
         $normalizeDir = substr($normalizeDir, 0, strlen($normalizeDir) - 1);
     }
     try {
         $dependency = new TagDependency(['tags' => [(new Tree())->getTableCacheTag()]]);
         if (!$normalizeDir) {
             $treeNode = Tree::getDb()->cache(function ($db) {
                 return Tree::find()->where(["site_code" => \Yii::$app->cms->site->code, "level" => 0])->one();
             }, null, $dependency);
             /*$treeNode = Tree::find()->where([
                   "site_code"         => \Yii::$app->cms->site->code,
                   "level"             => 0,
               ])->one();*/
         } else {
             /*$treeNode = Tree::getDb()->cache(function ($db) {
                   return Tree::find()->where([
                       (new Tree())->dirAttrName       => $normalizeDir,
                       "site_code"                     => \Yii::$app->cms->site->code,
                   ])->one();
               }, null, $dependency);*/
             $treeNode = Tree::find()->where(["dir" => $normalizeDir, "site_code" => \Yii::$app->cms->site->code])->one();
         }
     } catch (Exception $e) {
         if (in_array($e->getCode(), NotConnectedToDbException::$invalidConnectionCodes)) {
             throw new NotConnectedToDbException();
         }
     } catch (\yii\base\InvalidConfigException $e) {
         throw new NotConnectedToDbException();
     }
     if ($treeNode) {
         \Yii::$app->cms->setCurrentTree($treeNode);
         $params['id'] = $treeNode->id;
         return ['cms/tree/view', $params];
     } else {
         return false;
     }
 }
Exemplo n.º 11
0
 /**
  * @param Tree $tree
  * @return array
  */
 public function getAllIdsForChildren(Tree $tree)
 {
     $treeIds = [];
     /**
      * @var $query ActiveQuery
      */
     $childrens = $tree->getChildren()->with('children')->all();
     if ($childrens) {
         foreach ($childrens as $chidren) {
             if ($chidren->children) {
                 $treeIds[$chidren->id] = $chidren->id;
                 $treeIds = array_merge($treeIds, $this->getAllIdsForChildren($chidren));
             } else {
                 $treeIds[$chidren->id] = $chidren->id;
             }
         }
     }
     return $treeIds;
 }
Exemplo n.º 12
0
 /**
  * @param \yii\web\UrlManager $manager
  * @param \yii\web\Request $request
  * @return array|bool
  */
 public function parseRequest($manager, $request)
 {
     if ($this->mode === self::CREATION_ONLY) {
         return false;
     }
     if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
         return false;
     }
     $pathInfo = $request->getPathInfo();
     if ($this->host !== null) {
         $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
     }
     $params = $request->getQueryParams();
     $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix);
     $treeNode = null;
     $originalDir = $pathInfo;
     if ($suffix) {
         $originalDir = substr($pathInfo, 0, strlen($pathInfo) - strlen($suffix));
     }
     $dependency = new TagDependency(['tags' => [(new Tree())->getTableCacheTag()]]);
     if (!$pathInfo) {
         $treeNode = Tree::getDb()->cache(function ($db) {
             return Tree::find()->where(["site_code" => \Yii::$app->cms->site->code, "level" => 0])->one();
         }, null, $dependency);
     } else {
         $treeNode = Tree::find()->where(["dir" => $originalDir, "site_code" => \Yii::$app->cms->site->code])->one();
     }
     if ($treeNode) {
         \Yii::$app->cms->setCurrentTree($treeNode);
         $params['id'] = $treeNode->id;
         return ['cms/tree/view', $params];
     } else {
         return false;
     }
 }
Exemplo n.º 13
0
 /**
  * Создание дочерней ноды
  *
  * @param Tree $target
  * @return Tree
  * @throws Exception
  * @throws \skeeks\sx\validate\Exception
  */
 public function processCreateNode(Tree $target)
 {
     //Текущая сущьность должна быть уже сохранена
     if ($this->isNewRecord) {
         throw new Exception('Текущая сущьность должна быть уже сохранена');
     }
     //Новая сущьность должна быть еще не сохранена
     if (!$target->isNewRecord) {
         throw new Exception('Новая сущьность должна быть еще не сохранена');
     }
     //Установка атрибутов будущему ребенку
     $target->setAttributesForFutureParent($this);
     if (!$target->save(false)) {
         throw new Exception(\Yii::t('skeeks/cms', "Failed to create the child element:  ") . Json::encode($target->attributes));
     }
     $this->save(false);
     return $target;
 }
Exemplo n.º 14
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getElement()
 {
     return $this->hasOne(Tree::className(), ['id' => 'element_id']);
 }