Compare commits

..

1 Commits

Author SHA1 Message Date
d36afa5e7d Correction images vers image. 2017-10-11 14:49:10 +02:00
10 changed files with 81 additions and 151 deletions

View File

@@ -11,7 +11,7 @@
], ],
"require": { "require": {
"php": ">=7.0.0", "php": ">=7.0.0",
"laravel/lumen-framework": "5.5.*", "laravel/lumen-framework": "5.4.*",
"symfony/process" : "3.*", "symfony/process" : "3.*",
"intervention/image": "^2.4", "intervention/image": "^2.4",
"intervention/imagecache": "^2.3", "intervention/imagecache": "^2.3",

View File

@@ -1,51 +0,0 @@
<?php
use Spatie\ImageOptimizer\Optimizers\Svgo;
use Spatie\ImageOptimizer\Optimizers\Optipng;
use Spatie\ImageOptimizer\Optimizers\Gifsicle;
use Spatie\ImageOptimizer\Optimizers\Pngquant;
use Spatie\ImageOptimizer\Optimizers\Jpegoptim;
return [
/**
* When calling `optimize` the package will automatically determine which optimizers
* should run for the given image.
*/
'optimizers' => [
Jpegoptim::class => [
'--strip-all', // this strips out all text information such as comments and EXIF data
'--all-progressive', // this will make sure the resulting image is a progressive one
'-m85'
],
Pngquant::class => [
'--force' // required parameter for this package
],
Optipng::class => [
'-i0', // this will result in a non-interlaced, progressive scanned image
'-o2', // this set the optimization level to two (multiple IDAT compression trials)
'-quiet' // required parameter for this package
],
Svgo::class => [
'--disable=cleanupIDs' // disabling because it is know to cause troubles
],
Gifsicle::class => [
'-b', // required parameter for this package
'-O3' // this produces the slowest but best results
],
],
/**
* The maximum time in seconds each optimizer is allowed to run separately.
*/
'timeout' => 60,
/**
* If set to `true` all output of the optimizer binaries will be appended to the default log.
* You can also set this to a class that implements `Psr\Log\LoggerInterface`.
*/
'log_optimizer_activity' => false,
];

View File

@@ -11,7 +11,6 @@ return [
'custom' => \Meoran\Images\Templates\Custom::class, 'custom' => \Meoran\Images\Templates\Custom::class,
), ),
'middlewareAuth' => false,
'lifetime' => 10, 'lifetime' => 10,
'cache' => [ 'cache' => [
'path' => storage_path('app') 'path' => storage_path('app')

View File

@@ -20,7 +20,7 @@ class CreateAssociateImages extends Migration
$table->integer('relation_id'); $table->integer('relation_id');
$table->integer('position')->nullable(); $table->integer('position')->nullable();
$table->foreign('image_id')->references('id')->on('images')->onDelete('cascade'); $table->foreign('image_id')->references('id')->on('images');
}); });
} }

View File

@@ -4,7 +4,6 @@ namespace Meoran\Images\Console\Commands;
use FilesystemIterator; use FilesystemIterator;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use RecursiveDirectoryIterator; use RecursiveDirectoryIterator;
use RecursiveIteratorIterator; use RecursiveIteratorIterator;
@@ -40,13 +39,8 @@ class CacheGarbageCollectorCommand extends Command
*/ */
public function handle() public function handle()
{ {
$base = config('image.cache.path'); $path = storage_path('image.path');
if (empty($base)) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS));
$this->line("Le cache n'est pas configuré. End...");
return;
}
$fs = new Filesystem();
$files = collect($fs->allFiles($base));
/** /**
* @var \SplFileInfo $b * @var \SplFileInfo $b

View File

@@ -44,26 +44,18 @@ class RemoveUselessPicturesCommand extends Command
private function removeNonExistentPictures() private function removeNonExistentPictures()
{ {
$base = config('image.path'); $base = config('image.path');
if (empty($base)) {
throw new \Exception("Config image.path must be defined"); $it = new FilesystemIterator($base);
}
$fs = new Filesystem(); $fs = new Filesystem();
$files = collect($fs->allFiles($base)); $files = $fs->allFiles($base);
$filenames = $files->filter(function ($el) {
$mime = mime_content_type($el->getPathName());
if (strpos($mime, 'image/') === false) {
return false;
}
return true;
})->map(function ($el) {
return $el->getFilename();
});
var_dump($files);
exit;
/** /**
* Suppression des images qui n'existent pas physiquement * Suppression des images qui n'existent pas physiquement
*/ */
$linesToDelete = Image::whereNotIn('filename', $filenames)->get(); $linesToDelete = Image::whereNotIn('filename', $files)->get();
$delete = 0; $delete = 0;
foreach ($linesToDelete as $lineToDelete) { foreach ($linesToDelete as $lineToDelete) {
$lineToDelete->delete(); $lineToDelete->delete();
@@ -88,4 +80,28 @@ class RemoveUselessPicturesCommand extends Command
} }
/**
* Suppression des images qui existent physiquement et en base mais qui ne sont pas utilisées
*/
private function removeNotUsedPictures()
{
$base = config('picturesPath');
$pictures = Image::whereDoesntHave('section', function ($query) {
$query->withTrashed();
})->whereDoesntHave('news', function ($query) {
$query->withTrashed();
})->whereDoesntHave('pages', function ($query) {
$query->withTrashed();
})->get();
$delete = 0;
foreach ($pictures as $picture) {
if (is_file($base . $picture->filename)) {
unlink($base . $picture->filename);
}
$picture->delete();
$delete++;
}
$this->info("Images supprimées car non utilisées : ".$delete);
}
} }

View File

@@ -10,6 +10,8 @@ use Intervention\Image\Exception\NotSupportedException;
use Laravel\Lumen\Routing\Controller as BaseController; use Laravel\Lumen\Routing\Controller as BaseController;
use Meoran\Images\Model\Image; use Meoran\Images\Model\Image;
use Meoran\Images\Templates\Custom; use Meoran\Images\Templates\Custom;
use ReflectionFunction;
use ReflectionMethod;
class ImagesController extends BaseController class ImagesController extends BaseController
{ {
@@ -18,7 +20,7 @@ class ImagesController extends BaseController
{ {
$template = app('request')->input('template'); $template = app('request')->input('template');
if ($template === null) { if ($template === null) {
$template = 'large'; $template = 'original';
} }
switch (strtolower($template)) { switch (strtolower($template)) {
case 'original': case 'original':
@@ -36,24 +38,12 @@ class ImagesController extends BaseController
'image' => 'required|file|image' 'image' => 'required|file|image'
]); ]);
$content = $request->file('image'); $image = new Image(['content' => $request->file('image')]);
if (empty($content)) {
$content = $request->input('image');
}
$image = new Image(['content' => $content]);
$image->save(); $image->save();
return response()->json($image); return response()->json($image);
} }
public function delete($id)
{
$image = Image::findOrFail($id);
$image->delete();
return response()->json("Delete " . $id . " succesfully");
}
private function getOriginal($filename) private function getOriginal($filename)
{ {
$path = $this->getImagePathOrAbort($filename); $path = $this->getImagePathOrAbort($filename);
@@ -144,13 +134,11 @@ class ImagesController extends BaseController
{ {
// define mime type // define mime type
$mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content); $mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content);
$timeInSecondsToExpire = config('image.lifetime') * 60;
// return http response // return http response
return response($content, 200, array( return response($content, 200, array(
'Content-Type' => $mime, 'Content-Type' => $mime,
'Cache-Control' => 'max-age=' . $timeInSecondsToExpire . ', public', 'Cache-Control' => 'max-age=' . (config('image.lifetime') * 60) . ', public',
'Expires' => gmdate('D, d M Y H:i:s \G\M\T', time() + $timeInSecondsToExpire),
'Etag' => md5($content) 'Etag' => md5($content)
)); ));
} }

View File

@@ -4,6 +4,7 @@ namespace Meoran\Images\Model;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany; use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Query\Builder;
use Intervention\Image\Exception\NotReadableException; use Intervention\Image\Exception\NotReadableException;
use Intervention\Image\Image as InterventionImage; use Intervention\Image\Image as InterventionImage;
use Meoran\Images\Exception\InvalidContent; use Meoran\Images\Exception\InvalidContent;
@@ -25,10 +26,11 @@ class Image extends Model
protected $table = 'images'; protected $table = 'images';
public $fillable = [ public $fillable = [
'content',
'filename', 'filename',
'created_at', 'content',
'updated_at' 'position',
'created',
'updated'
]; ];
protected $dates = ['created_at', 'updated_at']; protected $dates = ['created_at', 'updated_at'];
protected $appends = ['url']; protected $appends = ['url'];
@@ -79,10 +81,10 @@ class Image extends Model
static function getAbsolutePath($filename) static function getAbsolutePath($filename)
{ {
$basePath = config('image.path'); $basePath = config('image.path');
if (empty($basePath)) {
throw new \Exception('You must defined config image.path'); $parts = array_slice(str_split(mb_strtolower(str_slug($filename, '')), 2), 0, 2);
}
$parts = array_slice(str_split(md5($filename), 2), 0, 2);
$path = $basePath . '/' . implode('/', $parts) . '/' . $filename; $path = $basePath . '/' . implode('/', $parts) . '/' . $filename;
return $path; return $path;
@@ -123,34 +125,25 @@ class Image extends Model
public function setContentAttribute($content) public function setContentAttribute($content)
{ {
$this->_content = app('image')->make($content)->orientate(); $this->_content = app('image')->make($content);
$this->setHash();
} }
public function getHashAttribute() public function getHashAttribute()
{ {
if (empty($this->content)) { if (!array_key_exists('hash', $this->attributes)) {
return null; $this->setHash();
} }
if (empty($this->content->getEncoded())) { return $this->attributes['hash'];
$this->content->encode();
}
return sha1($this->content->getEncoded());
} }
public function getExtensionAttribute() protected function setHash()
{ {
$mime = $this->content->mime();
if (empty($mime)) {
return null;
}
return str_replace('image/', '', $mime);
}
public function getMimeAttribute() {
if (empty($this->content)) { if (empty($this->content)) {
return null; $this->attributes['hash'] = null;
return;
} }
return $this->content->mime(); $this->attributes['hash'] = sha1($this->content->getEncoded());
} }
public function same(Image $image) public function same(Image $image)
@@ -212,20 +205,22 @@ class Image extends Model
*/ */
public static function createRelation(Model $class, $relationName) public static function createRelation(Model $class, $relationName)
{ {
$instance = $class->newRelatedInstance(static::class);
$foreignPivotKey = 'relation_id'; $instance = $class->newRelatedInstance(self::class);
$relatedPivotKey = 'image_id';
$table = 'associate_images'; $foreignKey = 'relation_id';
$relatedKey = 'image_id';
$name = 'relation'; $name = 'relation';
$table = 'associate_images';
$inverse = false;
$morph = new MorphToMany( $relation = new MorphToMany(
$instance->newQuery(), $class, $name, $table, $instance->newQuery(), $class, $name, $table,
$foreignPivotKey, $relatedPivotKey, $class->getKeyName(), $foreignKey, $relatedKey, $relationName, $inverse
$instance->getKeyName(), $relationName, false
); );
$morph->withPivot('position'); $relation->withPivot('position');
return $morph; return $relation;
} }
public function toArray() public function toArray()
@@ -235,4 +230,7 @@ class Image extends Model
return $attributes; return $attributes;
} }
public function scopeContent(Builder $builder, Image $image) {
$builder->where('hash', $image->hash);
}
} }

View File

@@ -21,7 +21,6 @@ class ImagesServiceProvider extends ServiceProvider
$this->loadMigrationsFrom(__DIR__ . '/../../database/migrations'); $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations');
$this->mergeConfigFrom(__DIR__ . '/../../config/image.php', 'image'); $this->mergeConfigFrom(__DIR__ . '/../../config/image.php', 'image');
$this->mergeConfigFrom(__DIR__ . '/../../config/image-optimizer.php', 'image-optimizer');
$this->app->register(ImageServiceProvider::class); $this->app->register(ImageServiceProvider::class);
@@ -35,34 +34,21 @@ class ImagesServiceProvider extends ServiceProvider
]); ]);
$this->commands([ $this->commands([
CacheGarbageCollectorCommand::class, // CacheGarbageCollectorCommand::class,
RemoveUselessPicturesCommand::class, // RemoveUselessPicturesCommand::class,
]); ]);
} }
} }
public function loadRoutes() public function loadRoutes()
{ {
$this->app->router->group([ $this->app->post('images/upload', [
'namespace' => '\Meoran\Images\Http\Controllers', 'as' => 'uploadImage', 'uses' => '\Meoran\Images\Http\Controllers\ImagesController@upload'
], function ($router) {
$addAuthMiddleware = config('image.middlewareAuth', false);
$authMiddleware = [];
if ($addAuthMiddleware) {
$authMiddleware = ['middleware' => 'auth'];
}
$router->post('images/upload', [
'as' => 'uploadImage', 'uses' => 'ImagesController@upload'
]+$authMiddleware);
$router->get('images/{filename}', [
'as' => 'getPicture', 'uses' => 'ImagesController@get'
]); ]);
$router->delete('images/{id}', [ $this->app->get('images/{filename}', [
'as' => 'deletePicture', 'uses' => 'ImagesController@delete' 'as' => 'getPicture', 'uses' => '\Meoran\Images\Http\Controllers\ImagesController@get'
]+$authMiddleware); ]);
});
} }
} }