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;
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]);
76 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
78 $img_str = $fetchResult->getBody();
79 if (empty($img_str)) {
80 Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
84 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
85 if (!$image->isValid()) {
86 Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
90 $filename = self::getFilename($contact['url']);
93 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
94 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
95 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
97 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
102 public static function storeAvatarByImage(array $contact, Image $image): array
104 $fields = ['photo' => '', 'thumb' => '', 'micro' => ''];
106 if (!DI::config()->get('system', 'avatar_cache')) {
107 self::deleteCache($contact);
111 if (Network::isLocalLink($contact['avatar']) || empty($contact['avatar'])) {
112 self::deleteCache($contact);
116 $filename = self::getFilename($contact['url']);
119 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
120 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
121 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
126 private static function getFilename(string $url): string
128 $guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST));
130 return substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
131 substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
134 private static function storeAvatarCache(Image $image, string $filename, int $size, int $timestamp): string
136 $image->scaleDown($size);
137 if (is_null($image) || !$image->isValid()) {
141 $path = $filename . $size . '.' . $image->getExt();
143 $basepath = self::basePath();
144 if (empty($basepath)) {
148 $filepath = $basepath . $path;
150 $dirpath = $basepath;
152 DI::profiler()->startRecording('file');
154 // Fetch the permission and group ownership of the "avatar" path and apply to all files
155 $dir_perm = fileperms($dirpath) & 0777;
156 $file_perm = fileperms($dirpath) & 0666;
157 $group = filegroup($dirpath);
159 // Check directory permissions of all parts of the path
160 foreach (explode('/', dirname($filename)) as $part) {
161 $dirpath .= $part . '/';
163 if (!file_exists($dirpath)) {
164 if (!@mkdir($dirpath, $dir_perm) && !file_exists($dirpath)) {
165 Logger::warning('Directory could not be created', ['directory' => $dirpath]);
167 } elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) {
168 Logger::warning('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
171 if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) {
172 Logger::warning('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
176 if (!file_put_contents($filepath, $image->asString())) {
177 Logger::warning('File could not be created', ['file' => $filepath]);
180 $old_perm = fileperms($filepath) & 0666;
181 $old_group = filegroup($filepath);
183 if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
184 Logger::warning('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
187 if (($old_group != $group) && !chgrp($filepath, $group)) {
188 Logger::warning('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
191 DI::profiler()->stopRecording();
193 if (!file_exists($filepath)) {
194 Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
198 return self::baseUrl() . $path . '?ts=' . $timestamp;
202 * Check if the avatar cache file is locally stored
204 * @param string $avatar
207 private static function isCacheFile(string $avatar): bool
209 return !empty(self::getCacheFile($avatar));
213 * Fetch the name of locally cached avatar pictures
215 * @param string $avatar
218 private static function getCacheFile(string $avatar): string
220 $parts = parse_url($avatar);
221 if (empty($parts['host']) || ($parts['host'] != parse_url(self::baseUrl(), PHP_URL_HOST))) {
225 $avatarpath = parse_url(self::baseUrl(), PHP_URL_PATH);
226 $pos = strpos($parts['path'], $avatarpath);
231 $filename = self::basePath() . substr($parts['path'], strlen($avatarpath));
233 DI::profiler()->startRecording('file');
234 $exists = file_exists($filename);
235 DI::profiler()->stopRecording();
244 * Delete locally cached avatar pictures of a contact
246 * @param string $avatar
249 public static function deleteCache(array $contact)
251 self::deleteCacheFile($contact['photo']);
252 self::deleteCacheFile($contact['thumb']);
253 self::deleteCacheFile($contact['micro']);
257 * Delete a locally cached avatar picture
259 * @param string $avatar
262 private static function deleteCacheFile(string $avatar)
264 $localFile = self::getCacheFile($avatar);
265 if (!empty($localFile)) {
267 Logger::debug('Unlink avatar', ['avatar' => $avatar]);
272 * Fetch the avatar base path
276 private static function basePath(): string
278 $basepath = DI::config()->get('system', 'avatar_cache_path');
279 if (empty($basepath)) {
280 $basepath = DI::basePath() . self::BASE_PATH;
282 $basepath = rtrim($basepath, '/') . '/';
284 if (!file_exists($basepath)) {
285 // We only automatically create the folder when it is in the web root
286 if (strpos($basepath, DI::basePath()) !== 0) {
287 Logger::warning('Base directory does not exist', ['directory' => $basepath]);
290 if (!mkdir($basepath, 0775)) {
291 Logger::warning('Base directory could not be created', ['directory' => $basepath]);
300 * Fetch the avatar base url
304 private static function baseUrl(): string
306 $baseurl = DI::config()->get('system', 'avatar_cache_url');
307 if (!empty($baseurl)) {
308 return rtrim($baseurl, '/') . '/';
311 return DI::baseUrl() . self::BASE_PATH;