Skip to content

Commit

Permalink
fix issue with replace, upload, move and delete files #137
Browse files Browse the repository at this point in the history
  • Loading branch information
nadar committed Jun 20, 2018
1 parent 55a76f6 commit cd59f04
Show file tree
Hide file tree
Showing 9 changed files with 132 additions and 140 deletions.
4 changes: 1 addition & 3 deletions src/Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use luya\admin\importers\AuthImporter;
use luya\admin\importers\FilterImporter;
use luya\admin\importers\PropertyImporter;
use luya\admin\importers\StorageImporter;
use luya\admin\filesystem\LocalFileSystem;

/**
Expand Down Expand Up @@ -277,7 +276,7 @@ public function getJsTranslationMessages()
'js_ngrest_rm_page', 'js_ngrest_rm_confirm', 'js_ngrest_error', 'js_ngrest_rm_update', 'js_ngrest_rm_success', 'js_tag_exists', 'js_tag_success', 'js_admin_reload', 'js_dir_till', 'js_dir_set_date', 'js_dir_table_add_row', 'js_dir_table_add_column', 'js_dir_image_description',
'js_dir_no_selection', 'js_dir_image_upload_ok', 'js_dir_image_filter_error', 'js_dir_upload_wait', 'js_dir_manager_upload_image_ok', 'js_dir_manager_rm_file_confirm', 'js_dir_manager_rm_file_ok', 'js_zaa_server_proccess',
'ngrest_select_no_selection', 'js_ngrest_toggler_success', 'js_filemanager_count_files_overlay', 'js_link_set_value', 'js_link_not_set', 'js_link_change_value', 'aws_changepassword_succes', 'js_account_update_profile_success', 'layout_filemanager_remove_dir_not_empty',
'ngrest_button_delete', 'layout_btn_reload', 'js_dir_manager_rm_file_confirm_title'
'ngrest_button_delete', 'layout_btn_reload', 'js_dir_manager_rm_file_confirm_title', 'js_dir_manager_rm_folder_confirm_title',
];
}

Expand Down Expand Up @@ -378,7 +377,6 @@ public function import(ImportControllerInterface $import)
AuthImporter::class,
FilterImporter::class,
PropertyImporter::class,
StorageImporter::class,
];
}

Expand Down
108 changes: 50 additions & 58 deletions src/apis/StorageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,7 @@
use luya\admin\filters\MediumThumbnail;
use luya\helpers\FileHelper;
use yii\web\BadRequestHttpException;
use yii\base\InvalidParamException;
use yii\web\NotFoundHttpException;
use yii\data\ActiveDataProvider;
use luya\admin\file\Query;
use yii\data\ArrayDataProvider;
use luya\admin\models\StorageImage;
use luya\admin\file\Item;
use luya\helpers\ArrayHelper;
Expand All @@ -47,12 +43,11 @@ class StorageController extends RestController
/**
* Flush the storage caching data.
*/
protected function flushApiCache()
protected function flushApiCache($folderId = 0, $page = 0)
{
Yii::$app->storage->flushArrays();
$this->deleteHasCache('storageApiDataFolders');
$this->deleteHasCache('storageApiDataFiles');
$this->deleteHasCache('storageApiDataImages');
$this->deleteHasCache(['storageApiDataFiles', (int) $folderId, (int) $page]);
}

// DATA READERS
Expand All @@ -64,22 +59,15 @@ protected function flushApiCache()
*/
public function actionDataFolders()
{
$cache = $this->getHasCache('storageApiDataFolders');

if ($cache === false) {
return $this->getOrSetHasCache('storageApiDataFolders', function() {
$folders = [];
foreach (Yii::$app->storage->findFolders() as $key => $folder) {
$folders[$key] = $folder->toArray();
$folders[$key]['toggle_open'] = (int) Yii::$app->adminuser->identity->setting->get('foldertree.'.$folder->id);
$folders[$key]['subfolder'] = Yii::$app->storage->getFolder($folder->id)->hasChild();
}

$this->setHasCache('storageApiDataFolders', $folders, new DbDependency(['sql' => 'SELECT MAX(id) FROM admin_storage_folder WHERE is_deleted=false']), 0);

return $folders;
}

return $cache;
}, 0, new DbDependency(['sql' => 'SELECT MAX(id) FROM admin_storage_folder WHERE is_deleted=false']));
}

/**
Expand All @@ -90,13 +78,12 @@ public function actionDataFolders()
public function actionDataFiles($folderId = 0, $page = 0)
{
$perPage = 50;
//$totalCount = (new Query())->where(['folder_id' => $folderId, 'is_hidden' => false, 'is_deleted' => false])->count();
$totalCount = StorageFile::find()->where(['folder_id' => $folderId, 'is_hidden' => false, 'is_deleted' => false])->count();

$tinyCrop = Yii::$app->storage->getFiltersArrayItem(TinyCrop::identifier());
$mediumThumbnail = Yii::$app->storage->getFiltersArrayItem(MediumThumbnail::identifier());

$files = $this->getOrSetHasCache(['storageApiDataFiles', $folderId, $page], function() use ($folderId, $page, $perPage, $tinyCrop, $mediumThumbnail) {
$files = $this->getOrSetHasCache(['storageApiDataFiles', (int) $folderId, (int) $page], function() use ($folderId, $page, $perPage, $tinyCrop, $mediumThumbnail) {
$files = [];
$fileQuery = StorageFile::find()
->where(['folder_id' => $folderId, 'is_hidden' => false, 'is_deleted' => false])
Expand Down Expand Up @@ -135,11 +122,19 @@ public function actionDataFiles($folderId = 0, $page = 0)
}

return $files;
}, 0, new DbDependency(['sql' => 'SELECT MAX(id) FROM admin_storage_file WHERE is_deleted=false']));
}, 0, new DbDependency(['sql' => 'SELECT MAX(upload_timestamp) FROM admin_storage_file WHERE is_deleted=false AND folder_id=:folderId', 'params' => [':folderId' => $folderId]]));

return $this->generatePaginationArrayResponse($page, $perPage, $totalCount, $files);
}

/**
*
* @param integer $currentPage
* @param integer $perPage
* @param integer $totalCount
* @param array $files
* @return array
*/
private function generatePaginationArrayResponse($currentPage, $perPage, $totalCount, array $files)
{
return [
Expand All @@ -153,35 +148,14 @@ private function generatePaginationArrayResponse($currentPage, $perPage, $totalC
];
}

/**
* Get all images from the storage container.
*
* @return array
*/
public function actionDataImages()
{
$cache = $this->getHasCache('storageApiDataImages');

if ($cache === false) {
$images = [];
foreach (Yii::$app->storage->findImages() as $image) {
if (!empty($image->file) && !$image->file->isHidden && !$image->file->isDeleted) {
$images[] = $image->toArray(['id', 'fileId', 'filterId', 'source', 'resolutionHeight', 'resolutionWidth']);
}
}
$this->setHasCache('storageApiDataImages', $images, new DbDependency(['sql' => 'SELECT MAX(id) FROM admin_storage_image']), 0);
return $images;
}

return $cache;
}

// ACTIONS

/**
* Get all storage file informations for a given ID.
*
* @param integer $fileId
* @throws NotFoundHttpException
* @return array
* @since 1.2.0
*/
public function actionFileInfo($id)
Expand All @@ -195,6 +169,13 @@ public function actionFileInfo($id)
return $model->toArray([], ['user', 'file', 'images']);
}

/**
*
* @param integer $id
* @throws NotFoundHttpException
* @return array
* @since 1.2.2
*/
public function actionImageInfo($id)
{
$model = StorageImage::find()->where(['id' => $id])->with(['file'])->one();
Expand All @@ -213,7 +194,7 @@ public function actionImageInfo($id)
* @return array
* @since 1.2.0
*/
public function actionFileUpdate($id)
public function actionFileUpdate($id, $pageId = 0)
{
$model = StorageFile::find()->where(['id' => $id])->with(['user'])->one();

Expand All @@ -225,7 +206,7 @@ public function actionFileUpdate($id)
$model->attributes = $post;

if ($model->update(true, ['name_original', 'inline_disposition']) !== false) {
$this->flushApiCache();
$this->flushApiCache($model->folder_id, $pageId);
return $model;
}

Expand All @@ -243,6 +224,7 @@ public function actionFilemanagerUpdateCaption()

$fileId = Yii::$app->request->post('id', false);
$captionsText = Yii::$app->request->post('captionsText', false);
$pageId = Yii::$app->request->post('pageId', 0);

if ($fileId && is_scalar($fileId) && $captionsText) {
$model = StorageFile::findOne($fileId);
Expand All @@ -251,7 +233,7 @@ public function actionFilemanagerUpdateCaption()
'caption' => I18n::encode($captionsText),
]);

$this->flushApiCache();
$this->flushApiCache($model->folder_id, $pageId);

return true;
}
Expand All @@ -274,7 +256,10 @@ public function actionImageFilter()
return ['error' => false, 'id' => $create->id];
}
} catch (Exception $err) {
return ['error' => true, 'message' => Module::t('api_storage_image_upload_error', ['error' => $err->getMessage()])];
return $this->sendArrayError([
'error' => true,
'message' => Module::t('api_storage_image_upload_error'),
]);
}
}

Expand All @@ -298,6 +283,8 @@ public function actionFileReplace()
$this->checkRouteAccess(self::PERMISSION_ROUTE);

$fileId = Yii::$app->request->post('fileId', false);
$pageId = Yii::$app->request->post('pageId', 0);
Yii::warning('replace request for file id' . $fileId, __METHOD__);
$raw = $_FILES['file'];
/** @var $file \luya\admin\file\Item */
if ($file = Yii::$app->storage->getFile($fileId)) {
Expand All @@ -312,8 +299,8 @@ public function actionFileReplace()
}

if (Storage::replaceFile($file->systemFileName, $newFileSource, $raw['name'])) {
foreach (Yii::$app->storage->findImages(['file_id' => $file->id]) as $img) {
Storage::removeImage($img->id, false);
foreach (StorageImage::find()->where(['file_id' => $file->id])->all() as $img) {
$removal = Storage::removeImage($img->id, false);
}

// calculate new file files based on new file
Expand All @@ -325,8 +312,7 @@ public function actionFileReplace()
'file_size' => $fileSize,
'upload_timestamp' => time(),
]);
$this->flushApiCache();

$this->flushApiCache($model->folder_id, $pageId);
return true;
}
}
Expand Down Expand Up @@ -377,8 +363,13 @@ public function actionFilemanagerMoveFiles()
$toFolderId = Yii::$app->request->post('toFolderId', 0);
$fileIds = Yii::$app->request->post('fileIds', []);

$currentPageId = Yii::$app->request->post('currentPageId', 0);
$currentFolderId = Yii::$app->request->post('currentFolderId', 0);

$response = Storage::moveFilesToFolder($fileIds, $toFolderId);
$this->flushApiCache();
$this->flushApiCache($currentFolderId, $currentPageId);
$this->flushApiCache($toFolderId, $currentPageId);
$this->flushHasCache($toFolderId, 0);
return $response;
}

Expand All @@ -391,13 +382,14 @@ public function actionFilemanagerMoveFiles()
public function actionFilemanagerRemoveFiles()
{
$this->checkRouteAccess(self::PERMISSION_ROUTE);

$pageId = Yii::$app->request->post('pageId', 0);
$folderId = Yii::$app->request->post('folderId', 0);
foreach (Yii::$app->request->post('ids', []) as $id) {
if (!Storage::removeFile($id)) {
return false;
}
}
$this->flushApiCache();
$this->flushApiCache($folderId, $pageId);
return true;
}

Expand All @@ -409,12 +401,12 @@ public function actionFilemanagerRemoveFiles()
*/
public function actionIsFolderEmpty($folderId)
{
$count = Yii::$app->storage->getFolder($folderId)->getFilesCount();
if ($count > 0) {
return false;
}
$count = StorageFile::find()->where(['folder_id' => $folderId, 'is_deleted' => false])->count();

return true;
return [
'count' => $count,
'empty' => $count > 0 ? false : true,
];
}

/**
Expand Down
6 changes: 4 additions & 2 deletions src/commands/StorageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@

use Yii;
use luya\admin\importers\StorageImporter;
use luya\console\Command;

/**
* LUYA Admin Storage command.
*
* As since 1.2 the storage importer is removed, we have to move all commands here, as they wont work since storage system refactoring.
*
* @author Martin Petrasch <martin.petrasch@zephir.ch>
* @author Basil Suter <basil@nadar.io>
* @since 1.0.0
*/
class StorageController extends \luya\console\Command
class StorageController extends Command
{
/**
* Delete orphaned files, but requires user confirmation to ensure delete process.
Expand Down Expand Up @@ -96,7 +99,6 @@ public function actionCleanupImageTable()
':filterId' => $row['filter_id'],
])->queryOne();


if (!$keep) {
$this->outputError('Unable to find the first row for this delete request. Skip this one');
continue;
Expand Down
5 changes: 3 additions & 2 deletions src/helpers/Storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

namespace luya\admin\helpers;

use Exception;
use luya\Exception;
use Yii;
use luya\admin\models\StorageFile;
use luya\admin\models\StorageImage;
use luya\admin\Module;
use yii\helpers\VarDumper;

/**
* Helper class to handle remove, upload and moving of storage files.
Expand Down Expand Up @@ -80,7 +81,7 @@ public static function removeFile($fileId, $cleanup = false)
* Remove an image from the storage system and database.
*
* @param integer $imageId The corresponding imageId for the {{\luya\admin\models\StorageImage}} Model to remove.
* @param boolean $cleanup If cleanup is enabled, all other images will be deleted. Event the {{\luya\admin\models\StorageFile}} will be removed
* @param boolean $cleanup If cleanup is enabled, all other images will be deleted. Even the {{\luya\admin\models\StorageFile}} will be removed
* from the database and filesystem. By default cleanup is disabled and will only remove the provided $imageId itself from {{\luya\admin\models\StorageImage}}.
* @return boolean
*/
Expand Down
1 change: 1 addition & 0 deletions src/importers/StorageImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
*
* Storage system importer behavior to cleanup the storage database and folder.
*
* @deprecated remove in 1.2.2
* @author Basil Suter <basil@nadar.io>
* @since 1.0.0
*/
Expand Down
1 change: 0 additions & 1 deletion src/models/StorageImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace luya\admin\models;

use Yii;

use yii\db\ActiveRecord;
use luya\helpers\FileHelper;

Expand Down
2 changes: 1 addition & 1 deletion src/resources/dist/js/main.uglified.js

Large diffs are not rendered by default.

Loading

0 comments on commit cd59f04

Please sign in to comment.