]> git.mxchange.org Git - friendica.git/blob - src/Contact/Avatar.php
Merge pull request #11603 from tobiasd/20220605-lng
[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 use Friendica\Util\Strings;
36
37 /**
38  * functions for handling contact avatar caching
39  */
40 class Avatar
41 {
42         const BASE_PATH = '/avatar/';
43
44         /**
45          * Returns a field array with locally cached avatar pictures
46          *
47          * @param array $contact Contact array
48          * @param string $avatar Link to avatar picture
49          * @param bool   $force  force picture update
50          * @return array
51          */
52         public static function fetchAvatarContact(array $contact, string $avatar, bool $force = false): array
53         {
54                 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), 'photo' => '', 'thumb' => '', 'micro' => ''];
55
56                 if (!DI::config()->get('system', 'avatar_cache')) {
57                         self::deleteCache($contact);
58                         return $fields;
59                 }
60
61                 if (Network::isLocalLink($avatar) || empty($avatar)) {
62                         self::deleteCache($contact);
63                         return $fields;
64                 }
65
66                 if (($avatar != $contact['avatar']) || $force) {
67                         self::deleteCache($contact);
68                         Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
69                 } elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) {
70                         $fields['photo'] = $contact['photo'];
71                         $fields['thumb'] = $contact['thumb'];
72                         $fields['micro'] = $contact['micro'];
73                         Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
74                         return $fields;
75                 }
76
77                 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
78
79                 $img_str = $fetchResult->getBody();
80                 if (empty($img_str)) {
81                         Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
82                         return $fields;
83                 }
84
85                 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
86                 if (!$image->isValid()) {
87                         Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
88                         return $fields;
89                 }
90
91                 $filename  = self::getFilename($contact['url']);
92                 $timestamp = time();
93
94                 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
95                 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
96                 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
97
98                 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
99
100                 return $fields;
101         }
102
103         public static function storeAvatarByImage(array $contact, Image $image): array
104         {
105                 $fields = ['photo' => '', 'thumb' => '', 'micro' => ''];
106
107                 if (!DI::config()->get('system', 'avatar_cache')) {
108                         self::deleteCache($contact);
109                         return $fields;
110                 }
111
112                 if (Network::isLocalLink($contact['avatar']) || empty($contact['avatar'])) {
113                         self::deleteCache($contact);
114                         return $fields;
115                 }
116
117                 $filename  = self::getFilename($contact['url']);
118                 $timestamp = time();
119
120                 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
121                 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
122                 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
123
124                 return $fields;
125         }
126
127         private static function getFilename(string $url)
128         {
129                 $guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST));
130
131                 return substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
132                         substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
133         }
134
135         private static function storeAvatarCache(Image $image, string $filename, int $size, int $timestamp): string
136         {
137                 $image->scaleDown($size);
138                 if (is_null($image) || !$image->isValid()) {
139                         return '';
140                 }
141
142                 $path = self::BASE_PATH . $filename . $size . '.' . $image->getExt();
143
144                 $filepath = DI::basePath() . $path;
145
146                 $dirpath = DI::basePath() . self::BASE_PATH;
147
148                 DI::profiler()->startRecording('file');
149
150                 if (!file_exists($dirpath)) {
151                         if (!mkdir($dirpath, 0775)) {
152                                 Logger::warning('Base directory could not be created', ['directory' => $dirpath]);
153                                 return '';
154                         }
155                 }
156
157                 // Fetch the permission and group ownership of the "avatar" path and apply to all files
158                 $dir_perm  = fileperms($dirpath) & 0777;
159                 $file_perm = fileperms($dirpath) & 0666;
160                 $group     = filegroup($dirpath);
161
162                 // Check directory permissions of all parts of the path
163                 foreach (explode('/', dirname($filename)) as $part) {
164                         $dirpath .= $part . '/';
165
166                         if (!file_exists($dirpath)) {
167                                 if (!mkdir($dirpath, $dir_perm)) {
168                                         Logger::warning('Directory could not be created', ['directory' => $dirpath]);
169                                 }
170                         } elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) {
171                                 Logger::notice('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
172                         }
173
174                         if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) {
175                                 Logger::notice('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
176                         }
177                 }
178
179                 if (!file_put_contents($filepath, $image->asString())) {
180                         Logger::warning('File could not be created', ['file' => $filepath]);
181                 }
182
183                 $old_perm  = fileperms($filepath) & 0666;
184                 $old_group = filegroup($filepath);
185
186                 if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
187                         Logger::notice('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
188                 }
189
190                 if (($old_group != $group) && !chgrp($filepath, $group)) {
191                         Logger::notice('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
192                 }
193
194                 DI::profiler()->stopRecording();
195
196                 if (!file_exists($filepath)) {
197                         Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
198                         return '';
199                 }
200
201                 return DI::baseUrl() . $path . '?ts=' . $timestamp;
202         }
203
204         /**
205          * Check if the avatar cache file is locally stored
206          *
207          * @param string $avatar
208          * @return boolean
209          */
210         private static function isCacheFile(string $avatar): bool
211         {
212                 return !empty(self::getCacheFile($avatar));
213         }
214
215         /**
216          * Fetch the name of locally cached avatar pictures
217          *
218          * @param string $avatar
219          * @return string
220          */
221         private static function getCacheFile(string $avatar): string
222         {
223                 $parts = parse_url($avatar);
224                 if (empty($parts['host']) || ($parts['host'] != DI::baseUrl()->getHostname())) {
225                         return '';
226                 }
227
228                 $pos = strpos($parts['path'], DI::baseUrl()->getUrlPath() . self::BASE_PATH);
229                 if ($pos !== 0) {
230                         return '';
231                 }
232
233                 $filename = DI::basePath() . $parts['path'];
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 }