]> git.mxchange.org Git - friendica.git/blob - src/Module/Photo.php
Detect the mimetype for external resources
[friendica.git] / src / Module / Photo.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\Module;
23
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Photo as MPhoto;
30 use Friendica\Model\Post;
31 use Friendica\Model\Storage\ExternalResource;
32 use Friendica\Util\Proxy;
33 use Friendica\Object\Image;
34 use Friendica\Util\Images;
35
36 /**
37  * Photo Module
38  */
39 class Photo extends BaseModule
40 {
41         /**
42          * Module initializer
43          *
44          * Fetch a photo or an avatar, in optional size, check for permissions and
45          * return the image
46          */
47         public static function rawContent(array $parameters = [])
48         {
49                 $totalstamp = microtime(true);
50
51                 if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
52                         header("HTTP/1.1 304 Not Modified");
53                         header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
54                         if (!empty($_SERVER["HTTP_IF_NONE_MATCH"])) {
55                                 header("Etag: " . $_SERVER["HTTP_IF_NONE_MATCH"]);
56                         }
57                         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
58                         header("Cache-Control: max-age=31536000");
59                         if (function_exists("header_remove")) {
60                                 header_remove("Last-Modified");
61                                 header_remove("Expires");
62                                 header_remove("Cache-Control");
63                         }
64                         exit;
65                 }
66
67                 $customsize = 0;
68                 $square_resize = true;
69                 $photo = false;
70                 $scale = null;
71                 $stamp = microtime(true);
72                 if (!empty($parameters['customsize'])) {
73                         $customsize = intval($parameters['customsize']);
74                         $uid = MPhoto::stripExtension($parameters['name']);
75                         $photo = self::getAvatar($uid, $parameters['type'], $customsize);
76                         $square_resize = !in_array($parameters['type'], ['media', 'preview']);
77                 } elseif (!empty($parameters['type'])) {
78                         $uid = MPhoto::stripExtension($parameters['name']);
79                         $photo = self::getAvatar($uid, $parameters['type'], Proxy::PIXEL_SMALL);
80                 } elseif (!empty($parameters['name'])) {
81                         $photoid = MPhoto::stripExtension($parameters['name']);
82                         $scale = 0;
83                         if (substr($photoid, -2, 1) == "-") {
84                                 $scale = intval(substr($photoid, -1, 1));
85                                 $photoid = substr($photoid, 0, -2);
86                         }
87                         $photo = MPhoto::getPhoto($photoid, $scale);
88                         if ($photo === false) {
89                                 throw new \Friendica\Network\HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
90                         }
91                 } else {
92                         throw new \Friendica\Network\HTTPException\BadRequestException();
93                 }
94                 $fetch = microtime(true) - $stamp;
95
96                 if ($photo === false) {
97                         throw new \Friendica\Network\HTTPException\NotFoundException();
98                 }
99
100                 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
101
102                 $stamp = microtime(true);
103                 $imgdata = MPhoto::getImageDataForPhoto($photo);
104
105                 // The mimetype for an external resources can only be known after it had been fetched
106                 if ($photo['backend-class'] == ExternalResource::NAME) {
107                         $mimetype = Images::getMimeTypeByData($imgdata);
108                         if (!empty($mimetype)) {
109                                 $photo['type'] = $mimetype;
110                         }
111                 }
112
113                 $data = microtime(true) - $stamp;
114
115                 if (empty($imgdata)) {
116                         Logger::warning("Invalid photo with id {$photo["id"]}.");
117                         throw new \Friendica\Network\HTTPException\InternalServerErrorException(DI::l10n()->t('Invalid photo with id %s.', $photo["id"]));
118                 }
119
120                 // if customsize is set and image is not a gif, resize it
121                 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
122                         $img = new Image($imgdata, $photo['type']);
123                         $img->scaleToSquare($customsize);
124                         $imgdata = $img->asString();
125                 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
126                         $img = new Image($imgdata, $photo['type']);
127                         $img->scaleDown($customsize);
128                         $imgdata = $img->asString();
129                 }
130
131                 if (function_exists("header_remove")) {
132                         header_remove("Pragma");
133                         header_remove("pragma");
134                 }
135
136                 header("Content-type: " . $photo['type']);
137
138                 $stamp = microtime(true);
139                 if (!$cacheable) {
140                         // it is a private photo that they have no permission to view.
141                         // tell the browser not to cache it, in case they authenticate
142                         // and subsequently have permission to see it
143                         header("Cache-Control: no-store, no-cache, must-revalidate");
144                 } else {
145                         $md5 = $photo['hash'] ?: md5($imgdata);
146                         header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
147                         header("Etag: \"{$md5}\"");
148                         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
149                         header("Cache-Control: max-age=31536000");
150                 }
151                 $checksum = microtime(true) - $stamp;
152
153                 $stamp = microtime(true);
154                 echo $imgdata;
155                 $output = microtime(true) - $stamp;
156
157                 $total = microtime(true) - $totalstamp;
158                 $rest = $total - ($fetch + $data + $checksum + $output);
159
160                 if (!is_null($scale) && ($scale < 4)) {
161                         Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
162                                 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
163                                 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
164                                 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
165                 }
166
167                 exit();
168         }
169
170         private static function getAvatar($uid, $type="avatar", $customsize)
171         {
172                 switch($type) {
173                         case "preview":
174                                 $media = DBA::selectFirst('post-media', ['preview', 'url', 'type', 'uri-id'], ['id' => $uid]);
175                                 if (empty($media)) {
176                                         return false;
177                                 }
178                                 $url = $media['preview'];
179
180                                 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
181                                         $url = $media['url'];
182                                 }
183
184                                 if (empty($url)) {
185                                         return false;
186                                 }
187
188                                 return MPhoto::createPhotoForExternalResource($url, (int)local_user());
189                         case "media":
190                                 $media = DBA::selectFirst('post-media', ['url', 'uri-id'], ['id' => $uid, 'type' => Post\Media::IMAGE]);
191                                 if (empty($media)) {
192                                         return false;
193                                 }
194
195                                 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user());
196                         case "contact":
197                                 $contact = Contact::getById($uid, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
198                                 if (empty($contact)) {
199                                         return false;
200                                 }
201                                 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
202                                         $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
203                                 }
204                                 if (!empty($contact['photo'])) {
205                                         // Fetch photo directly
206                                         $resourceid = MPhoto::ridFromURI($contact['photo']);
207                                         if (!empty($resourceid)) {
208                                                 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
209                                                 if (!empty($photo)) {
210                                                         return $photo;
211                                                 }
212                                         }
213                                         $url = $contact['photo'];
214                                 } elseif (!empty($contact['avatar'])) {
215                                         $url = $contact['avatar'];
216                                 } elseif ($customsize <= Proxy::PIXEL_MICRO) {
217                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
218                                 } elseif ($customsize <= Proxy::PIXEL_THUMB) {
219                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
220                                 } else {
221                                         $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
222                                 }
223                                 return MPhoto::createPhotoForExternalResource($url);
224                         case "header":
225                                 $contact = Contact::getById($uid, ['uid', 'url', 'header']);
226                                 if (empty($contact)) {
227                                         return false;
228                                 }
229                                 If (($contact['uid'] != 0) && empty($contact['header'])) {
230                                         $contact = Contact::getByURL($contact['url'], false, ['header']);
231                                 }
232                                 if (!empty($contact['header'])) {
233                                         $url = $contact['header'];
234                                 } else {
235                                         $url = DI::baseUrl() . '/images/blank.png';
236                                 }
237                                 return MPhoto::createPhotoForExternalResource($url);
238                         case "profile":
239                         case "custom":
240                                 $scale = 4;
241                                 break;
242                         case "micro":
243                                 $scale = 6;
244                                 break;
245                         case "avatar":
246                         default:
247                                 $scale = 5;
248                 }
249
250                 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $uid, "profile" => 1]);
251                 if (empty($photo)) {
252                         $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]) ?: [];
253
254                         switch($type) {
255                                 case "profile":
256                                 case "custom":
257                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
258                                         break;
259                                 case "micro":
260                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
261                                         break;
262                                 case "avatar":
263                                 default:
264                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
265                         }
266
267                         $parts = parse_url($default);
268                         if (!empty($parts['scheme']) || !empty($parts['host'])) {
269                                 $photo = MPhoto::createPhotoForExternalResource($default);
270                         } else {
271                                 $photo = MPhoto::createPhotoForSystemResource($default);
272                         }
273                 }
274                 return $photo;
275         }
276 }