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