示例#1
0
 /**
  * [init description].
  *
  * @return [type] [description]
  */
 public function init()
 {
     parent::init();
     $this->ctype = 'user';
     $this->uuid = !empty(\Yii::$app->getRequest()->getQueryParam('uuid')) ? \Yii::$app->getRequest()->getQueryParam('uuid') : null;
     // create default user element, if none is present
     $workspacePath = realpath(\Yii::getAlias('@webroot') . '/../workspace');
     if ($workspacePath === false) {
         throw new \yii\web\ServerErrorHttpException('The *workspace* folder could not be found - please create it in your project root');
     }
     $elementsPath = realpath($workspacePath . '/elements');
     if ($elementsPath === false) {
         throw new \yii\web\ServerErrorHttpException('The *elements* folder could not be found - please create it in your workspace folder');
     }
     $modelJson = realpath($elementsPath . '/' . $this->ctype . '.json');
     if ($modelJson === false) {
         file_put_contents($elementsPath . '/' . $this->ctype . '.json', '{"key":"user","label":"User","tabs":[{"label":"Login","key":"login","visible":false,"groups":[{"label":"Login","key":"login","fields":["email","password","login"]}]},{"label":"User","key":"user","groups":[{"label":"User","key":"user","fields":["email","password","state"]}]}],"fields":[{"label":"Email address","key":"email","type":"textInput","visibleInGrid":true,"rules":[["required"],["email"],["string",{"max":128}]]},{"label":"Password","key":"password","type":"passwordInput","visibleInGrid":false,"rules":[["required"],["string",{"max":128}]],"transform":"hash"},{"label":"Login","key":"login","type":"submitButton","visibleInGrid":false}, {"label":"Auth-Key","key":"authKey","type":"text","visibleInGrid":false}]}');
     }
     \Yii::$app->cache->flush();
     $usersProvider = new CrelishJsonDataProvider('user');
     $users = $usersProvider->rawAll();
     if (sizeof($users) == 0) {
         // Generate default admin.
         $adminUser = new CrelishDynamicJsonModel(['email', 'password', 'login', 'state'], ['ctype' => 'user']);
         $adminUser->email = '*****@*****.**';
         $adminUser->login = '******';
         $adminUser->password = '******';
         $adminUser->state = 1;
         $adminUser->authKey = \Yii::$app->security->generateRandomString();
         $adminUser->save();
     }
 }
 public static function processData($caller, $key, $data, &$processedData)
 {
     if (is_array($data) && sizeOf($data) > 0) {
         $include = new CrelishJsonDataProvider('asset', [], $data['uuid']);
         $processedData[$key] = $include->one();
     }
 }
 public static function processData($caller, $key, $data, &$processedData)
 {
     if (empty($processedData[$key])) {
         $processedData[$key] = [];
     }
     if ($data) {
         $filters = null;
         $sort = null;
         if (!empty($data['filter'])) {
             foreach ($data['filter'] as $filter) {
                 if (is_array($filter)) {
                     $filters[key($filter)] = $filter[key($filter)];
                 } elseif (!empty($_GET[$filter])) {
                     $filters[$filter] = $_GET[$filter];
                 }
             }
         }
         if (!empty($data['sort'])) {
             $sort['by'] = !empty($data['sort']['by']) ? $data['sort']['by'] : null;
             $sort['dir'] = !empty($data['sort']['dir']) ? $data['sort']['dir'] : null;
         }
         $sourceData = new CrelishJsonDataProvider($data['source'], ['filter' => $filters, 'sort' => $sort]);
         $processedData[$key] = $sourceData->raw();
     }
 }
 public static function processData($caller, $key, $data, &$processedData)
 {
     if (empty($processedData[$key])) {
         $processedData[$key] = [];
     }
     if ($data) {
         foreach ($data as $section => $subContent) {
             if (empty($processedData[$key][$section])) {
                 $processedData[$key][$section] = '';
             }
             foreach ($subContent as $subContentdata) {
                 $sourceData = new CrelishJsonDataProvider($subContentdata['ctype'], [], $subContentdata['uuid']);
                 // @todo: nesting again.
                 $sourceDataOut = $caller->processContent($subContentdata['ctype'], $sourceData->one());
                 $processedData[$key][$section] .= $caller->renderPartial($subContentdata['ctype'] . '.twig', ['data' => $sourceDataOut]);
             }
         }
     }
 }
示例#5
0
 public function run()
 {
     $nav = '';
     $elements = new CrelishJsonDataProvider('elements', ['key' => 'key', 'sort' => ['by' => 'label', 'dir' => 'ASC']]);
     $params[0] = $this->action;
     foreach (\Yii::$app->getRequest()->getQueryParams() as $param => $value) {
         $params[$param] = $value;
     }
     foreach ($elements->all()['models'] as $element) {
         if (array_key_exists('selectable', $element) && $element['selectable'] === false) {
             continue;
         }
         $css = $this->ctype == $element['key'] ? 'gc-active-filter' : '';
         $params[$this->selector] = $element['key'];
         $targetUrl = Url::to($params);
         $nav .= Html::tag('li', Html::a($element['label'], $targetUrl), ['class' => $css]);
     }
     return $nav;
 }
示例#6
0
    public function run()
    {
        $formKey = $this->formKey;
        $imgWrapper = $stringValue = "";
        if (is_array($this->data)) {
            $data = (object) $this->data;
            $stringValue = Json::encode($this->data);
            // Load asset.
            $asset = new CrelishJsonDataProvider($data->ctype, [], $data->uuid);
            $asset = (object) $asset->one();
            $imgWrapper = <<<EOT
      <div style="width: 200px;">
          <div class="c-card c-card--high gc-m--lbr-1 gc-bc--palette-white">
            <div class="c-card__content c-heading dz-filename gc-bc--palette-silver gc-to--ellipsis" id="asset-title">
              {$asset->title}
            </div>
            <div class="c-card__content">
              <div class="image gc-o--hidden" style="background-color: {$asset->colormain_hex};">
                <img class="lazy" data-original="{$asset->src}" height="140" src="{$asset->src}" id="asset-path" />
              </div>
              <div class="description gc-box--h-60 gc-to--ellipsis" id="asset-description">
                {$asset->description}
              </div>
            </div>
          </div>
        </div>
EOT;
        } else {
            $data = new \stdClass();
            $imgWrapper = <<<EOT
      <div style="width: 200px;">
          <div class="c-card c-card--high gc-m--lbr-1 gc-bc--palette-white">
            <div class="c-card__content c-heading dz-filename gc-bc--palette-silver gc-to--ellipsis" id="asset-title">

            </div>
            <div class="c-card__content">
              <div class="image gc-o--hidden">
                <img class="lazy" data-original="" height="140" src="" id="asset-path" />
              </div>
              <div class="description gc-box--h-60 gc-to--ellipsis" id="asset-description">

              </div>
            </div>
          </div>
        </div>
EOT;
        }
        $postUrl = Url::to('/crelish/asset/upload.html');
        $modelProvider = new CrelishJsonDataProvider('asset', ['sort' => ['by' => 'systitle', 'dir' => 'desc']], null);
        $out = <<<EOT
    <div class="form-group field-crelishdynamicmodel-body required">
      <label class="control-label col-sm-3" for="crelishdynamicmodel-body">Asset</label>
      <div class="col-sm-6">

        {$imgWrapper}

        <input type="hidden" name="CrelishDynamicJsonModel[{$formKey}]" id="CrelishDynamicJsonModel_{$formKey}" value='{$stringValue}' />
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Select asset</button>
        <div class="help-block help-block-error "></div>
      </div>
    </div>

    <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="asset-modal">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Asset selection</h4>
          </div>
          <div class="modal-body">
EOT;
        $out .= $this->render('assets.twig', ['dataProvider' => $modelProvider->raw()]);
        $out .= <<<EOT
          </div>
        </div>
      </div>
    </div>


    <script type="text/javascript">

      var activateAssetAssignment = function() {
        \$("#asset-modal a.asset-item").each(function() {
          \$(this).on('click', function(e) {
            e.preventDefault();
            var asset = \$(this).data("asset");
            \$("#CrelishDynamicJsonModel_{$this->formKey}").val(JSON.stringify({ ctype: "asset", uuid: asset.uuid }));
            \$("#asset-path").attr("src", asset.src);
            \$("#asset-title").text(asset.title);
            \$("#asset-description").text(asset.description);
            \$("#asset-modal").modal('hide');
          });
        });
      };

      \$("#assetList").on("pjax:end", function() {
        \$("img.lazy").lazyload({
          container:\$(".modal-body"),
          placeholder: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII='
        });
        activateAssetAssignment();
      });

      \$('#asset-modal').on('shown.bs.modal', function (e) {
        // Enable scrolling.
        \$('#asset-modal').perfectScrollbar();

        \$("#dropZone").dropzone({
          url: '{$postUrl}',
          paramName: "file", // The name that will be used to transfer the file
          maxFilesize: 250, // MB
          dictDefaultMessage: "<span class=\\"c-badge c-badge--secondary gc-shadow__soft\\">Click or drag files here to upload.</span>",
          init: function() {
            var myDropzone = this;

            this.on("complete", function(file) {
              setTimeout(function() {
                \$.pjax.reload({container:'#assetList'});
                myDropzone.removeFile(file);
              }, 250);
            });

          },
          accept: function(file, done) {
            if (file.name == "justinbieber.jpg") {
              done("Naha, you don't.");
            } else { done(); }
          }
        });

        \$("img.lazy").lazyload({
          container:\$("#asset-modal"),
          placeholder: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=',
          event : "doIt"
        });

        var timeout = setTimeout(function() {
          \$("img.lazy").trigger("doIt");
          activateAssetAssignment();
        }, 2500);

      });


    </script>

EOT;
        return $out;
    }
 /**
  * [resolvePathRequested description]
  * @return [type] [description]
  */
 private function resolvePathRequested()
 {
     $slug = $path = '';
     $ctype = 'page';
     $this->requestUrl = \Yii::$app->request->getPathInfo();
     if (!empty($this->requestUrl)) {
         $keys = explode('/', $this->requestUrl);
         if (count($keys) > 1) {
             $path = $keys[0];
             $slug = str_replace(".html", "", $keys[1]);
         } else {
             $slug = str_replace(".html", "", $keys[0]);
         }
     }
     $entryDataJoint = new CrelishJsonDataProvider($ctype, ['filter' => ['slug' => $slug]]);
     $entryModel = $entryDataJoint->one();
     $this->entryPoint = ['ctype' => $ctype, 'slug' => $slug, 'path' => $path, 'uuid' => $entryModel['uuid']];
 }
    public function run()
    {
        $elementType = !empty($_GET['cet']) ? $_GET['cet'] : 'page';
        $modelProvider = new CrelishJsonDataProvider($elementType, [], null);
        $filterModel = new CrelishDynamicJsonModel(['ctype' => $elementType]);
        $label = $this->field->label;
        $out = <<<EOT
    <div class="form-group field-crelishdynamicmodel-body required">
      <label class="control-label" for="crelishdynamicmodel-body">{$label}</label>
      <div class="">
        <matrix></matrix>
        <div class="help-block help-block-error "></div>
      </div>
    </div>

    <div class="modal fade matrix-modal-{$this->formKey}" tabindex="-1" role="dialog" aria-labelledby="matrix-modal-{$this->formKey}" id="matrix-modal-{$this->formKey}">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Content selection</h4>
          </div>
          <div class="modal-body">
EOT;
        $out .= $this->render('matrix.twig', ['dataProvider' => $modelProvider->raw(), 'filterModel ' => $filterModel, 'columns' => ['systitle', ['class' => ActionColumn::className(), 'template' => '{update}', 'buttons' => ['update' => function ($url, $model) {
            return Html::a('<span class="glyphicon glyphicon-plus"></span>', $url, ['title' => \Yii::t('app', 'Add'), 'data-pjax' => '0', 'data-content' => Json::encode(['uuid' => $model['uuid'], 'ctype' => $model['ctype']])]);
        }]]], 'ctype' => $elementType, 'formKey' => $this->formKey]);
        $out .= <<<EOT
          </div>
        </div>
      </div>
    </div>

    <script type="riot/tag">
      <matrix>
        <div class="o-grid">
          <div class="o-grid__cell" each={ item, i in data }>
            <span class="c-badge">{ item }</span>

            <div id="sortable">

              <div class="c-card" each={ i }>

                <div class="c-card__item c-card__item--divider">
                  <span class="glyphicon glyphicon-move" aria-hidden="true"></span>
                  { ctype }
                  <span class="c-input-group pull-right">
                    <button class="c-button gc-bc--palette-wetasphalt u-xsmall"><i class="glyphicon glyphicon-pencil"></i></button>
                    <button class="c-button gc-bc--palette-pomgranate u-xsmall"><i class="glyphicon glyphicon-trash"></i></button>
                  </span>
                </div>
                <div class="c-card__content">
                  <dl>
                    <span each={ info }>
                      <dt>{ label }</dt>
                      <dd>{ value }</dd>
                    </span>
                  </dl>
                </div>
              </div>

            </div>
            <button type="button" class="c-button c-button--ghost-primary c-button--block gc-mt--1" data-target=".matrix-modal-{$this->formKey}" onclick="openMatrixModal('{ item }')">Add content</button>
          </div>
        </div>
        <input type="hidden" name="CrelishDynamicJsonModel[{$this->formKey}]" id="CrelishDynamicJsonModel_{$this->formKey}" value="{ JSON.stringify(data) }" />

        // Logic goes here.
        var app = this
        this.data = opts.data

        edit(e) {
          this.text = e.target.value
        }

        add(e) {
          if (this.text) {
            this.items.push({ title: this.text })
            this.text = this.input.value = ''
          }
        }

        removeAllDone(e) {
          this.items = this.items.filter(function(item) {
            return !item.done
          })
        }

        // an two example how to filter items on the list
        whatShow(item) {
          return !item.hidden
        }

        onlyDone(item) {
          return item.done
        }

        toggle(e) {
          var item = e.item
          item.done = !item.done
          return true
        }

        this.on("mount", function() {
          var that = this;
          var matrixData = this.data;
          var el = document.getElementById('sortable');
          if(el) {
            var sortable = Sortable.create(el, {
              handle: '.glyphicon-move',
              animation: 150,
              onSort: function (evt) {
                // same properties as onUpdate
                matrixData.main.move(evt.oldIndex, evt.newIndex)
                app.data = matrixData;
                app.update();
              }
            });
          }
        });
      </matrix>
    </script>

    <script>
      var targetArea = 'main';

      var openMatrixModal = function( area ) {
        targetArea = area;
        \$('.matrix-modal-{$this->formKey}').modal('show');
      };

      var activateContentMatrix = function() {
        \$("#matrix-modal-{$this->formKey} a").each(function() {
          \$(this).on('click', function(e) {
            e.preventDefault();
            var content = \$(this).data("content");
            var origData = JSON.parse(\$("#CrelishDynamicJsonModel_{$this->formKey}").val());
            console.log(\$("#CrelishDynamicJsonModel_{$this->formKey}").val(), origData, targetArea);
            origData[targetArea].push( content );
            \$("#CrelishDynamicJsonModel_{$this->formKey}").val(JSON.stringify(origData));

            \$("#content-form").submit();
          });
        });
      };

      Array.prototype.move = function (old_index, new_index) {
        if (new_index >= this.length) {
          var k = new_index - this.length;
          while ((k--) + 1) {
            this.push(undefined);
          }
        }
        this.splice(new_index, 0, this.splice(old_index, 1)[0]);
        return this; // for testing purposes
      };

      \$("#matrix-modal-{$this->formKey}").on("pjax:end", function() {
        activateContentMatrix();
      });

      \$('#asset-modal').on('shown.bs.modal', function (e) {
        activateContentMatrix();
      });

      var tags = riot.mount('*', {
        data: {$this->data}
      });
    </script>
EOT;
        return $out;
    }
示例#9
0
 /**
  * [findIdentity description].
  *
  * @param [type] $id [description]
  *
  * @return [type] [description]
  */
 public static function findIdentity($id)
 {
     $userProvider = new CrelishJsonDataProvider('user', null, $id);
     $userData = $userProvider->one();
     self::prepareUserdata($userData);
     return new static($userData);
 }
 public function actionIndex()
 {
     $modelProvider = new CrelishJsonDataProvider($this->ctype, [], null);
     return $this->render('content.twig', ['dataProvider' => $modelProvider->raw(), 'columns' => $modelProvider->columns, 'ctype' => $this->ctype]);
 }
示例#11
0
 public function actionDelete()
 {
     $id = !empty(\Yii::$app->getRequest()->getQueryParam('uuid')) ? \Yii::$app->getRequest()->getQueryParam('uuid') : null;
     $modelProvider = new CrelishJsonDataProvider('asset', [], $id);
     $model = $modelProvider->one();
     if (@unlink(\Yii::getAlias('@webroot') . $model['src']) || !file_exists(\Yii::getAlias('@webroot') . $model['src'])) {
         $modelProvider->delete();
         \Yii::$app->session->setFlash('success', 'Asset deleted successfully...');
         header("Location: " . Url::to(['asset/index']));
         exit(0);
     }
     \Yii::$app->session->setFlash('danger', 'Asset could not be deleted...');
     header("Location: " . Url::to(['asset/index', ['uuid' => $model['uuid']]]));
     exit(0);
 }
 /**
  * [parseFolderContent description]
  * @param  [type] $folder [description]
  * @return [type]         [description]
  */
 public function parseFolderContent($folder)
 {
     $filesArr = [];
     $allModels = [];
     $fullFolder = \Yii::getAlias($this->pathAlias) . DIRECTORY_SEPARATOR . $folder;
     if (!file_exists($fullFolder)) {
         mkdir($fullFolder);
     }
     $files = FileHelper::findFiles($fullFolder, ['recursive' => false]);
     if (isset($files[0])) {
         foreach ($files as $file) {
             $filesArr[] = $file;
         }
     }
     foreach ($filesArr as $file) {
         $finalArr = [];
         $content = file_get_contents($file);
         $modelArr = json_decode($content, true);
         if (is_null($modelArr)) {
             $segments = explode(DIRECTORY_SEPARATOR, $file);
             CrelishBaseController::addError("Invalid JSON in " . array_pop($segments));
             continue;
         }
         $modelArr['id'] = $file;
         $modelArr['ctype'] = $this->ctype;
         // todo: Handle special fields... uncertain about this.
         foreach ($modelArr as $attr => $value) {
             if (strpos($attr, '__cr_include') !== false) {
                 // Include data.
                 $include = new CrelishJsonDataProvider($value['ctype'], [], $value['uuid']);
                 $finalArr[str_replace('__cr_include', '', $attr)] = $include->one();
             } else {
                 $finalArr[$attr] = $value;
             }
         }
         $allModels[] = $finalArr;
     }
     return $allModels;
 }
 public function parseFolderContent($folder)
 {
     $filesArr = [];
     $allModels = [];
     $fullFolder = \Yii::getAlias($this->pathAlias) . DIRECTORY_SEPARATOR . $folder;
     $files = FileHelper::findFiles($fullFolder);
     if (isset($files[0])) {
         foreach ($files as $file) {
             $filesArr[] = $file;
         }
     }
     foreach ($filesArr as $file) {
         $finalArr = [];
         $content = file_get_contents($file);
         $modelArr = json_decode($content, true);
         $modelArr['id'] = $file;
         $modelArr['ctype'] = $this->ctype;
         // todo: Handle special fields... uncertain about this.
         foreach ($modelArr as $attr => $value) {
             if (strpos($attr, '__cr_include') !== false) {
                 // Include data.
                 $include = new CrelishJsonDataProvider($value['ctype'], [], $value['uuid']);
                 $finalArr[str_replace('__cr_include', '', $attr)] = $include->one();
             } else {
                 $finalArr[$attr] = $value;
             }
         }
         $allModels[] = $finalArr;
     }
     return $allModels;
 }