]> git.mxchange.org Git - friendica.git/blob - src/Contact/Avatar.php
Console command to move avatars to the avatar cache
[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
48          * @param string $avatar
49          * @return array
50          */
51         public static function fetchAvatarContact(array $contact, string $avatar): 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)) {
61                         return $fields;
62                 }
63
64                 if ($avatar != $contact['avatar']) {
65                         self::deleteCache($contact);
66                         Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
67                 } elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) {
68                         $fields['photo'] = $contact['photo'];
69                         $fields['thumb'] = $contact['thumb'];
70                         $fields['micro'] = $contact['micro'];
71                         Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
72                         return $fields;
73                 }
74
75                 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
76
77                 $img_str = $fetchResult->getBody();
78                 if (empty($img_str)) {
79                         Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
80                         return $fields;
81                 }
82
83                 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
84                 if (!$image->isValid()) {
85                         Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
86                         return $fields;
87                 }
88
89                 $filename = self::getFilename($contact['url']);
90                 
91                 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL);
92                 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB);
93                 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO);
94
95                 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
96
97                 return $fields;
98         }
99
100         public static function storeAvatarByImage(array $contact, Image $image): array
101         {
102                 $fields = ['photo' => '', 'thumb' => '', 'micro' => ''];
103
104                 if (!DI::config()->get('system', 'avatar_cache')) {
105                         self::deleteCache($contact);
106                         return $fields;
107                 }
108
109                 if (Network::isLocalLink($contact['avatar'])) {
110                         return $fields;
111                 }
112
113                 $filename = self::getFilename($contact['url']);
114                 
115                 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL);
116                 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB);
117                 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO);
118
119                 return $fields;
120         }
121
122         private static function getFilename(string $url)
123         {
124                 $guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST));
125
126                 return substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
127                         substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
128         }
129
130         private static function storeAvatarCache(Image $image, string $filename, int $size): string
131         {
132                 $image->scaleDown($size);
133                 if (is_null($image) || !$image->isValid()) {
134                         return '';
135                 }
136
137                 $path = self::BASE_PATH . $filename . $size . '.' . $image->getExt();
138
139                 $filepath = DI::basePath() . $path;
140
141                 $dirpath = DI::basePath() . self::BASE_PATH;
142
143                 DI::profiler()->startRecording('file');
144
145                 // Fetch the permission and group ownership of the "avatar" path and apply to all files
146                 $dir_perm  = fileperms($dirpath) & 0777;
147                 $file_perm = fileperms($dirpath) & 0666;
148                 $group     = filegroup($dirpath);
149
150                 // Check directory permissions of all parts of the path
151                 foreach (explode('/', dirname($filename)) as $part) {
152                         $dirpath .= $part . '/';
153
154                         if (!file_exists($dirpath)) {
155                                 if (!mkdir($dirpath, $dir_perm)) {
156                                         Logger::warning('Directory could not be created', ['directory' => $dirpath]);
157                                 }
158                         } elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) {
159                                 Logger::notice('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
160                         }
161
162                         if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) {
163                                 Logger::notice('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
164                         }
165                 }
166
167                 if (!file_put_contents($filepath, $image->asString())) {
168                         Logger::warning('File could not be created', ['file' => $filepath]);
169                 }
170
171                 $old_perm  = fileperms($filepath) & 0666;
172                 $old_group = filegroup($filepath);
173
174                 if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
175                         Logger::notice('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
176                 }
177
178                 if (($old_group != $group) && !chgrp($filepath, $group)) {
179                         Logger::notice('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
180                 }
181
182                 DI::profiler()->stopRecording();
183
184                 if (!file_exists($filepath)) {
185                         Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
186                         return '';
187                 }
188
189                 return DI::baseUrl() . $path;
190         }
191
192         /**
193          * Check if the avatar cache file is locally stored
194          *
195          * @param string $avatar
196          * @return boolean
197          */
198         private static function isCacheFile(string $avatar): bool
199         {
200                 return !empty(self::getCacheFile($avatar));
201         }
202
203         /**
204          * Fetch the name of locally cached avatar pictures
205          *
206          * @param string $avatar
207          * @return string
208          */
209         private static function getCacheFile(string $avatar): string
210         {
211                 if (empty($avatar) || !Network::isLocalLink($avatar)) {
212                         return '';
213                 }
214
215                 $path = Strings::normaliseLink(DI::baseUrl() . self::BASE_PATH);
216
217                 if (Network::getUrlMatch($path, $avatar) != $path) {
218                         return '';
219                 }
220
221                 $filename = str_replace($path, DI::basePath(). self::BASE_PATH, Strings::normaliseLink($avatar));
222
223                 DI::profiler()->startRecording('file');
224                 $exists = file_exists($filename);
225                 DI::profiler()->stopRecording();
226
227                 if (!$exists) {
228                         return '';
229                 }
230                 return $filename;
231         }
232
233         /**
234          * Delete locally cached avatar pictures of a contact
235          *
236          * @param string $avatar
237          * @return void
238          */
239         public static function deleteCache(array $contact)
240         {
241                 self::deleteCacheFile($contact['photo']);
242                 self::deleteCacheFile($contact['thumb']);
243                 self::deleteCacheFile($contact['micro']);
244         }
245
246         /**
247          * Delete a locally cached avatar picture
248          *
249          * @param string $avatar
250          * @return void
251          */
252         private static function deleteCacheFile(string $avatar)
253         {
254                 $localFile = self::getCacheFile($avatar);
255                 if (!empty($localFile)) {
256                         unlink($localFile);
257                         Logger::debug('Unlink avatar', ['avatar' => $avatar]);
258                 }
259         }
260 }