]> git.mxchange.org Git - friendica.git/blob - src/Contact/Avatar.php
8aa72bf9ba247ba1200aa065313d0eb717e40a84
[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         /**
43          * Returns a field array with locally cached avatar pictures
44          *
45          * @param array $contact
46          * @param string $avatar
47          * @return array
48          */
49         public static function fetchAvatarContact(array $contact, string $avatar): array
50         {
51                 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), 'photo' => '', 'thumb' => '', 'micro' => ''];
52
53                 if (!DI::config()->get('system', 'avatar_cache')) {
54                         self::deleteCache($contact);
55                         return $fields;
56                 }
57
58                 if (Network::isLocalLink($avatar)) {
59                         return $fields;
60                 }
61
62                 if ($avatar != $contact['avatar']) {
63                         self::deleteCache($contact);
64                         Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
65                 } elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) {
66                         $fields['photo'] = $contact['photo'];
67                         $fields['thumb'] = $contact['thumb'];
68                         $fields['micro'] = $contact['micro'];
69                         Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
70                         return $fields;
71                 }
72
73                 $guid = Item::guidFromUri($contact['url'], parse_url($contact['url'], PHP_URL_HOST));
74
75                 $filename = substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
76                         substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
77
78                 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
79
80                 $img_str = $fetchResult->getBody();
81                 if (empty($img_str)) {
82                         Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
83                         return $fields;
84                 }
85
86                 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
87                 if (!$image->isValid()) {
88                         Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
89                         return $fields;
90                 }
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         private static function storeAvatarCache(Image $image, string $filename, int $size): string
102         {
103                 $image->scaleDown($size);
104                 if (is_null($image) || !$image->isValid()) {
105                         return '';
106                 }
107
108                 $path = '/avatar/' . $filename . $size . '.' . $image->getExt();
109
110                 $filepath = DI::basePath() . $path;
111
112                 $dirpath = DI::basePath() . '/avatar/';
113
114                 DI::profiler()->startRecording('file');
115
116                 // Fetch the permission and group ownership of the "avatar" path and apply to all files
117                 $dir_perm  = fileperms($dirpath) & 0777;
118                 $file_perm = fileperms($dirpath) & 0666;
119                 $group     = filegroup($dirpath);
120
121                 // Check directory permissions of all parts of the path
122                 foreach (explode('/', dirname($filename)) as $part) {
123                         $dirpath .= $part . '/';
124                         if (!file_exists($dirpath)) {
125                                 mkdir($dirpath, $dir_perm);
126                         } elseif (fileperms($dirpath) & 0777 != $dir_perm) {
127                                 chmod($dirpath, $dir_perm);
128                         }
129
130                         if (filegroup($dirpath) != $group) {
131                                 chgrp($dirpath, $group);
132                         }
133                 }
134
135                 file_put_contents($filepath, $image->asString());
136                 chmod($filepath, $file_perm);
137                 chgrp($filepath, $group);
138
139                 DI::profiler()->stopRecording();
140
141                 if (!file_exists($filepath)) {
142                         Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
143                         return '';
144                 }
145
146                 return DI::baseUrl() . $path;
147         }
148
149         /**
150          * Check if the avatar cache file is locally stored
151          *
152          * @param string $avatar
153          * @return boolean
154          */
155         private static function isCacheFile(string $avatar): bool
156         {
157                 return !empty(self::getCacheFile($avatar));
158         }
159
160         /**
161          * Fetch the name of locally cached avatar pictures
162          *
163          * @param string $avatar
164          * @return string
165          */
166         private static function getCacheFile(string $avatar): string
167         {
168                 if (empty($avatar) || !Network::isLocalLink($avatar)) {
169                         return '';
170                 }
171
172                 $path = Strings::normaliseLink(DI::baseUrl() . '/avatar');
173
174                 if (Network::getUrlMatch($path, $avatar) != $path) {
175                         return '';
176                 }
177
178                 $filename = str_replace($path, DI::basePath(). '/avatar/', Strings::normaliseLink($avatar));
179
180                 DI::profiler()->startRecording('file');
181                 $exists = file_exists($filename);
182                 DI::profiler()->stopRecording();
183
184                 if (!$exists) {
185                         return '';
186                 }
187                 return $filename;
188         }
189
190         /**
191          * Delete locally cached avatar pictures of a contact
192          *
193          * @param string $avatar
194          * @return void
195          */
196         public static function deleteCache(array $contact)
197         {
198                 self::deleteCacheFile($contact['photo']);
199                 self::deleteCacheFile($contact['thumb']);
200                 self::deleteCacheFile($contact['micro']);
201         }
202
203         /**
204          * Delete a locally cached avatar picture
205          *
206          * @param string $avatar
207          * @return void
208          */
209         private static function deleteCacheFile(string $avatar)
210         {
211                 $localFile = self::getCacheFile($avatar);
212                 if (!empty($localFile)) {
213                         unlink($localFile);
214                         Logger::debug('Unlink avatar', ['avatar' => $avatar]);
215                 }
216         }
217 }