3 * @copyright Copyright (C) 2010-2023, 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;
37 * functions for handling contact avatar caching
41 const BASE_PATH = '/avatar/';
44 * Returns a field array with locally cached avatar pictures
46 * @param array $contact Contact array
47 * @param string $avatar Link to avatar picture
48 * @param bool $force force picture update
51 public static function fetchAvatarContact(array $contact, string $avatar, bool $force = false): 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) || empty($avatar)) {
61 self::deleteCache($contact);
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]);
77 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
78 } catch (\Exception $exception) {
79 Logger::notice('Avatar is invalid', ['avatar' => $avatar, 'exception' => $exception]);
83 $img_str = $fetchResult->getBody();
84 if (empty($img_str)) {
85 Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
89 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
90 if (!$image->isValid()) {
91 Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
95 $filename = self::getFilename($contact['url'], $avatar);
98 $fields['blurhash'] = $image->getBlurHash();
100 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
101 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
102 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
104 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
109 public static function storeAvatarByImage(array $contact, Image $image): array
111 $fields = ['photo' => '', 'thumb' => '', 'micro' => ''];
113 if (!DI::config()->get('system', 'avatar_cache')) {
114 self::deleteCache($contact);
118 if (Network::isLocalLink($contact['avatar']) || empty($contact['avatar'])) {
119 self::deleteCache($contact);
123 $filename = self::getFilename($contact['url'], $contact['avatar']);
126 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
127 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
128 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
133 private static function getFilename(string $url, string $host): string
135 $guid = Item::guidFromUri($url, $host);
137 return substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
138 substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
141 private static function storeAvatarCache(Image $image, string $filename, int $size, int $timestamp): string
143 $image->scaleDown($size);
144 if (is_null($image) || !$image->isValid()) {
148 $path = $filename . $size . '.' . $image->getExt();
150 $basepath = self::basePath();
151 if (empty($basepath)) {
155 $filepath = $basepath . $path;
157 $dirpath = $basepath;
159 DI::profiler()->startRecording('file');
161 // Fetch the permission and group ownership of the "avatar" path and apply to all files
162 $dir_perm = fileperms($dirpath) & 0777;
163 $file_perm = fileperms($dirpath) & 0666;
164 $group = filegroup($dirpath);
166 // Check directory permissions of all parts of the path
167 foreach (explode('/', dirname($filename)) as $part) {
168 $dirpath .= $part . '/';
170 if (!file_exists($dirpath)) {
171 if (!@mkdir($dirpath, $dir_perm) && !file_exists($dirpath)) {
172 Logger::warning('Directory could not be created', ['directory' => $dirpath]);
174 } elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) {
175 Logger::warning('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
178 if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) {
179 Logger::warning('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
183 if (!file_put_contents($filepath, $image->asString())) {
184 Logger::warning('File could not be created', ['file' => $filepath]);
187 $old_perm = fileperms($filepath) & 0666;
188 $old_group = filegroup($filepath);
190 if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
191 Logger::warning('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
194 if (($old_group != $group) && !chgrp($filepath, $group)) {
195 Logger::warning('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
198 DI::profiler()->stopRecording();
200 if (!file_exists($filepath)) {
201 Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
205 return self::baseUrl() . $path . '?ts=' . $timestamp;
209 * Check if the avatar cache file is locally stored
211 * @param string $avatar
214 private static function isCacheFile(string $avatar): bool
216 return !empty(self::getCacheFile($avatar));
220 * Fetch the name of locally cached avatar pictures
222 * @param string $avatar
225 private static function getCacheFile(string $avatar): string
227 $parts = parse_url($avatar);
228 if (empty($parts['host']) || ($parts['host'] != parse_url(self::baseUrl(), PHP_URL_HOST))) {
232 $avatarpath = parse_url(self::baseUrl(), PHP_URL_PATH);
233 $pos = strpos($parts['path'], $avatarpath);
238 $filename = self::basePath() . substr($parts['path'], strlen($avatarpath));
240 DI::profiler()->startRecording('file');
241 $exists = file_exists($filename);
242 DI::profiler()->stopRecording();
251 * Delete locally cached avatar pictures of a contact
253 * @param string $avatar
256 public static function deleteCache(array $contact): bool
258 $existed = (self::isCacheFile($contact['photo']) || self::isCacheFile($contact['thumb']) || self::isCacheFile($contact['micro']));
259 self::deleteCacheFile($contact['photo']);
260 self::deleteCacheFile($contact['thumb']);
261 self::deleteCacheFile($contact['micro']);
267 * Delete a locally cached avatar picture
269 * @param string $avatar
272 private static function deleteCacheFile(string $avatar)
274 $localFile = self::getCacheFile($avatar);
275 if (!empty($localFile)) {
277 Logger::debug('Unlink avatar', ['avatar' => $avatar]);
282 * Fetch the avatar base path
286 private static function basePath(): string
288 $basepath = DI::config()->get('system', 'avatar_cache_path');
289 if (empty($basepath)) {
290 $basepath = DI::basePath() . self::BASE_PATH;
292 $basepath = rtrim($basepath, '/') . '/';
294 if (!file_exists($basepath)) {
295 // We only automatically create the folder when it is in the web root
296 if (strpos($basepath, DI::basePath()) !== 0) {
297 Logger::warning('Base directory does not exist', ['directory' => $basepath]);
300 if (!mkdir($basepath, 0775)) {
301 Logger::warning('Base directory could not be created', ['directory' => $basepath]);
310 * Fetch the avatar base url
314 private static function baseUrl(): string
316 $baseurl = DI::config()->get('system', 'avatar_cache_url');
317 if (!empty($baseurl)) {
318 return rtrim($baseurl, '/') . '/';
321 return DI::baseUrl() . self::BASE_PATH;