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