<commit_before><?php
/**
 * @copyright Copyright (C) 2010-2022, the Friendica project
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Friendica\Contact;

use Friendica\Core\Logger;
use Friendica\DI;
use Friendica\Model\Item;
use Friendica\Network\HTTPClient\Client\HttpClientAccept;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Object\Image;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\HTTPSignature;
use Friendica\Util\Images;
use Friendica\Util\Network;
use Friendica\Util\Proxy;
use Friendica\Util\Strings;

/**
 * functions for handling contact avatar caching
 */
class Avatar
{
	const BASE_PATH = '/avatar/';

	/**
	 * Returns a field array with locally cached avatar pictures
	 *
	 * @param array $contact Contact array
	 * @param string $avatar Link to avatar picture
	 * @param bool   $force  force picture update
	 * @return array
	 */
	public static function fetchAvatarContact(array $contact, string $avatar, bool $force = false): array
	{
		$fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), 'photo' => '', 'thumb' => '', 'micro' => ''];

		if (!DI::config()->get('system', 'avatar_cache')) {
			self::deleteCache($contact);
			return $fields;
		}

		if (Network::isLocalLink($avatar) || empty($avatar)) {
			self::deleteCache($contact);
			return $fields;
		}

		if (($avatar != $contact['avatar']) || $force) {
			self::deleteCache($contact);
			Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
		} elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) {
			$fields['photo'] = $contact['photo'];
			$fields['thumb'] = $contact['thumb'];
			$fields['micro'] = $contact['micro'];
			Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
			return $fields;
		}

		$fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);

		$img_str = $fetchResult->getBody();
		if (empty($img_str)) {
			Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
			return $fields;
		}

		$image = new Image($img_str, Images::getMimeTypeByData($img_str));
		if (!$image->isValid()) {
			Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
			return $fields;
		}

		$filename  = self::getFilename($contact['url']);
		$timestamp = time();

		$fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
		$fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
		$fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);

		Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);

		return $fields;
	}

	public static function storeAvatarByImage(array $contact, Image $image): array
	{
		$fields = ['photo' => '', 'thumb' => '', 'micro' => ''];

		if (!DI::config()->get('system', 'avatar_cache')) {
			self::deleteCache($contact);
			return $fields;
		}

		if (Network::isLocalLink($contact['avatar']) || empty($contact['avatar'])) {
			self::deleteCache($contact);
			return $fields;
		}

		$filename  = self::getFilename($contact['url']);
		$timestamp = time();

		$fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
		$fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
		$fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);

		return $fields;
	}

	private static function getFilename(string $url)
	{
		$guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST));

		return substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
			substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
	}

	private static function storeAvatarCache(Image $image, string $filename, int $size, int $timestamp): string
	{
		$image->scaleDown($size);
		if (is_null($image) || !$image->isValid()) {
			return '';
		}

		$path = self::BASE_PATH . $filename . $size . '.' . $image->getExt();

		$filepath = DI::basePath() . $path;

		$dirpath = DI::basePath() . self::BASE_PATH;

		DI::profiler()->startRecording('file');

		// Fetch the permission and group ownership of the "avatar" path and apply to all files
		$dir_perm  = fileperms($dirpath) & 0777;
		$file_perm = fileperms($dirpath) & 0666;
		$group     = filegroup($dirpath);<commit_msg>Ensure that the avatar base path exists<commit_after><?php
/**
 * @copyright Copyright (C) 2010-2022, the Friendica project
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Friendica\Contact;

use Friendica\Core\Logger;
use Friendica\DI;
use Friendica\Model\Item;
use Friendica\Network\HTTPClient\Client\HttpClientAccept;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Object\Image;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\HTTPSignature;
use Friendica\Util\Images;
use Friendica\Util\Network;
use Friendica\Util\Proxy;
use Friendica\Util\Strings;

/**
 * functions for handling contact avatar caching
 */
class Avatar
{
	const BASE_PATH = '/avatar/';

	/**
	 * Returns a field array with locally cached avatar pictures
	 *
	 * @param array $contact Contact array
	 * @param string $avatar Link to avatar picture
	 * @param bool   $force  force picture update
	 * @return array
	 */
	public static function fetchAvatarContact(array $contact, string $avatar, bool $force = false): array
	{
		$fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), 'photo' => '', 'thumb' => '', 'micro' => ''];

		if (!DI::config()->get('system', 'avatar_cache')) {
			self::deleteCache($contact);
			return $fields;
		}

		if (Network::isLocalLink($avatar) || empty($avatar)) {
			self::deleteCache($contact);
			return $fields;
		}

		if (($avatar != $contact['avatar']) || $force) {
			self::deleteCache($contact);
			Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
		} elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) {
			$fields['photo'] = $contact['photo'];
			$fields['thumb'] = $contact['thumb'];
			$fields['micro'] = $contact['micro'];
			Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
			return $fields;
		}

		$fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);

		$img_str = $fetchResult->getBody();
		if (empty($img_str)) {
			Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
			return $fields;
		}

		$image = new Image($img_str, Images::getMimeTypeByData($img_str));
		if (!$image->isValid()) {
			Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
			return $fields;
		}

		$filename  = self::getFilename($contact['url']);
		$timestamp = time();

		$fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
		$fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
		$fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);

		Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);

		return $fields;
	}

	public static function storeAvatarByImage(array $contact, Image $image): array
	{
		$fields = ['photo' => '', 'thumb' => '', 'micro' => ''];

		if (!DI::config()->get('system', 'avatar_cache')) {
			self::deleteCache($contact);
			return $fields;
		}

		if (Network::isLocalLink($contact['avatar']) || empty($contact['avatar'])) {
			self::deleteCache($contact);
			return $fields;
		}

		$filename  = self::getFilename($contact['url']);
		$timestamp = time();

		$fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL, $timestamp);
		$fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
		$fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);

		return $fields;
	}

	private static function getFilename(string $url)
	{
		$guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST));

		return substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
			substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
	}

	private static function storeAvatarCache(Image $image, string $filename, int $size, int $timestamp): string
	{
		$image->scaleDown($size);
		if (is_null($image) || !$image->isValid()) {
			return '';
		}

		$path = self::BASE_PATH . $filename . $size . '.' . $image->getExt();

		$filepath = DI::basePath() . $path;

		$dirpath = DI::basePath() . self::BASE_PATH;

		DI::profiler()->startRecording('file');

		if (!file_exists($dirpath)) {
			if (!mkdir($dirpath, 0775)) {
				Logger::warning('Base directory could not be created', ['directory' => $dirpath]);
				return '';
			}
		}

		// Fetch the permission and group ownership of the "avatar" path and apply to all files
		$dir_perm  = fileperms($dirpath) & 0777;
		$file_perm = fileperms($dirpath) & 0666;
		$group     = filegroup($dirpath);
{'fraction_non_alphanumeric': 0.17641588393936575, 'fraction_numerical': 0.006881800427787594, 'mean_word_length': 4.76931330472103, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 56, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1643602', 'n_tokens_mistral': 3722, 'n_tokens_neox': 3392, 'n_words': 889}