This commit is contained in:
2024-05-20 15:37:46 +03:00
commit 00b7dbd0b7
10404 changed files with 3285853 additions and 0 deletions

View File

@ -0,0 +1,13 @@
<?php
namespace Nextend\Framework\Image;
abstract class AbstractPlatformImage {
public function initLightbox() {
}
public function onImageUploaded($filename) {
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace Nextend\Framework\Image\Block\ImageManager;
use Nextend\Framework\Asset\Js\Js;
use Nextend\Framework\Image\ImageManager;
use Nextend\Framework\Image\ModelImage;
use Nextend\Framework\Visual\AbstractBlockVisual;
use Nextend\SmartSlider3\Application\Admin\Layout\Block\Forms\Button\BlockButtonApply;
use Nextend\SmartSlider3\Application\Admin\Layout\Block\Forms\Button\BlockButtonCancel;
use Nextend\SmartSlider3\Application\Admin\TraitAdminUrl;
class BlockImageManager extends AbstractBlockVisual {
use TraitAdminUrl;
/** @var ModelImage */
protected $model;
/**
* @return ModelImage
*/
public function getModel() {
return $this->model;
}
public function display() {
$this->model = new ModelImage($this);
$this->renderTemplatePart('Index');
}
public function displayTopBar() {
$buttonCancel = new BlockButtonCancel($this);
$buttonCancel->addClass('n2_fullscreen_editor__cancel');
$buttonCancel->display();
$buttonApply = new BlockButtonApply($this);
$buttonApply->addClass('n2_fullscreen_editor__save');
$buttonApply->display();
}
public function displayContent() {
Js::addFirstCode("
new _N2.NextendImageManager({
visuals: " . json_encode(ImageManager::$loaded) . ",
ajaxUrl: '" . $this->getAjaxUrlImage() . "'
});
");
$this->getModel()
->renderForm();
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace Nextend\Framework\Image\Block\ImageManager;
/**
* @var BlockImageManager $this
*/
?>
<div id="n2-lightbox-image" class="n2_fullscreen_editor">
<div class="n2_fullscreen_editor__overlay"></div>
<div class="n2_fullscreen_editor__window">
<div class="n2_fullscreen_editor__nav_bar">
<div class="n2_fullscreen_editor__nav_bar_label">
<?php n2_e('Image manager'); ?>
</div>
<div class="n2_fullscreen_editor__nav_bar_actions">
<?php $this->displayTopBar(); ?>
</div>
</div>
<div class="n2_fullscreen_editor__content">
<div class="n2_fullscreen_editor__content_content n2_container_scrollable">
<?php $this->displayContent(); ?>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,94 @@
<?php
namespace Nextend\Framework\Image;
use Nextend\Framework\Controller\Admin\AdminVisualManagerAjaxController;
use Nextend\Framework\Notification\Notification;
use Nextend\Framework\Request\Request;
class ControllerAjaxImage extends AdminVisualManagerAjaxController {
protected $type = 'image';
public function actionLoadVisualForImage() {
$this->validateToken();
$model = $this->getModel();
$image = Request::$REQUEST->getVar('image');
$visual = $model->getVisual($image);
if (!empty($visual)) {
$this->response->respond(array(
'visual' => $visual
));
} else {
if (($visual = $model->addVisual($image, ImageStorage::$emptyImage))) {
$this->response->respond(array(
'visual' => $visual
));
}
}
Notification::error(n2_('Unexpected error'));
$this->response->error();
}
public function actionAddVisual() {
$this->validateToken();
$image = Request::$REQUEST->getVar('image');
$this->validateVariable(!empty($image), 'image');
$model = $this->getModel();
if (($visual = $model->addVisual($image, Request::$REQUEST->getVar('value')))) {
$this->response->respond(array(
'visual' => $visual
));
}
Notification::error(n2_('Unexpected error'));
$this->response->error();
}
public function actionDeleteVisual() {
$this->validateToken();
$visualId = Request::$REQUEST->getInt('visualId');
$this->validateVariable($visualId > 0, 'image');
$model = $this->getModel();
if (($visual = $model->deleteVisual($visualId))) {
$this->response->respond(array(
'visual' => $visual
));
}
Notification::error(n2_('Not editable'));
$this->response->error();
}
public function actionChangeVisual() {
$this->validateToken();
$visualId = Request::$REQUEST->getInt('visualId');
$this->validateVariable($visualId > 0, 'image');
$model = $this->getModel();
if (($visual = $model->changeVisual($visualId, Request::$REQUEST->getVar('value')))) {
$this->response->respond(array(
'visual' => $visual
));
}
Notification::error(n2_('Unexpected error'));
$this->response->error();
}
public function getModel() {
return new ModelImage($this);
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace Nextend\Framework\Image;
use Nextend\Framework\Asset\Js\Js;
use Nextend\Framework\Filesystem\Filesystem;
use Nextend\Framework\Image\Joomla\JoomlaImage;
use Nextend\Framework\Image\WordPress\WordPressImage;
use Nextend\Framework\Misc\Base64;
use Nextend\Framework\Pattern\SingletonTrait;
use Nextend\Framework\ResourceTranslator\ResourceTranslator;
class Image {
use SingletonTrait;
/**
* @var AbstractPlatformImage
*/
private static $platformImage;
public function __construct() {
self::$platformImage = new WordPressImage();
}
public static function init() {
if (!self::$platformImage) {
new Image();
}
}
public static function enqueueHelper() {
$parameters = array(
'siteKeywords' => ResourceTranslator::getResourceIdentifierKeywords(),
'imageUrls' => ResourceTranslator::getResourceIdentifierUrls(),
'protocolRelative' => ResourceTranslator::isProtocolRelative()
);
$parameters['placeholderImage'] = '$ss3-frontend$/images/placeholder/image.png';
$parameters['placeholderRepeatedImage'] = '$ss3-frontend$/images/placeholder/image.png';
Js::addFirstCode('new _N2.ImageHelper(' . json_encode($parameters) . ');');
}
public static function initLightbox() {
self::$platformImage->initLightbox();
}
public static function onImageUploaded($filename) {
self::$platformImage->onImageUploaded($filename);
}
public static function SVGToBase64($image) {
$ext = pathinfo($image, PATHINFO_EXTENSION);
if ($ext == 'svg' && ResourceTranslator::isResource($image)) {
return 'data:image/svg+xml;base64,' . Base64::encode(Filesystem::readFile(ResourceTranslator::toPath($image)));
}
return ResourceTranslator::toUrl($image);
}
}

View File

@ -0,0 +1,709 @@
<?php
namespace Nextend\Framework\Image;
use Exception;
use Nextend\Framework\Cache\CacheImage;
use Nextend\Framework\Filesystem\Filesystem;
use Nextend\Framework\Misc\Base64;
use Nextend\Framework\Parser\Color;
use Nextend\Framework\ResourceTranslator\ResourceTranslator;
use Nextend\Framework\Url\Url;
class ImageEdit {
public static function resizeImage($group, $imageUrlOrPath, $targetWidth, $targetHeight, $lazy = false, $mode = 'cover', $backgroundColor = false, $resizeRemote = false, $quality = 100, $optimize = false, $x = 50, $y = 50) {
if (strpos($imageUrlOrPath, Filesystem::getBasePath()) === 0) {
$imageUrl = Url::pathToUri($imageUrlOrPath);
} else {
$imageUrl = ResourceTranslator::toUrl(ResourceTranslator::pathToResource($imageUrlOrPath));
}
if (!extension_loaded('gd') || $targetWidth <= 0 || $targetHeight <= 0) {
return $imageUrl;
}
$quality = max(0, min(100, $quality));
$originalImageUrl = $imageUrl;
if (substr($imageUrl, 0, 2) == '//') {
$imageUrl = parse_url(Url::getFullUri(), PHP_URL_SCHEME) . ':' . $imageUrl;
}
$imageUrl = Url::relativetoabsolute($imageUrl);
$imagePath = Filesystem::absoluteURLToPath($imageUrl);
$cache = new CacheImage($group);
if ($lazy) {
$cache->setLazy(true);
}
if ($imagePath == $imageUrl) {
// The image is not local
if (!$resizeRemote) {
return $originalImageUrl;
}
$pathInfo = pathinfo(parse_url($imageUrl, PHP_URL_PATH));
$extension = false;
if (isset($pathInfo['extension'])) {
$extension = self::validateGDExtension($pathInfo['extension']);
}
$extension = self::checkMetaExtension($originalImageUrl, $extension);
if (!$extension) {
return $originalImageUrl;
}
if (strtolower($extension) === 'webp' && !function_exists('imagecreatefromwebp')) {
return $originalImageUrl;
}
$resizedPath = $cache->makeCache($extension, array(
self::class,
'_resizeRemoteImage'
), array(
$extension,
$imageUrl,
$targetWidth,
$targetHeight,
$mode,
$backgroundColor,
$quality,
$optimize,
$x,
$y
));
if (substr($resizedPath, 0, 5) == 'http:' || substr($resizedPath, 0, 6) == 'https:') {
return $resizedPath;
}
if ($resizedPath === $originalImageUrl) {
return $originalImageUrl;
}
return Filesystem::pathToAbsoluteURL($resizedPath);
} else {
$extension = false;
$imageType = @self::exif_imagetype($imagePath);
switch ($imageType) {
case IMAGETYPE_JPEG:
$extension = 'jpg';
break;
case IMAGETYPE_PNG:
if (self::isPNG8($imagePath)) {
// GD cannot resize palette PNG so we return the original image
return $originalImageUrl;
}
$extension = 'png';
break;
case IMAGETYPE_WEBP:
if (!function_exists('imagecreatefromwebp')) {
return $originalImageUrl;
}
$extension = 'webp';
break;
}
if (!$extension) {
return $originalImageUrl;
}
return Filesystem::pathToAbsoluteURL($cache->makeCache($extension, array(
self::class,
'_resizeImage'
), array(
$extension,
$imagePath,
$targetWidth,
$targetHeight,
$mode,
$backgroundColor,
$quality,
$optimize,
$x,
$y
)));
}
}
public static function _resizeRemoteImage($targetFile, $extension, $imageUrl, $targetWidth, $targetHeight, $mode, $backgroundColor, $quality, $optimize, $x, $y) {
return self::_resizeImage($targetFile, $extension, $imageUrl, $targetWidth, $targetHeight, $mode, $backgroundColor, $quality, $optimize, $x, $y);
}
public static function _resizeImage($targetFile, $extension, $imagePath, $targetWidth, $targetHeight, $mode, $backgroundColor, $quality = 100, $optimize = false, $x = 50, $y = 50) {
$targetDir = dirname($targetFile);
$rotated = false;
if ($extension == 'png') {
$image = @imagecreatefrompng($imagePath);
} else if ($extension == 'jpg') {
$image = @imagecreatefromjpeg($imagePath);
if (function_exists("exif_read_data")) {
$exif = @exif_read_data($imagePath);
$rotated = self::getOrientation($exif, $image);
if ($rotated) {
imagedestroy($image);
$image = $rotated;
}
}
} else if ($extension == 'webp') {
//@TODO: should we need to care about rotation?
$image = @imagecreatefromwebp($imagePath);
}
if (isset($image) && $image) {
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
if ($optimize) {
if ($originalWidth <= $targetWidth || $originalHeight <= $targetHeight) {
if (!Filesystem::existsFolder($targetDir)) {
Filesystem::createFolder($targetDir);
}
if ($extension == 'png') {
imagesavealpha($image, true);
imagealphablending($image, false);
imagepng($image, $targetFile);
} else if ($extension == 'jpg') {
imagejpeg($image, $targetFile, $quality);
} else if ($extension == 'webp') {
imagesavealpha($image, true);
imagealphablending($image, false);
imagewebp($image, $targetFile, $quality);
}
imagedestroy($image);
return true;
}
if ($originalWidth / $targetWidth > $originalHeight / $targetHeight) {
$targetWidth = round($originalWidth / ($originalHeight / $targetHeight));
} else {
$targetHeight = round($originalHeight / ($originalWidth / $targetWidth));
}
}
if ($rotated || $originalWidth != $targetWidth || $originalHeight != $targetHeight) {
$newImage = imagecreatetruecolor($targetWidth, $targetHeight);
if ($extension == 'png' || $extension == 'webp') {
imagesavealpha($newImage, true);
imagealphablending($newImage, false);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($image, 0, 0, $targetWidth, $targetHeight, $transparent);
} else if ($extension == 'jpg' && $backgroundColor) {
$rgb = Color::hex2rgb($backgroundColor);
$background = imagecolorallocate($newImage, $rgb[0], $rgb[1], $rgb[2]);
imagefilledrectangle($newImage, 0, 0, $targetWidth, $targetHeight, $background);
}
list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = self::imageMode($targetWidth, $targetHeight, $originalWidth, $originalHeight, $mode, $x, $y);
imagecopyresampled($newImage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
imagedestroy($image);
} else {
$newImage = $image;
}
if (!Filesystem::existsFolder($targetDir)) {
Filesystem::createFolder($targetDir);
}
if ($extension == 'png') {
imagepng($newImage, $targetFile);
} else if ($extension == 'jpg') {
imagejpeg($newImage, $targetFile, $quality);
} else if ($extension == 'webp') {
imagewebp($newImage, $targetFile, $quality);
}
imagedestroy($newImage);
return true;
}
throw new Exception('Unable to resize image: ' . $imagePath);
}
public static function scaleImage($group, $imageUrlOrPath, $scale = 1, $resizeRemote = false, $quality = 100) {
if (strpos($imageUrlOrPath, Filesystem::getBasePath()) === 0) {
$imageUrl = Url::pathToUri($imageUrlOrPath);
} else {
$imageUrl = ResourceTranslator::toUrl($imageUrlOrPath);
}
if (!extension_loaded('gd') || $scale <= 0) {
return $imageUrl;
}
$quality = max(0, min(100, $quality));
$originalImageUrl = $imageUrl;
if (substr($imageUrl, 0, 2) == '//') {
$imageUrl = parse_url(Url::getFullUri(), PHP_URL_SCHEME) . ':' . $imageUrl;
}
$imageUrl = Url::relativetoabsolute($imageUrl);
$imagePath = Filesystem::absoluteURLToPath($imageUrl);
$cache = new CacheImage($group);
if ($imagePath == $imageUrl) {
// The image is not local
if (!$resizeRemote) {
return $originalImageUrl;
}
$pathInfo = pathinfo(parse_url($imageUrl, PHP_URL_PATH));
$extension = false;
if (isset($pathInfo['extension'])) {
$extension = self::validateGDExtension($pathInfo['extension']);
}
$extension = self::checkMetaExtension($imageUrl, $extension);
if (!$extension) {
return $originalImageUrl;
}
if (strtolower($extension) === 'webp' && !function_exists('imagecreatefromwebp')) {
return $originalImageUrl;
}
return ResourceTranslator::urlToResource(Filesystem::pathToAbsoluteURL($cache->makeCache($extension, array(
self::class,
'_scaleRemoteImage'
), array(
$extension,
$imageUrl,
$scale,
$quality
))));
} else {
$extension = false;
$imageType = @self::exif_imagetype($imagePath);
switch ($imageType) {
case IMAGETYPE_JPEG:
$extension = 'jpg';
break;
case IMAGETYPE_PNG:
if (self::isPNG8($imagePath)) {
// GD cannot resize palette PNG so we return the original image
return $originalImageUrl;
}
$extension = 'png';
break;
case IMAGETYPE_WEBP:
if (!function_exists('imagecreatefromwebp')) {
return $originalImageUrl;
}
$extension = 'webp';
break;
}
if (!$extension) {
return $originalImageUrl;
}
return ResourceTranslator::urlToResource(Filesystem::pathToAbsoluteURL($cache->makeCache($extension, array(
self::class,
'_scaleImage'
), array(
$extension,
$imagePath,
$scale,
$quality
))));
}
}
public static function _scaleRemoteImage($targetFile, $extension, $imageUrl, $scale, $quality) {
return self::_scaleImage($targetFile, $extension, $imageUrl, $scale, $quality);
}
public static function _scaleImage($targetFile, $extension, $imagePath, $scale, $quality = 100) {
$targetDir = dirname($targetFile);
$image = false;
if ($extension == 'png') {
$image = @imagecreatefrompng($imagePath);
} else if ($extension == 'jpg') {
$image = @imagecreatefromjpeg($imagePath);
if (function_exists("exif_read_data")) {
$exif = @exif_read_data($imagePath);
$rotated = self::getOrientation($exif, $image);
if ($rotated) {
imagedestroy($image);
$image = $rotated;
}
}
} else if ($extension == 'webp') {
//@TODO: should we need to care about rotation?
$image = @imagecreatefromwebp($imagePath);
}
if ($image) {
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
$targetWidth = $originalWidth * $scale;
$targetHeight = $originalHeight * $scale;
if ((isset($rotated) && $rotated) || $originalWidth != $targetWidth || $originalHeight != $targetHeight) {
$newImage = imagecreatetruecolor($targetWidth, $targetHeight);
if ($extension == 'png' || $extension == 'webp') {
imagesavealpha($newImage, true);
imagealphablending($newImage, false);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($image, 0, 0, $targetWidth, $targetHeight, $transparent);
}
list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = self::imageMode($targetWidth, $targetHeight, $originalWidth, $originalHeight);
imagecopyresampled($newImage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
imagedestroy($image);
} else {
$newImage = $image;
}
if (!Filesystem::existsFolder($targetDir)) {
Filesystem::createFolder($targetDir);
}
if ($extension == 'png') {
imagepng($newImage, $targetFile);
} else if ($extension == 'jpg') {
imagejpeg($newImage, $targetFile, $quality);
} else if ($extension == 'webp') {
imagewebp($newImage, $targetFile, $quality);
}
imagedestroy($newImage);
return true;
}
throw new Exception('Unable to scale image: ' . $imagePath);
}
private static function getOrientation($exif, $image) {
if ($exif && !empty($exif['Orientation'])) {
$rotated = false;
switch ($exif['Orientation']) {
case 3:
$rotated = imagerotate($image, 180, 0);
break;
case 6:
$rotated = imagerotate($image, -90, 0);
break;
case 8:
$rotated = imagerotate($image, 90, 0);
break;
}
return $rotated;
}
return false;
}
private static function imageMode($width, $height, $originalWidth, $OriginalHeight, $mode = 'cover', $x = 50, $y = 50) {
$dst_x = 0;
$dst_y = 0;
$src_x = 0;
$src_y = 0;
$dst_w = $width;
$dst_h = $height;
$src_w = $originalWidth;
$src_h = $OriginalHeight;
$horizontalRatio = $width / $originalWidth;
$verticalRatio = $height / $OriginalHeight;
if ($horizontalRatio > $verticalRatio) {
$new_h = round($horizontalRatio * $OriginalHeight);
$dst_y = round(($height - $new_h) / 2 * $y / 50);
$dst_h = $new_h;
} else {
$new_w = round($verticalRatio * $originalWidth);
$dst_x = round(($width - $new_w) / 2 * $x / 50);
$dst_w = $new_w;
}
return array(
$dst_x,
$dst_y,
$src_x,
$src_y,
$dst_w,
$dst_h,
$src_w,
$src_h
);
}
private static function validateGDExtension($extension) {
static $validExtensions = array(
'png' => 'png',
'jpg' => 'jpg',
'jpeg' => 'jpg',
'gif' => 'gif',
'webp' => 'webp',
'svg' => 'svg'
);
$extension = strtolower($extension);
if (isset($validExtensions[$extension])) {
return $validExtensions[$extension];
}
return false;
}
private static function validateExtension($extension) {
static $validExtensions = array(
'png' => 'png',
'jpg' => 'jpg',
'jpeg' => 'jpg',
'gif' => 'gif',
'webp' => 'webp',
'svg' => 'svg'
);
$extension = strtolower($extension);
if (isset($validExtensions[$extension])) {
return $validExtensions[$extension];
}
return false;
}
public static function base64Transparent() {
return 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
}
public static function base64($imagePath, $image) {
$pathInfo = pathinfo(parse_url($imagePath, PHP_URL_PATH));
$extension = self::validateExtension($pathInfo['extension']);
if ($extension) {
return 'data:image/' . $extension . ';base64,' . Base64::encode(Filesystem::readFile($imagePath));
}
return ResourceTranslator::toUrl($image);
}
public static function exif_imagetype($filename) {
if (!function_exists('exif_imagetype')) {
if ((list($width, $height, $type, $attr) = getimagesize($filename)) !== false) {
return $type;
}
return false;
}
return exif_imagetype($filename);
}
public static function isPNG8($path) {
$fp = fopen($path, 'r');
fseek($fp, 25);
$data = fgets($fp, 2);
fclose($fp);
if (ord($data) == 3) {
return true;
}
return false;
}
public static function scaleImageWebp($group, $imageUrlOrPath, $options) {
$options = array_merge(array(
'mode' => 'scale',
'scale' => 1,
'quality' => 100,
'remote' => false
), $options);
if (strpos($imageUrlOrPath, Filesystem::getBasePath()) === 0) {
$imageUrl = Url::pathToUri($imageUrlOrPath);
} else {
$imageUrl = ResourceTranslator::toUrl($imageUrlOrPath);
}
if (!extension_loaded('gd') || $options['mode'] === 'scale' && $options['scale'] <= 0) {
return Filesystem::pathToAbsoluteURL($imageUrl);
}
$options['quality'] = max(0, min(100, $options['quality']));
$originalImageUrl = $imageUrl;
if (substr($imageUrl, 0, 2) == '//') {
$imageUrl = parse_url(Url::getFullUri(), PHP_URL_SCHEME) . ':' . $imageUrl;
}
$imageUrl = Url::relativetoabsolute($imageUrl);
$imagePath = Filesystem::absoluteURLToPath($imageUrl);
$cache = new CacheImage($group);
if ($imagePath == $imageUrl) {
// The image is not local
if (!$options['remote']) {
return $originalImageUrl;
}
$pathInfo = pathinfo(parse_url($imageUrl, PHP_URL_PATH));
$extension = false;
if (isset($pathInfo['extension'])) {
$extension = self::validateGDExtension($pathInfo['extension']);
}
$extension = self::checkMetaExtension($imageUrl, $extension);
if (!$extension || (strtolower($extension) === 'webp' && !function_exists('imagecreatefromwebp')) || !ini_get('allow_url_fopen')) {
return $originalImageUrl;
}
return ResourceTranslator::urlToResource(Filesystem::pathToAbsoluteURL($cache->makeCache('webp', array(
self::class,
'_scaleRemoteImageWebp'
), array(
$extension,
$imageUrl,
$options
))));
} else {
$extension = false;
$imageType = @self::exif_imagetype($imagePath);
switch ($imageType) {
case IMAGETYPE_JPEG:
$extension = 'jpg';
break;
case IMAGETYPE_PNG:
$extension = 'png';
break;
case IMAGETYPE_WEBP:
if (!function_exists('imagecreatefromwebp')) {
return $originalImageUrl;
}
$extension = 'webp';
break;
}
if (!$extension) {
return $originalImageUrl;
}
return ResourceTranslator::urlToResource(Filesystem::pathToAbsoluteURL($cache->makeCache('webp', array(
self::class,
'_scaleImageWebp'
), array(
$extension,
$imagePath,
$options
))));
}
}
public static function _scaleRemoteImageWebp($targetFile, $extension, $imageUrl, $options) {
return self::_scaleImageWebp($targetFile, $extension, $imageUrl, $options);
}
public static function _scaleImageWebp($targetFile, $extension, $imagePath, $options) {
$options = array_merge(array(
'focusX' => 50,
'focusY' => 50,
), $options);
$targetDir = dirname($targetFile);
$image = false;
if ($extension == 'png') {
$image = @imagecreatefrompng($imagePath);
if (!imageistruecolor($image)) {
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
}
} else if ($extension == 'jpg') {
$image = @imagecreatefromjpeg($imagePath);
if (function_exists("exif_read_data")) {
$exif = @exif_read_data($imagePath);
$rotated = self::getOrientation($exif, $image);
if ($rotated) {
imagedestroy($image);
$image = $rotated;
}
}
} else if ($extension == 'webp') {
//@TODO: should we need to care about rotation?
$image = @imagecreatefromwebp($imagePath);
if (!imageistruecolor($image)) {
imagepalettetotruecolor($image);
imagealphablending($image, true);
imagesavealpha($image, true);
}
}
if ($image) {
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
switch ($options['mode']) {
case 'scale':
$targetWidth = round($originalWidth * $options['scale']);
$targetHeight = round($originalHeight * $options['scale']);
break;
case 'resize':
$targetWidth = $options['width'];
$targetHeight = $options['height'];
break;
}
if ((isset($rotated) && $rotated) || $originalWidth != $targetWidth || $originalHeight != $targetHeight) {
$newImage = imagecreatetruecolor($targetWidth, $targetHeight);
if ($extension == 'png') {
imagesavealpha($newImage, true);
imagealphablending($newImage, false);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($image, 0, 0, $targetWidth, $targetHeight, $transparent);
}
list($dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) = self::imageMode($targetWidth, $targetHeight, $originalWidth, $originalHeight, 'cover', $options['focusX'], $options['focusY']);
imagecopyresampled($newImage, $image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
imagedestroy($image);
} else {
$newImage = $image;
}
if (!Filesystem::existsFolder($targetDir)) {
Filesystem::createFolder($targetDir);
}
imagewebp($newImage, $targetFile, $options['quality']);
imagedestroy($newImage);
return true;
}
throw new Exception('Unable to scale image: ' . $imagePath);
}
public static function checkMetaExtension($imageUrl, $originalExtension) {
if (strpos($imageUrl, 'dst-jpg') !== false) {
return 'jpg';
} else if (strpos($imageUrl, 'dst-png') !== false) {
return 'png';
} else if (strpos($imageUrl, 'dst-webp') !== false) {
return 'webp';
} else {
// not Instagram or Facebook url
return $originalExtension;
}
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace Nextend\Framework\Image;
use Nextend\Framework\Image\Block\ImageManager\BlockImageManager;
use Nextend\Framework\Misc\Base64;
use Nextend\Framework\Pattern\VisualManagerTrait;
class ImageManager {
use VisualManagerTrait;
/**
* @var ImageStorage
*/
private static $model;
public static $loaded = array();
public function display() {
$imageManagerBlock = new BlockImageManager($this->MVCHelper);
$imageManagerBlock->display();
}
public static function init() {
self::$model = new ImageStorage();
}
public static function hasImageData($image) {
$image = self::$model->getByImage($image);
if (!empty($image)) {
return true;
}
return false;
}
public static function getImageData($image, $read = false) {
$visual = self::$model->getByImage($image);
if (empty($visual)) {
if ($read) {
return false;
} else {
$id = self::addImageData($image, ImageStorage::$emptyImage);
$visual = self::$model->getById($id);
}
}
self::$loaded[] = $visual;
return array_merge(ImageStorage::$emptyImage, json_decode(Base64::decode($visual['value']), true));
}
public static function addImageData($image, $value) {
return self::$model->add($image, $value);
}
public static function setImageData($image, $value) {
self::$model->setByImage($image, $value);
}
}
ImageManager::init();

View File

@ -0,0 +1,149 @@
<?php
namespace Nextend\Framework\Image;
use Nextend\Framework\Database\AbstractPlatformConnectorTable;
use Nextend\Framework\Database\Database;
use Nextend\Framework\Misc\Base64;
class ImageStorage {
/**
* @var AbstractPlatformConnectorTable
*/
private $tableImageStorage;
public static $emptyImage = array(
'desktop-retina' => array(
'image' => ''
),
'tablet' => array(
'image' => ''
),
'mobile' => array(
'image' => ''
)
);
public function __construct() {
$this->tableImageStorage = Database::getTable("nextend2_image_storage");
}
public function getById($id) {
return $this->tableImageStorage->findByAttributes(array(
"id" => $id
));
}
public function getByImage($image) {
static $cache = array();
if (!isset($cache[$image])) {
$cache[$image] = $this->tableImageStorage->findByAttributes(array(
"hash" => md5($image)
));
}
return $cache[$image];
}
public function setById($id, $value) {
if (is_array($value)) {
$value = Base64::encode(json_encode($value));
}
$result = $this->getById($id);
if ($result !== null) {
$this->tableImageStorage->update(array('value' => $value), array(
"id" => $id
));
return true;
}
return false;
}
public function setByImage($image, $value) {
if (is_array($value)) {
$value = Base64::encode(json_encode($value));
}
$result = $this->getByImage($image);
if ($result !== null) {
$this->tableImageStorage->update(array('value' => $value), array(
"id" => $result['id']
));
return true;
}
return false;
}
public function getAll() {
return $this->tableImageStorage->findAllByAttributes(array(), array(
"id",
"hash",
"image",
"value"
));
}
public function set($image, $value) {
if (is_array($value)) {
$value = Base64::encode(json_encode($value));
}
$result = $this->getByImage($image);
if (empty($result)) {
return $this->add($image, $value);
} else {
$attributes = array(
"id" => $result['id']
);
$this->tableImageStorage->update(array('value' => $value), $attributes);
return true;
}
}
public function add($image, $value) {
if (is_array($value)) {
$value = Base64::encode(json_encode($value));
}
$this->tableImageStorage->insert(array(
"hash" => md5($image),
"image" => $image,
"value" => $value
));
return $this->tableImageStorage->insertId();
}
public function deleteById($id) {
$this->tableImageStorage->deleteByAttributes(array(
"id" => $id
));
return true;
}
public function deleteByImage($image) {
$this->tableImageStorage->deleteByAttributes(array(
"hash" => md5($image)
));
return true;
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace Nextend\Framework\Image;
use Nextend\Framework\Form\Container\ContainerTable;
use Nextend\Framework\Form\ContainerInterface;
use Nextend\Framework\Form\Element\EmptyArea;
use Nextend\Framework\Form\Element\Text\FieldImage;
use Nextend\Framework\Form\Form;
use Nextend\Framework\Visual\ModelVisual;
class ModelImage extends ModelVisual {
protected $type = 'image';
/** @var ImageStorage */
protected $storage;
protected function init() {
$this->storage = new ImageStorage();
}
public function renderForm() {
$form = new Form($this, 'n2-image-editor');
$container = $form->getContainer();
$desktopTable = new ContainerTable($container, 'desktop', n2_('Desktop'));
$previewRow = $desktopTable->createRow('desktop-preview');
new EmptyArea($previewRow, 'desktop-preview', n2_('Preview'));
$this->renderDeviceTab($container, 'desktop-retina', n2_('Desktop retina'));
$this->renderDeviceTab($container, 'tablet', n2_('Tablet'));
$this->renderDeviceTab($container, 'mobile', n2_('Mobile'));
$form->render();
}
/**
* @param ContainerInterface $container
*/
private function renderDeviceTab($container, $name, $label) {
$table = new ContainerTable($container, $name, $label);
$row1 = $table->createRow('desktop-row-1');
new FieldImage($row1, $name . '-image', n2_('Image'));
$previewRow = $table->createRow($name . '-preview');
new EmptyArea($previewRow, $name . '-preview', n2_('Preview'));
}
public function addVisual($image, $visual) {
$visualId = $this->storage->add($image, $visual);
$visual = $this->storage->getById($visualId);
if (!empty($visual)) {
return $visual;
}
return false;
}
public function getVisual($image) {
return $this->storage->getByImage($image);
}
public function deleteVisual($id) {
$visual = $this->storage->getById($id);
$this->storage->deleteById($id);
return $visual;
}
public function changeVisual($id, $value) {
if ($this->storage->setById($id, $value)) {
return $this->storage->getById($id);
}
return false;
}
public function getVisuals($setId) {
return $this->storage->getAll();
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace Nextend\Framework\Image\WordPress;
use Nextend\Framework\Image\AbstractPlatformImage;
use Nextend\Framework\Platform\Platform;
use Nextend\Framework\ResourceTranslator\ResourceTranslator;
use function wp_check_filetype;
use function wp_upload_dir;
class WordPressImage extends AbstractPlatformImage {
public function __construct() {
$wp_upload_dir = wp_upload_dir();
ResourceTranslator::createResource('$upload$', rtrim(Platform::getPublicDirectory(), "/\\"), rtrim($wp_upload_dir['baseurl'], "/\\"));
}
public function initLightbox() {
wp_enqueue_media();
}
public function onImageUploaded($filename) {
$filename = str_replace(DIRECTORY_SEPARATOR, '/', $filename); // fix for Windows servers
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype(basename($filename), null);
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment($attachment, $filename);
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
}
}