File: D:/HostingSpaces/SBogers104/angeliekly.nl/workbench/komma/kms/src/Komma/Kms/Images/ImageService.php
<?php namespace Komma\Kms\Images;
/**
* Short description for the file.
*
* @author Komma <support@komma.pro>
* @copyright (c) 2012-2015, Komma
*/
use Komma\Kms\Files\FileService;
use Komma\Kms\Images\Models\Image;
use View;
use File;
use Gregwar\Image\Image as ImageCropper;
class ImageService
{
/**
* The subfolder in the uploads dir
*
* @var string
*/
public $subfolder = 'images';
/**
* The attribute_key makes it possible
* to save multiple images fields per model
*
* @var string
*/
public $attribute_key = '';
/**
* Options for the upload
*
* @var array
*/
public $options = [];
/**
* @var
*/
protected $originalFilename;
/**
* @var
*/
protected $fullPath;
/**
* @var
*/
protected $path;
/**
* Check if the upload is comming from a dynamic page
*
* @var bool
*/
protected $dynamic = false;
/**
* ImageService constructor.
* Set the default upload option
*
*/
public function __construct()
{
$this->options = [
'original' => ['method' => 'fit', 'width' => 2000, 'height' => 8000],
'large' => ['method' => 'fit', 'width' => 1200, 'height' => 8000],
'medium' => ['method' => 'fit', 'width' => 500, 'height' => 8000],
'thumb' => ['method' => 'crop', 'width' => 128, 'height' => 128]
];
}
/**
* Set a value to an variable
*
* @param $variable name of the variable
* @param null $value
*/
public function setUp($variable, $value = null)
{
if ($value) $this->$variable = $value;
}
/**
* Upload the given images
*
*
* @param $files
* @param array $fileSizes
* @param bool $dynamic
* @return array
*/
public function uploadImages($files, $fileSizes = [], $dynamic = false)
{
//If filesizes is empty use the default from $this->options
if (!empty($fileSizes)) $this->options = $fileSizes;
//Set global dynamic parameter
$this->dynamic = $dynamic;
//check if the array is empty after filter (will delete [0=>[o=>]])
//if( $files == null || count(array_filter($files)) == 0)return array();
$images = [];
foreach ($files as $key => $file) {
//If it is an empty file, continue
if ($file == null) continue;
//Get the original filename
$this->originalFilename = \Str::slug(basename($file->getClientOriginalName(), $file->getClientOriginalExtension())) . '.' . $file->getClientOriginalExtension();
//Generate the full path
$this->fullPath = $this->subfolder == null ? \Config::get('kms::paths.full_path_images') : \Config::get('kms::paths.full_path_images') . '/' . $this->subfolder;
//generate the normal path
$this->path = $this->subfolder == null ? \Config::get('kms::paths.path_images') : \Config::get('kms::paths.path_images') . '/' . $this->subfolder;
if(isset($file->tmpName) && $file->tmpName == 'file'){
$images[$key]['thumb'] = $this->uploadImage('thumb', $file);
continue;
}
// Save Original
$images[$key]['original'] = $this->uploadImage('original', $file);
// Save Large
$images[$key]['large'] = $this->uploadImage('large', $file);
// Save Medium
$images[$key]['medium'] = $this->uploadImage('medium', $file);
// Save Small
$images[$key]['small'] = $this->uploadImage('small', $file);
// Save Thumb
$images[$key]['thumb'] = $this->uploadImage('thumb', $file);
}
//Return the paths for the set images
return $images;
}
/**
* Resize and save an image to the server
*
* @param $name
* @param $file
* @return string
* @throws \Exception
*/
protected function uploadImage($name, $file)
{
//If there is no nane, return empty string
if (!isset($this->options[$name])) return '';
//create a imageCropper and open the $file
$image = ImageCropper::open($file);
//Create an unique filename
$filename = time() . '-' . $name . '-' . $this->originalFilename;
//switch between the methods
switch ($this->options[$name]['method']) {
case 'fit':
//This will fit the image between the set with and height, but keep de aspect ratio, and saves it to the server.
$image->cropResize($this->options[$name]['width'], $this->options[$name]['height'])->enableProgressive()->save($this->fullPath . '/' . $filename, 'guess', 100);
break;
case 'crop':
//This will crop the image between the set with and height, and saves it to the server.
$image->zoomCrop($this->options[$name]['width'], $this->options[$name]['height'])->enableProgressive()->save($this->fullPath . '/' . $filename, 'guess', 100);
break;
}
return $this->path . '/' . $filename;
}
/**
* Save the imageLocation to the database
*
* @param $savedImage
* @return Image
*/
public function saveImageToDatabase($savedImage)
{
//New Image model
$image = New Image;
//Set urls
$image->original_image_url = $savedImage['original'];
$image->large_image_url = $savedImage['large'];
$image->medium_image_url = $savedImage['medium'];
$image->small_image_url = $savedImage['small'];
$image->thumb_image_url = $savedImage['thumb'];
//Set if it is an dynamic page
if ($this->dynamic) $image->imageble_type = 'dynamic_page';
//Set the attribute_key
$image->attribute_key = $this->attribute_key;
//save
$image->save();
//return the image
return $image;
}
/**
* Save the imageLocation to the database
*
* @param $savedImage
* @return Image
*/
public function saveGifToDatabase($savedImage, $attribute_key = 'images', $dynamic = false)
{
//New Image model
$image = New Image;
//Set urls
$image->original_image_url = $savedImage->path;
$image->large_image_url = '';
$image->medium_image_url = '';
$image->small_image_url = '';
$image->thumb_image_url = $savedImage->path;
//Set if it is an dynamic page
if ($dynamic) $image->imageble_type = 'dynamic_page';
//Set the attribute_key
$image->attribute_key = $attribute_key;
//save
$image->save();
//return the image
return $image;
}
/**
* This method links the images with an model
*
* @param $input_key
* @param $model
* @param null $attributeKey
* @return bool
*/
public function linkImagesToModel($input_key, $model, $attributeKey = null)
{
//check if the the input for the $input_key exists
if (!\Input::has($input_key)) return;
//Get decode the json from the input
$imagesIds = json_decode(\Input::get($input_key));
if (!$attributeKey) $attributeKey = $input_key;
//Load the images for an given model and the chosen attribute_key
$modelImages = Image::where('imageble_id', $model->id)
->where('imageble_type', get_class($model))
->where('attribute_key', '=', $attributeKey)
->get()
->keyBy('id');
//IF there are no images, stop
if (!$images = Image::whereIn('id', $imagesIds)->get()) return false;
//Loop trougth the images
foreach ($imagesIds as $key => $imagesId) {
if (!$image = $images->find($imagesId)) continue;
//Set model id
$image->imageble_id = $model->id;
//Set model class
$image->imageble_type = get_class($model);
//attribute_key
$image->attribute_key = $attributeKey;
//set the sort order, the key +1
$image->sort_order = $key + 1;
//save
$image->save();
if (isset($modelImages[$imagesId])) unset($modelImages[$imagesId]);
}
//Disable old images
$this->disableOldImage($modelImages, $attributeKey);
return $images;
}
/**
* This links the images to an dynamic page
*
* @param $imagesIds
* @param $blockId
* @return array|bool
*/
public function linkDynamicPageImages($imagesIds, $blockId)
{
if (!$images = Image::whereIn('id', $imagesIds)->get()) return false;
$listImages = [];
foreach ($imagesIds as $key => $imagesId) {
if (!$image = $images->find($imagesId)) continue;
$image->sort_order = $key + 1;
$image->imageble_id = $blockId;
$image->save();
$listImages[] = $image;
}
return $listImages;
}
/**
* Disable the old images, and filter
*
* @param $images
* @param null $attributeKey
*/
public function disableOldImage($images, $attributeKey = null)
{
$this->filterOldImages($attributeKey);
Image::whereIn('id', $images->modelKeys())->update(['imageble_id' => 0]);
}
/**
* This filters old images and deletes these
*
* @param null $attributeKey
*/
public function filterOldImages($attributeKey = null)
{
$images = Image::where('attribute_key', '=', $attributeKey)
->where(function ($query) {
$query->where('imageble_id', '=', 0)
->orWhere('imageble_id', '=', '');
})
->get();
$this->deleteImages($images);
}
/**
* Delete all imageSizes for a given image from the server
*
* @param $imageCollection
*/
public function deleteImages($imageCollection)
{
foreach ($imageCollection as $image) {
$this->deleteFile(public_path() . '/' . $image->original_image_url);
$this->deleteFile(public_path() . '/' . $image->large_image_url);
$this->deleteFile(public_path() . '/' . $image->medium_image_url);
$this->deleteFile(public_path() . '/' . $image->small_image_url);
$this->deleteFile(public_path() . '/' . $image->thumb_image_url);
}
Image::destroy($imageCollection->modelKeys());
}
/**
* Check if the file exist, and delete this
*
* @param $location
* @return bool
*/
public function deleteFile($location)
{
if (!is_file($location)) return false;
unlink($location);
}
/**
* Clean the images that belong to an dynamic page
*
* @param $fileIds
* @param $blockId
*/
public function cleanDynamicPageImages($fileIds, $blockId)
{
$images = Image::where('imageble_id', '=', $blockId)
->where('imageble_type', '=', 'dynamic_page')
->whereNotIn('id', $fileIds)
->get();
$this->deleteImages($images);
}
}