]> git.mxchange.org Git - friendica.git/blob - src/Module/Photo.php
Use rawContent for Special Options to avoid a protected options() method
[friendica.git] / src / Module / Photo.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\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\Core\Storage\Type\ExternalResource;
33 use Friendica\Core\Storage\Type\SystemResource;
34 use Friendica\Model\User;
35 use Friendica\Network\HTTPException;
36 use Friendica\Network\HTTPException\NotModifiedException;
37 use Friendica\Object\Image;
38 use Friendica\Util\Images;
39 use Friendica\Util\Network;
40 use Friendica\Util\ParseUrl;
41 use Friendica\Util\Proxy;
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         protected function rawContent(array $request = [])
55         {
56                 $totalstamp = microtime(true);
57
58                 if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {
59                         header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
60                         if (!empty($_SERVER["HTTP_IF_NONE_MATCH"])) {
61                                 header("Etag: " . $_SERVER["HTTP_IF_NONE_MATCH"]);
62                         }
63                         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
64                         header("Cache-Control: max-age=31536000");
65                         if (function_exists("header_remove")) {
66                                 header_remove("Last-Modified");
67                                 header_remove("Expires");
68                                 header_remove("Cache-Control");
69                         }
70                         throw new NotModifiedException();
71                 }
72
73                 Profile::addVisitorCookieForHTTPSigner();
74
75                 $customsize = 0;
76                 $square_resize = true;
77                 $scale = null;
78                 $stamp = microtime(true);
79                 // User avatar
80                 if (!empty($this->parameters['type'])) {
81                         if (!empty($this->parameters['customsize'])) {
82                                 $customsize = intval($this->parameters['customsize']);
83                                 $square_resize = !in_array($this->parameters['type'], ['media', 'preview']);
84                         }
85
86                         if (!empty($this->parameters['guid'])) {
87                                 $guid = $this->parameters['guid'];
88                                 $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]);
89                                 if (empty($account)) {
90                                         throw new HTTPException\NotFoundException();
91                                 }
92
93                                 $id = $account['id'];
94                         }
95
96                         // Contact Id Fallback, to remove after version 2021.12
97                         if (isset($this->parameters['contact_id'])) {
98                                 $id = intval($this->parameters['contact_id']);
99                         }
100
101                         if (!empty($this->parameters['nickname_ext'])) {
102                                 $nickname = pathinfo($this->parameters['nickname_ext'], PATHINFO_FILENAME);
103                                 $user = User::getByNickname($nickname, ['uid']);
104                                 if (empty($user)) {
105                                         throw new HTTPException\NotFoundException();
106                                 }
107
108                                 $id = $user['uid'];
109                         }
110
111                         // User Id Fallback, to remove after version 2021.12
112                         if (!empty($this->parameters['uid_ext'])) {
113                                 $id = intval(pathinfo($this->parameters['uid_ext'], PATHINFO_FILENAME));
114                         }
115
116                         // Please refactor this for the love of everything that's good
117                         if (isset($this->parameters['id'])) {
118                                 $id = $this->parameters['id'];
119                         }
120
121                         if (empty($id)) {
122                                 Logger::notice('No picture id was detected', ['parameters' => $this->parameters, 'query' => DI::args()->getQueryString()]);
123                                 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
124                         }
125
126                         $photo = self::getPhotoByid($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
127                 } else {
128                         $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
129                         $scale = 0;
130                         if (substr($photoid, -2, 1) == "-") {
131                                 $scale = intval(substr($photoid, -1, 1));
132                                 $photoid = substr($photoid, 0, -2);
133                         }
134                         $photo = MPhoto::getPhoto($photoid, $scale);
135                         if ($photo === false) {
136                                 throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo with id %s is not available.', $photoid));
137                         }
138                 }
139
140                 $fetch = microtime(true) - $stamp;
141
142                 if ($photo === false) {
143                         throw new HTTPException\NotFoundException();
144                 }
145
146                 $cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true);
147
148                 $stamp = microtime(true);
149
150                 $imgdata = MPhoto::getImageDataForPhoto($photo);
151                 if (empty($imgdata)) {
152                         throw new HTTPException\NotFoundException();
153                 }
154
155                 // The mimetype for an external or system resource can only be known reliably after it had been fetched
156                 if (in_array($photo['backend-class'], [ExternalResource::NAME, SystemResource::NAME])) {
157                         $mimetype = Images::getMimeTypeByData($imgdata);
158                         if (!empty($mimetype)) {
159                                 $photo['type'] = $mimetype;
160                         }
161                 }
162
163                 $data = microtime(true) - $stamp;
164
165                 if (empty($imgdata)) {
166                         Logger::warning('Invalid photo', ['id' => $photo['id']]);
167                         if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
168                                 $reference = json_decode($photo['backend-ref'], true);
169                                 $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
170                         } else {
171                                 $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']);
172                         }
173                         throw new HTTPException\InternalServerErrorException($error);
174                 }
175
176                 // if customsize is set and image is not a gif, resize it
177                 if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
178                         $img = new Image($imgdata, $photo['type']);
179                         $img->scaleToSquare($customsize);
180                         $imgdata = $img->asString();
181                 } elseif ($photo['type'] !== "image/gif" && $customsize > 0) {
182                         $img = new Image($imgdata, $photo['type']);
183                         $img->scaleDown($customsize);
184                         $imgdata = $img->asString();
185                 }
186
187                 if (function_exists("header_remove")) {
188                         header_remove("Pragma");
189                         header_remove("pragma");
190                 }
191
192                 header("Content-type: " . $photo['type']);
193
194                 $stamp = microtime(true);
195                 if (!$cacheable) {
196                         // it is a private photo that they have no permission to view.
197                         // tell the browser not to cache it, in case they authenticate
198                         // and subsequently have permission to see it
199                         header("Cache-Control: no-store, no-cache, must-revalidate");
200                 } else {
201                         $md5 = $photo['hash'] ?: md5($imgdata);
202                         header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
203                         header("Etag: \"{$md5}\"");
204                         header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
205                         header("Cache-Control: max-age=31536000");
206                 }
207                 $checksum = microtime(true) - $stamp;
208
209                 $stamp = microtime(true);
210                 echo $imgdata;
211                 $output = microtime(true) - $stamp;
212
213                 $total = microtime(true) - $totalstamp;
214                 $rest = $total - ($fetch + $data + $checksum + $output);
215
216                 if (!is_null($scale) && ($scale < 4)) {
217                         Logger::info('Performance:', ['scale' => $scale, 'resource' => $photo['resource-id'],
218                                 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
219                                 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
220                                 'output' => number_format($output, 3), 'rest' => number_format($rest, 3)]);
221                 }
222
223                 exit();
224         }
225
226         private static function getPhotoByid(int $id, $type, $customsize)
227         {
228                 switch($type) {
229                         case "preview":
230                                 $media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
231                                 if (empty($media)) {
232                                         return false;
233                                 }
234                                 $url = $media['preview'];
235
236                                 if (empty($url) && ($media['type'] == Post\Media::IMAGE)) {
237                                         $url = $media['url'];
238                                 }
239
240                                 if (empty($url)) {
241                                         return false;
242                                 }
243
244                                 if (Network::isLocalLink($url) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $url, $matches)) {
245                                         return MPhoto::getPhoto($matches[1], $matches[2]);
246                                 }
247
248                                 return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
249                         case "media":
250                                 $media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
251                                 if (empty($media)) {
252                                         return false;
253                                 }
254
255                                 if (Network::isLocalLink($media['url']) && preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'], $matches)) {
256                                         return MPhoto::getPhoto($matches[1], $matches[2]);
257                                 }
258
259                                 return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
260                         case "link":
261                                 $link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
262                                 if (empty($link)) {
263                                         return false;
264                                 }
265
266                                 return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
267                         case "contact":
268                                 $contact = Contact::getById($id, ['uid', 'url', 'avatar', 'photo', 'xmpp', 'addr']);
269                                 if (empty($contact)) {
270                                         return false;
271                                 }
272                                 If (($contact['uid'] != 0) && empty($contact['photo']) && empty($contact['avatar'])) {
273                                         $contact = Contact::getByURL($contact['url'], false, ['avatar', 'photo', 'xmpp', 'addr']);
274                                 }
275                                 if (!empty($contact['photo']) && !empty($contact['avatar'])) {
276                                         // Fetch photo directly
277                                         $resourceid = MPhoto::ridFromURI($contact['photo']);
278                                         if (!empty($resourceid)) {
279                                                 $photo = MPhoto::selectFirst([], ['resource-id' => $resourceid], ['order' => ['scale']]);
280                                                 if (!empty($photo)) {
281                                                         return $photo;
282                                                 }
283                                         }
284                                         // We continue with the avatar link when the photo link is invalid
285                                         $url = $contact['avatar'];
286                                 } elseif (!empty($contact['avatar'])) {
287                                         $url = $contact['avatar'];
288                                 }
289                                 $mimetext = '';
290                                 if (!empty($url)) {
291                                         $mime = ParseUrl::getContentType($url);
292                                         if (!empty($mime)) {
293                                                 $mimetext = $mime[0] . '/' . $mime[1];
294                                         } else {
295                                                 Logger::info('Invalid file', ['url' => $url]);
296                                         }
297                                         if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
298                                                 Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
299                                                 $mimetext = '';
300                                         }
301                                 }
302                                 if (empty($mimetext)) {
303                                         if ($customsize <= Proxy::PIXEL_MICRO) {
304                                                 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
305                                         } elseif ($customsize <= Proxy::PIXEL_THUMB) {
306                                                 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
307                                         } else {
308                                                 $url = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
309                                         }
310                                 }
311                                 return MPhoto::createPhotoForExternalResource($url, 0, $mimetext);
312                         case "header":
313                                 $contact = Contact::getById($id, ['uid', 'url', 'header']);
314                                 if (empty($contact)) {
315                                         return false;
316                                 }
317                                 If (($contact['uid'] != 0) && empty($contact['header'])) {
318                                         $contact = Contact::getByURL($contact['url'], false, ['header']);
319                                 }
320                                 if (!empty($contact['header'])) {
321                                         $url = $contact['header'];
322                                 } else {
323                                         $url = DI::baseUrl() . '/images/blank.png';
324                                 }
325                                 return MPhoto::createPhotoForExternalResource($url);
326                         case "profile":
327                         case "custom":
328                                 $scale = 4;
329                                 break;
330                         case "micro":
331                                 $scale = 6;
332                                 break;
333                         case "avatar":
334                         default:
335                                 $scale = 5;
336                 }
337
338                 $photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
339                 if (empty($photo)) {
340                         $contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
341
342                         switch($type) {
343                                 case "profile":
344                                 case "custom":
345                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
346                                         break;
347                                 case "micro":
348                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
349                                         break;
350                                 case "avatar":
351                                 default:
352                                         $default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
353                         }
354
355                         $parts = parse_url($default);
356                         if (!empty($parts['scheme']) || !empty($parts['host'])) {
357                                 $photo = MPhoto::createPhotoForExternalResource($default);
358                         } else {
359                                 $photo = MPhoto::createPhotoForSystemResource($default);
360                         }
361                 }
362                 return $photo;
363         }
364 }