Passed
Push — master ( ed7adc...d02aa6 )
by Yannick
09:57
created

ChamiloExtension::getThemeLogoUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\Twig\Extension;
8
9
use Chamilo\CoreBundle\Entity\ResourceIllustrationInterface;
10
use Chamilo\CoreBundle\Entity\User;
11
use Chamilo\CoreBundle\Helpers\NameConventionHelper;
12
use Chamilo\CoreBundle\Helpers\ThemeHelper;
13
use Chamilo\CoreBundle\Repository\Node\IllustrationRepository;
14
use Chamilo\CoreBundle\Twig\SettingsHelper;
15
use Security;
16
use Sylius\Bundle\SettingsBundle\Model\SettingsInterface;
17
use Symfony\Component\Routing\RouterInterface;
18
use Twig\Extension\AbstractExtension;
19
use Twig\TwigFilter;
20
use Twig\TwigFunction;
21
22
/**
23
 * Extend Twig with specifics from Chamilo. For globals, look into TwigListener.php.
24
 */
25
class ChamiloExtension extends AbstractExtension
26
{
27
    private IllustrationRepository $illustrationRepository;
28
    private SettingsHelper $helper;
29
    private RouterInterface $router;
30
    private NameConventionHelper $nameConventionHelper;
31
32
    public function __construct(
33
        IllustrationRepository $illustrationRepository,
34
        SettingsHelper $helper,
35
        RouterInterface $router,
36
        NameConventionHelper $nameConventionHelper,
37
        private readonly ThemeHelper $themeHelper
38
    ) {
39
        $this->illustrationRepository = $illustrationRepository;
40
        $this->helper = $helper;
41
        $this->router = $router;
42
        $this->nameConventionHelper = $nameConventionHelper;
43
    }
44
45
    public function getFilters(): array
46
    {
47
        return [
48
            new TwigFilter('var_dump', 'var_dump'),
49
            new TwigFilter('icon', 'Display::get_icon_path'),
50
            new TwigFilter('mdi_icon', 'Display::getMdiIconSimple'),
51
            new TwigFilter('mdi_icon_t', 'Display::getMdiIconTranslate'),
52
            new TwigFilter('get_lang', 'get_lang'),
53
            new TwigFilter('get_plugin_lang', 'get_plugin_lang'),
54
            new TwigFilter('api_get_local_time', 'api_get_local_time'),
55
            new TwigFilter('api_convert_and_format_date', 'api_convert_and_format_date'),
56
            new TwigFilter('format_date', 'api_format_date'),
57
            new TwigFilter('format_file_size', 'format_file_size'),
58
            new TwigFilter('date_to_time_ago', 'Display::dateToStringAgoAndLongDate'),
59
            new TwigFilter('api_get_configuration_value', 'api_get_configuration_value'),
60
            new TwigFilter('remove_xss', 'Security::remove_XSS'),
61
            new TwigFilter('user_complete_name', 'UserManager::formatUserFullName'),
62
            new TwigFilter('user_complete_name_with_link', $this->completeUserNameWithLink(...)),
63
            new TwigFilter('illustration', $this->getIllustration(...)),
64
            new TwigFilter('api_get_setting', $this->getSettingsParameter(...)),
65
        ];
66
    }
67
68
    public function getFunctions(): array
69
    {
70
        return [
71
            new TwigFunction('chamilo_settings_all', $this->getSettings(...)),
72
            new TwigFunction('chamilo_settings_get', $this->getSettingsParameter(...)),
73
            new TwigFunction('chamilo_settings_has', [$this, 'hasSettingsParameter']),
74
            new TwigFunction('password_checker_js', [$this, 'getPasswordCheckerJs'], ['is_safe' => ['html']]),
75
            new TwigFunction('theme_asset', $this->getThemeAssetUrl(...)),
76
            new TwigFunction('theme_asset_link_tag', $this->getThemeAssetLinkTag(...), ['is_safe' => ['html']]),
77
            new TwigFunction('theme_asset_base64', $this->getThemeAssetBase64Encoded(...)),
78
            new TwigFunction('theme_logo', $this->getThemeLogoUrl(...)),
79
        ];
80
    }
81
82
    public function getThemeLogoUrl(string $type = 'header', bool $absoluteUrl = false): string
83
    {
84
        return $this->themeHelper->getPreferredLogoUrl($type, $absoluteUrl);
85
    }
86
87
    public function completeUserNameWithLink(User $user): string
88
    {
89
        $url = $this->router->generate(
90
            'legacy_main',
91
            [
92
                'name' => '/inc/ajax/user_manager.ajax.php?a=get_user_popup&user_id='.$user->getId(),
93
            ]
94
        );
95
96
        $name = $this->nameConventionHelper->getPersonName($user);
97
98
        return "<a href=\"$url\" class=\"ajax\">$name</a>";
99
    }
100
101
    public function getIllustration(ResourceIllustrationInterface $resource): string
102
    {
103
        return $this->illustrationRepository->getIllustrationUrl($resource);
104
    }
105
106
    public function getSettings($namespace): SettingsInterface
107
    {
108
        return $this->helper->getSettings($namespace);
109
    }
110
111
    public function getSettingsParameter($name)
112
    {
113
        return $this->helper->getSettingsParameter($name);
114
    }
115
116
    /**
117
     * Generates and returns JavaScript code for a password strength checker.
118
     */
119
    public function getPasswordCheckerJs(string $passwordInputId): ?string
120
    {
121
        $checkPass = api_get_setting('allow_strength_pass_checker');
122
        $useStrengthPassChecker = 'true' === $checkPass;
123
124
        if (false === $useStrengthPassChecker) {
125
            return null;
126
        }
127
128
        $minRequirements = Security::getPasswordRequirements()['min'];
129
130
        $options = [
131
            'rules' => [],
132
        ];
133
134
        if ($minRequirements['length'] > 0) {
135
            $options['rules'][] = [
136
                'minChar' => $minRequirements['length'],
137
                'pattern' => '.',
138
                'helpText' => \sprintf(
139
                    get_lang('Minimum %s characters in total'),
140
                    $minRequirements['length']
141
                ),
142
            ];
143
        }
144
145
        if ($minRequirements['lowercase'] > 0) {
146
            $options['rules'][] = [
147
                'minChar' => $minRequirements['lowercase'],
148
                'pattern' => '[a-z]',
149
                'helpText' => \sprintf(
150
                    get_lang('Minimum %s lowercase characters'),
151
                    $minRequirements['lowercase']
152
                ),
153
            ];
154
        }
155
156
        if ($minRequirements['uppercase'] > 0) {
157
            $options['rules'][] = [
158
                'minChar' => $minRequirements['uppercase'],
159
                'pattern' => '[A-Z]',
160
                'helpText' => \sprintf(
161
                    get_lang('Minimum %s uppercase characters'),
162
                    $minRequirements['uppercase']
163
                ),
164
            ];
165
        }
166
167
        if ($minRequirements['numeric'] > 0) {
168
            $options['rules'][] = [
169
                'minChar' => $minRequirements['numeric'],
170
                'pattern' => '[0-9]',
171
                'helpText' => \sprintf(
172
                    get_lang('Minimum %s numerical (0-9) characters'),
173
                    $minRequirements['numeric']
174
                ),
175
            ];
176
        }
177
178
        if ($minRequirements['specials'] > 0) {
179
            $options['rules'][] = [
180
                'minChar' => $minRequirements['specials'],
181
                'pattern' => '[!"#$%&\'()*+,\-./\\\:;<=>?@[\]^_`{|}~]',
182
                'helpText' => \sprintf(
183
                    get_lang('Minimum %s special characters'),
184
                    $minRequirements['specials']
185
                ),
186
            ];
187
        }
188
189
        return "<script>
190
        (function($) {
191
            $.fn.passwordCheckerChange = function(options) {
192
                var settings = $.extend({
193
                    rules: []
194
                }, options );
195
196
                return this.each(function() {
197
                    var \$passwordInput = $(this);
198
                    var \$requirements = $('#password-requirements');
199
200
                    function validatePassword(password) {
201
                        var html = '';
202
203
                        settings.rules.forEach(function(rule) {
204
                            var isValid = new RegExp(rule.pattern).test(password) && password.length >= rule.minChar;
205
                            var color = isValid ? 'green' : 'red';
206
                            html += '<li style=\"color:' + color + '\">' + rule.helpText + '</li>';
207
                        });
208
209
                        \$requirements.html(html);
210
                    }
211
212
                    \$passwordInput.on('input', function() {
213
                        validatePassword(\$passwordInput.val());
214
                        \$requirements.show();
215
                    });
216
217
                    \$passwordInput.on('blur', function() {
218
                        \$requirements.hide();
219
                    });
220
                });
221
            };
222
        }(jQuery));
223
224
        $(function() {
225
            $('".$passwordInputId."').passwordCheckerChange(".json_encode($options).');
226
        });
227
        </script>';
228
    }
229
230
    /**
231
     * Returns the name of the extension.
232
     */
233
    public function getName(): string
234
    {
235
        return 'chamilo_extension';
236
    }
237
238
    public function getThemeAssetUrl(string $path, bool $absoluteUrl = false): string
239
    {
240
        return $this->themeHelper->getThemeAssetUrl($path, $absoluteUrl);
241
    }
242
243
    public function getThemeAssetLinkTag(string $path, bool $absoluteUrl = false): string
244
    {
245
        return $this->themeHelper->getThemeAssetLinkTag($path, $absoluteUrl);
246
    }
247
248
    public function getThemeAssetBase64Encoded(string $path): string
249
    {
250
        return $this->themeHelper->getAssetBase64Encoded($path);
251
    }
252
}
253