]> git.mxchange.org Git - friendica.git/blob - src/Contact/Avatar.php
Apply feedback and describe the encoding method
[friendica.git] / src / Contact / Avatar.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Contact;
23
24 use Friendica\Core\Logger;
25 use Friendica\DI;
26 use Friendica\Model\Item;
27 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
28 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
29 use Friendica\Object\Image;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\HTTPSignature;
32 use Friendica\Util\Images;
33 use Friendica\Util\Network;
34 use Friendica\Util\Proxy;
35
36 /**
37  * functions for handling contact avatar caching
38  */
39 class Avatar
40 {
41         const BASE_PATH = '/avatar/';
42
43         /**
44          * Returns a field array with locally cached avatar pictures
45          *
46          * @param array $contact Contact array
47          * @param string $avatar Link to avatar picture
48          * @param bool   $force  force picture update
49          * @return array
50          */
51         public static function fetchAvatarContact(array $contact, string $avatar, bool $force = false): array
52         {
53                 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), 'photo' => '', 'thumb' => '', 'micro' => ''];
54
55                 if (!DI::config()->get('system', 'avatar_cache')) {
56                         self::deleteCache($contact);
57                         return $fields;
58                 }
59
60                 if (Network::isLocalLink($avatar) || empty($avatar)) {
61                         self::deleteCache($contact);
62                         return $fields;
63                 }
64
65                 if (($avatar != $contact['avatar']) || $force) {
66                         self::deleteCache($contact);
67                         Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
68                 } elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) {
69                         $fields['photo'] = $contact['photo'];
70                         $fields['thumb'] = $contact['thumb'];
71                         $fields['micro'] = $contact['micro'];
72                         Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
73                         return $fields;
74                 }
75
76                 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
77
78                 $img_str = $fetchResult->getBody();
79                 if (empty($img_str)) {
80                         Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
81                         return $fields;
82                 }
83
84                 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
85                 if (!$image->isValid()) {
86                         Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
87                         return $fields;
88                 }
89
90                 $filename  = self::getFilename($contact['url']);
91                 $timestamp = time();
92
93                 $fields['blurhash'] = $image->getBlurHash();
94
95                 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
96                 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
97                 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
98
99                 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
100
101                 return $fields;
102         }
103
104         public static function storeAvatarByImage(array $contact, Image $image): array
105         {
106                 $fields = ['photo' => '', 'thumb' => '', 'micro' => ''];
107
108                 if (!DI::config()->get('system', 'avatar_cache')) {
109                         self::deleteCache($contact);
110                         return $fields;
111                 }
112
113                 if (Network::isLocalLink($contact['avatar']) || empty($contact['avatar'])) {
114                         self::deleteCache($contact);
115                         return $fields;
116                 }
117
118                 $filename  = self::getFilename($contact['url']);
119                 $timestamp = time();
120
121                 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
122                 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
123                 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
124
125                 return $fields;
126         }
127
128         private static function getFilename(string $url): string
129         {
130                 $guid = Item::guidFromUri($url);
131
132                 return substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
133                         substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
134         }
135
136         private static function storeAvatarCache(Image $image, string $filename, int $size, int $timestamp): string
137         {
138                 $image->scaleDown($size);
139                 if (is_null($image) || !$image->isValid()) {
140                         return '';
141                 }
142
143                 $path = $filename . $size . '.' . $image->getExt();
144
145                 $basepath = self::basePath();
146                 if (empty($basepath)) {
147                         return '';
148                 }
149
150                 $filepath = $basepath . $path;
151
152                 $dirpath = $basepath;
153
154                 DI::profiler()->startRecording('file');
155
156                 // Fetch the permission and group ownership of the "avatar" path and apply to all files
157                 $dir_perm  = fileperms($dirpath) & 0777;
158                 $file_perm = fileperms($dirpath) & 0666;
159                 $group     = filegroup($dirpath);
160
161                 // Check directory permissions of all parts of the path
162                 foreach (explode('/', dirname($filename)) as $part) {
163                         $dirpath .= $part . '/';
164
165                         if (!file_exists($dirpath)) {
166                                 if (!@mkdir($dirpath, $dir_perm) && !file_exists($dirpath)) {
167                                         Logger::warning('Directory could not be created', ['directory' => $dirpath]);
168                                 }
169                         } elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) {
170                                 Logger::warning('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
171                         }
172
173                         if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) {
174                                 Logger::warning('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
175                         }
176                 }
177
178                 if (!file_put_contents($filepath, $image->asString())) {
179                         Logger::warning('File could not be created', ['file' => $filepath]);
180                 }
181
182                 $old_perm  = fileperms($filepath) & 0666;
183                 $old_group = filegroup($filepath);
184
185                 if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
186                         Logger::warning('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
187                 }
188
189                 if (($old_group != $group) && !chgrp($filepath, $group)) {
190                         Logger::warning('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
191                 }
192
193                 DI::profiler()->stopRecording();
194
195                 if (!file_exists($filepath)) {
196                         Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
197                         return '';
198                 }
199
200                 return self::baseUrl() . $path . '?ts=' . $timestamp;
201         }
202
203         /**
204          * Check if the avatar cache file is locally stored
205          *
206          * @param string $avatar
207          * @return boolean
208          */
209         private static function isCacheFile(string $avatar): bool
210         {
211                 return !empty(self::getCacheFile($avatar));
212         }
213
214         /**
215          * Fetch the name of locally cached avatar pictures
216          *
217          * @param string $avatar
218          * @return string
219          */
220         private static function getCacheFile(string $avatar): string
221         {
222                 $parts = parse_url($avatar);
223                 if (empty($parts['host']) || ($parts['host'] != parse_url(self::baseUrl(), PHP_URL_HOST))) {
224                         return '';
225                 }
226
227                 $avatarpath = parse_url(self::baseUrl(), PHP_URL_PATH);
228                 $pos = strpos($parts['path'], $avatarpath);
229                 if ($pos !== 0) {
230                         return '';
231                 }
232
233                 $filename = self::basePath() . substr($parts['path'], strlen($avatarpath));
234
235                 DI::profiler()->startRecording('file');
236                 $exists = file_exists($filename);
237                 DI::profiler()->stopRecording();
238
239                 if (!$exists) {
240                         return '';
241                 }
242                 return $filename;
243         }
244
245         /**
246          * Delete locally cached avatar pictures of a contact
247          *
248          * @param string $avatar
249          * @return void
250          */
251         public static function deleteCache(array $contact)
252         {
253                 self::deleteCacheFile($contact['photo']);
254                 self::deleteCacheFile($contact['thumb']);
255                 self::deleteCacheFile($contact['micro']);
256         }
257
258         /**
259          * Delete a locally cached avatar picture
260          *
261          * @param string $avatar
262          * @return void
263          */
264         private static function deleteCacheFile(string $avatar)
265         {
266                 $localFile = self::getCacheFile($avatar);
267                 if (!empty($localFile)) {
268                         @unlink($localFile);
269                         Logger::debug('Unlink avatar', ['avatar' => $avatar]);
270                 }
271         }
272
273         /**
274          * Fetch the avatar base path
275          *
276          * @return string
277          */
278         private static function basePath(): string
279         {
280                 $basepath = DI::config()->get('system', 'avatar_cache_path');
281                 if (empty($basepath)) {
282                         $basepath = DI::basePath() . self::BASE_PATH;
283                 }
284                 $basepath = rtrim($basepath, '/') . '/';
285
286                 if (!file_exists($basepath)) {
287                         // We only automatically create the folder when it is in the web root
288                         if (strpos($basepath, DI::basePath()) !== 0) {
289                                 Logger::warning('Base directory does not exist', ['directory' => $basepath]);
290                                 return '';
291                         }
292                         if (!mkdir($basepath, 0775)) {
293                                 Logger::warning('Base directory could not be created', ['directory' => $basepath]);
294                                 return '';
295                         }
296                 }
297
298                 return $basepath;
299         }
300
301         /**
302          * Fetch the avatar base url
303          *
304          * @return string
305          */
306         private static function baseUrl(): string
307         {
308                 $baseurl = DI::config()->get('system', 'avatar_cache_url');
309                 if (!empty($baseurl)) {
310                         return rtrim($baseurl, '/') . '/';
311                 }
312
313                 return DI::baseUrl() . self::BASE_PATH;
314         }
315 }