Files
firefly-iii/app/Support/Twig/General.php

394 lines
14 KiB
PHP
Raw Permalink Normal View History

2015-05-01 20:17:06 +02:00
<?php
2022-12-29 19:42:26 +01:00
/**
* General.php
2020-02-16 13:56:52 +01:00
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* 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.
2017-10-21 08:40:00 +02:00
*
* This program is distributed in the hope that it will be useful,
2017-10-21 08:40:00 +02:00
* 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.
2017-10-21 08:40:00 +02:00
*
* 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/>.
*/
declare(strict_types=1);
2015-05-01 20:17:06 +02:00
2015-05-01 22:44:35 +02:00
namespace FireflyIII\Support\Twig;
2015-05-01 20:17:06 +02:00
2015-05-17 10:01:47 +02:00
use Carbon\Carbon;
2015-05-01 20:17:06 +02:00
use FireflyIII\Models\Account;
2019-04-16 16:20:46 +02:00
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
2018-07-31 19:28:56 +02:00
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Support\Facades\Amount;
2025-12-26 20:02:09 +01:00
use FireflyIII\Support\Facades\FireflyConfig;
use FireflyIII\Support\Facades\Steam;
2020-08-27 20:22:52 +02:00
use FireflyIII\Support\Search\OperatorQuerySearch;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
2025-05-24 17:07:12 +02:00
use Illuminate\Support\Facades\Route;
2025-09-02 18:38:34 +02:00
use League\CommonMark\GithubFlavoredMarkdownConverter;
use Override;
2019-12-28 09:44:56 +01:00
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
2025-05-27 17:06:15 +02:00
use function Safe\parse_url;
2015-05-01 20:17:06 +02:00
/**
2017-11-15 12:25:49 +01:00
* Class TwigSupport.
2015-05-01 20:17:06 +02:00
*/
2019-12-28 09:44:56 +01:00
class General extends AbstractExtension
2015-05-01 20:17:06 +02:00
{
#[Override]
2016-02-06 10:15:07 +01:00
public function getFilters(): array
2015-05-01 20:17:06 +02:00
{
2026-01-23 15:09:50 +01:00
return [$this->balance(), $this->formatFilesize(), $this->mimeIcon(), $this->markdown(), $this->phpHostName()];
2015-06-06 17:40:41 +02:00
}
2025-09-26 06:05:37 +02:00
#[Override]
public function getFunctions(): array
{
return [
$this->phpdate(),
$this->activeRouteStrict(),
$this->activeRoutePartial(),
$this->activeRoutePartialObjectType(),
$this->menuOpenRoutePartial(),
$this->formatDate(),
$this->getMetaField(),
$this->hasRole(),
$this->getRootSearchOperator(),
$this->carbonize(),
$this->fireflyIIIConfig(),
2025-09-26 06:05:37 +02:00
];
}
/**
* Will return "active" when a part of the route matches the argument.
* ie. "accounts" will match "accounts.index".
*/
protected function activeRoutePartial(): TwigFunction
{
2026-01-23 15:09:50 +01:00
return new TwigFunction('activeRoutePartial', static function (): string {
$args = func_get_args();
$route = $args[0]; // name of the route.
$name = Route::getCurrentRoute()->getName() ?? '';
2026-01-23 15:09:50 +01:00
if (str_contains($name, $route)) {
return 'active';
2025-09-26 06:05:37 +02:00
}
2026-01-23 15:09:50 +01:00
return '';
});
2025-09-26 06:05:37 +02:00
}
/**
* This function will return "active" when the current route matches the first argument (even partly)
* but, the variable $objectType has been set and matches the second argument.
*/
protected function activeRoutePartialObjectType(): TwigFunction
{
return new TwigFunction(
'activeRoutePartialObjectType',
2025-11-09 09:08:03 +01:00
static function (array $context): string {
2025-09-26 06:05:37 +02:00
[, $route, $objectType] = func_get_args();
$activeObjectType = $context['objectType'] ?? false;
2025-09-26 06:05:37 +02:00
2026-01-23 15:09:50 +01:00
if ($objectType === $activeObjectType && false !== stripos((string) Route::getCurrentRoute()->getName(), (string) $route)) {
2025-09-26 06:05:37 +02:00
return 'active';
}
return '';
},
['needs_context' => true]
);
}
/**
* Will return "active" when the current route matches the given argument
* exactly.
*/
protected function activeRouteStrict(): TwigFunction
{
2026-01-23 15:09:50 +01:00
return new TwigFunction('activeRouteStrict', static function (): string {
$args = func_get_args();
$route = $args[0]; // name of the route.
2025-09-26 06:05:37 +02:00
2026-01-23 15:09:50 +01:00
if (\Route::getCurrentRoute()->getName() === $route) {
return 'active';
2025-09-26 06:05:37 +02:00
}
2026-01-23 15:09:50 +01:00
return '';
});
2025-09-26 06:05:37 +02:00
}
2023-06-21 12:34:58 +02:00
/**
* Show account balance. Only used on the front page of Firefly III.
*/
protected function balance(): TwigFilter
{
return new TwigFilter('balance', static function (?Account $account): string {
2026-01-23 15:09:50 +01:00
if (!$account instanceof Account) {
return '0';
}
2023-12-20 19:35:52 +01:00
2026-01-23 15:09:50 +01:00
/** @var Carbon $date */
$date = now();
2025-11-08 19:23:31 +01:00
2026-01-23 15:09:50 +01:00
// get the date from the current session. If it's in the future, keep `now()`.
/** @var Carbon $session */
$session = clone session('end', today(config('app.timezone'))->endOfMonth());
2026-01-23 15:09:50 +01:00
if ($session->lt($date)) {
$date = $session->copy();
$date->endOfDay();
}
Log::debug(sprintf('twig balance: Call finalAccountBalance with date/time "%s"', $date->toIso8601String()));
// 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized.
$info = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id];
2026-01-23 15:09:50 +01:00
// $info = Steam::finalAccountBalance($account, $date);
$currency = Steam::getAccountCurrency($account);
$primary = Amount::getPrimaryCurrency();
$convertToPrimary = Amount::convertToPrimary();
$usePrimary = $convertToPrimary && $primary->id !== $currency->id;
$currency ??= $primary;
2026-01-23 15:09:50 +01:00
$strings = [];
foreach ($info as $key => $balance) {
if ('balance' === $key) {
// balance in account currency.
if (!$usePrimary) {
$strings[] = Amount::formatAnything($currency, $balance, false);
}
2026-01-23 15:09:50 +01:00
continue;
2024-07-31 13:09:55 +02:00
}
2026-01-23 15:09:50 +01:00
if ('pc_balance' === $key) {
// balance in primary currency.
if ($usePrimary) {
$strings[] = Amount::formatAnything($primary, $balance, false);
}
2026-01-23 15:09:50 +01:00
continue;
}
// for multi currency accounts.
if ($usePrimary && $key !== $primary->code) {
$strings[] = Amount::formatAnything(Amount::getTransactionCurrencyByCode($key), $balance, false);
}
2023-06-21 12:34:58 +02:00
}
2026-01-23 15:09:50 +01:00
return implode(', ', $strings);
// return \FireflyIII\Support\Facades\Steam::balance($account, $date);
});
2023-06-21 12:34:58 +02:00
}
2025-09-26 06:05:37 +02:00
protected function carbonize(): TwigFunction
2023-06-21 12:34:58 +02:00
{
return new TwigFunction('carbonize', static fn (string $date): Carbon => new Carbon($date, config('app.timezone')));
2023-06-21 12:34:58 +02:00
}
/**
2025-09-26 06:05:37 +02:00
* Formats a string as a thing by converting it to a Carbon first.
2023-06-21 12:34:58 +02:00
*/
2025-09-26 06:05:37 +02:00
protected function formatDate(): TwigFunction
2023-06-21 12:34:58 +02:00
{
2026-01-23 15:09:50 +01:00
return new TwigFunction('formatDate', static function (string $date, string $format): string {
$carbon = new Carbon($date);
2023-06-21 12:34:58 +02:00
2026-01-23 15:09:50 +01:00
return $carbon->isoFormat($format);
});
2023-06-21 12:34:58 +02:00
}
/**
2025-09-26 06:05:37 +02:00
* Used to convert 1024 to 1kb etc.
2023-06-21 12:34:58 +02:00
*/
2025-09-26 06:05:37 +02:00
protected function formatFilesize(): TwigFilter
2023-06-21 12:34:58 +02:00
{
2026-01-23 15:09:50 +01:00
return new TwigFilter('filesize', static function (int $size): string {
// less than one GB, more than one MB
if ($size < (1024 * 1024 * 2014) && $size >= (1024 * 1024)) {
return round($size / (1024 * 1024), 2).' MB';
2026-01-23 15:09:50 +01:00
}
2023-06-21 12:34:58 +02:00
2026-01-23 15:09:50 +01:00
// less than one MB
if ($size < (1024 * 1024)) {
return round($size / 1024, 2).' KB';
2023-06-21 12:34:58 +02:00
}
2026-01-23 15:09:50 +01:00
return $size.' bytes';
2026-01-23 15:09:50 +01:00
});
2023-06-21 12:34:58 +02:00
}
/**
2025-09-26 06:05:37 +02:00
* TODO Remove me when v2 hits.
2023-06-21 12:34:58 +02:00
*/
2025-09-26 06:05:37 +02:00
protected function getMetaField(): TwigFunction
2023-06-21 12:34:58 +02:00
{
2026-01-23 15:09:50 +01:00
return new TwigFunction('accountGetMetaField', static function (Account $account, string $field): string {
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
$result = $repository->getMetaValue($account, $field);
if (null === $result) {
return '';
2025-09-26 06:05:37 +02:00
}
2026-01-23 15:09:50 +01:00
return $result;
});
2023-06-21 12:34:58 +02:00
}
2025-09-26 06:05:37 +02:00
protected function getRootSearchOperator(): TwigFunction
2023-06-21 12:34:58 +02:00
{
2026-01-23 15:09:50 +01:00
return new TwigFunction('getRootSearchOperator', static function (string $operator): string {
$result = OperatorQuerySearch::getRootOperator($operator);
2023-06-21 12:34:58 +02:00
2026-01-23 15:09:50 +01:00
return str_replace('-', 'not_', $result);
});
2023-06-21 12:34:58 +02:00
}
2023-05-29 13:56:55 +02:00
/**
2025-09-26 06:05:37 +02:00
* Will return true if the user is of role X.
2023-05-29 13:56:55 +02:00
*/
2025-09-26 06:05:37 +02:00
protected function hasRole(): TwigFunction
2023-05-29 13:56:55 +02:00
{
2026-01-23 15:09:50 +01:00
return new TwigFunction('hasRole', static function (string $role): bool {
$repository = app(UserRepositoryInterface::class);
2026-01-23 15:09:50 +01:00
return $repository->hasRole(auth()->user(), $role);
});
2023-05-29 13:56:55 +02:00
}
2025-09-26 06:05:37 +02:00
protected function markdown(): TwigFilter
2023-05-29 13:56:55 +02:00
{
2025-09-26 06:05:37 +02:00
return new TwigFilter(
'markdown',
static function (string $text): string {
2026-01-23 15:09:50 +01:00
$converter = new GithubFlavoredMarkdownConverter(['allow_unsafe_links' => false, 'max_nesting_level' => 5, 'html_input' => 'escape']);
return (string) $converter->convert($text);
2023-05-29 13:56:55 +02:00
},
2025-09-26 06:05:37 +02:00
['is_safe' => ['html']]
2023-05-29 13:56:55 +02:00
);
}
/**
2023-06-21 12:34:58 +02:00
* Will return "menu-open" when a part of the route matches the argument.
* ie. "accounts" will match "accounts.index".
2023-05-29 13:56:55 +02:00
*/
2023-06-21 12:34:58 +02:00
protected function menuOpenRoutePartial(): TwigFunction
2023-05-29 13:56:55 +02:00
{
2026-01-23 15:09:50 +01:00
return new TwigFunction('menuOpenRoutePartial', static function (): string {
$args = func_get_args();
$route = $args[0]; // name of the route.
$name = Route::getCurrentRoute()->getName() ?? '';
2026-01-23 15:09:50 +01:00
if (str_contains($name, $route)) {
return 'menu-open';
2023-05-29 13:56:55 +02:00
}
2026-01-23 15:09:50 +01:00
return '';
});
2023-05-29 13:56:55 +02:00
}
/**
2025-09-26 06:05:37 +02:00
* Show icon with attachment.
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
2023-05-29 13:56:55 +02:00
*/
2025-09-26 06:05:37 +02:00
protected function mimeIcon(): TwigFilter
2023-05-29 13:56:55 +02:00
{
2025-09-26 06:05:37 +02:00
return new TwigFilter(
'mimeIcon',
static fn (string $string): string => match ($string) {
'application/pdf' => 'fa-file-pdf-o',
2026-01-23 15:09:50 +01:00
'image/webp',
'image/png',
'image/jpeg',
'image/svg+xml',
'image/heic',
'image/heic-sequence',
'application/vnd.oasis.opendocument.image' => 'fa-file-image-o',
2026-01-23 15:09:50 +01:00
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'application/x-iwork-pages-sffpages',
'application/vnd.sun.xml.writer',
'application/vnd.sun.xml.writer.template',
'application/vnd.sun.xml.writer.global',
'application/vnd.stardivision.writer',
'application/vnd.stardivision.writer-global',
'application/vnd.oasis.opendocument.text',
'application/vnd.oasis.opendocument.text-template',
'application/vnd.oasis.opendocument.text-web',
'application/vnd.oasis.opendocument.text-master' => 'fa-file-word-o',
2026-01-23 15:09:50 +01:00
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'application/vnd.sun.xml.calc',
'application/vnd.sun.xml.calc.template',
'application/vnd.stardivision.calc',
'application/vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.spreadsheet-template' => 'fa-file-excel-o',
2026-01-23 15:09:50 +01:00
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.presentationml.template',
'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'application/vnd.sun.xml.impress',
'application/vnd.sun.xml.impress.template',
'application/vnd.stardivision.impress',
'application/vnd.oasis.opendocument.presentation',
'application/vnd.oasis.opendocument.presentation-template' => 'fa-file-powerpoint-o',
2026-01-23 15:09:50 +01:00
'application/vnd.sun.xml.draw',
'application/vnd.sun.xml.draw.template',
'application/vnd.stardivision.draw',
'application/vnd.oasis.opendocument.chart' => 'fa-paint-brush',
2026-01-23 15:09:50 +01:00
'application/vnd.oasis.opendocument.graphics',
'application/vnd.oasis.opendocument.graphics-template',
'application/vnd.sun.xml.math',
'application/vnd.stardivision.math',
'application/vnd.oasis.opendocument.formula',
'application/vnd.oasis.opendocument.database' => 'fa-calculator',
default => 'fa-file-o'
2025-09-26 06:05:37 +02:00
},
['is_safe' => ['html']]
2023-05-29 13:56:55 +02:00
);
}
/**
2025-09-26 06:05:37 +02:00
* Show URL host name
2023-05-29 13:56:55 +02:00
*/
2025-09-26 06:05:37 +02:00
protected function phpHostName(): TwigFilter
2023-05-29 13:56:55 +02:00
{
2026-01-23 15:09:50 +01:00
return new TwigFilter('phphost', static function (string $string): string {
$proto = parse_url($string, PHP_URL_SCHEME);
$host = parse_url($string, PHP_URL_HOST);
if (is_array($host)) {
$host = implode(' ', $host);
2023-05-29 13:56:55 +02:00
}
2026-01-23 15:09:50 +01:00
if (is_array($proto)) {
$proto = implode(' ', $proto);
}
return e(sprintf('%s://%s', $proto, $host));
});
2023-05-29 13:56:55 +02:00
}
/**
2025-09-26 06:05:37 +02:00
* Basic example thing for some views.
2023-05-29 13:56:55 +02:00
*/
2025-09-26 06:05:37 +02:00
protected function phpdate(): TwigFunction
2020-08-27 20:22:52 +02:00
{
2026-01-23 15:09:50 +01:00
return new TwigFunction('phpdate', date(...));
2020-08-27 20:22:52 +02:00
}
2025-12-26 20:02:09 +01:00
private function fireflyIIIConfig()
{
return new TwigFunction('fireflyiiiconfig', static fn (string $string, mixed $default): mixed => FireflyConfig::get($string, $default)->data);
2025-12-26 20:02:09 +01:00
}
}