<?php
//----------------------------------------------------------------------
// src/Services/Common/ImageTools.php
//----------------------------------------------------------------------
namespace App\Services\Common;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\Access;
use App\Entity\SocietyGroup;
use App\Entity\Client\Individual;
use App\Entity\Client\Store;
use App\Entity\Common\Attachment;
use App\Entity\Common\Image;
use App\Entity\Common\MimeType;
use App\Entity\Config\Config;
use App\Entity\Equipment\Equipment;
use App\Entity\HR\HumanResource;
use App\Entity\Media\Article;
use App\Entity\Mission\Mission;
use App\Entity\Platform\Society;
use App\Entity\Product\Product;
use App\Services\LogTools;
class ImageTools
{
public function __construct(ManagerRegistry $doctrine, LogTools $logTools, UrlGeneratorInterface $router, Security $security)
{
$this->em = $doctrine->getManager();
$this->logTools = $logTools;
$this->security = $security;
$this->router = $router;
}
public function getQuestionMarkLogo()
{
return "assets/custom_society_group_icons/question-mark.png";
}
public function getRequiredParamsForForm()
{
// Get Accepted MimeTypes
$mimeTypes = $this->getActiveImageMimeTypes();
// ... and extensions for display
$allowedExtensions = $this->getActiveImageExtensionsAsString();
// Get the max file size allowed
$filesize = $this->em->getRepository(Config::class)->findOneByName(Config::DEFAULT_UPLOAD_MAX_FILE_SIZE);
if ($filesize === null)
{
// This should not happen
$this->logTools->errorlog("Config::DEFAULT_UPLOAD_MAX_FILE_SIZE not found");
$filesize = 512 . "M";
}
else
{
$filesize = $filesize->getValue()."M";
}
return array(
'filesize' => $filesize,
'mimeTypes' => $mimeTypes,
'allowedExtensions' => $allowedExtensions,
);
}
public function getActiveMimeTypes()
{
$objects = $this->em->getRepository(MimeType::class)
->findBy(array(
'isActive' => 1,
), array(
'mime' => 'asc',
));
$output = array();
foreach ($objects as $object)
{
$output[] = $object->getMime();
}
return $output;
}
public function getActiveImageMimeTypes()
{
$objects = $this->em->getRepository(MimeType::class)
->findBy(array(
'isActive' => 1,
'isImage' => 1,
), array(
'mime' => 'asc',
));
$output = array();
foreach ($objects as $object)
{
$output[] = $object->getMime();
}
return $output;
}
public function getActiveExtensions()
{
$objects = $this->em->getRepository(MimeType::class)
->findBy(array(
'isActive' => 1,
), array(
'mime' => 'asc',
));
$output = array();
foreach ($objects as $object)
{
$output[] = $object->getExtension();
}
return $output;
}
public function getActiveImageExtensions()
{
$objects = $this->em->getRepository(MimeType::class)
->findBy(array(
'isActive' => 1,
'isImage' => 1,
), array(
'mime' => 'asc',
));
$output = array();
foreach ($objects as $object)
{
$output[] = $object->getExtension();
}
return $output;
}
public function getActiveExtensionsAsString()
{
$objects = $this->em->getRepository(MimeType::class)
->findBy(array(
'isActive' => 1,
), array(
'mime' => 'asc',
));
$output = "";
foreach ($objects as $object)
{
$output .= $object->getExtension();
$output .= ", ";
}
if ($output != "")
{
$output = substr($output,0,-1);
$output = substr($output,0,-1);
}
return $output;
}
public function getActiveImageExtensionsAsString()
{
$objects = $this->em->getRepository(MimeType::class)
->findBy(array(
'isActive' => 1,
'isImage' => 1,
), array(
'mime' => 'asc',
));
$output = "";
foreach ($objects as $object)
{
$output .= $object->getExtension();
$output .= ", ";
}
if ($output != "")
{
$output = substr($output,0,-1);
$output = substr($output,0,-1);
}
return $output;
}
public function getProfilePathForSocietyGroup(SocietyGroup $group, $quality = 0)
{
if ($group->getLogo() !== null)
{
return $group->getLogo()->getUrlForDisplay($quality);
}
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return $logoPath->getValue();
}
public function getLogoPathForSocietyGroup(SocietyGroup $societyGroup, $quality = 0)
{
if ($societyGroup->getLogo() !== null)
{
return $societyGroup->getLogo()->getUrlForDisplay($quality);
}
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return $logoPath->getValue();
}
public function getPhpLogoPathForSociety(Society $society, $quality = 0)
{
if ($society->getLogo() !== null)
{
return $society->getLogo()->getPhpPath($quality);
}
if ($society->getGroup() !== null && $society->getGroup()->getLogo() !== null)
{
return $society->getGroup()->getLogo()->getPhpPath($quality);
}
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return $logoPath->getValue();
}
public function getLogoPathForSociety(Society $society, $quality = 0)
{
if ($society->getLogo() !== null)
{
return $society->getLogo()->getUrlForDisplay($quality);
}
if ($society->getGroup() !== null && $society->getGroup()->getLogo() !== null)
{
return $society->getGroup()->getLogo()->getUrlForDisplay($quality);
}
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return $logoPath->getValue();
}
public function getProfilePathForHumanResource(HumanResource $humanResource, $quality = 0)
{
if ($humanResource->getProfileImage() !== null)
return $humanResource->getProfileImage()->getUrlForDisplay($quality);
//$logoPath = $this->getDefaultCameraPathForQuality($quality);
$logoPath = $this->getDefaultPathForHumanResource($quality);
return $logoPath->getValue();
}
public function getProfilePathForStore(Store $store, $quality = 0)
{
if ($store->getLogo() !== null)
return $store->getLogo()->getUrlForDisplay($quality);
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return $logoPath->getValue();
}
public function getProfilePathForClient($client, $quality)
{
if ($client !== null)
{
if ($client->getIndividual() !== null)
return $this->getProfilePathForIndividual($client->getIndividual(), $quality);
if ($client->getStore() !== null)
return $this->getProfilePathForStore($client->getStore(), $quality);
}
$configRepository = $this->em->getRepository(Config::class);
return $configRepository->findOneByName(Config::IMG_PATH_NC)->getValue();
}
// TODO
// Check why this method is not in AttachmentTools
public function getLogoPathForEquipment(Equipment $equipment, $quality = 0)
{
$image = null;
$mainImageId = $equipment->getMainImageId();
foreach ($equipment->getAttachments() as $att)
{
// Get main Image if it's defined
if ($mainImageId !== null)
{
if ($att->isImage() && $att->getId() == $mainImageId)
{
$image = $att;
break;
}
}
else
{
if ($att->isImage())
{
$image = $att;
break;
}
}
}
if ($image !== null)
{
$url = $this->router->generate('icod_platform_attachment_view', array(
'id' => $att->getId(),
'quality' => $quality,
));
return $url;
}
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return "/".$logoPath->getValue();
}
public function getLogoPathForMission(Mission $mission, $quality = 0)
{
$image = null;
// Plan.io Task #3427
if ($this->security->isGranted('view_confidential_attachments_for_missions'))
{
$attachments = $this->em->getRepository(Attachment::class)->findBy(array(
'mission' => $mission,
), array(
'creationDate' => 'DESC',
));
}
else
{
$attachments = $this->em->getRepository(Attachment::class)->findBy(array(
'mission' => $mission,
'confidential' => 0,
), array(
'creationDate' => 'DESC',
));
}
// Plan.io Task #4309
$mainImageId = $mission->getMainImageId();
foreach ($attachments as $att)
{
// Get main Image if it's defined
if ($mainImageId !== null)
{
if ($att->isImage() && $att->getId() == $mainImageId)
{
$image = $att;
break;
}
}
else
{
if ($att->isImage())
{
$image = $att;
break;
}
}
}
if ($image !== null)
{
$url = $this->router->generate('icod_platform_attachment_view', array(
'id' => $att->getId(),
'quality' => $quality,
));
return $url;
}
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return "/".$logoPath->getValue();
}
public function getLogoPathForArticle(Article $article, $quality = 0)
{
$image = $article->getThumbnail();
if ($image !== null)
{
$url = $this->router->generate('icod_platform_attachment_view', array(
'id' => $image->getId(),
'quality' => $quality,
));
return $url;
}
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return "/".$logoPath->getValue();
}
public function getLogoPathForProduct(Product $product, $quality = 0)
{
if ($product->getLogo() !== null)
return $product->getLogo()->getUrlForDisplay($quality);
$logoPath = $this->getDefaultCameraPathForQuality($quality);
return $logoPath->getValue();
}
public function getProfilePathForIndividual(Individual $outputdividual, $quality = 0)
{
$configRepository = $this->em->getRepository(Config::class);
$logoPath = null;
if ($outputdividual->getTitle() !== null)
{
if ($outputdividual->getTitle()->isSir())
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_M);
else
if ($outputdividual->getTitle()->isMadam())
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_F);
}
if ($logoPath === null)
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_NC);
}
return $logoPath->getValue();
}
public function getAllProfilePath()
{
$configRepository = $this->em->getRepository(Config::class);
$imgPathMConfig = $configRepository->findOneByName(Config::IMG_PATH_M);
$imgPathFConfig = $configRepository->findOneByName(Config::IMG_PATH_F);
$imgPathNCConfig = $configRepository->findOneByName(Config::IMG_PATH_NC);
return array(
'img_path_m' => $imgPathMConfig !== null ? $imgPathMConfig->getValue() : '',
'img_path_f' => $imgPathFConfig !== null ? $imgPathFConfig->getValue() : '',
'img_path_nc' => $imgPathNCConfig !== null ? $imgPathNCConfig->getValue() : '',
);
}
protected function getDefaultPathForHumanResource($quality)
{
$configRepository = $this->em->getRepository(Config::class);
switch($quality)
{
case 480:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_M_480);
break;
}
case 128:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_M_128);
break;
}
case 80:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_M_80);
break;
}
case 64:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_M_64);
break;
}
default:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_M_480);
break;
}
}
return $logoPath;
}
protected function getDefaultCameraPathForQuality($quality)
{
$configRepository = $this->em->getRepository(Config::class);
switch($quality)
{
case 1024:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_CAMERA_1024);
break;
}
case 512:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_CAMERA_512);
break;
}
case 256:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_CAMERA_256);
break;
}
case 128:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_CAMERA_128);
break;
}
case 80:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_CAMERA_80);
break;
}
case 64:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_CAMERA_64);
break;
}
default:
{
$logoPath = $configRepository->findOneByName(Config::IMG_PATH_CAMERA);
break;
}
}
return $logoPath;
}
public function handleProductLogo($product)
{
// Craft the file name
$imageName = "product_".$product->getId();
// Get extension
$extension = $product->getTempLogoExtension();
if ($extension != 'png' && $extension != 'jpg')
{
return null;
}
// Create a Image object
$image = new Image();
// Set it as a direct upload to bypass doctrine events
$image->setDirectUpload(1);
// Set the SocietyGroup, so we can get the correct path
$image->setSocietyGroup($product->getSocietyGroup());
// This renames the file using the timestamp
$image->setName($imageName);
$image->setExtension($extension);
// We need to flush the image in order to have its id
$this->em->persist($image);
try
{
$this->em->flush();
}
catch (\Exception $e)
{
$this->logTools->errorLog($e->getMessage());
return null;
}
// Get the correct file name with its destination
$finalImage = $image->getPhpPath();
// Now get the image from the JS
$imageData = $product->getTempLogoBase64();
$imageData = base64_decode($imageData);
if ($imageData === false)
{
return null;
}
$source = imagecreatefromstring($imageData);
if ($source === false)
{
return null;
}
$localion = $image->getPhpPathOnly();
if (!file_exists($localion))
{
if (!mkdir($localion, 0755, true))
{
return null;
}
}
if ($extension == 'jpg')
$imageSave = imagejpeg($source, $finalImage, 100);
else
{
imagealphablending($source, false);
imagesavealpha($source, true);
$imageSave = imagepng($source, $finalImage);
}
if ($imageSave === false)
{
return null;
}
imagedestroy($source);
// Make smaller versions
$original = $finalImage;
list($width, $height) = getimagesize($original);
if ($extension == 'jpg')
$exif = @exif_read_data($original);
else
$exif = null;
if ($exif !== null && !empty($exif) && array_key_exists('Orientation', $exif))
$ort = $exif['Orientation'];
else
$ort = null;
$name128 = $image->getPhpPathOnly().'/'.$image->getId().'_128.'.$extension;
$name256 = $image->getPhpPathOnly().'/'.$image->getId().'_256.'.$extension;
$name512 = $image->getPhpPathOnly().'/'.$image->getId().'_512.'.$extension;
$name1024 = $image->getPhpPathOnly().'/'.$image->getId().'_1024.'.$extension;
$this->smart_resize_image( $original, null, 128, 0, true, $name128, false, false, 75, false, $ort);
$this->smart_resize_image( $original, null, 256, 0, true, $name256, false, false, 75, false, $ort);
$this->smart_resize_image( $original, null, 512, 0, true, $name512, false, false, 75, false, $ort);
$this->smart_resize_image( $original, null, 1024, 0, true, $name1024, false, false, 75, false, $ort);
// Attach the image to the main object
$product->setLogo($image);
$this->em->persist($product);
try
{
$this->em->flush();
}
catch (\Exception $e)
{
$this->logTools->errorLog($e->getMessage());
return null;
}
return $image;
}
public function hasExifData($extension)
{
$ext_whitelist = array('jpg', 'jpeg', 'tiff', 'tif');
$extension = strtolower($this->extension);
if (in_array($extension, $ext_whitelist))
{
return true;
}
else
{
return false;
}
}
public function handleOrientation($filePath)
{
if(exif_imagetype($filePath) == IMAGETYPE_JPEG)
{
try
{
$exif = exif_read_data($filePath);
}
catch (\Exception $exp)
{
$exif = false;
}
if ($exif)
{
if (!empty($exif) && array_key_exists('Orientation', $exif) && !empty($exif['Orientation']))
{
$imageResource = imagecreatefromjpeg($filePath); // provided that the image is jpeg. Use relevant function otherwise
switch ($exif['Orientation'])
{
case 3:
{
$image = imagerotate($imageResource, 180, 0);
break;
}
case 6:
{
$image = imagerotate($imageResource, -90, 0);
break;
}
case 8:
{
$image = imagerotate($imageResource, 90, 0);
break;
}
default:
{
$image = $imageResource;
break;
}
}
}
}
else
{
$image = imagecreatefromjpeg($filePath);
}
return $image;
}
}
// https://github.com/Nimrod007/PHP_image_resize
/**
* easy image resize function
* @param $file - file name to resize
* @param $string - The image data, as a string
* @param $width - new image width
* @param $height - new image height
* @param $proportional - keep image proportional, default is no
* @param $output - name of the new file (include path if needed)
* @param $delete_original - if true the original image will be deleted
* @param $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink
* @param $quality - enter 1-100 (100 is best quality) default is 100
* @param $grayscale - if true, image will be grayscale (default is false)
* @return boolean|resource
*/
public function smart_resize_image(
$file,
$string = null,
$width = 0,
$height = 0,
$proportional = false,
$output = 'file',
$delete_original = true,
$use_linux_commands = false,
$quality = 100,
$grayscale = false,
$ort = null
)
{
if ( $height <= 0 && $width <= 0 ) return false;
if ( $file === null && $string === null ) return false;
// Setting defaults and meta
$outputfo = $file !== null ? getimagesize($file) : getimagesizefromstring($string);
$image = '';
$final_width = 0;
$final_height = 0;
list($width_old, $height_old) = $outputfo;
$cropHeight = $cropWidth = 0;
// Calculating proportionality
if ($proportional)
{
if ($width == 0) $factor = $height/$height_old;
elseif ($height == 0) $factor = $width/$width_old;
else $factor = min( $width / $width_old, $height / $height_old );
$final_width = round( $width_old * $factor );
$final_height = round( $height_old * $factor );
}
else
{
$final_width = ( $width <= 0 ) ? $width_old : $width;
$final_height = ( $height <= 0 ) ? $height_old : $height;
$widthX = $width_old / $width;
$heightX = $height_old / $height;
$x = min($widthX, $heightX);
$cropWidth = ($width_old - $width * $x) / 2;
$cropHeight = ($height_old - $height * $x) / 2;
}
// Loading image to memory according to type
switch ( $outputfo[2] )
{
case IMAGETYPE_JPEG: $file !== null ? $image = imagecreatefromjpeg($file) : $image = imagecreatefromstring($string); break;
case IMAGETYPE_GIF: $file !== null ? $image = imagecreatefromgif($file) : $image = imagecreatefromstring($string); break;
case IMAGETYPE_PNG: $file !== null ? $image = imagecreatefrompng($file) : $image = imagecreatefromstring($string); break;
default: return false;
}
// Making the image grayscale, if needed
if ($grayscale)
{
imagefilter($image, IMG_FILTER_GRAYSCALE);
}
// This is the resizing/resampling/transparency-preserving magic
$image_resized = imagecreatetruecolor( $final_width, $final_height );
if ( ($outputfo[2] == IMAGETYPE_GIF) || ($outputfo[2] == IMAGETYPE_PNG) )
{
$transparency = imagecolortransparent($image);
$palletsize = imagecolorstotal($image);
if ($transparency >= 0 && $transparency < $palletsize)
{
$transparent_color = imagecolorsforindex($image, $transparency);
$transparency = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
imagefill($image_resized, 0, 0, $transparency);
imagecolortransparent($image_resized, $transparency);
}
elseif ($outputfo[2] == IMAGETYPE_PNG)
{
imagealphablending($image_resized, false);
$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
imagefill($image_resized, 0, 0, $color);
imagesavealpha($image_resized, true);
}
}
imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);
// Reapply original Orientation
if (!empty($ort))
{
switch ($ort)
{
case 3:
$image_resized = imagerotate($image_resized, 180, 0);
break;
case 6:
$image_resized = imagerotate($image_resized, -90, 0);
break;
case 8:
$image_resized = imagerotate($image_resized, 90, 0);
break;
}
}
// Taking care of original, if needed
if ( $delete_original )
{
@unlink($file);
}
// Preparing a method of providing result
switch ( strtolower($output) )
{
case 'browser':
$mime = image_type_to_mime_type($outputfo[2]);
header("Content-type: $mime");
$output = null;
break;
case 'file':
$output = $file;
break;
case 'return':
return $image_resized;
break;
default:
break;
}
// Writing image according to type to the output destination and image quality
switch ( $outputfo[2] )
{
case IMAGETYPE_GIF: imagegif($image_resized, $output); break;
case IMAGETYPE_JPEG: imagejpeg($image_resized, $output, $quality); break;
case IMAGETYPE_PNG:
$quality = 9 - (int)((0.9*$quality)/10.0);
imagepng($image_resized, $output, $quality);
break;
default: return false;
}
return true;
}
}