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