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