]> git.mxchange.org Git - friendica.git/blob - src/Contact/Avatar.php
Escape the "share" as well
[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                         if (!file_exists($dirpath)) {
128                                 if (!mkdir($dirpath, $dir_perm)) {
129                                         Logger::warning('Directory could not be created', ['directory' => $dirpath]);
130                                 }
131                         } elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) {
132                                 Logger::notice('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
133                         }
134
135                         if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) {
136                                 Logger::notice('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
137                         }
138                 }
139
140                 if (!file_put_contents($filepath, $image->asString())) {
141                         Logger::warning('File could not be created', ['file' => $filepath]);
142                 }
143
144                 $old_perm  = fileperms($filepath) & 0666;
145                 $old_group = filegroup($filepath);
146
147                 if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
148                         Logger::notice('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
149                 }
150
151                 if (($old_group != $group) && !chgrp($filepath, $group)) {
152                         Logger::notice('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
153                 }
154
155                 DI::profiler()->stopRecording();
156
157                 if (!file_exists($filepath)) {
158                         Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
159                         return '';
160                 }
161
162                 return DI::baseUrl() . $path;
163         }
164
165         /**
166          * Check if the avatar cache file is locally stored
167          *
168          * @param string $avatar
169          * @return boolean
170          */
171         private static function isCacheFile(string $avatar): bool
172         {
173                 return !empty(self::getCacheFile($avatar));
174         }
175
176         /**
177          * Fetch the name of locally cached avatar pictures
178          *
179          * @param string $avatar
180          * @return string
181          */
182         private static function getCacheFile(string $avatar): string
183         {
184                 if (empty($avatar) || !Network::isLocalLink($avatar)) {
185                         return '';
186                 }
187
188                 $path = Strings::normaliseLink(DI::baseUrl() . self::BASE_PATH);
189
190                 if (Network::getUrlMatch($path, $avatar) != $path) {
191                         return '';
192                 }
193
194                 $filename = str_replace($path, DI::basePath(). self::BASE_PATH, Strings::normaliseLink($avatar));
195
196                 DI::profiler()->startRecording('file');
197                 $exists = file_exists($filename);
198                 DI::profiler()->stopRecording();
199
200                 if (!$exists) {
201                         return '';
202                 }
203                 return $filename;
204         }
205
206         /**
207          * Delete locally cached avatar pictures of a contact
208          *
209          * @param string $avatar
210          * @return void
211          */
212         public static function deleteCache(array $contact)
213         {
214                 self::deleteCacheFile($contact['photo']);
215                 self::deleteCacheFile($contact['thumb']);
216                 self::deleteCacheFile($contact['micro']);
217         }
218
219         /**
220          * Delete a locally cached avatar picture
221          *
222          * @param string $avatar
223          * @return void
224          */
225         private static function deleteCacheFile(string $avatar)
226         {
227                 $localFile = self::getCacheFile($avatar);
228                 if (!empty($localFile)) {
229                         unlink($localFile);
230                         Logger::debug('Unlink avatar', ['avatar' => $avatar]);
231                 }
232         }
233 }