Passed
Push — master ( 6761c6...82c8fb )
by Angel Fernando Quiroz
08:20 queued 13s
created

SettingsManager::getSetting()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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