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