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