From 40509961cdf571a91920fd3286d5d58deac562be Mon Sep 17 00:00:00 2001 From: rocho Date: Fri, 27 Nov 2015 15:27:46 +0100 Subject: [PATCH 1/4] add UploadController 'rest' controller --- .gitignore | 3 ++ backend/controllers/SiteController.php | 11 ++++-- backend/controllers/UploadController.php | 46 ++++++++++++++++++++++++ backend/models/UploadForm.php | 24 +++++++++++++ backend/views/layouts/header.php | 6 +++- backend/views/site/upload.php | 24 +++++++++++++ frontend/web/profile/.gitkeep | 0 7 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 backend/controllers/UploadController.php create mode 100644 backend/models/UploadForm.php create mode 100644 backend/views/site/upload.php create mode 100644 frontend/web/profile/.gitkeep diff --git a/.gitignore b/.gitignore index e587688..9b126c3 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ phpunit.phar /phpunit.xml /node_modules + +/frontend/web/profile/** +!/frontend/web/profile/.gitkeep \ No newline at end of file diff --git a/backend/controllers/SiteController.php b/backend/controllers/SiteController.php index 73bd4ec..a72bc07 100644 --- a/backend/controllers/SiteController.php +++ b/backend/controllers/SiteController.php @@ -6,6 +6,7 @@ use yii\filters\AccessControl; use yii\web\Controller; use common\models\LoginForm; use yii\filters\VerbFilter; +use backend\models\UploadForm; /** * Site controller @@ -22,7 +23,7 @@ class SiteController extends Controller 'class' => AccessControl::className(), 'rules' => [ [ - 'actions' => ['login', 'error'], + 'actions' => ['login', 'error','upload-image'], 'allow' => true, ], [ @@ -55,7 +56,6 @@ class SiteController extends Controller public function actionIndex() { - Yii::$app->security->generatePasswordHash('test'); return $this->render('index'); } @@ -85,4 +85,11 @@ class SiteController extends Controller return $this->goHome(); } + + public function actionUploadImage(){ + \yii::$app->request->enableCsrfValidation = false; + $model = new UploadForm(); + + return $this->render('upload', ['model' =>$model]); + } } diff --git a/backend/controllers/UploadController.php b/backend/controllers/UploadController.php new file mode 100644 index 0000000..b043596 --- /dev/null +++ b/backend/controllers/UploadController.php @@ -0,0 +1,46 @@ + + user->isGuest ){?> diff --git a/backend/views/site/upload.php b/backend/views/site/upload.php new file mode 100644 index 0000000..57e9f0a --- /dev/null +++ b/backend/views/site/upload.php @@ -0,0 +1,24 @@ + + +
+ + ['enctype' => 'multipart/form-data']]); ?> + + +
+ 'btn btn-primary']) ?> +
+ + + +
+ \ No newline at end of file diff --git a/frontend/web/profile/.gitkeep b/frontend/web/profile/.gitkeep new file mode 100644 index 0000000..e69de29 From ed80f8720dd83a834cb471bb2805e73d2bdda66f Mon Sep 17 00:00:00 2001 From: Roland Schneider Date: Sun, 29 Nov 2015 08:28:09 +0100 Subject: [PATCH 2/4] add Image and Upload helper classes --- .gitignore | 3 +- backend/controllers/UploadController.php | 51 +++--- backend/models/UploadForm.php | 25 ++- backend/views/site/upload.php | 1 + common/components/GD.php | 164 ++++++++++++++++++ common/components/Image.php | 99 +++++++++++ common/components/Upload.php | 50 ++++++ common/models/Image.php | 60 +++++++ .../m151127_152631_add__table__image.php | 43 +++++ ...table__customer__add__column__id_image.php | 30 ++++ 10 files changed, 501 insertions(+), 25 deletions(-) create mode 100644 common/components/GD.php create mode 100644 common/components/Image.php create mode 100644 common/components/Upload.php create mode 100644 common/models/Image.php create mode 100644 console/migrations/m151127_152631_add__table__image.php create mode 100644 console/migrations/m151127_214503_alter__table__customer__add__column__id_image.php diff --git a/.gitignore b/.gitignore index 9b126c3..1d62e63 100644 --- a/.gitignore +++ b/.gitignore @@ -32,4 +32,5 @@ phpunit.phar /node_modules /frontend/web/profile/** -!/frontend/web/profile/.gitkeep \ No newline at end of file +!/frontend/web/profile/.gitkeep +/frontend/web/uploads/** \ No newline at end of file diff --git a/backend/controllers/UploadController.php b/backend/controllers/UploadController.php index b043596..bd75a0e 100644 --- a/backend/controllers/UploadController.php +++ b/backend/controllers/UploadController.php @@ -1,8 +1,11 @@ load(Yii::$app->request->post()) && $model->validate()) { + + + $model->image = UploadedFile::getInstance($model, 'image'); + + /**save into frontend/web/uploads/profile*/ + $path = \common\components\Image::upload($model->image,'profile'); + + $image = new Image(); + $image->path = $path; + $image->save(); + + /* the result object that is sent to client*/ -// /* Generate unique name */ - $filename = \Yii::getAlias('@frontend') ."/web/profile/" . uniqid() . $extension; - echo $filename; - -// /* Open a file for writing */ - $fp = fopen( $filename, "w" ); - - /* Read the data 1 KB at a time - and write to the file */ - while( $data = fread( $postdata, 1024 ) ) - fwrite( $fp, $data ); - - /* Close the streams */ - fclose( $fp ); - fclose( $postdata ); - - /* the result object that is sent to client*/ - - echo "ok"; + $resp['ok'] = 1; + $resp['id_image'] = $image->id_image; + }else{ + $resp['ok'] = 0; + $resp['message'] = print_r($model->errors,true); + } + + return $resp; } } \ No newline at end of file diff --git a/backend/models/UploadForm.php b/backend/models/UploadForm.php index a98d27f..38a9090 100644 --- a/backend/models/UploadForm.php +++ b/backend/models/UploadForm.php @@ -3,22 +3,45 @@ namespace backend\models; use yii\base\Model; use common\models\User; +use common\models\Image; class UploadForm extends Model{ + const SECRET= "aN6obLS2wMFzXw2VQBar"; + public $image ; + public $secret; + /** * @inheritdoc * @formatter:off */ public function rules() { - return [['image',function ($attribute, $params) {}], ]; + return [ + + [['image'], 'image', 'mimeTypes' => 'image/jpeg, image/png', 'extensions'=>'jpg, png'], + [['image'], 'required',], + [['secret'], 'required'], + [['secret'], 'validSecret'], + + ]; } + public function validSecret(){ + if ( $this->secret != self::SECRET ){ + $this->addError("secret","Invalid secret"); + } + } + + public function save(){ + + $image = new Image(); + return true; } + } \ No newline at end of file diff --git a/backend/views/site/upload.php b/backend/views/site/upload.php index 57e9f0a..5006035 100644 --- a/backend/views/site/upload.php +++ b/backend/views/site/upload.php @@ -13,6 +13,7 @@ use backend\models\UploadForm; ['enctype' => 'multipart/form-data']]); ?> + field($model, "image")->fileInput()?>
'btn btn-primary']) ?> diff --git a/common/components/GD.php b/common/components/GD.php new file mode 100644 index 0000000..9bafe16 --- /dev/null +++ b/common/components/GD.php @@ -0,0 +1,164 @@ +_mime = image_type_to_mime_type($imageData[2]); + $this->_width = $imageData[0]; + $this->_height = $imageData[1]; + + switch ($this->_mime) { + case 'image/jpeg': + $this->_image = imagecreatefromjpeg($file); + break; + case 'image/png': + $this->_image = imagecreatefrompng($file); + break; + case 'image/gif': + $this->_image = imagecreatefromgif($file); + break; + } + } + } + + public function resize($width = null, $height = null) + { + if(!$this->_image || (!$width && !$height)){ + return false; + } + + if(!$width) + { + if ($this->_height > $height) { + $ratio = $this->_height / $height; + $newWidth = round($this->_width / $ratio); + $newHeight = $height; + } else { + $newWidth = $this->_width; + $newHeight = $this->_height; + } + } + elseif(!$height) + { + if ($this->_width > $width) { + $ratio = $this->_width / $width; + $newWidth = $width; + $newHeight = round($this->_height / $ratio); + } else { + $newWidth = $this->_width; + $newHeight = $this->_height; + } + } + else + { + $newWidth = $width; + $newHeight = $height; + } + + $resizedImage = imagecreatetruecolor($newWidth, $newHeight); + imagealphablending($resizedImage, false); + + imagecopyresampled( + $resizedImage, + $this->_image, + 0, + 0, + 0, + 0, + $newWidth, + $newHeight, + $this->_width, + $this->_height + ); + + $this->_image = $resizedImage; + } + + public function cropThumbnail($width, $height) + { + if(!$this->_image || !$width || !$height){ + return false; + } + + $sourceRatio = $this->_width / $this->_height; + $thumbRatio = $width / $height; + + $newWidth = $this->_width; + $newHeight = $this->_height; + + if($sourceRatio !== $thumbRatio) + { + if($this->_width >= $this->_height){ + if($thumbRatio > 1){ + $newHeight = $this->_width / $thumbRatio; + if($newHeight > $this->_height){ + $newWidth = $this->_height * $thumbRatio; + $newHeight = $this->_height; + } + } elseif($thumbRatio == 1) { + $newWidth = $this->_height; + $newHeight = $this->_height; + } else { + $newWidth = $this->_height * $thumbRatio; + } + } else { + if($thumbRatio > 1){ + $newHeight = $this->_width / $thumbRatio; + } elseif($thumbRatio == 1) { + $newWidth = $this->_width; + $newHeight = $this->_width; + } else { + $newHeight = $this->_width / $thumbRatio; + if($newHeight > $this->_height){ + $newHeight = $this->_height; + $newWidth = $this->_height * $thumbRatio; + } + } + } + } + + $resizedImage = imagecreatetruecolor($width, $height); + imagealphablending($resizedImage, false); + + imagecopyresampled( + $resizedImage, + $this->_image, + 0, + 0, + round(($this->_width - $newWidth) / 2), + round(($this->_height - $newHeight) / 2), + $width, + $height, + $newWidth, + $newHeight + ); + + $this->_image = $resizedImage; + } + + public function save($file, $quality = 90) + { + switch($this->_mime) { + case 'image/jpeg': + return imagejpeg($this->_image, $file, $quality); + break; + case 'image/png': + imagesavealpha($this->_image, true); + return imagepng($this->_image, $file); + break; + case 'image/gif': + return imagegif($this->_image, $file); + break; + } + return false; + } +} \ No newline at end of file diff --git a/common/components/Image.php b/common/components/Image.php new file mode 100644 index 0000000..cb333ca --- /dev/null +++ b/common/components/Image.php @@ -0,0 +1,99 @@ +tempName, $fileName, $resizeWidth, $resizeHeight, $resizeCrop) + : $fileInstance->saveAs($fileName); + + if(!$uploaded){ + throw new HttpException(500, 'Cannot upload file "'.$fileName.'". Please check write permissions.'); + } + + return Upload::getLink($fileName); + } + + /** + * + * @param unknown $filename + * @param unknown $width + * @param unknown $height + * @param string $crop + * @return string + */ + static function thumb($filename, $width = null, $height = null, $crop = true) + { + if($filename && file_exists(($filename = Yii::getAlias('@frontend/web') . $filename))) + { + $info = pathinfo($filename); + $thumbName = $info['filename'] . '-' . md5( filemtime($filename) . (int)$width . (int)$height . (int)$crop ) . '.' . $info['extension']; + $thumbFile = Yii::getAlias('@frontend/web') . DIRECTORY_SEPARATOR . Upload::$UPLOADS_DIR . DIRECTORY_SEPARATOR . 'thumbs' . DIRECTORY_SEPARATOR . $thumbName; + $thumbWebFile = '/' . Upload::$UPLOADS_DIR . '/thumbs/' . $thumbName; + if(file_exists($thumbFile)){ + return $thumbWebFile; + } + elseif(FileHelper::createDirectory(dirname($thumbFile), 0777) && self::copyResizedImage($filename, $thumbFile, $width, $height, $crop)){ + return $thumbWebFile; + } + } + return ''; + } + + static function copyResizedImage($inputFile, $outputFile, $width, $height = null, $crop = true) + { + if (extension_loaded('gd')) + { + $image = new GD($inputFile); + + if($height) { + if($width && $crop){ + $image->cropThumbnail($width, $height); + } else { + $image->resize($width, $height); + } + } else { + $image->resize($width); + } + return $image->save($outputFile); + } + elseif(extension_loaded('imagick')) + { + $image = new \Imagick($inputFile); + + if($height && !$crop) { + $image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1, true); + } + else{ + $image->resizeImage($width, null, \Imagick::FILTER_LANCZOS, 1); + } + + if($height && $crop){ + $image->cropThumbnailImage($width, $height); + } + + return $image->writeImage($outputFile); + } + else { + throw new HttpException(500, 'Please install GD or Imagick extension'); + } + } +} \ No newline at end of file diff --git a/common/components/Upload.php b/common/components/Upload.php new file mode 100644 index 0000000..fd51eba --- /dev/null +++ b/common/components/Upload.php @@ -0,0 +1,50 @@ +saveAs($fileName)){ + throw new HttpException(500, 'Cannot upload file "'.$fileName.'". Please check write permissions.'); + } + return Upload::getLink($fileName); + } + + static function getUploadPath($dir) + { + $uploadPath = $dir = Yii::getAlias('@frontend/web').DIRECTORY_SEPARATOR.self::$UPLOADS_DIR.($dir ? DIRECTORY_SEPARATOR.$dir : ''); + if(!FileHelper::createDirectory($uploadPath)){ + throw new HttpException(500, 'Cannot create "'.$uploadPath.'". Please check write permissions.'); + } + return $uploadPath; + } + + static function getLink($fileName) + { + return str_replace('\\', '/', str_replace(Yii::getAlias('@frontend/web'), '', $fileName)); + } + + static function getFileName($fileInstanse, $namePostfix = true) + { + $baseName = str_ireplace('.'.$fileInstanse->extension, '', $fileInstanse->name); + $fileName = StringHelper::truncate(Inflector::slug($baseName), 32, ''); + if($namePostfix || !$fileName) { + $fileName .= ($fileName ? '-' : '') . substr(uniqid(md5(rand()), true), 0, 10); + } + $fileName .= '.' . $fileInstanse->extension; + + return $fileName; + } +} \ No newline at end of file diff --git a/common/models/Image.php b/common/models/Image.php new file mode 100644 index 0000000..8ae7821 --- /dev/null +++ b/common/models/Image.php @@ -0,0 +1,60 @@ + 255] + ]; + } + + /** + * @inheritdoc + */ + public function behaviors() + { + return [ + [ 'class' => TimestampBehavior::className(), + 'value' => function(){ return date('Y-m-d H:i:s' ); } + ] + ]; + } + + /** + * @inheritdoc + */ + public function attributeLabels() + { + return [ + 'id_image' => Yii::t('common/image', 'Id Image'), + 'path' => Yii::t('common/image', 'Path'), + 'created_at' => Yii::t('common/image', 'Created At'), + 'updated_at' => Yii::t('common/image', 'Updated At'), + ]; + } +} diff --git a/console/migrations/m151127_152631_add__table__image.php b/console/migrations/m151127_152631_add__table__image.php new file mode 100644 index 0000000..98f5d04 --- /dev/null +++ b/console/migrations/m151127_152631_add__table__image.php @@ -0,0 +1,43 @@ +db->driverName === 'mysql') { + // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci + $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; + } + + $this->createTable('{{%image}}', [ + 'id_image' => $this->primaryKey(), + 'path' => $this->string(255), + 'created_at' => $this->dateTime()->notNull(), + 'updated_at' => $this->dateTime()->notNull(), + ], $tableOptions); + + } + + public function down() + { + echo "m151127_152631_add__table__image cannot be reverted.\n"; + + return false; + } + + /* + // Use safeUp/safeDown to run migration code within a transaction + public function safeUp() + { + } + + public function safeDown() + { + } + */ +} diff --git a/console/migrations/m151127_214503_alter__table__customer__add__column__id_image.php b/console/migrations/m151127_214503_alter__table__customer__add__column__id_image.php new file mode 100644 index 0000000..9dff562 --- /dev/null +++ b/console/migrations/m151127_214503_alter__table__customer__add__column__id_image.php @@ -0,0 +1,30 @@ +addColumn("customer", "id_image", "int"); + } + + public function down() + { + echo "m151127_214503_alter__table__customer__add__column__id_image cannot be reverted.\n"; + + return false; + } + + /* + // Use safeUp/safeDown to run migration code within a transaction + public function safeUp() + { + } + + public function safeDown() + { + } + */ +} From 17a339badfa82048dad038e448bd888372d25264 Mon Sep 17 00:00:00 2001 From: Roland Schneider Date: Sun, 29 Nov 2015 11:08:04 +0100 Subject: [PATCH 3/4] change backand request csrf settings --- backend/config/main.php | 13 ++++++++++++- common/config/params.php | 2 +- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/backend/config/main.php b/backend/config/main.php index fbb4bd2..70d7514 100644 --- a/backend/config/main.php +++ b/backend/config/main.php @@ -14,17 +14,28 @@ return [ 'bootstrap' => ['log'], 'modules' => [], 'components' => [ + 'request' => [ + 'csrfParam' => '_backendCSRF', + 'csrfCookie' => [ + 'httpOnly' => true, + 'path' => '/backend/web', + ], + ], 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, 'identityCookie' => [ 'name' => '_backendUser', // unique for backend - 'path'=>'/backend/web' // correct path for the backend app. + 'path'=>'/backend/web', // correct path for the backend app. + 'httpOnly' => true, ] ], 'session' => [ 'name' => '_backendSessionId', // unique for backend 'savePath' => __DIR__ . '/../runtime', // a temporary folder on backend + 'cookieParams' => [ + 'path' => '/backend/web', + ], ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, diff --git a/common/config/params.php b/common/config/params.php index f8d2974..359c9f8 100644 --- a/common/config/params.php +++ b/common/config/params.php @@ -3,5 +3,5 @@ return [ 'adminEmail' => 'rocho02@gmail.com', 'supportEmail' => 'rocho02@gmail.com', 'user.passwordResetTokenExpire' => 3600, - 'version' => 'v0.0.4' + 'version' => 'v0.0.5' ]; From 5a1d2ff632b605ea7afed77e9143777251ec249a Mon Sep 17 00:00:00 2001 From: Roland Schneider Date: Sun, 29 Nov 2015 11:13:06 +0100 Subject: [PATCH 4/4] edit change log vor version 0.0.5 --- changelog.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/changelog.txt b/changelog.txt index 920719a..d2b26d5 100644 --- a/changelog.txt +++ b/changelog.txt @@ -1,3 +1,5 @@ +-0.0.5 + a backend csrf config változtatása -0.0.4 új admin theme : admin lte recepció/tranzakciók menü ki/bekapcsolható