Passed
Pull Request — master (#5597)
by
unknown
06:58
created

ChamiloExtension::getSettings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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