public function init() { $this->name = "Управление файлами хранилища"; $this->modelShowAttribute = "src"; $this->modelClassName = StorageFile::className(); parent::init(); }
/** * @return null|StorageFile */ public function getImage() { $imageId = $this->model->{$this->attribute}; if (!$imageId) { return null; } return StorageFile::findOne($imageId); }
/** * Читка всех сгенерированных миниатюр */ public function actionClearAllThumbnails() { /** * @var $files StorageFile[] */ if ($files = StorageFile::find()->all()) { foreach ($files as $file) { $file->deleteTmpDir(); } } }
/** * * Загрузить файл в хранилище, добавить в базу, вернуть модель StorageFile * * @param UploadedFile|string|File $file объект UploadedFile или File или rootPath до файла локально или http:// путь к файлу (TODO:: доделать) * @param array $data данные для сохранения в базу * @param null $clusterId идентификатор кластера по умолчанию будет выбран первый из конфигурации * @return StorageFile * @throws Exception */ public function upload($file, $data = [], $clusterId = null) { //Для начала всегда загружаем файл во временную диррикторию $tmpdir = Dir::runtimeTmp(); $tmpfile = $tmpdir->newFile(); if ($file instanceof UploadedFile) { $extension = File::object($file->name)->getExtension(); $tmpfile->setExtension($extension); if (!$file->saveAs($tmpfile->getPath())) { throw new Exception("Файл не загружен во временную диррикторию"); } } else { if ($file instanceof File || is_string($file) && BaseUrl::isRelative($file)) { $file = File::object($file); $tmpfile->setExtension($file->getExtension()); $tmpfile = $file->move($tmpfile); } else { if (is_string($file) && !BaseUrl::isRelative($file)) { $curl_session = curl_init($file); if (!$curl_session) { throw new Exception("Неверная ссылка"); } curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_session, CURLOPT_BINARYTRANSFER, true); $file_content = curl_exec($curl_session); curl_close($curl_session); if (!$file_content) { throw new Exception("Не удалось скачать файл"); } $extension = pathinfo($file, PATHINFO_EXTENSION); $pos = strpos($extension, "?"); if ($pos === false) { } else { $extension = substr($extension, 0, $pos); } if ($extension) { $tmpfile->setExtension($extension); } $is_file_saved = file_put_contents($tmpfile, $file_content); if (!$is_file_saved) { throw new Exception("Не удалось сохранить файл"); } //Если в ссылке нет расширения if (!$extension) { $tmpfile = new File($tmpfile->getPath()); try { $mimeType = FileHelper::getMimeType($tmpfile->getPath(), null, false); } catch (InvalidConfigException $e) { throw new Exception("Не удалось пределить расширение файла: " . $e->getMessage()); } if (!$mimeType) { throw new Exception("Не удалось пределить расширение файла"); } $extensions = FileHelper::getExtensionsByMimeType($mimeType); if ($extensions) { if (in_array("jpg", $extensions)) { $extension = 'jpg'; } else { if (in_array("png", $extensions)) { $extension = 'png'; } else { $extension = $extensions[0]; } } $newFile = new File($tmpfile->getPath()); $newFile->setExtension($extension); $tmpfile = $tmpfile->copy($newFile); } } } else { throw new Exception("Файл должен быть определен как \\yii\\web\\UploadedFile или \\skeeks\\sx\\File или string"); } } } $data["type"] = $tmpfile->getType(); $data["mime_type"] = $tmpfile->getMimeType(); $data["size"] = $tmpfile->size()->getBytes(); $data["extension"] = $tmpfile->getExtension(); //Елси это изображение if ($tmpfile->getType() == 'image') { if (extension_loaded('gd')) { list($width, $height, $type, $attr) = getimagesize($tmpfile->toString()); $data["image_height"] = $height; $data["image_width"] = $width; } } if ($cluster = $this->getCluster($clusterId)) { if ($newFileSrc = $cluster->upload($tmpfile)) { $data = array_merge($data, ["src" => $cluster->getPublicSrc($newFileSrc), "cluster_id" => $cluster->getId(), "cluster_file" => $newFileSrc]); } } $file = new StorageFile($data); $file->save(false); return $file; }
/** * @return \yii\db\ActiveQuery */ public function getFiles() { return $this->hasMany(StorageFile::className(), ['id' => 'storage_file_id'])->via('cmsContentElementFiles'); }
/** * @return \yii\db\ActiveQuery */ public function getStorageFiles() { return $this->hasMany(StorageFile::className(), ['created_by' => 'id']); }
public function safeUp() { $rows = (new \yii\db\Query())->select(['id', 'files'])->from('cms_tree')->all(); if ($rows) { foreach ($rows as $row) { /** * @var \skeeks\cms\models\CmsTree $model */ if (!($modelId = \yii\helpers\ArrayHelper::getValue($row, 'id'))) { continue; } if (!($model = \skeeks\cms\models\CmsTree::findOne($modelId))) { continue; } $files = \yii\helpers\ArrayHelper::getValue($row, 'files'); if (!$files) { continue; } $files = Json::decode($files); if ($images = \yii\helpers\ArrayHelper::getValue($files, 'images')) { foreach ($images as $src) { $storageFile = \skeeks\cms\models\StorageFile::find()->where(['src' => $src])->one(); if ($storageFile) { if (!$model->getCmsTreeImages()->andWhere(['storage_file_id' => $storageFile->id])->one()) { $model->link('images', $storageFile); } } } } if ($files = \yii\helpers\ArrayHelper::getValue($files, 'files')) { foreach ($files as $src) { $storageFile = \skeeks\cms\models\StorageFile::find()->where(['src' => $src])->one(); if ($storageFile) { if (!$model->getCmsTreeFiles()->andWhere(['storage_file_id' => $storageFile->id])->one()) { $model->link('files', $storageFile); } } } } } } $rows = (new \yii\db\Query())->select(['id', 'files'])->from('cms_content_element')->all(); if ($rows) { foreach ($rows as $row) { /** * @var \skeeks\cms\models\CmsContentElement $model */ if (!($modelId = \yii\helpers\ArrayHelper::getValue($row, 'id'))) { continue; } if (!($model = \skeeks\cms\models\CmsContentElement::findOne($modelId))) { continue; } $files = \yii\helpers\ArrayHelper::getValue($row, 'files'); if (!$files) { continue; } $files = Json::decode($files); if ($images = \yii\helpers\ArrayHelper::getValue($files, 'images')) { foreach ($images as $src) { $storageFile = \skeeks\cms\models\StorageFile::find()->where(['src' => $src])->one(); if ($storageFile) { if (!$model->getCmsContentElementImages()->andWhere(['storage_file_id' => $storageFile->id])->one()) { $model->link('images', $storageFile); } } } } if ($files = \yii\helpers\ArrayHelper::getValue($files, 'files')) { foreach ($files as $src) { $storageFile = \skeeks\cms\models\StorageFile::find()->where(['src' => $src])->one(); if ($storageFile) { if (!$model->getCmsContentElementFiles()->andWhere(['storage_file_id' => $storageFile->id])->one()) { $model->link('files', $storageFile); } } } } } } }
/** * @return \yii\db\ActiveQuery */ public function getImage() { return $this->hasOne(StorageFile::className(), ['id' => 'image_id']); }
<p></p> <? $dataProvider->pagination->defaultPageSize = 10; ?> <?php echo \skeeks\cms\modules\admin\widgets\GridViewHasSettings::widget(['dataProvider' => $dataProvider, 'filterModel' => $search->getLoadedModel(), 'pjaxOptions' => ['id' => 'sx-storage-files'], 'columns' => [['class' => \yii\grid\DataColumn::className(), 'value' => function (\skeeks\cms\models\StorageFile $model) { return \yii\helpers\Html::a('<i class="glyphicon glyphicon-circle-arrow-left"></i> ' . \Yii::t('skeeks/cms', 'Choose file'), $model->src, ['class' => 'btn btn-primary', 'onclick' => 'sx.SelectFile.submit("' . $model->src . '"); return false;', 'data-pjax' => 0]); }, 'format' => 'raw'], ['class' => \skeeks\cms\modules\admin\grid\ActionColumn::className(), 'controller' => \Yii::$app->createController('cms/admin-storage-files')[0], 'isOpenNewWindow' => true], ['class' => \yii\grid\DataColumn::className(), 'value' => function (\skeeks\cms\models\StorageFile $model) { if ($model->isImage()) { $smallImage = \Yii::$app->imaging->getImagingUrl($model->src, new \skeeks\cms\components\imaging\filters\Thumbnail()); return "<a href='" . $model->src . "' data-pjax='0' class='sx-fancybox' title='" . \Yii::t('skeeks/cms', 'Increase') . "'>\n <img src='" . $smallImage . "' />\n </a>"; } return \yii\helpers\Html::tag('span', $model->extension, ['class' => 'label label-primary', 'style' => 'font-size: 18px;']); }, 'format' => 'raw'], 'name', ['class' => \yii\grid\DataColumn::className(), 'value' => function (\skeeks\cms\models\StorageFile $model) { $model->cluster_id; $cluster = \Yii::$app->storage->getCluster($model->cluster_id); return $cluster->name; }, 'filter' => \yii\helpers\ArrayHelper::map(\Yii::$app->storage->getClusters(), 'id', 'name'), 'format' => 'html', 'attribute' => 'cluster_id'], ['attribute' => 'mime_type', 'filter' => \yii\helpers\ArrayHelper::map(\skeeks\cms\models\StorageFile::find()->groupBy(['mime_type'])->all(), 'mime_type', 'mime_type')], ['attribute' => 'extension', 'filter' => \yii\helpers\ArrayHelper::map(\skeeks\cms\models\StorageFile::find()->groupBy(['extension'])->all(), 'extension', 'extension')], ['class' => \skeeks\cms\grid\FileSizeColumnData::className(), 'attribute' => 'size'], ['class' => \skeeks\cms\grid\CreatedAtColumn::className()], ['class' => \skeeks\cms\grid\CreatedByColumn::className()]]]); ?> <?php echo $form->fieldSetEnd(); ?> <hr /> <?php echo \yii\helpers\Html::a("<i class='glyphicon glyphicon-question-sign'></i>", "#", ['class' => 'btn btn-default', 'onclick' => "sx.dialog({'title' : '" . \Yii::t('skeeks/cms', 'Help') . "', 'content' : '#sx-help'}); return false;"]); ?> <div style="display: none;" id="sx-help"> <?\Yii::t('skeeks/cms','Help in the process of writing ...')?> </div>