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