Passed
Pull Request — master (#5974)
by Angel Fernando Quiroz
08:25
created

SettingsManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 5
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Settings;
8
9
use Chamilo\CoreBundle\Entity\AccessUrl;
10
use Chamilo\CoreBundle\Entity\Course;
11
use Chamilo\CoreBundle\Entity\SettingsCurrent;
12
use Doctrine\ORM\EntityManager;
13
use Doctrine\ORM\EntityRepository;
14
use InvalidArgumentException;
15
use Sylius\Bundle\SettingsBundle\Event\SettingsEvent;
16
use Sylius\Bundle\SettingsBundle\Manager\SettingsManagerInterface;
17
use Sylius\Bundle\SettingsBundle\Model\Settings;
18
use Sylius\Bundle\SettingsBundle\Model\SettingsInterface;
19
use Sylius\Bundle\SettingsBundle\Registry\ServiceRegistryInterface;
20
use Sylius\Bundle\SettingsBundle\Schema\SchemaInterface;
21
use Sylius\Bundle\SettingsBundle\Schema\SettingsBuilder;
22
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
23
use Symfony\Component\HttpFoundation\RequestStack;
24
use Symfony\Component\Validator\ConstraintViolationListInterface;
25
use Symfony\Component\Validator\Exception\ValidatorException;
26
27
use const ARRAY_FILTER_USE_KEY;
28
29
/**
30
 * Handles the platform settings.
31
 */
32
class SettingsManager implements SettingsManagerInterface
33
{
34
    protected ?AccessUrl $url = null;
35
36
    protected ServiceRegistryInterface $schemaRegistry;
37
38
    protected EntityManager $manager;
39
40
    protected EntityRepository $repository;
41
42
    protected EventDispatcherInterface $eventDispatcher;
43
44
    /**
45
     * Runtime cache for resolved parameters.
46
     *
47
     * @var Settings[]
48
     */
49
    protected array $resolvedSettings = [];
50
51
    /**
52
     * @var null|array<string, Settings>|mixed[]
53
     */
54
    protected ?array $schemaList;
55
56
    protected RequestStack $request;
57
58
    public function __construct(
59
        ServiceRegistryInterface $schemaRegistry,
60
        EntityManager $manager,
61
        EntityRepository $repository,
62
        EventDispatcherInterface $eventDispatcher,
63
        RequestStack $request
64
    ) {
65
        $this->schemaRegistry = $schemaRegistry;
66
        $this->manager = $manager;
67
        $this->repository = $repository;
68
        $this->eventDispatcher = $eventDispatcher;
69
        $this->request = $request;
70
        $this->schemaList = [];
71
    }
72
73
    public function getUrl(): ?AccessUrl
74
    {
75
        return $this->url;
76
    }
77
78
    public function setUrl(AccessUrl $url): void
79
    {
80
        $this->url = $url;
81
    }
82
83
    public function updateSchemas(AccessUrl $url): void
84
    {
85
        $this->url = $url;
86
        $schemas = array_keys($this->getSchemas());
87
        foreach ($schemas as $schema) {
88
            $settings = $this->load($this->convertServiceToNameSpace($schema));
89
            $this->update($settings);
90
        }
91
    }
92
93
    public function installSchemas(AccessUrl $url): void
94
    {
95
        $this->url = $url;
96
        $schemas = array_keys($this->getSchemas());
97
        foreach ($schemas as $schema) {
98
            $settings = $this->load($this->convertServiceToNameSpace($schema));
99
            $this->save($settings);
100
        }
101
    }
102
103
    /**
104
     * @return array|AbstractSettingsSchema[]
105
     */
106
    public function getSchemas(): array
107
    {
108
        return $this->schemaRegistry->all();
109
    }
110
111
    public function convertNameSpaceToService(string $category): string
112
    {
113
        return 'chamilo_core.settings.'.$category;
114
    }
115
116
    public function convertServiceToNameSpace(string $category): string
117
    {
118
        return str_replace('chamilo_core.settings.', '', $category);
119
    }
120
121
    public function updateSetting(string $name, $value): void
122
    {
123
        $name = $this->validateSetting($name);
124
125
        [$category, $name] = explode('.', $name);
126
        $settings = $this->load($category);
127
128
        if (!$settings->has($name)) {
129
            $message = \sprintf("Parameter %s doesn't exists.", $name);
130
131
            throw new InvalidArgumentException($message);
132
        }
133
134
        $settings->set($name, $value);
135
        $this->update($settings);
136
    }
137
138
    /**
139
     * Get a specific configuration setting, getting from the previously stored
140
     * PHP session data whenever possible.
141
     *
142
     * @param string $name       The setting name (composed if in a category, i.e. 'platform.institution')
143
     * @param bool   $loadFromDb Whether to load from the database
144
     */
145
    public function getSetting(string $name, bool $loadFromDb = false): mixed
146
    {
147
        $name = $this->validateSetting($name);
148
149
        [$category, $name] = explode('.', $name);
150
151
        if ($loadFromDb) {
152
            $settings = $this->load($category, $name);
153
            if ($settings->has($name)) {
154
                return $settings->get($name);
155
            }
156
157
            return null;
158
        }
159
160
        $this->loadAll();
161
162
        if (!empty($this->schemaList) && isset($this->schemaList[$category])) {
163
            $settings = $this->schemaList[$category];
164
            if ($settings->has($name)) {
165
                return $settings->get($name);
166
            }
167
            error_log("Attempted to access undefined setting '$name' in category '$category'.");
168
169
            return null;
170
        }
171
172
        throw new InvalidArgumentException(\sprintf('Category %s not found', $category));
173
    }
174
175
    public function loadAll(): void
176
    {
177
        $session = null;
178
179
        if ($this->request->getCurrentRequest()) {
180
            $session = $this->request->getCurrentRequest()->getSession();
181
            $schemaList = $session->get('schemas');
182
            if (!empty($schemaList)) {
183
                $this->schemaList = $schemaList;
184
185
                return;
186
            }
187
        }
188
189
        $schemas = array_keys($this->getSchemas());
190
        $schemaList = [];
191
        $settingsBuilder = new SettingsBuilder();
192
        $all = $this->getAllParametersByCategory();
193
194
        foreach ($schemas as $schema) {
195
            $schemaRegister = $this->schemaRegistry->get($schema);
196
            $schemaRegister->buildSettings($settingsBuilder);
197
            $name = $this->convertServiceToNameSpace($schema);
198
            $settings = new Settings();
199
200
            /** @var array<string, mixed> $parameters */
201
            $parameters = $all[$name] ?? [];
202
203
            $knownParameters = array_filter(
204
                $parameters,
205
                fn ($key): bool => $settingsBuilder->isDefined($key),
206
                ARRAY_FILTER_USE_KEY
207
            );
208
209
            $transformers = $settingsBuilder->getTransformers();
210
            foreach ($transformers as $parameter => $transformer) {
211
                if (\array_key_exists($parameter, $knownParameters)) {
212
                    if ('course_creation_use_template' === $parameter) {
213
                        if (empty($knownParameters[$parameter])) {
214
                            $knownParameters[$parameter] = null;
215
                        }
216
                    } else {
217
                        $knownParameters[$parameter] = $transformer->reverseTransform($knownParameters[$parameter]);
218
                    }
219
                }
220
            }
221
222
            $parameters = $settingsBuilder->resolve($knownParameters);
223
            $settings->setParameters($parameters);
224
            $schemaList[$name] = $settings;
225
        }
226
        $this->schemaList = $schemaList;
227
        if ($session && $this->request->getCurrentRequest()) {
228
            $session->set('schemas', $schemaList);
229
        }
230
    }
231
232
    public function load(string $schemaAlias, ?string $namespace = null, bool $ignoreUnknown = true): SettingsInterface
233
    {
234
        $settings = new Settings();
235
        $schemaAliasNoPrefix = $schemaAlias;
236
        $schemaAlias = 'chamilo_core.settings.'.$schemaAlias;
237
        if ($this->schemaRegistry->has($schemaAlias)) {
238
            /** @var SchemaInterface $schema */
239
            $schema = $this->schemaRegistry->get($schemaAlias);
240
        } else {
241
            return $settings;
242
        }
243
244
        $settings->setSchemaAlias($schemaAlias);
245
246
        // We need to get a plain parameters array since we use the options resolver on it
247
        $parameters = $this->getParameters($schemaAliasNoPrefix);
248
        $settingsBuilder = new SettingsBuilder();
249
        $schema->buildSettings($settingsBuilder);
250
251
        // Remove unknown settings' parameters (e.g. From a previous version of the settings schema)
252
        if (true === $ignoreUnknown) {
253
            foreach ($parameters as $name => $value) {
254
                if (!$settingsBuilder->isDefined($name)) {
255
                    unset($parameters[$name]);
256
                }
257
            }
258
        }
259
260
        foreach ($settingsBuilder->getTransformers() as $parameter => $transformer) {
261
            if (\array_key_exists($parameter, $parameters)) {
262
                $parameters[$parameter] = $transformer->reverseTransform($parameters[$parameter]);
263
            }
264
        }
265
266
        $parameters = $settingsBuilder->resolve($parameters);
267
        $settings->setParameters($parameters);
268
269
        return $settings;
270
    }
271
272
    public function update(SettingsInterface $settings): void
273
    {
274
        $namespace = $settings->getSchemaAlias();
275
276
        /** @var SchemaInterface $schema */
277
        $schema = $this->schemaRegistry->get($settings->getSchemaAlias());
278
279
        $settingsBuilder = new SettingsBuilder();
280
        $schema->buildSettings($settingsBuilder);
281
        $parameters = $settingsBuilder->resolve($settings->getParameters());
282
        // Transform value. Example array to string using transformer. Example:
283
        // 1. Setting "tool_visible_by_default_at_creation" it's a multiple select
284
        // 2. Is defined as an array in class DocumentSettingsSchema
285
        // 3. Add transformer for that variable "ArrayToIdentifierTransformer"
286
        // 4. Here we recover the transformer and convert the array to string
287
        foreach ($parameters as $parameter => $value) {
288
            $parameters[$parameter] = $this->transformToString($value);
289
        }
290
291
        $settings->setParameters($parameters);
292
        $category = $this->convertServiceToNameSpace($settings->getSchemaAlias());
293
        $persistedParameters = $this->repository->findBy([
294
            'category' => $category,
295
        ]);
296
297
        $persistedParametersMap = [];
298
299
        /** @var SettingsCurrent $parameter */
300
        foreach ($persistedParameters as $parameter) {
301
            $persistedParametersMap[$parameter->getVariable()] = $parameter;
302
        }
303
304
        $url = $this->getUrl();
305
        $simpleCategoryName = str_replace('chamilo_core.settings.', '', $namespace);
306
307
        foreach ($parameters as $name => $value) {
308
            if (isset($persistedParametersMap[$name])) {
309
                $parameter = $persistedParametersMap[$name];
310
                $parameter->setSelectedValue($value);
311
                $parameter->setCategory($simpleCategoryName);
312
                $this->manager->persist($parameter);
313
            } else {
314
                $parameter = (new SettingsCurrent())
315
                    ->setVariable($name)
316
                    ->setCategory($simpleCategoryName)
317
                    ->setTitle($name)
318
                    ->setSelectedValue($value)
319
                    ->setUrl($url)
320
                    ->setAccessUrlChangeable(1)
321
                    ->setAccessUrlLocked(1)
322
                ;
323
324
                $this->manager->persist($parameter);
325
            }
326
        }
327
328
        $this->manager->flush();
329
    }
330
331
    /**
332
     * @throws ValidatorException
333
     */
334
    public function save(SettingsInterface $settings): void
335
    {
336
        $namespace = $settings->getSchemaAlias();
337
338
        /** @var SchemaInterface $schema */
339
        $schema = $this->schemaRegistry->get($settings->getSchemaAlias());
340
341
        $settingsBuilder = new SettingsBuilder();
342
        $schema->buildSettings($settingsBuilder);
343
        $parameters = $settingsBuilder->resolve($settings->getParameters());
344
        // Transform value. Example array to string using transformer. Example:
345
        // 1. Setting "tool_visible_by_default_at_creation" it's a multiple select
346
        // 2. Is defined as an array in class DocumentSettingsSchema
347
        // 3. Add transformer for that variable "ArrayToIdentifierTransformer"
348
        // 4. Here we recover the transformer and convert the array to string
349
        foreach ($parameters as $parameter => $value) {
350
            $parameters[$parameter] = $this->transformToString($value);
351
        }
352
        $settings->setParameters($parameters);
353
        $persistedParameters = $this->repository->findBy([
354
            'category' => $this->convertServiceToNameSpace($settings->getSchemaAlias()),
355
        ]);
356
        $persistedParametersMap = [];
357
        foreach ($persistedParameters as $parameter) {
358
            $persistedParametersMap[$parameter->getVariable()] = $parameter;
359
        }
360
361
        $url = $this->getUrl();
362
        $simpleCategoryName = str_replace('chamilo_core.settings.', '', $namespace);
363
364
        foreach ($parameters as $name => $value) {
365
            if (isset($persistedParametersMap[$name])) {
366
                $parameter = $persistedParametersMap[$name];
367
                $parameter->setSelectedValue($value);
368
            } else {
369
                $parameter = (new SettingsCurrent())
370
                    ->setVariable($name)
371
                    ->setCategory($simpleCategoryName)
372
                    ->setTitle($name)
373
                    ->setSelectedValue($value)
374
                    ->setUrl($url)
375
                    ->setAccessUrlChangeable(1)
376
                    ->setAccessUrlLocked(1)
377
                ;
378
379
                $this->manager->persist($parameter);
380
            }
381
        }
382
383
        $this->manager->flush();
384
    }
385
386
    /**
387
     * @param string $keyword
388
     */
389
    public function getParametersFromKeywordOrderedByCategory($keyword): array
390
    {
391
        $query = $this->repository->createQueryBuilder('s')
392
            ->where('s.variable LIKE :keyword OR s.title LIKE :keyword')
393
            ->setParameter('keyword', "%{$keyword}%")
394
        ;
395
        $parametersFromDb = $query->getQuery()->getResult();
396
        $parameters = [];
397
398
        /** @var SettingsCurrent $parameter */
399
        foreach ($parametersFromDb as $parameter) {
400
            $parameters[$parameter->getCategory()][] = $parameter;
401
        }
402
403
        return $parameters;
404
    }
405
406
    /**
407
     * @param string $namespace
408
     * @param string $keyword
409
     * @param bool   $returnObjects
410
     *
411
     * @return array
412
     */
413
    public function getParametersFromKeyword($namespace, $keyword = '', $returnObjects = false)
414
    {
415
        if (empty($keyword)) {
416
            $criteria = [
417
                'category' => $namespace,
418
            ];
419
            $parametersFromDb = $this->repository->findBy($criteria);
420
        } else {
421
            $query = $this->repository->createQueryBuilder('s')
422
                ->where('s.variable LIKE :keyword')
423
                ->setParameter('keyword', "%{$keyword}%")
424
            ;
425
            $parametersFromDb = $query->getQuery()->getResult();
426
        }
427
428
        if ($returnObjects) {
429
            return $parametersFromDb;
430
        }
431
        $parameters = [];
432
433
        /** @var SettingsCurrent $parameter */
434
        foreach ($parametersFromDb as $parameter) {
435
            $parameters[$parameter->getVariable()] = $parameter->getSelectedValue();
436
        }
437
438
        return $parameters;
439
    }
440
441
    private function validateSetting(string $name): string
442
    {
443
        if (!str_contains($name, '.')) {
444
            // throw new \InvalidArgumentException(sprintf('Parameter must be in format "namespace.name", "%s" given.', $name));
445
446
            // This code allows the possibility of calling
447
            // api_get_setting('allow_skills_tool') instead of
448
            // the "correct" way api_get_setting('platform.allow_skills_tool')
449
            $items = $this->getVariablesAndCategories();
450
451
            if (isset($items[$name])) {
452
                $originalName = $name;
453
                $name = $this->renameVariable($name);
454
                $category = $this->fixCategory(
455
                    strtolower($name),
456
                    strtolower($items[$originalName])
457
                );
458
                $name = $category.'.'.$name;
459
            } else {
460
                $message = \sprintf('Parameter must be in format "category.name", "%s" given.', $name);
461
462
                throw new InvalidArgumentException($message);
463
            }
464
        }
465
466
        return $name;
467
    }
468
469
    /**
470
     * Load parameter from database.
471
     *
472
     * @param string $namespace
473
     *
474
     * @return array
475
     */
476
    private function getParameters($namespace)
477
    {
478
        $parameters = [];
479
        $category = $this->repository->findBy(['category' => $namespace]);
480
481
        /** @var SettingsCurrent $parameter */
482
        foreach ($category as $parameter) {
483
            $parameters[$parameter->getVariable()] = $parameter->getSelectedValue();
484
        }
485
486
        return $parameters;
487
    }
488
489
    private function getAllParametersByCategory()
490
    {
491
        $parameters = [];
492
        $all = $this->repository->findAll();
493
494
        /** @var SettingsCurrent $parameter */
495
        foreach ($all as $parameter) {
496
            $parameters[$parameter->getCategory()][$parameter->getVariable()] = $parameter->getSelectedValue();
497
        }
498
499
        return $parameters;
500
    }
501
502
    /*private function transformParameters(SettingsBuilder $settingsBuilder, array $parameters)
503
     * {
504
     * $transformedParameters = $parameters;
505
     * foreach ($settingsBuilder->getTransformers() as $parameter => $transformer) {
506
     * if (array_key_exists($parameter, $parameters)) {
507
     * $transformedParameters[$parameter] = $transformer->reverseTransform($parameters[$parameter]);
508
     * }
509
     * }
510
     * return $transformedParameters;
511
     * }*/
512
513
    /**
514
     * Get variables and categories as in 1.11.x.
515
     */
516
    private function getVariablesAndCategories(): array
517
    {
518
        return [
519
            'Institution' => 'Platform',
520
            'InstitutionUrl' => 'Platform',
521
            'siteName' => 'Platform',
522
            'site_name' => 'Platform',
523
            'emailAdministrator' => 'admin',
524
            // 'emailAdministrator' => 'Platform',
525
            'administratorSurname' => 'admin',
526
            'administratorTelephone' => 'admin',
527
            'administratorName' => 'admin',
528
            'show_administrator_data' => 'Platform',
529
            'show_tutor_data' => 'Session',
530
            'show_teacher_data' => 'Platform',
531
            'show_toolshortcuts' => 'Course',
532
            'allow_group_categories' => 'Course',
533
            'server_type' => 'Platform',
534
            'platformLanguage' => 'Language',
535
            'showonline' => 'Platform',
536
            'profile' => 'User',
537
            'default_document_quotum' => 'Course',
538
            'registration' => 'User',
539
            'default_group_quotum' => 'Course',
540
            'allow_registration' => 'Platform',
541
            'allow_registration_as_teacher' => 'Platform',
542
            'allow_lostpassword' => 'Platform',
543
            'allow_user_headings' => 'Course',
544
            'allow_personal_agenda' => 'agenda',
545
            'display_coursecode_in_courselist' => 'Platform',
546
            'display_teacher_in_courselist' => 'Platform',
547
            'permanently_remove_deleted_files' => 'Tools',
548
            'dropbox_allow_overwrite' => 'Tools',
549
            'dropbox_max_filesize' => 'Tools',
550
            'dropbox_allow_just_upload' => 'Tools',
551
            'dropbox_allow_student_to_student' => 'Tools',
552
            'dropbox_allow_group' => 'Tools',
553
            'dropbox_allow_mailing' => 'Tools',
554
            'extended_profile' => 'User',
555
            'student_view_enabled' => 'Platform',
556
            'show_navigation_menu' => 'Course',
557
            'enable_tool_introduction' => 'course',
558
            'page_after_login' => 'Platform',
559
            'time_limit_whosonline' => 'Platform',
560
            'breadcrumbs_course_homepage' => 'Course',
561
            'example_material_course_creation' => 'Platform',
562
            'account_valid_duration' => 'Platform',
563
            'use_session_mode' => 'Session',
564
            'allow_email_editor' => 'Tools',
565
            // 'registered' => null',
566
            // 'donotlistcampus' =>'null',
567
            'show_email_addresses' => 'Platform',
568
            'service_ppt2lp' => 'NULL',
569
            'upload_extensions_list_type' => 'Security',
570
            'upload_extensions_blacklist' => 'Security',
571
            'upload_extensions_whitelist' => 'Security',
572
            'upload_extensions_skip' => 'Security',
573
            'upload_extensions_replace_by' => 'Security',
574
            'show_number_of_courses' => 'Platform',
575
            'show_empty_course_categories' => 'Platform',
576
            'show_back_link_on_top_of_tree' => 'Platform',
577
            'show_different_course_language' => 'Platform',
578
            'split_users_upload_directory' => 'Tuning',
579
            'hide_dltt_markup' => 'Languages',
580
            'display_categories_on_homepage' => 'Platform',
581
            'permissions_for_new_directories' => 'Security',
582
            'permissions_for_new_files' => 'Security',
583
            'show_tabs' => 'Platform',
584
            'default_forum_view' => 'Course',
585
            'platform_charset' => 'Languages',
586
            'noreply_email_address' => 'Platform',
587
            'survey_email_sender_noreply' => 'Course',
588
            'gradebook_enable' => 'Gradebook',
589
            'gradebook_score_display_coloring' => 'Gradebook',
590
            'gradebook_score_display_custom' => 'Gradebook',
591
            'gradebook_score_display_colorsplit' => 'Gradebook',
592
            'gradebook_score_display_upperlimit' => 'Gradebook',
593
            'gradebook_number_decimals' => 'Gradebook',
594
            'user_selected_theme' => 'Platform',
595
            'allow_course_theme' => 'Course',
596
            'show_closed_courses' => 'Platform',
597
            'extendedprofile_registration' => 'User',
598
            'extendedprofile_registrationrequired' => 'User',
599
            'add_users_by_coach' => 'Session',
600
            'extend_rights_for_coach' => 'Security',
601
            'extend_rights_for_coach_on_survey' => 'Security',
602
            'course_create_active_tools' => 'Tools',
603
            'show_session_coach' => 'Session',
604
            'allow_users_to_create_courses' => 'Platform',
605
            'allow_message_tool' => 'Tools',
606
            'allow_social_tool' => 'Tools',
607
            'allow_students_to_browse_courses' => 'Platform',
608
            'show_session_data' => 'Session',
609
            'allow_use_sub_language' => 'language',
610
            'show_glossary_in_documents' => 'Course',
611
            'allow_terms_conditions' => 'Platform',
612
            'search_enabled' => 'Search',
613
            'search_prefilter_prefix' => 'Search',
614
            'search_show_unlinked_results' => 'Search',
615
            'show_courses_descriptions_in_catalog' => 'Course',
616
            'allow_coach_to_edit_course_session' => 'Session',
617
            'show_glossary_in_extra_tools' => 'Course',
618
            'send_email_to_admin_when_create_course' => 'Platform',
619
            'go_to_course_after_login' => 'Course',
620
            'math_asciimathML' => 'Editor',
621
            'enabled_asciisvg' => 'Editor',
622
            'include_asciimathml_script' => 'Editor',
623
            'youtube_for_students' => 'Editor',
624
            'block_copy_paste_for_students' => 'Editor',
625
            'more_buttons_maximized_mode' => 'Editor',
626
            'students_download_folders' => 'Document',
627
            'users_copy_files' => 'Tools',
628
            'allow_students_to_create_groups_in_social' => 'Tools',
629
            'allow_send_message_to_all_platform_users' => 'Message',
630
            'message_max_upload_filesize' => 'Tools',
631
            'use_users_timezone' => 'profile',
632
            // 'use_users_timezone' => 'Timezones',
633
            'timezone_value' => 'platform',
634
            // 'timezone_value' => 'Timezones',
635
            'allow_user_course_subscription_by_course_admin' => 'Security',
636
            'show_link_bug_notification' => 'Platform',
637
            'show_link_ticket_notification' => 'Platform',
638
            'course_validation' => 'course',
639
            // 'course_validation' => 'Platform',
640
            'course_validation_terms_and_conditions_url' => 'Platform',
641
            'enabled_wiris' => 'Editor',
642
            'allow_spellcheck' => 'Editor',
643
            'force_wiki_paste_as_plain_text' => 'Editor',
644
            'enabled_googlemaps' => 'Editor',
645
            'enabled_imgmap' => 'Editor',
646
            'enabled_support_svg' => 'Tools',
647
            'pdf_export_watermark_enable' => 'Platform',
648
            'pdf_export_watermark_by_course' => 'Platform',
649
            'pdf_export_watermark_text' => 'Platform',
650
            'enabled_insertHtml' => 'Editor',
651
            'students_export2pdf' => 'Document',
652
            'exercise_min_score' => 'Course',
653
            'exercise_max_score' => 'Course',
654
            'show_users_folders' => 'Tools',
655
            'show_default_folders' => 'Tools',
656
            'show_chat_folder' => 'Tools',
657
            'enabled_text2audio' => 'Tools',
658
            'course_hide_tools' => 'Course',
659
            'enabled_support_pixlr' => 'Tools',
660
            'show_groups_to_users' => 'Session',
661
            'accessibility_font_resize' => 'Platform',
662
            'hide_courses_in_sessions' => 'Session',
663
            'enable_quiz_scenario' => 'Course',
664
            'filter_terms' => 'Security',
665
            'header_extra_content' => 'Tracking',
666
            'footer_extra_content' => 'Tracking',
667
            'show_documents_preview' => 'Tools',
668
            'htmlpurifier_wiki' => 'Editor',
669
            'cas_activate' => 'CAS',
670
            'cas_server' => 'CAS',
671
            'cas_server_uri' => 'CAS',
672
            'cas_port' => 'CAS',
673
            'cas_protocol' => 'CAS',
674
            'cas_add_user_activate' => 'CAS',
675
            'update_user_info_cas_with_ldap' => 'CAS',
676
            'student_page_after_login' => 'Platform',
677
            'teacher_page_after_login' => 'Platform',
678
            'drh_page_after_login' => 'Platform',
679
            'sessionadmin_page_after_login' => 'Session',
680
            'student_autosubscribe' => 'Platform',
681
            'teacher_autosubscribe' => 'Platform',
682
            'drh_autosubscribe' => 'Platform',
683
            'sessionadmin_autosubscribe' => 'Session',
684
            'scorm_cumulative_session_time' => 'Course',
685
            'allow_hr_skills_management' => 'Gradebook',
686
            'enable_help_link' => 'Platform',
687
            'teachers_can_change_score_settings' => 'Gradebook',
688
            'allow_users_to_change_email_with_no_password' => 'User',
689
            'show_admin_toolbar' => 'display',
690
            'allow_global_chat' => 'Platform',
691
            'languagePriority1' => 'language',
692
            'languagePriority2' => 'language',
693
            'languagePriority3' => 'language',
694
            'languagePriority4' => 'language',
695
            'login_is_email' => 'Platform',
696
            'courses_default_creation_visibility' => 'Course',
697
            'gradebook_enable_grade_model' => 'Gradebook',
698
            'teachers_can_change_grade_model_settings' => 'Gradebook',
699
            'gradebook_default_weight' => 'Gradebook',
700
            'ldap_description' => 'LDAP',
701
            'shibboleth_description' => 'Shibboleth',
702
            'facebook_description' => 'Facebook',
703
            'gradebook_locking_enabled' => 'Gradebook',
704
            'gradebook_default_grade_model_id' => 'Gradebook',
705
            'allow_session_admins_to_manage_all_sessions' => 'Session',
706
            'allow_skills_tool' => 'Platform',
707
            'allow_public_certificates' => 'Course',
708
            'platform_unsubscribe_allowed' => 'Platform',
709
            'enable_iframe_inclusion' => 'Editor',
710
            'show_hot_courses' => 'Platform',
711
            'enable_webcam_clip' => 'Tools',
712
            'use_custom_pages' => 'Platform',
713
            'tool_visible_by_default_at_creation' => 'Tools',
714
            'prevent_session_admins_to_manage_all_users' => 'Session',
715
            'documents_default_visibility_defined_in_course' => 'Tools',
716
            'enabled_mathjax' => 'Editor',
717
            'meta_twitter_site' => 'Tracking',
718
            'meta_twitter_creator' => 'Tracking',
719
            'meta_title' => 'Tracking',
720
            'meta_description' => 'Tracking',
721
            'meta_image_path' => 'Tracking',
722
            'allow_teachers_to_create_sessions' => 'Session',
723
            'institution_address' => 'Platform',
724
            'chamilo_database_version' => 'null',
725
            'cron_remind_course_finished_activate' => 'Crons',
726
            'cron_remind_course_expiration_frequency' => 'Crons',
727
            'cron_remind_course_expiration_activate' => 'Crons',
728
            'allow_coach_feedback_exercises' => 'Session',
729
            'allow_my_files' => 'Platform',
730
            'ticket_allow_student_add' => 'Ticket',
731
            'ticket_send_warning_to_all_admins' => 'Ticket',
732
            'ticket_warn_admin_no_user_in_category' => 'Ticket',
733
            'ticket_allow_category_edition' => 'Ticket',
734
            'load_term_conditions_section' => 'Platform',
735
            'show_terms_if_profile_completed' => 'Ticket',
736
            'hide_home_top_when_connected' => 'Platform',
737
            'hide_global_announcements_when_not_connected' => 'Platform',
738
            'course_creation_use_template' => 'Course',
739
            'allow_strength_pass_checker' => 'Security',
740
            'allow_captcha' => 'Security',
741
            'captcha_number_mistakes_to_block_account' => 'Security',
742
            'captcha_time_to_block' => 'Security',
743
            'drh_can_access_all_session_content' => 'Session',
744
            'display_groups_forum_in_general_tool' => 'Tools',
745
            'allow_tutors_to_assign_students_to_session' => 'Session',
746
            'allow_lp_return_link' => 'Course',
747
            'hide_scorm_export_link' => 'Course',
748
            'hide_scorm_copy_link' => 'Course',
749
            'hide_scorm_pdf_link' => 'Course',
750
            'session_days_before_coach_access' => 'Session',
751
            'session_days_after_coach_access' => 'Session',
752
            'pdf_logo_header' => 'Course',
753
            'order_user_list_by_official_code' => 'Platform',
754
            'email_alert_manager_on_new_quiz' => 'exercise',
755
            'show_official_code_exercise_result_list' => 'Tools',
756
            'course_catalog_hide_private' => 'Platform',
757
            'catalog_show_courses_sessions' => 'Platform',
758
            'auto_detect_language_custom_pages' => 'Platform',
759
            'lp_show_reduced_report' => 'Course',
760
            'allow_session_course_copy_for_teachers' => 'Session',
761
            'hide_logout_button' => 'Platform',
762
            'redirect_admin_to_courses_list' => 'Platform',
763
            'course_images_in_courses_list' => 'Course',
764
            'student_publication_to_take_in_gradebook' => 'Gradebook',
765
            'certificate_filter_by_official_code' => 'Gradebook',
766
            'exercise_max_ckeditors_in_page' => 'Tools',
767
            'document_if_file_exists_option' => 'Tools',
768
            'add_gradebook_certificates_cron_task_enabled' => 'Gradebook',
769
            'openbadges_backpack' => 'Gradebook',
770
            'cookie_warning' => 'Tools',
771
            'hide_course_group_if_no_tools_available' => 'Tools',
772
            'catalog_allow_session_auto_subscription' => 'Session',
773
            'registration.soap.php.decode_utf8' => 'Platform',
774
            'allow_delete_attendance' => 'Tools',
775
            'gravatar_enabled' => 'Platform',
776
            'gravatar_type' => 'Platform',
777
            'limit_session_admin_role' => 'Session',
778
            'show_session_description' => 'Session',
779
            'hide_certificate_export_link_students' => 'Gradebook',
780
            'hide_certificate_export_link' => 'Gradebook',
781
            'dropbox_hide_course_coach' => 'Tools',
782
            'dropbox_hide_general_coach' => 'Tools',
783
            'session_course_ordering' => 'Session',
784
            'gamification_mode' => 'Platform',
785
            'prevent_multiple_simultaneous_login' => 'Security',
786
            'gradebook_detailed_admin_view' => 'Gradebook',
787
            'course_catalog_published' => 'Course',
788
            'user_reset_password' => 'Security',
789
            'user_reset_password_token_limit' => 'Security',
790
            'my_courses_view_by_session' => 'Session',
791
            'show_full_skill_name_on_skill_wheel' => 'Platform',
792
            'messaging_allow_send_push_notification' => 'WebServices',
793
            'messaging_gdc_project_number' => 'WebServices',
794
            'messaging_gdc_api_key' => 'WebServices',
795
            'teacher_can_select_course_template' => 'Course',
796
            'enable_record_audio' => 'Tools',
797
            'allow_show_skype_account' => 'Platform',
798
            'allow_show_linkedin_url' => 'Platform',
799
            'enable_profile_user_address_geolocalization' => 'User',
800
            'show_official_code_whoisonline' => 'Profile',
801
            'icons_mode_svg' => 'display',
802
            'user_name_order' => 'display',
803
            'user_name_sort_by' => 'display',
804
            'default_calendar_view' => 'agenda',
805
            'exercise_invisible_in_session' => 'exercise',
806
            'configure_exercise_visibility_in_course' => 'exercise',
807
            'allow_download_documents_by_api_key' => 'Webservices',
808
            'profiling_filter_adding_users' => 'profile',
809
            'donotlistcampus' => 'platform',
810
            'course_creation_splash_screen' => 'Course',
811
            'translate_html' => 'Editor',
812
            'enable_bootstrap_in_documents_html' => 'Course',
813
        ];
814
    }
815
816
    /**
817
     * Rename old variable with variable used in Chamilo 2.0.
818
     *
819
     * @param string $variable
820
     */
821
    private function renameVariable($variable)
822
    {
823
        $list = [
824
            'timezone_value' => 'timezone',
825
            'Institution' => 'institution',
826
            'SiteName' => 'site_name',
827
            'siteName' => 'site_name',
828
            'InstitutionUrl' => 'institution_url',
829
            'registration' => 'required_profile_fields',
830
            'platformLanguage' => 'platform_language',
831
            'languagePriority1' => 'language_priority_1',
832
            'languagePriority2' => 'language_priority_2',
833
            'languagePriority3' => 'language_priority_3',
834
            'languagePriority4' => 'language_priority_4',
835
            'gradebook_score_display_coloring' => 'my_display_coloring',
836
            'ProfilingFilterAddingUsers' => 'profiling_filter_adding_users',
837
            'course_create_active_tools' => 'active_tools_on_create',
838
            'emailAdministrator' => 'administrator_email',
839
            'administratorSurname' => 'administrator_surname',
840
            'administratorName' => 'administrator_name',
841
            'administratorTelephone' => 'administrator_phone',
842
            'registration.soap.php.decode_utf8' => 'decode_utf8',
843
            'profile' => 'changeable_options',
844
        ];
845
846
        return $list[$variable] ?? $variable;
847
    }
848
849
    /**
850
     * Replace old Chamilo 1.x category with 2.0 version.
851
     *
852
     * @param string $variable
853
     * @param string $defaultCategory
854
     */
855
    private function fixCategory($variable, $defaultCategory)
856
    {
857
        $settings = [
858
            'cookie_warning' => 'platform',
859
            'donotlistcampus' => 'platform',
860
            'administrator_email' => 'admin',
861
            'administrator_surname' => 'admin',
862
            'administrator_name' => 'admin',
863
            'administrator_phone' => 'admin',
864
            'exercise_max_ckeditors_in_page' => 'exercise',
865
            'allow_hr_skills_management' => 'skill',
866
            'accessibility_font_resize' => 'display',
867
            'account_valid_duration' => 'profile',
868
            'allow_global_chat' => 'chat',
869
            'allow_lostpassword' => 'registration',
870
            'allow_registration' => 'registration',
871
            'allow_registration_as_teacher' => 'registration',
872
            'required_profile_fields' => 'registration',
873
            'allow_skills_tool' => 'skill',
874
            'allow_students_to_browse_courses' => 'display',
875
            'allow_terms_conditions' => 'registration',
876
            'allow_users_to_create_courses' => 'course',
877
            'auto_detect_language_custom_pages' => 'language',
878
            'platform_language' => 'language',
879
            'course_validation' => 'course',
880
            'course_validation_terms_and_conditions_url' => 'course',
881
            'display_categories_on_homepage' => 'display',
882
            'display_coursecode_in_courselist' => 'course',
883
            'display_teacher_in_courselist' => 'course',
884
            'drh_autosubscribe' => 'registration',
885
            'drh_page_after_login' => 'registration',
886
            'enable_help_link' => 'display',
887
            'example_material_course_creation' => 'course',
888
            'login_is_email' => 'profile',
889
            'noreply_email_address' => 'mail',
890
            'page_after_login' => 'registration',
891
            'pdf_export_watermark_by_course' => 'document',
892
            'pdf_export_watermark_enable' => 'document',
893
            'pdf_export_watermark_text' => 'document',
894
            'platform_unsubscribe_allowed' => 'registration',
895
            'send_email_to_admin_when_create_course' => 'course',
896
            'show_admin_toolbar' => 'display',
897
            'show_administrator_data' => 'display',
898
            'show_back_link_on_top_of_tree' => 'display',
899
            'show_closed_courses' => 'display',
900
            'show_different_course_language' => 'display',
901
            'show_email_addresses' => 'display',
902
            'show_empty_course_categories' => 'display',
903
            'show_full_skill_name_on_skill_wheel' => 'skill',
904
            'show_hot_courses' => 'display',
905
            'show_link_bug_notification' => 'display',
906
            'show_number_of_courses' => 'display',
907
            'show_teacher_data' => 'display',
908
            'showonline' => 'display',
909
            'student_autosubscribe' => 'registration',
910
            'student_page_after_login' => 'registration',
911
            'student_view_enabled' => 'course',
912
            'teacher_autosubscribe' => 'registration',
913
            'teacher_page_after_login' => 'registration',
914
            'time_limit_whosonline' => 'display',
915
            'user_selected_theme' => 'profile',
916
            'hide_global_announcements_when_not_connected' => 'announcement',
917
            'hide_home_top_when_connected' => 'display',
918
            'hide_logout_button' => 'display',
919
            'institution_address' => 'platform',
920
            'redirect_admin_to_courses_list' => 'admin',
921
            'use_custom_pages' => 'platform',
922
            'allow_group_categories' => 'group',
923
            'allow_user_headings' => 'display',
924
            'default_document_quotum' => 'document',
925
            'default_forum_view' => 'forum',
926
            'default_group_quotum' => 'document',
927
            'enable_quiz_scenario' => 'exercise',
928
            'exercise_max_score' => 'exercise',
929
            'exercise_min_score' => 'exercise',
930
            'pdf_logo_header' => 'platform',
931
            'show_glossary_in_documents' => 'document',
932
            'show_glossary_in_extra_tools' => 'glossary',
933
            'survey_email_sender_noreply' => 'survey',
934
            'allow_coach_feedback_exercises' => 'exercise',
935
            'sessionadmin_autosubscribe' => 'registration',
936
            'sessionadmin_page_after_login' => 'registration',
937
            'show_tutor_data' => 'display',
938
            'allow_social_tool' => 'social',
939
            'allow_message_tool' => 'message',
940
            'allow_email_editor' => 'editor',
941
            'show_link_ticket_notification' => 'display',
942
            'permissions_for_new_directories' => 'document',
943
            'enable_profile_user_address_geolocalization' => 'profile',
944
            'allow_show_skype_account' => 'profile',
945
            'allow_show_linkedin_url' => 'profile',
946
            'allow_students_to_create_groups_in_social' => 'social',
947
            'default_calendar_view' => 'agenda',
948
            'documents_default_visibility_defined_in_course' => 'document',
949
            'message_max_upload_filesize' => 'message',
950
            'course_create_active_tools' => 'course',
951
            'tool_visible_by_default_at_creation' => 'document',
952
            'show_users_folders' => 'document',
953
            'show_default_folders' => 'document',
954
            'show_chat_folder' => 'chat',
955
            'enabled_support_svg' => 'editor',
956
            'enabled_support_pixlr' => 'editor',
957
            'enable_webcam_clip' => 'document',
958
            'enable_record_audio' => 'course',
959
            'enabled_text2audio' => 'document',
960
            'permanently_remove_deleted_files' => 'document',
961
            'allow_delete_attendance' => 'attendance',
962
            'display_groups_forum_in_general_tool' => 'forum',
963
            'dropbox_allow_overwrite' => 'dropbox',
964
            'allow_user_course_subscription_by_course_admin' => 'course',
965
            'hide_course_group_if_no_tools_available' => 'group',
966
            'extend_rights_for_coach_on_survey' => 'survey',
967
            'show_official_code_exercise_result_list' => 'exercise',
968
            'dropbox_max_filesize' => 'dropbox',
969
            'dropbox_allow_just_upload' => 'dropbox',
970
            'dropbox_allow_student_to_student' => 'dropbox',
971
            'dropbox_allow_group' => 'dropbox',
972
            'dropbox_allow_mailing' => 'dropbox',
973
            'upload_extensions_list_type' => 'document',
974
            'upload_extensions_blacklist' => 'document',
975
            'upload_extensions_skip' => 'document',
976
            'changeable_options' => 'profile',
977
            'users_copy_files' => 'document',
978
            'document_if_file_exists_option' => 'document',
979
            'permissions_for_new_files' => 'document',
980
            'extended_profile' => 'profile',
981
            'split_users_upload_directory' => 'profile',
982
            'show_documents_preview' => 'document',
983
            'messaging_allow_send_push_notification' => 'webservice',
984
            'messaging_gdc_project_number' => 'webservice',
985
            'messaging_gdc_api_key' => 'webservice',
986
            'allow_download_documents_by_api_key' => 'webservice',
987
            'profiling_filter_adding_users' => 'profile',
988
            'hide_dltt_markup' => 'language',
989
            'active_tools_on_create' => 'course',
990
        ];
991
992
        return $settings[$variable] ?? $defaultCategory;
993
    }
994
995
    private function transformToString($value): string
996
    {
997
        if (is_array($value)) {
998
            return implode(',', $value);
999
        }
1000
1001
        if ($value instanceof Course) {
1002
            return (string) $value->getId();
1003
        }
1004
1005
        if (is_bool($value)) {
1006
            return $value ? 'true' : 'false';
1007
        }
1008
1009
        if (is_null($value)) {
1010
            return '';
1011
        }
1012
1013
        return (string) $value;
1014
    }
1015
}
1016