/
ImageUtil.class.php
283 lines (246 loc) · 8.99 KB
/
ImageUtil.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
<?php
namespace wcf\util;
use GuzzleHttp\Psr7\Header;
use wcf\system\exception\SystemException;
use wcf\system\image\ImageHandler;
/**
* Contains image-related functions.
*
* @author Marcel Werk
* @copyright 2001-2019 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\Util
*/
final class ImageUtil
{
/**
* image extensions
* @var array
*/
protected static $imageExtensions = ['jpeg', 'jpg', 'png', 'gif', "webp"];
/**
* Checks the content of an image for bad sections, e.g. the use of javascript
* and returns false if any bad stuff was found.
*
* @param string $file
* @return bool
*/
public static function checkImageContent($file)
{
// get file content
$content = \file_get_contents($file);
// remove some characters
$content = \strtolower(\preg_replace('/[^a-z0-9<\(]+/i', '', $content));
$content = \str_replace('description', '', $content);
// search for javascript
if (
\strpos($content, 'script') !== false
|| \strpos($content, 'javascript') !== false
|| \strpos($content, 'expression(') !== false
) {
return false;
}
return true;
}
/**
* Checks whether a given file is a valid image.
*
* @param string $location
* @param string|null $filename
* @param bool $handleSvgAsValidImage flag, whether a svg file is handled as image
* @return bool
*/
public static function isImage($location, $filename = null, $handleSvgAsValidImage = false)
{
if ($filename === null) {
$filename = \basename($location);
}
if (@\getimagesize($location) !== false) {
$extension = \pathinfo($filename, \PATHINFO_EXTENSION);
if (\in_array(\mb_strtolower($extension), self::$imageExtensions)) {
return true;
}
} elseif ($handleSvgAsValidImage) {
if (
\in_array(FileUtil::getMimeType($location), ['image/svg', 'image/svg+xml'])
&& \mb_strtolower(\pathinfo($filename, \PATHINFO_EXTENSION)) === 'svg'
) {
return true;
}
}
return false;
}
/**
* Return the file extension for an image with the given mime type.
*
* @param string $mimeType
* @return string
* @see http://www.php.net/manual/en/function.image-type-to-mime-type.php
*/
public static function getExtensionByMimeType($mimeType)
{
switch ($mimeType) {
case 'image/gif':
return 'gif';
case 'image/jpeg':
return 'jpg';
case 'image/png':
return 'png';
case 'application/x-shockwave-flash':
return 'swf';
case 'image/psd':
return 'psd';
case 'image/bmp':
case 'image/x-ms-bmp':
return 'bmp';
case 'image/tiff':
return 'tiff';
case 'image/webp':
return 'webp';
default:
return '';
}
}
/**
* Enforces dimensions for given image.
*
* @param string $filename
* @param int $maxWidth
* @param int $maxHeight
* @param bool $obtainDimensions
* @return string new filename if file was changed, otherwise old filename
* @since 5.2
*/
public static function enforceDimensions($filename, $maxWidth, $maxHeight, $obtainDimensions = true)
{
$imageData = \getimagesize($filename);
if ($imageData[0] > $maxWidth || $imageData[1] > $maxHeight) {
$adapter = ImageHandler::getInstance()->getAdapter();
$adapter->loadFile($filename);
$filename = FileUtil::getTemporaryFilename();
$thumbnail = $adapter->createThumbnail($maxWidth, $maxHeight, $obtainDimensions);
$adapter->writeImage($thumbnail, $filename);
// Clear thumbnail as soon as possible to free up the memory.
// This is technically useless, but done for consistency.
$thumbnail = null;
}
return $filename;
}
/**
* Rotates the given image based on the orientation stored in the exif data.
*
* @param string $filename
* @return string new filename if file was changed, otherwise old filename
* @since 5.2
*/
public static function fixOrientation($filename)
{
try {
$exifData = ExifUtil::getExifData($filename);
if (!empty($exifData)) {
$orientation = ExifUtil::getOrientation($exifData);
if ($orientation != ExifUtil::ORIENTATION_ORIGINAL) {
$adapter = ImageHandler::getInstance()->getAdapter();
$adapter->loadFile($filename);
$newImage = null;
switch ($orientation) {
case ExifUtil::ORIENTATION_180_ROTATE:
$newImage = $adapter->rotate(180);
break;
case ExifUtil::ORIENTATION_90_ROTATE:
$newImage = $adapter->rotate(90);
break;
case ExifUtil::ORIENTATION_270_ROTATE:
$newImage = $adapter->rotate(270);
break;
case ExifUtil::ORIENTATION_HORIZONTAL_FLIP:
case ExifUtil::ORIENTATION_VERTICAL_FLIP:
case ExifUtil::ORIENTATION_VERTICAL_FLIP_270_ROTATE:
case ExifUtil::ORIENTATION_HORIZONTAL_FLIP_270_ROTATE:
// unsupported
break;
}
if ($newImage !== null) {
if ($newImage instanceof \Imagick) {
$newImage->setImageOrientation(\Imagick::ORIENTATION_TOPLEFT);
}
$adapter->load($newImage, $adapter->getType());
}
$newFilename = FileUtil::getTemporaryFilename();
$adapter->writeImage($newFilename);
$filename = $newFilename;
}
}
} catch (SystemException $e) {
}
return $filename;
}
/**
* Examines the `accept` header to determine if the browser
* supports WebP images.
*
* @since 5.4
*/
public static function browserSupportsWebp(): bool
{
static $supportsWebP = null;
if ($supportsWebP === null) {
$supportsWebP = false;
if (!empty($_SERVER["HTTP_ACCEPT"])) {
$acceptableMimeTypes = \array_map(static function ($acceptableMimeType) {
[$mimeType] = ArrayUtil::trim(\explode(";", $acceptableMimeType), false);
return $mimeType;
}, Header::splitList($_SERVER["HTTP_ACCEPT"]));
if (\in_array("image/webp", $acceptableMimeTypes)) {
$supportsWebP = true;
}
}
}
return $supportsWebP;
}
/**
* Creates a WebP variant of the source image. Returns `true` if a
* `webp` file was created, `false` if a jpeg was created and `null`
* if no action was taken.
*/
public static function createWebpVariant(string $sourceLocation, string $outputFilenameWithoutExtension): ?bool
{
$imageData = \getimagesize($sourceLocation);
if ($imageData === false) {
throw new \InvalidArgumentException("The source location is not a valid image.");
}
$extension = self::getExtensionByMimeType($imageData['mime']);
switch ($extension) {
case 'gif':
// GIFs are not processed.
return null;
case 'jpg':
case 'png':
case 'webp':
break;
default:
throw new \InvalidArgumentException(\sprintf(
"Unsupported image format '%s', expecting one of 'gif', 'jpg', 'png' or 'webp'.",
$extension
));
}
$imageAdapter = ImageHandler::getInstance()->getAdapter();
$imageAdapter->loadFile($sourceLocation);
$image = $imageAdapter->getImage();
// The source file is a webp, create a fallback jpeg instead.
if ($imageData[2] === \IMAGETYPE_WEBP) {
$imageAdapter->saveImageAs($image, "{$outputFilenameWithoutExtension}.jpg", "jpeg", 80);
return false;
} else {
$imageAdapter->saveImageAs($image, "{$outputFilenameWithoutExtension}.webp", "webp", 80);
return true;
}
}
/**
* Forbid creation of ImageUtil objects.
*/
private function __construct()
{
// does nothing
}
}