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