3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Contact;
24 use Friendica\Core\Logger;
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;
38 * functions for handling contact avatar caching
42 const BASE_PATH = '/avatar/';
45 * Returns a field array with locally cached avatar pictures
47 * @param array $contact
48 * @param string $avatar
51 public static function fetchAvatarContact(array $contact, string $avatar): array
53 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), 'photo' => '', 'thumb' => '', 'micro' => ''];
55 if (!DI::config()->get('system', 'avatar_cache')) {
56 self::deleteCache($contact);
60 if (Network::isLocalLink($avatar)) {
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]);
75 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
77 $img_str = $fetchResult->getBody();
78 if (empty($img_str)) {
79 Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
83 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
84 if (!$image->isValid()) {
85 Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
89 $filename = self::getFilename($contact['url']);
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);
95 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
100 public static function storeAvatarByImage(array $contact, Image $image): array
102 $fields = ['photo' => '', 'thumb' => '', 'micro' => ''];
104 if (!DI::config()->get('system', 'avatar_cache')) {
105 self::deleteCache($contact);
109 if (Network::isLocalLink($contact['avatar'])) {
113 $filename = self::getFilename($contact['url']);
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);
122 private static function getFilename(string $url)
124 $guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST));
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) . '-';
130 private static function storeAvatarCache(Image $image, string $filename, int $size): string
132 $image->scaleDown($size);
133 if (is_null($image) || !$image->isValid()) {
137 $path = self::BASE_PATH . $filename . $size . '.' . $image->getExt();
139 $filepath = DI::basePath() . $path;
141 $dirpath = DI::basePath() . self::BASE_PATH;
143 DI::profiler()->startRecording('file');
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);
150 // Check directory permissions of all parts of the path
151 foreach (explode('/', dirname($filename)) as $part) {
152 $dirpath .= $part . '/';
154 if (!file_exists($dirpath)) {
155 if (!mkdir($dirpath, $dir_perm)) {
156 Logger::warning('Directory could not be created', ['directory' => $dirpath]);
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]);
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]);
167 if (!file_put_contents($filepath, $image->asString())) {
168 Logger::warning('File could not be created', ['file' => $filepath]);
171 $old_perm = fileperms($filepath) & 0666;
172 $old_group = filegroup($filepath);
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]);
178 if (($old_group != $group) && !chgrp($filepath, $group)) {
179 Logger::notice('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
182 DI::profiler()->stopRecording();
184 if (!file_exists($filepath)) {
185 Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
189 return DI::baseUrl() . $path;
193 * Check if the avatar cache file is locally stored
195 * @param string $avatar
198 private static function isCacheFile(string $avatar): bool
200 return !empty(self::getCacheFile($avatar));
204 * Fetch the name of locally cached avatar pictures
206 * @param string $avatar
209 private static function getCacheFile(string $avatar): string
211 if (empty($avatar) || !Network::isLocalLink($avatar)) {
215 $path = Strings::normaliseLink(DI::baseUrl() . self::BASE_PATH);
217 if (Network::getUrlMatch($path, $avatar) != $path) {
221 $filename = str_replace($path, DI::basePath(). self::BASE_PATH, Strings::normaliseLink($avatar));
223 DI::profiler()->startRecording('file');
224 $exists = file_exists($filename);
225 DI::profiler()->stopRecording();
234 * Delete locally cached avatar pictures of a contact
236 * @param string $avatar
239 public static function deleteCache(array $contact)
241 self::deleteCacheFile($contact['photo']);
242 self::deleteCacheFile($contact['thumb']);
243 self::deleteCacheFile($contact['micro']);
247 * Delete a locally cached avatar picture
249 * @param string $avatar
252 private static function deleteCacheFile(string $avatar)
254 $localFile = self::getCacheFile($avatar);
255 if (!empty($localFile)) {
257 Logger::debug('Unlink avatar', ['avatar' => $avatar]);