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 Contact array
48 * @param string $avatar Link to avatar picture
49 * @param bool $force force picture update
52 public static function fetchAvatarContact(array $contact, string $avatar, bool $force = false): array
54 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), 'photo' => '', 'thumb' => '', 'micro' => ''];
56 if (!DI::config()->get('system', 'avatar_cache')) {
57 self::deleteCache($contact);
61 if (Network::isLocalLink($avatar) || empty($avatar)) {
62 self::deleteCache($contact);
66 if (($avatar != $contact['avatar']) || $force) {
67 self::deleteCache($contact);
68 Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
69 } elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) {
70 $fields['photo'] = $contact['photo'];
71 $fields['thumb'] = $contact['thumb'];
72 $fields['micro'] = $contact['micro'];
73 Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
77 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
79 $img_str = $fetchResult->getBody();
80 if (empty($img_str)) {
81 Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
85 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
86 if (!$image->isValid()) {
87 Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
91 $filename = self::getFilename($contact['url']);
94 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
95 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
96 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
98 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
103 public static function storeAvatarByImage(array $contact, Image $image): array
105 $fields = ['photo' => '', 'thumb' => '', 'micro' => ''];
107 if (!DI::config()->get('system', 'avatar_cache')) {
108 self::deleteCache($contact);
112 if (Network::isLocalLink($contact['avatar']) || empty($contact['avatar'])) {
113 self::deleteCache($contact);
117 $filename = self::getFilename($contact['url']);
120 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
121 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
122 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
127 private static function getFilename(string $url)
129 $guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST));
131 return substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
132 substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
135 private static function storeAvatarCache(Image $image, string $filename, int $size, int $timestamp): string
137 $image->scaleDown($size);
138 if (is_null($image) || !$image->isValid()) {
142 $path = self::BASE_PATH . $filename . $size . '.' . $image->getExt();
144 $filepath = DI::basePath() . $path;
146 $dirpath = DI::basePath() . self::BASE_PATH;
148 DI::profiler()->startRecording('file');
150 // Fetch the permission and group ownership of the "avatar" path and apply to all files
151 $dir_perm = fileperms($dirpath) & 0777;
152 $file_perm = fileperms($dirpath) & 0666;
153 $group = filegroup($dirpath);
155 // Check directory permissions of all parts of the path
156 foreach (explode('/', dirname($filename)) as $part) {
157 $dirpath .= $part . '/';
159 if (!file_exists($dirpath)) {
160 if (!mkdir($dirpath, $dir_perm)) {
161 Logger::warning('Directory could not be created', ['directory' => $dirpath]);
163 } elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) {
164 Logger::notice('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
167 if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) {
168 Logger::notice('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
172 if (!file_put_contents($filepath, $image->asString())) {
173 Logger::warning('File could not be created', ['file' => $filepath]);
176 $old_perm = fileperms($filepath) & 0666;
177 $old_group = filegroup($filepath);
179 if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
180 Logger::notice('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
183 if (($old_group != $group) && !chgrp($filepath, $group)) {
184 Logger::notice('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
187 DI::profiler()->stopRecording();
189 if (!file_exists($filepath)) {
190 Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
194 return DI::baseUrl() . $path . '?ts=' . $timestamp;
198 * Check if the avatar cache file is locally stored
200 * @param string $avatar
203 private static function isCacheFile(string $avatar): bool
205 return !empty(self::getCacheFile($avatar));
209 * Fetch the name of locally cached avatar pictures
211 * @param string $avatar
214 private static function getCacheFile(string $avatar): string
216 $parts = parse_url($avatar);
217 if (empty($parts['host']) || ($parts['host'] != DI::baseUrl()->getHostname())) {
221 $pos = strpos($parts['path'], DI::baseUrl()->getUrlPath() . self::BASE_PATH);
226 $filename = DI::basePath() . $parts['path'];
228 DI::profiler()->startRecording('file');
229 $exists = file_exists($filename);
230 DI::profiler()->stopRecording();
239 * Delete locally cached avatar pictures of a contact
241 * @param string $avatar
244 public static function deleteCache(array $contact)
246 self::deleteCacheFile($contact['photo']);
247 self::deleteCacheFile($contact['thumb']);
248 self::deleteCacheFile($contact['micro']);
252 * Delete a locally cached avatar picture
254 * @param string $avatar
257 private static function deleteCacheFile(string $avatar)
259 $localFile = self::getCacheFile($avatar);
260 if (!empty($localFile)) {
262 Logger::debug('Unlink avatar', ['avatar' => $avatar]);