]> git.mxchange.org Git - friendica.git/blob - src/Util/Images.php
Fixed max value check, improved request value fetching
[friendica.git] / src / Util / Images.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use Friendica\Core\Logger;
25 use Friendica\DI;
26 use Friendica\Model\Photo;
27
28 /**
29  * Image utilities
30  */
31 class Images
32 {
33         /**
34          * Maps Mime types to Imagick formats
35          *
36          * @return array
37          */
38         public static function getFormatsMap()
39         {
40                 $m = [
41                         'image/jpeg' => 'JPG',
42                         'image/png' => 'PNG',
43                         'image/gif' => 'GIF'
44                 ];
45
46                 return $m;
47         }
48
49         /**
50          * Return file extension for mime type
51          * @param string $mimetype
52          * @return string
53          */
54         public static function getExtensionByMimeType(string $mimetype): string
55         {
56                 switch ($mimetype) {
57                         case 'image/png':
58                                 $imagetype = IMAGETYPE_PNG;
59                                 break;
60
61                         case 'image/gif':
62                                 $imagetype = IMAGETYPE_GIF;
63                                 break;
64
65                         default:
66                                 $imagetype = IMAGETYPE_JPEG;
67                                 break;
68                 }
69
70                 return image_type_to_extension($imagetype);
71         }
72
73         /**
74          * Returns supported image mimetypes and corresponding file extensions
75          *
76          * @return array
77          */
78         public static function supportedTypes()
79         {
80                 $types = [
81                         'image/jpeg' => 'jpg'
82                 ];
83                 if (class_exists('Imagick')) {
84                         // Imagick::queryFormats won't help us a lot there...
85                         // At least, not yet, other parts of friendica uses this array
86                         $types += [
87                                 'image/png' => 'png',
88                                 'image/gif' => 'gif'
89                         ];
90                 } elseif (imagetypes() & IMG_PNG) {
91                         $types += [
92                                 'image/png' => 'png'
93                         ];
94                 }
95
96                 return $types;
97         }
98
99         /**
100          * Fetch image mimetype from the image data or guessing from the file name
101          *
102          * @param string $image_data Image data
103          * @param string $filename   File name (for guessing the type via the extension)
104          * @param string $mime       default mime type
105          *
106          * @return string
107          * @throws \Exception
108          */
109         public static function getMimeTypeByData(string $image_data, string $filename = '', string $mime = '')
110         {
111                 if (substr($mime, 0, 6) == 'image/') {
112                         Logger::info('Using default mime type', ['filename' => $filename, 'mime' => $mime]);
113                         return $mime;
114                 }
115
116                 $image = @getimagesizefromstring($image_data);
117                 if (!empty($image['mime'])) {
118                         Logger::info('Mime type detected via data', ['filename' => $filename, 'default' => $mime, 'mime' => $image['mime']]);
119                         return $image['mime'];
120                 }
121
122                 return self::guessTypeByExtension($filename);
123         }
124
125         /**
126          * Fetch image mimetype from the image data or guessing from the file name
127          *
128          * @param string $sourcefile Source file of the image
129          * @param string $filename   File name (for guessing the type via the extension)
130          * @param string $mime       default mime type
131          *
132          * @return string
133          * @throws \Exception
134          */
135         public static function getMimeTypeBySource(string $sourcefile, string $filename = '', string $mime = '')
136         {
137                 if (substr($mime, 0, 6) == 'image/') {
138                         Logger::info('Using default mime type', ['filename' => $filename, 'mime' => $mime]);
139                         return $mime;
140                 }
141
142                 $image = @getimagesize($sourcefile);
143                 if (!empty($image['mime'])) {
144                         Logger::info('Mime type detected via file', ['filename' => $filename, 'default' => $mime, 'image' => $image]);
145                         return $image['mime'];
146                 }
147
148                 return self::guessTypeByExtension($filename);
149         }
150
151         /**
152          * Guess image mimetype from the filename
153          *
154          * @param string $filename   Image filename
155          *
156          * @return string
157          * @throws \Exception
158          */
159         public static function guessTypeByExtension(string $filename)
160         {
161                 $ext = pathinfo(parse_url($filename, PHP_URL_PATH), PATHINFO_EXTENSION);
162                 $types = self::supportedTypes();
163                 $type = 'image/jpeg';
164                 foreach ($types as $m => $e) {
165                         if ($ext == $e) {
166                                 $type = $m;
167                         }
168                 }
169
170                 Logger::info('Mime type guessed via extension', ['filename' => $filename, 'type' => $type]);
171                 return $type;
172         }
173
174         /**
175          * @param string $url
176          * @return array
177          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
178          */
179         public static function getInfoFromURLCached($url)
180         {
181                 $data = [];
182
183                 if (empty($url)) {
184                         return $data;
185                 }
186
187                 $data = DI::cache()->get($url);
188
189                 if (empty($data) || !is_array($data)) {
190                         $data = self::getInfoFromURL($url);
191
192                         DI::cache()->set($url, $data);
193                 }
194
195                 return $data;
196         }
197
198         /**
199          * @param string $url
200          * @return array
201          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
202          */
203         public static function getInfoFromURL($url)
204         {
205                 $data = [];
206
207                 if (empty($url)) {
208                         return $data;
209                 }
210
211                 if (Network::isLocalLink($url) && ($data = Photo::getResourceData($url))) {
212                         $photo = Photo::selectFirst([], ['resource-id' => $data['guid'], 'scale' => $data['scale']]);
213                         if (!empty($photo)) {
214                                 $img_str = Photo::getImageDataForPhoto($photo);
215                         }
216                         // @todo Possibly add a check for locally stored files
217                 }
218
219                 if (empty($img_str)) {
220                         $img_str = DI::httpClient()->fetch($url, 4);
221                 }
222
223                 if (!$img_str) {
224                         return [];
225                 }
226
227                 $filesize = strlen($img_str);
228
229                 try {
230                         $data = @getimagesizefromstring($img_str);
231                 } catch (\Exception $e) {
232                         return [];
233                 }
234
235                 if ($data) {
236                         $data['size'] = $filesize;
237                 }
238
239                 return $data;
240         }
241
242         /**
243          * @param integer $width
244          * @param integer $height
245          * @param integer $max
246          * @return array
247          */
248         public static function getScalingDimensions($width, $height, $max)
249         {
250                 if ((!$width) || (!$height)) {
251                         return ['width' => 0, 'height' => 0];
252                 }
253
254                 if ($width > $max && $height > $max) {
255                         // very tall image (greater than 16:9)
256                         // constrain the width - let the height float.
257
258                         if ((($height * 9) / 16) > $width) {
259                                 $dest_width = $max;
260                                 $dest_height = intval(($height * $max) / $width);
261                         } elseif ($width > $height) {
262                                 // else constrain both dimensions
263                                 $dest_width = $max;
264                                 $dest_height = intval(($height * $max) / $width);
265                         } else {
266                                 $dest_width = intval(($width * $max) / $height);
267                                 $dest_height = $max;
268                         }
269                 } else {
270                         if ($width > $max) {
271                                 $dest_width = $max;
272                                 $dest_height = intval(($height * $max) / $width);
273                         } else {
274                                 if ($height > $max) {
275                                         // very tall image (greater than 16:9)
276                                         // but width is OK - don't do anything
277
278                                         if ((($height * 9) / 16) > $width) {
279                                                 $dest_width = $width;
280                                                 $dest_height = $height;
281                                         } else {
282                                                 $dest_width = intval(($width * $max) / $height);
283                                                 $dest_height = $max;
284                                         }
285                                 } else {
286                                         $dest_width = $width;
287                                         $dest_height = $height;
288                                 }
289                         }
290                 }
291
292                 return ['width' => $dest_width, 'height' => $dest_height];
293         }
294 }