<commit_before><?php
/**
 * General.php
 * Copyright (c) 2019 <EMAIL>
 *
 * 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.
 *
 * 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/>.
 */
declare(strict_types=1);

namespace FireflyIII\Support\Twig;

use Carbon\Carbon;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Support\Search\OperatorQuerySearch;
use League\CommonMark\CommonMarkConverter;
use League\CommonMark\Environment;
use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
use Route;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

/**
 * Class TwigSupport.
 */
class General extends AbstractExtension
{
    /**
     * @return array
     */
    public function getFilters(): array
    {
        return [
            $this->balance(),
            $this->formatFilesize(),
            $this->mimeIcon(),
            $this->markdown(),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions(): array
    {
        return [
            $this->phpdate(),
            $this->activeRouteStrict(),
            $this->activeRoutePartial(),
            $this->activeRoutePartialObjectType(),
            $this->menuOpenRoutePartial(),
            $this->formatDate(),
            $this->getMetaField(),
            $this->hasRole(),
            $this->getRootSearchOperator(),
        ];
    }

    protected function getRootSearchOperator(): TwigFunction
    {
        return new TwigFunction(
            'getRootSearchOperator',
            static function (string $operator): string {
                return OperatorQuerySearch::getRootOperator($operator);
            }
        );
    }

    /**
     * Will return "active" when a part of the route matches the argument.
     * ie. "accounts" will match "accounts.index".
     *
     * @return TwigFunction
     */
    protected function activeRoutePartial(): TwigFunction
    {
        return new TwigFunction(
            'activeRoutePartial',
            static function (): string {
                $args  = func_get_args();
                $route = $args[0]; // name of the route.
                $name  = Route::getCurrentRoute()->getName() ?? '';
                if (!(false === strpos($name, $route))) {
                    return 'active';
                }

                return '';
            }
        );
    }

    /**
     * Will return "menu-open" when a part of the route matches the argument.
     * ie. "accounts" will match "accounts.index".
     *
     * @return TwigFunction
     */
    protected function menuOpenRoutePartial(): TwigFunction
    {
        return new TwigFunction(
            'menuOpenRoutePartial',
            static function (): string {
                $args  = func_get_args();
                $route = $args[0]; // name of the route.
                $name  = Route::getCurrentRoute()->getName() ?? '';
                if (!(false === strpos($name, $route))) {
                    return 'menu-open';
                }

                return '';
            }
        );
    }

    /**
     * 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.
     *
     * @return TwigFunction
     */
    protected function activeRoutePartialObjectType(): TwigFunction
    {
        return new TwigFunction(
            'activeRoutePartialObjectType',
            static function ($context): string {
                [, $route, $objectType] = func_get_args();
                $activeObjectType = $context['objectType'] ?? false;

                if ($objectType === $activeObjectType && !(false === stripos(Route::getCurrentRoute()->getName(), $route))) {
                    return 'active';
                }

                return '';
            },
            ['needs_context' => true]
        );
    }

    /**
     * Will return "active" when the current route matches the given argument
     * exactly.
     *
     * @return TwigFunction
     */
    protected function activeRouteStrict(): TwigFunction
    {
        return new TwigFunction(
            'activeRouteStrict',
            static function (): string {
                $args  = func_get_args();
                $route = $args[0]; // name of the route.

                if (Route::getCurrentRoute()->getName() === $route) {
                    return 'active';
                }

                return '';
            }
        );
    }

    /**
     * Show account balance. Only used on the front page of Firefly III.
     *
     * @return TwigFilter
     */
    protected function balance(): TwigFilter
    {
        return new TwigFilter(
            'balance',
            static function (?Account $account): string {
                if (null === $account) {
                    return '0';
                }
                /** @var Carbon $date */
                $date = session('end', Carbon::now()->endOfMonth());

                return app('steam')->balance($account, $date);
            }
        );
    }

    /**
     * Formats a string as a thing by converting it to a Carbon first.
     *
     * @return TwigFunction
     */
    protected function formatDate(): TwigFunction
    {
        return new TwigFunction(
            'formatDate',
            function (string $date, string $format): string {
                $carbon = new Carbon($date);

                return $carbon->formatLocalized($format);
            }
        );
    }

    /**
     * Used to convert 1024 to 1kb etc.
     *
     * @return TwigFilter
     */
    protected function formatFilesize(): TwigFilter
    {
        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';
                }

                // less than one MB
                if ($size < (1024 * 1024)) {
                    return round($size / 1024, 2) . ' KB';
                }

                return $size . ' bytes';
            }
        );
    }

    /**
     * @return TwigFunction
     * @deprecated  because it uses a query in a view
     * TODO remove me.
     */
    protected function getMetaField(): TwigFunction
    {
        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 '';
                }

                return $result;
            }
        );
    }

    /**
     * Will return true if the user is of role X.
     *
     * @return TwigFunction
     */
    protected function hasRole(): TwigFunction
    {
        return new TwigFunction(
            'hasRole',
            static function (string $role): bool {
                $repository = app(UserRepositoryInterface::class);
                if ($repository->hasRole(auth()->user(), $role)) {
                    return true;
                }

                return false;
            }
        );
    }

    /**
     * @return TwigFilter
     */
    protected function markdown(): TwigFilter
    {
        return new TwigFilter(
            'markdown',
            static function (string $text): string {
                $environment = Environment::createCommonMarkEnvironment();
                $environment->addExtension(new GithubFlavoredMarkdownExtension());

                $converter = new CommonMarkConverter([], $environment);
                return $converter->convertToHtml($text);
            }, ['is_safe' => ['html']]
        );
    }

    /**
     * Show icon with attachment.
     *
     * @return TwigFilter
     */
    protected function mimeIcon(): TwigFilter
    {
        return new TwigFilter(
            'mimeIcon',
            static function (string $string): string {
                switch ($string) {
                    default:
                        return 'fa-file-o';
                    case 'application/pdf':
                        return 'fa-file-pdf-o';
                    /* image */
                    case 'image/png':
                    case 'image/jpeg':
                    case 'image/svg+xml':
                    case 'image/heic':<commit_msg>Better note escape<commit_after><?php
/**
 * General.php
 * Copyright (c) 2019 <EMAIL>
 *
 * 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.
 *
 * 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/>.
 */
declare(strict_types=1);

namespace FireflyIII\Support\Twig;

use Carbon\Carbon;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Support\Search\OperatorQuerySearch;
use League\CommonMark\CommonMarkConverter;
use League\CommonMark\Environment;
use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
use Route;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

/**
 * Class TwigSupport.
 */
class General extends AbstractExtension
{
    /**
     * @return array
     */
    public function getFilters(): array
    {
        return [
            $this->balance(),
            $this->formatFilesize(),
            $this->mimeIcon(),
            $this->markdown(),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions(): array
    {
        return [
            $this->phpdate(),
            $this->activeRouteStrict(),
            $this->activeRoutePartial(),
            $this->activeRoutePartialObjectType(),
            $this->menuOpenRoutePartial(),
            $this->formatDate(),
            $this->getMetaField(),
            $this->hasRole(),
            $this->getRootSearchOperator(),
        ];
    }

    protected function getRootSearchOperator(): TwigFunction
    {
        return new TwigFunction(
            'getRootSearchOperator',
            static function (string $operator): string {
                return OperatorQuerySearch::getRootOperator($operator);
            }
        );
    }

    /**
     * Will return "active" when a part of the route matches the argument.
     * ie. "accounts" will match "accounts.index".
     *
     * @return TwigFunction
     */
    protected function activeRoutePartial(): TwigFunction
    {
        return new TwigFunction(
            'activeRoutePartial',
            static function (): string {
                $args  = func_get_args();
                $route = $args[0]; // name of the route.
                $name  = Route::getCurrentRoute()->getName() ?? '';
                if (!(false === strpos($name, $route))) {
                    return 'active';
                }

                return '';
            }
        );
    }

    /**
     * Will return "menu-open" when a part of the route matches the argument.
     * ie. "accounts" will match "accounts.index".
     *
     * @return TwigFunction
     */
    protected function menuOpenRoutePartial(): TwigFunction
    {
        return new TwigFunction(
            'menuOpenRoutePartial',
            static function (): string {
                $args  = func_get_args();
                $route = $args[0]; // name of the route.
                $name  = Route::getCurrentRoute()->getName() ?? '';
                if (!(false === strpos($name, $route))) {
                    return 'menu-open';
                }

                return '';
            }
        );
    }

    /**
     * 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.
     *
     * @return TwigFunction
     */
    protected function activeRoutePartialObjectType(): TwigFunction
    {
        return new TwigFunction(
            'activeRoutePartialObjectType',
            static function ($context): string {
                [, $route, $objectType] = func_get_args();
                $activeObjectType = $context['objectType'] ?? false;

                if ($objectType === $activeObjectType && !(false === stripos(Route::getCurrentRoute()->getName(), $route))) {
                    return 'active';
                }

                return '';
            },
            ['needs_context' => true]
        );
    }

    /**
     * Will return "active" when the current route matches the given argument
     * exactly.
     *
     * @return TwigFunction
     */
    protected function activeRouteStrict(): TwigFunction
    {
        return new TwigFunction(
            'activeRouteStrict',
            static function (): string {
                $args  = func_get_args();
                $route = $args[0]; // name of the route.

                if (Route::getCurrentRoute()->getName() === $route) {
                    return 'active';
                }

                return '';
            }
        );
    }

    /**
     * Show account balance. Only used on the front page of Firefly III.
     *
     * @return TwigFilter
     */
    protected function balance(): TwigFilter
    {
        return new TwigFilter(
            'balance',
            static function (?Account $account): string {
                if (null === $account) {
                    return '0';
                }
                /** @var Carbon $date */
                $date = session('end', Carbon::now()->endOfMonth());

                return app('steam')->balance($account, $date);
            }
        );
    }

    /**
     * Formats a string as a thing by converting it to a Carbon first.
     *
     * @return TwigFunction
     */
    protected function formatDate(): TwigFunction
    {
        return new TwigFunction(
            'formatDate',
            function (string $date, string $format): string {
                $carbon = new Carbon($date);

                return $carbon->formatLocalized($format);
            }
        );
    }

    /**
     * Used to convert 1024 to 1kb etc.
     *
     * @return TwigFilter
     */
    protected function formatFilesize(): TwigFilter
    {
        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';
                }

                // less than one MB
                if ($size < (1024 * 1024)) {
                    return round($size / 1024, 2) . ' KB';
                }

                return $size . ' bytes';
            }
        );
    }

    /**
     * @return TwigFunction
     * @deprecated  because it uses a query in a view
     * TODO remove me.
     */
    protected function getMetaField(): TwigFunction
    {
        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 '';
                }

                return $result;
            }
        );
    }

    /**
     * Will return true if the user is of role X.
     *
     * @return TwigFunction
     */
    protected function hasRole(): TwigFunction
    {
        return new TwigFunction(
            'hasRole',
            static function (string $role): bool {
                $repository = app(UserRepositoryInterface::class);
                if ($repository->hasRole(auth()->user(), $role)) {
                    return true;
                }

                return false;
            }
        );
    }

    /**
     * @return TwigFilter
     */
    protected function markdown(): TwigFilter
    {
        return new TwigFilter(
            'markdown',
            static function (string $text): string {
                $environment = Environment::createCommonMarkEnvironment();
                $environment->addExtension(new GithubFlavoredMarkdownExtension());

                $converter = new CommonMarkConverter(['allow_unsafe_links' => false, 'max_nesting_level' => 3, 'html_input' => 'escape'], $environment);

                return $converter->convertToHtml($text);
            }, ['is_safe' => ['html']]
        );
    }

    /**
     * Show icon with attachment.
     *
     * @return TwigFilter
     */
    protected function mimeIcon(): TwigFilter
    {
        return new TwigFilter(
            'mimeIcon',
            static function (string $string): string {
                switch ($string) {
                    default:
                        return 'fa-file-o';
                    case 'application/pdf':
                        return 'fa-file-pdf-o';
                    /* image */
                    case 'image/png':
                    case 'image/jpeg':
                    case 'image/svg+xml':
                    case 'image/heic':
{'fraction_non_alphanumeric': 0.11082186686500557, 'fraction_numerical': 0.006109546831004622, 'mean_word_length': 1.6253835425383543, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 66, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, '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': '3192938', 'n_tokens_mistral': 4934, 'n_tokens_neox': 4620, 'n_words': 1320}