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 $guid = Item::guidFromUri($contact['url'], parse_url($contact['url'], PHP_URL_HOST));
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) . '-';
80 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
82 $img_str = $fetchResult->getBody();
83 if (empty($img_str)) {
84 Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
88 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
89 if (!$image->isValid()) {
90 Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
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);
98 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
103 private static function storeAvatarCache(Image $image, string $filename, int $size): string
105 $image->scaleDown($size);
106 if (is_null($image) || !$image->isValid()) {
110 $path = self::BASE_PATH . $filename . $size . '.' . $image->getExt();
112 $filepath = DI::basePath() . $path;
114 $dirpath = DI::basePath() . self::BASE_PATH;
116 DI::profiler()->startRecording('file');
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);
123 // Check directory permissions of all parts of the path
124 foreach (explode('/', dirname($filename)) as $part) {
125 $dirpath .= $part . '/';
127 $old_perm = fileperms($dirpath) & 0777;
128 $old_group = filegroup($dirpath);
130 if (!file_exists($dirpath)) {
131 if (!mkdir($dirpath, $dir_perm)) {
132 Logger::warning('Directory could not be created', ['directory' => $dirpath]);
134 } elseif (($old_perm != $dir_perm) && !chmod($dirpath, $dir_perm)) {
135 Logger::notice('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
138 if (($old_group != $group) && !chgrp($dirpath, $group)) {
139 Logger::notice('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
143 if (!file_put_contents($filepath, $image->asString())) {
144 Logger::warning('File could not be created', ['file' => $filepath]);
147 $old_perm = fileperms($filepath) & 0666;
148 $old_group = filegroup($filepath);
150 if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
151 Logger::notice('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
154 if (($old_group != $group) && !chgrp($filepath, $group)) {
155 Logger::notice('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
158 DI::profiler()->stopRecording();
160 if (!file_exists($filepath)) {
161 Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]);
165 return DI::baseUrl() . $path;
169 * Check if the avatar cache file is locally stored
171 * @param string $avatar
174 private static function isCacheFile(string $avatar): bool
176 return !empty(self::getCacheFile($avatar));
180 * Fetch the name of locally cached avatar pictures
182 * @param string $avatar
185 private static function getCacheFile(string $avatar): string
187 if (empty($avatar) || !Network::isLocalLink($avatar)) {
191 $path = Strings::normaliseLink(DI::baseUrl() . self::BASE_PATH);
193 if (Network::getUrlMatch($path, $avatar) != $path) {
197 $filename = str_replace($path, DI::basePath(). self::BASE_PATH, Strings::normaliseLink($avatar));
199 DI::profiler()->startRecording('file');
200 $exists = file_exists($filename);
201 DI::profiler()->stopRecording();
210 * Delete locally cached avatar pictures of a contact
212 * @param string $avatar
215 public static function deleteCache(array $contact)
217 self::deleteCacheFile($contact['photo']);
218 self::deleteCacheFile($contact['thumb']);
219 self::deleteCacheFile($contact['micro']);
223 * Delete a locally cached avatar picture
225 * @param string $avatar
228 private static function deleteCacheFile(string $avatar)
230 $localFile = self::getCacheFile($avatar);
231 if (!empty($localFile)) {
233 Logger::debug('Unlink avatar', ['avatar' => $avatar]);