Passed
Push — master ( 212654...8aa330 )
by Angel Fernando Quiroz
11:04
created

handlePlugins()   F

Complexity

Conditions 13
Paths 410

Size

Total Lines 98
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 63
c 0
b 0
f 0
nc 410
nop 0
dl 0
loc 98
rs 3.4228

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
5
use Chamilo\CoreBundle\Entity\Plugin as PluginEntity;
6
use Chamilo\CoreBundle\Entity\SystemTemplate;
7
use ChamiloSession as Session;
8
use Symfony\Component\Filesystem\Filesystem;
9
use Chamilo\CoreBundle\Framework\Container;
10
use Chamilo\CoreBundle\Entity\Asset;
11
use Chamilo\CoreBundle\Component\Utils\ActionIcon;
12
use Chamilo\CoreBundle\Component\Utils\ObjectIcon;
13
use Chamilo\CoreBundle\Component\Utils\StateIcon;
14
15
/**
16
 * Library of the settings.php file.
17
 *
18
 * @author Julio Montoya <[email protected]>
19
 * @author Guillaume Viguier <[email protected]>
20
 *
21
 * @since Chamilo 1.8.7
22
 */
23
define('CSS_UPLOAD_PATH', api_get_path(SYMFONY_SYS_PATH).'var/themes/');
24
25
/**
26
 * This function allows easy activating and inactivating of regions.
27
 *
28
 * @author Julio Montoya <[email protected]> Beeznest 2012
29
 */
30
function handleRegions()
31
{
32
    if (isset($_POST['submit_plugins'])) {
33
        storeRegions();
34
        // Add event to the system log.
35
        $user_id = api_get_user_id();
36
        $category = $_GET['category'];
37
        Event::addEvent(
0 ignored issues
show
Bug introduced by
The method addEvent() does not exist on Event. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

37
        Event::/** @scrutinizer ignore-call */ 
38
               addEvent(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
38
            LOG_CONFIGURATION_SETTINGS_CHANGE,
39
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
40
            $category,
41
            api_get_utc_datetime(),
42
            $user_id
43
        );
44
        echo Display::return_message(get_lang('The settings have been stored'), 'confirmation');
45
    }
46
47
    $plugin_obj = new AppPlugin();
48
    $installed_plugins = $plugin_obj->getInstalledPlugins();
49
50
    echo '<form name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'">';
51
    echo '<table class="data_table">';
52
    echo '<tr>';
53
    echo '<th width="400px">';
54
    echo get_lang('Plugin');
55
    echo '</th><th>';
56
    echo get_lang('Regions');
57
    echo '</th>';
58
    echo '</th>';
59
    echo '</tr>';
60
61
    /* We display all the possible plugins and the checkboxes */
62
    $plugin_region_list = [];
63
    $my_plugin_list = $plugin_obj->getPluginRegions();
64
    foreach ($my_plugin_list as $plugin_item) {
65
        $plugin_region_list[$plugin_item] = $plugin_item;
66
    }
67
68
    // Removing course tool
69
    unset($plugin_region_list['course_tool_plugin']);
70
71
    foreach ($installed_plugins as $pluginName) {
72
        $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/plugin.php';
73
74
        if (file_exists($plugin_info_file)) {
75
            $plugin_info = [];
76
            require $plugin_info_file;
77
            if (isset($_GET['name']) && $_GET['name'] === $pluginName) {
78
                echo '<tr class="row_selected">';
79
            } else {
80
                echo '<tr>';
81
            }
82
            echo '<td>';
83
            echo '<h4>'.$plugin_info['title'].' <small>v'.$plugin_info['version'].'</small></h4>';
84
            echo '<p>'.$plugin_info['comment'].'</p>';
85
            echo '</td><td>';
86
            $selected_plugins = $plugin_obj->get_areas_by_plugin($pluginName);
87
            $region_list = [];
88
            $isAdminPlugin = isset($plugin_info['is_admin_plugin']) && $plugin_info['is_admin_plugin'];
89
            $isCoursePlugin = isset($plugin_info['is_course_plugin']) && $plugin_info['is_course_plugin'];
90
91
            if (!$isAdminPlugin && !$isCoursePlugin) {
92
                $region_list = $plugin_region_list;
93
            } else {
94
                if ($isAdminPlugin) {
95
                    $region_list['menu_administrator'] = 'menu_administrator';
96
                }
97
                if ($isCoursePlugin) {
98
                    $region_list['course_tool_plugin'] = 'course_tool_plugin';
99
                }
100
            }
101
102
            echo Display::select(
103
                'plugin_'.$pluginName.'[]',
104
                $region_list,
105
                $selected_plugins,
106
                ['multiple' => 'multiple', 'style' => 'width:500px'],
107
                true,
108
                get_lang('none')
109
            );
110
            echo '</td></tr>';
111
        }
112
    }
113
    echo '</table>';
114
    echo '<br />';
115
    echo '<button class="btn btn--success" type="submit" name="submit_plugins">'.get_lang('Enable the selected plugins').'</button></form>';
116
}
117
118
function handleExtensions()
119
{
120
    echo Display::page_subheader(get_lang('Configure extensions'));
121
    echo '<a class="btn btn--success" href="configure_extensions.php?display=ppt2lp" role="button">'.get_lang('Chamilo RAPID').'</a>';
122
}
123
124
/**
125
 * This function allows easy activating and inactivating of plugins.
126
 *
127
 * @todo: a similar function needs to be written to activate or inactivate additional tools.
128
 *
129
 * @author Patrick Cool <[email protected]>, Ghent University
130
 * @author Julio Montoya <[email protected]> Beeznest 2012
131
 */
132
function handlePlugins()
133
{
134
    Session::erase('plugin_data');
135
    $pluginRepo = Container::getPluginRepository();
136
137
    $allPlugins = (new AppPlugin())->read_plugins_from_path();
138
139
    echo '<div class="p-6 bg-white shadow-lg rounded-lg">';
140
141
    // Header
142
    echo '<div class="mb-4 flex items-center justify-between">';
143
    echo '<h2 class="text-2xl font-semibold text-gray-90">'.get_lang('Manage Plugins').'</h2>';
144
    echo '<p class="text-gray-50 text-sm">'.get_lang('Install, activate or deactivate plugins easily.').'</p>';
145
    echo '</div>';
146
147
    echo '<table class="w-full border border-gray-25 rounded-lg shadow-md">';
148
    echo '<thead>';
149
    echo '<tr class="bg-gray-10 text-left">';
150
    echo '<th class="p-3 border-b border-gray-25">'.get_lang('Plugin').'</th>';
151
    echo '<th class="p-3 border-b border-gray-25">'.get_lang('Version').'</th>';
152
    echo '<th class="p-3 border-b border-gray-25">'.get_lang('Status').'</th>';
153
    echo '<th class="p-3 border-b border-gray-25 text-center">'.get_lang('Actions').'</th>';
154
    echo '</tr>';
155
    echo '</thead>';
156
    echo '<tbody>';
157
158
    foreach ($allPlugins as $pluginName) {
159
        $pluginInfoFile = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/plugin.php';
160
161
        if (!file_exists($pluginInfoFile)) {
162
            continue;
163
        }
164
165
        $plugin_info = [];
166
167
        require $pluginInfoFile;
168
169
        /** @var PluginEntity|null $plugin */
170
        $plugin = $pluginRepo->findOneBy(['title' => $pluginName]);
171
        $pluginConfiguration = $plugin?->getConfigurationsByAccessUrl(Container::getAccessUrlHelper()->getCurrent());
172
        $isInstalled = $plugin && $plugin->isInstalled();
173
        $isEnabled = $plugin && $pluginConfiguration && $pluginConfiguration->isActive();
174
175
        // Status badge
176
        $statusBadge = $isInstalled
177
            ? ($isEnabled
178
                ? '<span class="px-2 py-1 text-sm font-semibold text-success-button-text bg-success/10 rounded-full">'.get_lang('Enabled').'</span>'
179
                : '<span class="px-2 py-1 text-sm font-semibold text-warning-button-text bg-warning/10 rounded-full">'.get_lang('Disabled').'</span>')
180
            : '<span class="px-2 py-1 text-sm font-semibold text-gray-50 bg-gray-20 rounded-full">'.get_lang('Not Installed').'</span>';
181
182
        echo '<tr class="border-t border-gray-25 hover:bg-gray-15 transition duration-200">';
183
        echo '<td class="p-3 font-medium">'.$plugin_info['title'].'</td>';
184
        echo '<td class="p-3">'.$plugin_info['version'].'</td>';
185
        echo '<td class="p-3">'.$statusBadge.'</td>';
186
        echo '<td class="p-3 text-center">';
187
188
        echo '<div class="flex justify-center gap-2">';
189
190
        if ($isInstalled) {
191
            echo '<button class="plugin-action bg-warning text-white px-4 py-2 rounded-md transition hover:bg-warning/80 flex items-center gap-2"
192
                    data-plugin="'.$pluginName.'" data-action="uninstall">
193
                    <i class="mdi mdi-trash-can-outline"></i> '.get_lang('Uninstall').'
194
                  </button>';
195
196
            $toggleAction = $isEnabled ? 'disable' : 'enable';
197
            $toggleText = $isEnabled ? get_lang('Disable') : get_lang('Enable');
198
            $toggleColor = $isEnabled
199
                ? 'bg-gray-50 text-gray-90 hover:bg-gray-90 hover:text-white'
200
                : 'bg-success text-success-button-text hover:bg-success/80';
201
202
            $toggleIcon = $isEnabled ? 'mdi mdi-toggle-switch-off-outline' : 'mdi mdi-toggle-switch-outline';
203
204
            echo '<button class="plugin-action '.$toggleColor.' px-4 py-2 rounded-md transition flex items-center gap-2"
205
                    data-plugin="'.$pluginName.'" data-action="'.$toggleAction.'">
206
                    <i class="'.$toggleIcon.'"></i> '.$toggleText.'
207
                  </button>';
208
        } else {
209
            echo '<button class="plugin-action bg-success text-white px-4 py-2 rounded-md transition hover:bg-success/80 flex items-center gap-2"
210
                    data-plugin="'.$pluginName.'" data-action="install">
211
                    <i class="mdi mdi-download"></i> '.get_lang('Install').'
212
                  </button>';
213
        }
214
215
        echo '</div>';
216
        echo '</td>';
217
        echo '</tr>';
218
    }
219
220
    echo '</tbody></table>';
221
    echo '</div>';
222
223
    echo '<script>
224
    $(document).ready(function () {
225
        $(".plugin-action").click(function () {
226
            var pluginName = $(this).data("plugin");
227
            var action = $(this).data("action");
228
229
            $.post("'.api_get_path(WEB_AJAX_PATH).'plugin.ajax.php", { a: action, plugin: pluginName }, function(response) {
230
                var data = JSON.parse(response);
231
                if (data.success) {
232
                    location.reload();
233
                } else {
234
                    alert("Error: " + data.error);
235
                }
236
            });
237
        });
238
    });
239
    </script>';
240
}
241
242
/**
243
 * Creates the folder (if needed) and uploads the stylesheet in it.
244
 *
245
 * @param array $values  the values of the form
246
 * @param array $picture the values of the uploaded file
247
 *
248
 * @return bool
249
 *
250
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
251
 *
252
 * @version May 2008
253
 *
254
 * @since v1.8.5
255
 */
256
function uploadStylesheet($values, $picture)
257
{
258
    $result = false;
259
    // Valid name for the stylesheet folder.
260
    $style_name = api_preg_replace('/[^A-Za-z0-9]/', '', $values['name_stylesheet']);
261
    if (empty($style_name) || is_array($style_name)) {
262
        // The name of the uploaded stylesheet doesn't have the expected format
263
        return $result;
264
    }
265
    $cssToUpload = CSS_UPLOAD_PATH;
266
267
    // Check if a virtual instance vchamilo is used
268
    $virtualInstanceTheme = api_get_configuration_value('virtual_css_theme_folder');
269
    if (!empty($virtualInstanceTheme)) {
270
        $cssToUpload = $cssToUpload.$virtualInstanceTheme.'/';
271
    }
272
273
    // Create the folder if needed.
274
    if (!is_dir($cssToUpload.$style_name.'/')) {
275
        mkdir($cssToUpload.$style_name.'/', api_get_permissions_for_new_directories());
276
    }
277
278
    $info = pathinfo($picture['name']);
279
280
    if ('zip' == $info['extension']) {
281
        // Try to open the file and extract it in the theme.
282
        $zip = new ZipArchive();
283
        if ($zip->open($picture['tmp_name'])) {
284
            // Make sure all files inside the zip are images or css.
285
            $num_files = $zip->numFiles;
286
            $valid = true;
287
            $single_directory = true;
288
            $invalid_files = [];
289
290
            $allowedFiles = getAllowedFileTypes();
291
292
            for ($i = 0; $i < $num_files; $i++) {
293
                $file = $zip->statIndex($i);
294
                if ('/' != substr($file['name'], -1)) {
295
                    $path_parts = pathinfo($file['name']);
296
                    if (!in_array($path_parts['extension'], $allowedFiles)) {
297
                        $valid = false;
298
                        $invalid_files[] = $file['name'];
299
                    }
300
                }
301
302
                if (false === strpos($file['name'], '/')) {
303
                    $single_directory = false;
304
                }
305
            }
306
            if (!$valid) {
307
                $error_string = '<ul>';
308
                foreach ($invalid_files as $invalid_file) {
309
                    $error_string .= '<li>'.$invalid_file.'</li>';
310
                }
311
                $error_string .= '</ul>';
312
                echo Display::return_message(
313
                    get_lang('The only accepted extensions in the ZIP file are .jp(e)g, .png, .gif and .css.').$error_string,
314
                    'error',
315
                    false
316
                );
317
            } else {
318
                // If the zip does not contain a single directory, extract it.
319
                if (!$single_directory) {
320
                    // Extract zip file.
321
                    $zip->extractTo($cssToUpload.$style_name.'/');
322
                    $result = true;
323
                } else {
324
                    $extraction_path = $cssToUpload.$style_name.'/';
325
                    $mode = api_get_permissions_for_new_directories();
326
                    for ($i = 0; $i < $num_files; $i++) {
327
                        $entry = $zip->getNameIndex($i);
328
                        if ('/' == substr($entry, -1)) {
329
                            continue;
330
                        }
331
332
                        $pos_slash = strpos($entry, '/');
333
                        $entry_without_first_dir = substr($entry, $pos_slash + 1);
334
                        // If there is still a slash, we need to make sure the directories are created.
335
                        if (false !== strpos($entry_without_first_dir, '/')) {
336
                            if (!is_dir($extraction_path.dirname($entry_without_first_dir))) {
337
                                // Create it.
338
                                @mkdir($extraction_path.dirname($entry_without_first_dir), $mode, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

338
                                /** @scrutinizer ignore-unhandled */ @mkdir($extraction_path.dirname($entry_without_first_dir), $mode, true);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
339
                            }
340
                        }
341
342
                        $fp = $zip->getStream($entry);
343
                        $ofp = fopen($extraction_path.dirname($entry_without_first_dir).'/'.basename($entry), 'w');
344
345
                        while (!feof($fp)) {
346
                            fwrite($ofp, fread($fp, 8192));
347
                        }
348
349
                        fclose($fp);
350
                        fclose($ofp);
351
                    }
352
                    $result = true;
353
                }
354
            }
355
            $zip->close();
356
        } else {
357
            echo Display::return_message(get_lang('Error reading ZIP file').$info['extension'], 'error', false);
358
        }
359
    } else {
360
        // Simply move the file.
361
        move_uploaded_file($picture['tmp_name'], $cssToUpload.$style_name.'/'.$picture['name']);
362
        $result = true;
363
    }
364
365
    if ($result) {
366
        $fs = new Filesystem();
367
        $fs->mirror(
368
            CSS_UPLOAD_PATH,
369
            api_get_path(SYMFONY_SYS_PATH).'var/themes/',
370
            null,
371
            ['override' => true]
372
        );
373
    }
374
375
    return $result;
376
}
377
378
/**
379
 * Store plugin regions.
380
 */
381
function storeRegions()
382
{
383
    $plugin_obj = new AppPlugin();
384
385
    // Get a list of all current 'Plugins' settings
386
    $installed_plugins = $plugin_obj->getInstalledPlugins();
387
    $shortlist_installed = [];
388
    if (!empty($installed_plugins)) {
389
        foreach ($installed_plugins as $plugin) {
390
            if (isset($plugin['subkey'])) {
391
                $shortlist_installed[] = $plugin['subkey'];
392
            }
393
        }
394
    }
395
396
    $plugin_list = $plugin_obj->read_plugins_from_path();
397
398
    foreach ($plugin_list as $plugin) {
399
        if (isset($_POST['plugin_'.$plugin])) {
400
            $areas_to_installed = $_POST['plugin_'.$plugin];
401
            if (!empty($areas_to_installed)) {
402
                $plugin_obj->removeAllRegions($plugin);
403
                foreach ($areas_to_installed as $region) {
404
                    if (!empty($region) && '-1' != $region) {
405
                        $plugin_obj->add_to_region($plugin, $region);
406
                    }
407
                }
408
            }
409
        }
410
    }
411
}
412
413
/**
414
 * This function checks if the given style is a recognize style that exists in the css directory as
415
 * a standalone directory.
416
 *
417
 * @param string $style
418
 *
419
 * @return bool True if this style is recognized, false otherwise
420
 */
421
function isStyle($style)
422
{
423
    $themeList = api_get_themes();
424
425
    return in_array($style, array_keys($themeList));
426
}
427
428
/**
429
 * Search options
430
 * TODO: support for multiple site. aka $_configuration['access_url'] == 1.
431
 *
432
 * @author Marco Villegas <[email protected]>
433
 */
434
function handleSearch()
435
{
436
    global $SettingsStored, $_configuration;
437
438
    $search_enabled = api_get_setting('search_enabled');
439
440
    $form = new FormValidator(
441
        'search-options',
442
        'post',
443
        api_get_self().'?category=Search'
444
    );
445
    $values = api_get_settings_options('search_enabled');
446
    $form->addElement('header', null, get_lang('Fulltext search'));
447
448
    $group = formGenerateElementsGroup($form, $values, 'search_enabled');
449
450
    // SearchEnabledComment
451
    $form->addGroup(
452
        $group,
453
        'search_enabled',
454
        [get_lang('Fulltext search'), get_lang('This feature allows you to index most of the documents uploaded to your portal, then provide a search feature for users.<br />This feature will not index documents that have already been uploaded, so it is important to enable (if wanted) at the beginning of your implementation.<br />Once enabled, a search box will appear in the courses list of every user. Searching for a specific term will bring a list of corresponding documents, exercises or forum topics, filtered depending on the availability of these contents to the user.')],
455
        null,
456
        false
457
    );
458
459
    $search_enabled = api_get_setting('search_enabled');
460
461
    if ($form->validate()) {
462
        $formValues = $form->exportValues();
463
        setConfigurationSettingsInDatabase($formValues, $_configuration['access_url']);
464
        $search_enabled = $formValues['search_enabled'];
465
        echo Display::return_message($SettingsStored, 'confirm');
466
    }
467
    $specific_fields = get_specific_field_list();
468
469
    if ('true' == $search_enabled) {
470
        $values = api_get_settings_options('search_show_unlinked_results');
471
        $group = formGenerateElementsGroup(
472
            $form,
473
            $values,
474
            'search_show_unlinked_results'
475
        );
476
        $form->addGroup(
477
            $group,
478
            'search_show_unlinked_results',
479
            [
480
                get_lang('Full-text search: show unlinked results'),
481
                get_lang('When showing the results of a full-text search, what should be done with the results that are not accessible to the current user?'),
482
            ],
483
            null,
484
            false
485
        );
486
        $default_values['search_show_unlinked_results'] = api_get_setting('search_show_unlinked_results');
0 ignored issues
show
Comprehensibility Best Practice introduced by
$default_values was never initialized. Although not strictly required by PHP, it is generally a good practice to add $default_values = array(); before regardless.
Loading history...
487
488
        $sf_values = [];
489
        foreach ($specific_fields as $sf) {
490
            $sf_values[$sf['code']] = $sf['name'];
491
        }
492
        $url = Display::div(
493
            Display::url(
494
                get_lang('Add a specific search field'),
495
                'specific_fields.php'
496
            ),
497
            ['class' => 'sectioncomment']
498
        );
499
        if (empty($sf_values)) {
500
            $form->addElement('label', [get_lang('Specific Field for prefilter'), $url]);
501
        } else {
502
            $form->addElement(
503
                'select',
504
                'search_prefilter_prefix',
505
                [get_lang('Specific Field for prefilter'), $url],
506
                $sf_values,
507
                ''
508
            );
509
            $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix');
510
        }
511
    }
512
513
    $default_values['search_enabled'] = $search_enabled;
514
515
    $form->addButtonSave(get_lang('Save'));
516
    $form->setDefaults($default_values);
517
518
    echo '<div id="search-options-form">';
519
    $form->display();
520
    echo '</div>';
521
522
    if ('true' == $search_enabled) {
523
        //$xapianPath = api_get_path(SYS_UPLOAD_PATH).'plugins/xapian/searchdb';
524
525
        /*
526
        @todo Test the Xapian connection
527
        if (extension_loaded('xapian')) {
528
            require_once 'xapian.php';
529
            try {
530
                $db = new XapianDatabase($xapianPath.'/');
531
            } catch (Exception $e) {
532
                var_dump($e->getMessage());
533
            }
534
535
            require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
536
            require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
537
            require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
538
539
            $indexable = new IndexableChunk();
540
            $indexable->addValue("content", 'Test');
541
542
            $di = new ChamiloIndexer();
543
            $di->connectDb(NULL, NULL, 'english');
544
            $di->addChunk($indexable);
545
            $did = $di->index();
546
        }
547
        */
548
549
        $xapianLoaded = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Validate'));
550
        $dir_exists = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Validate'));
551
        $dir_is_writable = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Validate'));
552
        $specific_fields_exists = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Validate'));
553
554
        //Testing specific fields
555
        if (empty($specific_fields)) {
556
            $specific_fields_exists = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Add a specific search field')
557
            );
558
        }
559
        //Testing xapian extension
560
        if (!extension_loaded('xapian')) {
561
            $xapianLoaded = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Error'));
562
        }
563
        //Testing xapian searchdb path
564
        if (!is_dir($xapianPath)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $xapianPath seems to be never defined.
Loading history...
565
            $dir_exists = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Error'));
566
        }
567
        //Testing xapian searchdb path is writable
568
        if (!is_writable($xapianPath)) {
569
            $dir_is_writable = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Error'));
570
        }
571
572
        $data = [];
573
        $data[] = [get_lang('Xapian module installed'), $xapianLoaded];
574
        $data[] = [get_lang('The directory exists').' - '.$xapianPath, $dir_exists];
575
        $data[] = [get_lang('Is writable').' - '.$xapianPath, $dir_is_writable];
576
        $data[] = [get_lang('Available custom search fields'), $specific_fields_exists];
577
578
        showSearchSettingsTable($data);
579
        showSearchToolsStatusTable();
580
    }
581
}
582
583
/**
584
 * Wrapper for the templates.
585
 *
586
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
587
 * @author Julio Montoya.
588
 *
589
 * @version August 2008
590
 *
591
 * @since v1.8.6
592
 */
593
function handleTemplates()
594
{
595
    /* Drive-by fix to avoid undefined var warnings, without repeating
596
     * isset() combos all over the place. */
597
    $action = isset($_GET['action']) ? $_GET['action'] : "invalid";
598
599
    if ('add' != $action) {
600
        echo '<div class="actions" style="margin-left: 1px;">';
601
        echo '<a href="settings.php?category=Templates&action=add">'.
602
                Display::getMdiIcon(ObjectIcon::TEMPLATE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add a template')).'</a>';
603
        echo '</div>';
604
    }
605
606
    if ('add' == $action || ('edit' == $action && is_numeric($_GET['id']))) {
607
        addEditTemplate();
608
609
        // Add event to the system log.
610
        $user_id = api_get_user_id();
611
        $category = $_GET['category'];
612
        Event::addEvent(
613
            LOG_CONFIGURATION_SETTINGS_CHANGE,
614
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
615
            $category,
616
            api_get_utc_datetime(),
617
            $user_id
618
        );
619
    } else {
620
        if ('delete' == $action && is_numeric($_GET['id'])) {
621
            deleteTemplate($_GET['id']);
622
623
            // Add event to the system log
624
            $user_id = api_get_user_id();
625
            $category = $_GET['category'];
626
            Event::addEvent(
627
                LOG_CONFIGURATION_SETTINGS_CHANGE,
628
                LOG_CONFIGURATION_SETTINGS_CATEGORY,
629
                $category,
630
                api_get_utc_datetime(),
631
                $user_id
632
            );
633
        }
634
        displayTemplates();
635
    }
636
}
637
638
/**
639
 * Display a sortable table with all the templates that the platform administrator has defined.
640
 *
641
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
642
 *
643
 * @version August 2008
644
 *
645
 * @since v1.8.6
646
 */
647
function displayTemplates()
648
{
649
    $table = new SortableTable(
650
        'templates',
651
        'getNumberOfTemplates',
652
        'getTemplateData',
653
        1
654
    );
655
    $table->set_additional_parameters(
656
        ['category' => Security::remove_XSS($_GET['category'])]
657
    );
658
    $table->set_header(0, get_lang('Image'), true, ['style' => 'width: 101px;']);
659
    $table->set_header(1, get_lang('Title'));
660
    $table->set_header(2, get_lang('Detail'), false, ['style' => 'width:50px;']);
661
    $table->set_column_filter(2, 'actionsFilter');
662
    $table->set_column_filter(0, 'searchImageFilter');
663
    $table->display();
664
}
665
666
/**
667
 * Gets the number of templates that are defined by the platform admin.
668
 *
669
 * @return int
670
 *
671
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
672
 *
673
 * @version August 2008
674
 *
675
 * @since v1.8.6
676
 */
677
function getNumberOfTemplates()
678
{
679
    // Database table definition.
680
    $table = Database::get_main_table('system_template');
681
682
    // The sql statement.
683
    $sql = "SELECT COUNT(id) AS total FROM $table";
684
    $result = Database::query($sql);
685
    $row = Database::fetch_array($result);
686
687
    // Returning the number of templates.
688
    return $row['total'];
689
}
690
691
/**
692
 * Gets all the template data for the sortable table.
693
 *
694
 * @param int    $from            the start of the limit statement
695
 * @param int    $number_of_items the number of elements that have to be retrieved from the database
696
 * @param int    $column          the column that is
697
 * @param string $direction       the sorting direction (ASC or DESC)
698
 *
699
 * @return array
700
 *
701
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
702
 *
703
 * @version August 2008
704
 *
705
 * @since v1.8.6
706
 */
707
function getTemplateData($from, $number_of_items, $column, $direction)
708
{
709
    // Database table definition.
710
    $table_system_template = Database::get_main_table('system_template');
711
712
    $from = (int) $from;
713
    $number_of_items = (int) $number_of_items;
714
    $column = (int) $column;
715
    $direction = !in_array(strtolower(trim($direction)), ['asc', 'desc']) ? 'asc' : $direction;
716
    // The sql statement.
717
    $sql = "SELECT id as col0, title as col1, id as col2 FROM $table_system_template";
718
    $sql .= " ORDER BY col$column $direction ";
719
    $sql .= " LIMIT $from,$number_of_items";
720
    $result = Database::query($sql);
721
    $return = [];
722
    while ($row = Database::fetch_array($result)) {
723
        $row['1'] = get_lang($row['1']);
724
        $return[] = $row;
725
    }
726
    // Returning all the information for the sortable table.
727
    return $return;
728
}
729
730
/**
731
 * display the edit and delete icons in the sortable table.
732
 *
733
 * @param int $id the id of the template
734
 *
735
 * @return string code for the link to edit and delete the template
736
 *
737
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
738
 *
739
 * @version August 2008
740
 *
741
 * @since v1.8.6
742
 */
743
function actionsFilter($id)
744
{
745
    $return = '<a href="settings.php?category=Templates&action=edit&id='.Security::remove_XSS($id).'">'.Display::getMdiIcon(ActionIcon::EDIT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Edit')).'</a>';
746
    $return .= '<a href="settings.php?category=Templates&action=delete&id='.Security::remove_XSS($id).'" onClick="javascript:if(!confirm('."'".get_lang('Please confirm your choice')."'".')) return false;">'.Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Delete')).'</a>';
747
748
    return $return;
749
}
750
751
function searchImageFilter(int $id): string
752
{
753
    $em = Database::getManager();
754
755
    /** @var SystemTemplate $template */
756
    $template = $em->find(SystemTemplate::class, $id);
757
758
    if (null !== $template->getImage()) {
759
        $assetRepo = Container::getAssetRepository();
760
        $imageUrl = $assetRepo->getAssetUrl($template->getImage());
761
762
        return '<img src="'.$imageUrl.'" alt="'.get_lang('Template preview').'"/>';
763
    } else {
764
        return '<img src="'.api_get_path(WEB_PUBLIC_PATH).'img/template_thumb/noimage.gif" alt="'.get_lang('NoTemplate preview').'"/>';
765
    }
766
}
767
768
/**
769
 * Add (or edit) a template. This function displays the form and also takes
770
 * care of uploading the image and storing the information in the database.
771
 *
772
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
773
 *
774
 * @version August 2008
775
 *
776
 * @since v1.8.6
777
 */
778
function addEditTemplate()
779
{
780
    $em = Database::getManager();
781
    $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
782
783
    $assetRepo = Container::getAssetRepository();
784
785
    /** @var SystemTemplate $template */
786
    $template = $id ? $em->find(SystemTemplate::class, $id) : new SystemTemplate();
787
788
    $form = new FormValidator(
789
        'template',
790
        'post',
791
        'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).'&id='.$id
792
    );
793
794
    // Setting the form elements: the header.
795
    if ('add' == $_GET['action']) {
796
        $title = get_lang('Add a template');
797
    } else {
798
        $title = get_lang('Template edition');
799
    }
800
    $form->addElement('header', '', $title);
801
802
    // Setting the form elements: the title of the template.
803
    $form->addText('title', get_lang('Title'), false);
804
    $form->addText('comment', get_lang('Description'), false);
805
806
    // Setting the form elements: the content of the template (wysiwyg editor).
807
    $form->addHtmlEditor(
808
        'template_text',
809
        get_lang('Text'),
810
        true,
811
        true,
812
        ['ToolbarSet' => 'Documents', 'Width' => '100%', 'Height' => '400']
813
    );
814
815
    // Setting the form elements: the form to upload an image to be used with the template.
816
    if (!$template->hasImage()) {
817
        // Picture
818
        $form->addFile(
819
            'template_image',
820
            get_lang('Add image'),
821
            ['id' => 'picture', 'class' => 'picture-form', 'crop_image' => true, 'crop_ratio' => '1 / 1']
822
        );
823
        $allowedPictureTypes = api_get_supported_image_extensions(false);
824
        $form->addRule('template_image', get_lang('Only PNG, JPG or GIF images allowed').' ('.implode(',', $allowedPictureTypes).')', 'filetype', $allowedPictureTypes);
825
    }
826
827
    // Setting the form elements: a little bit of information about the template image.
828
    $form->addElement('static', 'file_comment', '', get_lang('This image will represent the template in the templates list. It should be no larger than 100x70 pixels'));
829
830
    // Getting all the information of the template when editing a template.
831
    if ('edit' == $_GET['action']) {
832
        $defaults['template_id'] = $id;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$defaults was never initialized. Although not strictly required by PHP, it is generally a good practice to add $defaults = array(); before regardless.
Loading history...
833
        $defaults['template_text'] = $template->getContent();
834
        // Forcing get_lang().
835
        $defaults['title'] = $template->getTitle();
836
        $defaults['comment'] = $template->getComment();
837
838
        // Adding an extra field: a hidden field with the id of the template we are editing.
839
        $form->addElement('hidden', 'template_id');
840
841
        // Adding an extra field: a preview of the image that is currently used.
842
843
        if ($template->hasImage()) {
844
            $imageUrl = $assetRepo->getAssetUrl($template->getImage());
845
            $form->addElement(
846
                'static',
847
                'template_image_preview',
848
                '',
849
                '<img src="'.$imageUrl
850
                    .'" alt="'.get_lang('Template preview')
851
                    .'"/>'
852
            );
853
            $form->addCheckBox('delete_image', null, get_lang('Delete picture'));
854
        } else {
855
            $form->addElement(
856
                'static',
857
                'template_image_preview',
858
                '',
859
                '<img src="'.api_get_path(WEB_PUBLIC_PATH).'img/template_thumb/noimage.gif" alt="'.get_lang('NoTemplate preview').'"/>'
860
            );
861
        }
862
863
        // Setting the information of the template that we are editing.
864
        $form->setDefaults($defaults);
865
    }
866
    // Setting the form elements: the submit button.
867
    $form->addButtonSave(get_lang('Validate'), 'submit');
868
869
    // Setting the rules: the required fields.
870
    if (!$template->hasImage()) {
871
        $form->addRule(
872
            'template_image',
873
            get_lang('Required field'),
874
            'required'
875
        );
876
        $form->addRule('title', get_lang('Required field'), 'required');
877
    }
878
879
    // if the form validates (complies to all rules) we save the information,
880
    // else we display the form again (with error message if needed)
881
    if ($form->validate()) {
882
        $check = Security::check_token('post');
883
884
        if ($check) {
885
            // Exporting the values.
886
            $values = $form->exportValues();
887
            $asset = null;
888
            if (isset($values['delete_image']) && !empty($id)) {
889
                deleteTemplateImage($id);
890
            }
891
892
            // Upload the file.
893
            if (!empty($_FILES['template_image']['name'])) {
894
                $picture = $_FILES['template_image'];
895
                if (!empty($picture['name'])) {
896
                    $asset = (new Asset())
897
                        ->setCategory(Asset::SYSTEM_TEMPLATE)
898
                        ->setTitle($picture['name'])
899
                    ;
900
                    if (!empty($values['picture_crop_result'])) {
901
                        $asset->setCrop($values['picture_crop_result']);
902
                    }
903
                    $asset = $assetRepo->createFromRequest($asset, $picture);
904
                }
905
            }
906
907
            // Store the information in the database (as insert or as update).
908
            $bootstrap = api_get_bootstrap_and_font_awesome();
909
            $viewport = '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
910
911
            if ('add' == $_GET['action']) {
912
                $templateContent = '<head>'.$viewport.'<title>'.$values['title'].'</title>'.$bootstrap.'</head>'
913
                    .$values['template_text'];
914
                $template
915
                    ->setTitle($values['title'])
916
                    ->setComment(Security::remove_XSS($values['comment']))
917
                    ->setContent(Security::remove_XSS($templateContent, COURSEMANAGERLOWSECURITY))
918
                    ->setImage($asset);
919
                $em->persist($template);
920
                $em->flush();
921
922
                // Display a feedback message.
923
                echo Display::return_message(
924
                    get_lang('Template added'),
925
                    'confirm'
926
                );
927
                echo '<a href="settings.php?category=Templates&action=add">'.
928
                    Display::getMdiIcon(ObjectIcon::TEMPLATE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add a template')).
929
                    '</a>';
930
            } else {
931
                $templateContent = '<head>'.$viewport.'<title>'.$values['title'].'</title>'.$bootstrap.'</head>'
932
                    .$values['template_text'];
933
934
                $template
935
                    ->setTitle($values['title'])
936
                    ->setContent(Security::remove_XSS($templateContent, COURSEMANAGERLOWSECURITY));
937
938
                if ($asset) {
939
                    $template->setImage($asset);
940
                }
941
942
                $em->persist($template);
943
                $em->flush();
944
945
                // Display a feedback message.
946
                echo Display::return_message(get_lang('Template edited'), 'confirm');
947
            }
948
        }
949
        Security::clear_token();
950
        displayTemplates();
951
    } else {
952
        $token = Security::get_token();
953
        $form->addElement('hidden', 'sec_token');
954
        $form->setConstants(['sec_token' => $token]);
955
        // Display the form.
956
        $form->display();
957
    }
958
}
959
960
/**
961
 * Deletes the template picture as asset.
962
 *
963
 * @param int $id
964
 */
965
function deleteTemplateImage($id)
966
{
967
    $em = Database::getManager();
968
969
    /** @var SystemTemplate $template */
970
    $template = $em->find(SystemTemplate::class, $id);
971
972
    if ($template && $template->hasImage()) {
973
        $image = $template->getImage();
974
        $em->remove($image);
975
        $em->flush();
976
    }
977
}
978
979
/**
980
 * Delete a template.
981
 *
982
 * @param int $id the id of the template that has to be deleted
983
 *
984
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
985
 *
986
 * @version August 2008
987
 *
988
 * @since v1.8.6
989
 */
990
function deleteTemplate($id)
991
{
992
    $id = intval($id);
993
    // First we remove the image.
994
    $table = Database::get_main_table('system_template');
995
    $sql = "SELECT * FROM $table WHERE id = $id";
996
    $result = Database::query($sql);
997
    $row = Database::fetch_array($result);
998
    if (!empty($row['image'])) {
999
        @unlink(api_get_path(SYS_APP_PATH).'home/default_platform_document/template_thumb/'.$row['image']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

999
        /** @scrutinizer ignore-unhandled */ @unlink(api_get_path(SYS_APP_PATH).'home/default_platform_document/template_thumb/'.$row['image']);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
Bug introduced by
The constant SYS_APP_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1000
    }
1001
1002
    // Now we remove it from the database.
1003
    $sql = "DELETE FROM $table WHERE id = $id";
1004
    Database::query($sql);
1005
1006
    deleteTemplateImage($id);
1007
1008
    // Display a feedback message.
1009
    echo Display::return_message(get_lang('Template deleted'), 'confirm');
1010
}
1011
1012
/**
1013
 * @param array $settings
1014
 * @param array $settings_by_access_list
1015
 *
1016
 * @throws \Doctrine\ORM\ORMException
1017
 * @throws \Doctrine\ORM\OptimisticLockException
1018
 * @throws \Doctrine\ORM\TransactionRequiredException
1019
 *
1020
 * @return FormValidator
1021
 */
1022
function generateSettingsForm($settings, $settings_by_access_list)
1023
{
1024
    global $_configuration, $settings_to_avoid, $convert_byte_to_mega_list;
1025
    $em = Database::getManager();
1026
    $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS);
1027
1028
    $form = new FormValidator(
1029
        'settings',
1030
        'post',
1031
        'settings.php?category='.Security::remove_XSS($_GET['category'])
1032
    );
1033
1034
    $form->addElement(
1035
        'hidden',
1036
        'search_field',
1037
        (!empty($_GET['search_field']) ? Security::remove_XSS($_GET['search_field']) : null)
1038
    );
1039
1040
    $url_id = api_get_current_access_url_id();
1041
1042
    $default_values = [];
1043
    $url_info = api_get_access_url($url_id);
1044
    $i = 0;
1045
    $addedSettings = [];
1046
    foreach ($settings as $row) {
1047
        if (in_array($row['variable'], array_keys($settings_to_avoid))) {
1048
            continue;
1049
        }
1050
1051
        if (in_array($row['variable'], $addedSettings)) {
1052
            continue;
1053
        }
1054
1055
        $addedSettings[] = $row['variable'];
1056
1057
        if (api_get_multiple_access_url()) {
1058
            if (api_is_global_platform_admin()) {
1059
                if (0 == $row['access_url_locked']) {
1060
                    if (1 == $url_id) {
1061
                        if ('1' == $row['access_url_changeable']) {
1062
                            $form->addElement(
1063
                                'html',
1064
                                '<div class="float-right"><a class="share_this_setting" data_status = "0"  data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
1065
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</a></div>'
1066
                            );
1067
                        } else {
1068
                            $form->addElement(
1069
                                'html',
1070
                                '<div class="float-right"><a class="share_this_setting" data_status = "1" data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
1071
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon-disabled', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</a></div>'
1072
                            );
1073
                        }
1074
                    } else {
1075
                        if ('1' == $row['access_url_changeable']) {
1076
                            $form->addElement(
1077
                                'html',
1078
                                '<div class="float-right">'.
1079
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</div>'
1080
                            );
1081
                        } else {
1082
                            $form->addElement(
1083
                                'html',
1084
                                '<div class="float-right">'.
1085
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon-disabled', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</div>'
1086
                            );
1087
                        }
1088
                    }
1089
                }
1090
            }
1091
        }
1092
1093
        $hideme = [];
1094
        $hide_element = false;
1095
1096
        if (1 != $_configuration['access_url']) {
1097
            if (0 == $row['access_url_changeable']) {
1098
                // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element.
1099
                $hide_element = true;
1100
                $hideme = ['disabled'];
1101
            } elseif (1 == $url_info['active']) {
1102
                // We show the elements.
1103
                if (empty($row['variable'])) {
1104
                    $row['variable'] = 0;
1105
                }
1106
                if (empty($row['subkey'])) {
1107
                    $row['subkey'] = 0;
1108
                }
1109
                if (empty($row['category'])) {
1110
                    $row['category'] = 0;
1111
                }
1112
                if (isset($settings_by_access_list[$row['variable']]) &&
1113
                    isset($settings_by_access_list[$row['variable']][$row['subkey']]) &&
1114
                    is_array($settings_by_access_list[$row['variable']][$row['subkey']][$row['category']])
1115
                ) {
1116
                    // We are sure that the other site have a selected value.
1117
                    if ('' != $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value']) {
1118
                        $row['selected_value'] = $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value'];
1119
                    }
1120
                }
1121
                // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
1122
            }
1123
        }
1124
1125
        switch ($row['type']) {
1126
            case 'textfield':
1127
                if (in_array($row['variable'], $convert_byte_to_mega_list)) {
1128
                    $form->addElement(
1129
                        'text',
1130
                        $row['variable'],
1131
                        [
1132
                            get_lang($row['title']),
1133
                            get_lang($row['comment']),
1134
                            get_lang('MB'),
1135
                        ],
1136
                        ['maxlength' => '8', 'aria-label' => get_lang($row['title'])]
1137
                    );
1138
                    $form->applyFilter($row['variable'], 'html_filter');
1139
                    $default_values[$row['variable']] = round($row['selected_value'] / 1024 / 1024, 1);
1140
                } elseif ('account_valid_duration' == $row['variable']) {
1141
                    $form->addElement(
1142
                        'text',
1143
                        $row['variable'],
1144
                        [
1145
                            get_lang($row['title']),
1146
                            get_lang($row['comment']),
1147
                        ],
1148
                        ['maxlength' => '5', 'aria-label' => get_lang($row['title'])]
1149
                    );
1150
                    $form->applyFilter($row['variable'], 'html_filter');
1151
1152
                    // For platform character set selection:
1153
                    // Conversion of the textfield to a select box with valid values.
1154
                    $default_values[$row['variable']] = $row['selected_value'];
1155
                } elseif ('platform_charset' == $row['variable']) {
1156
                    break;
1157
                } else {
1158
                    $hideme['class'] = 'col-md-4';
1159
                    $hideme['aria-label'] = get_lang($row['title']);
1160
                    $form->addElement(
1161
                        'text',
1162
                        $row['variable'],
1163
                        [
1164
                            get_lang($row['title']),
1165
                            get_lang($row['comment']),
1166
                        ],
1167
                        $hideme
1168
                    );
1169
                    $form->applyFilter($row['variable'], 'html_filter');
1170
                    $default_values[$row['variable']] = $row['selected_value'];
1171
                }
1172
                break;
1173
            case 'textarea':
1174
                if ('header_extra_content' == $row['variable']) {
1175
                    $file = api_get_home_path().'header_extra_content.txt';
0 ignored issues
show
Bug introduced by
The function api_get_home_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1175
                    $file = /** @scrutinizer ignore-call */ api_get_home_path().'header_extra_content.txt';
Loading history...
1176
                    $value = '';
1177
                    if (file_exists($file)) {
1178
                        $value = file_get_contents($file);
1179
                    }
1180
                    $form->addElement(
1181
                        'textarea',
1182
                        $row['variable'],
1183
                        [get_lang($row['title']), get_lang($row['comment'])],
1184
                        ['rows' => '10', 'id' => $row['variable']],
1185
                        $hideme
1186
                    );
1187
                    $default_values[$row['variable']] = $value;
1188
                } elseif ('footer_extra_content' == $row['variable']) {
1189
                    $file = api_get_home_path().'footer_extra_content.txt';
1190
                    $value = '';
1191
                    if (file_exists($file)) {
1192
                        $value = file_get_contents($file);
1193
                    }
1194
                    $form->addElement(
1195
                        'textarea',
1196
                        $row['variable'],
1197
                        [get_lang($row['title']), get_lang($row['comment'])],
1198
                        ['rows' => '10', 'id' => $row['variable']],
1199
                        $hideme
1200
                    );
1201
                    $default_values[$row['variable']] = $value;
1202
                } else {
1203
                    $form->addElement(
1204
                        'textarea',
1205
                        $row['variable'],
1206
                        [get_lang($row['title']),
1207
                        get_lang($row['comment']), ],
1208
                        ['rows' => '10', 'id' => $row['variable']],
1209
                        $hideme
1210
                    );
1211
                    $default_values[$row['variable']] = $row['selected_value'];
1212
                }
1213
                break;
1214
            case 'radio':
1215
                $values = api_get_settings_options($row['variable']);
1216
                $group = [];
1217
                if (is_array($values)) {
1218
                    foreach ($values as $key => $value) {
1219
                        $element = &$form->createElement(
1220
                            'radio',
1221
                            $row['variable'],
1222
                            '',
1223
                            get_lang($value['display_text']),
1224
                            $value['value']
1225
                        );
1226
                        if ($hide_element) {
1227
                            $element->freeze();
1228
                        }
1229
                        $group[] = $element;
1230
                    }
1231
                }
1232
                $form->addGroup(
1233
                    $group,
1234
                    $row['variable'],
1235
                    [get_lang($row['title']), get_lang($row['comment'])],
1236
                    null,
1237
                    false
1238
                );
1239
                $default_values[$row['variable']] = $row['selected_value'];
1240
                break;
1241
            case 'checkbox':
1242
                // 1. We collect all the options of this variable.
1243
                $sql = "SELECT * FROM $table_settings_current
1244
                        WHERE variable='".$row['variable']."' AND access_url =  1";
1245
1246
                $result = Database::query($sql);
1247
                $group = [];
1248
                while ($rowkeys = Database::fetch_array($result)) {
1249
                    // Profile tab option should be hidden when the social tool is enabled.
1250
                    if ('true' == api_get_setting('allow_social_tool')) {
1251
                        if ('show_tabs' === $rowkeys['variable'] && 'my_profile' === $rowkeys['subkey']) {
1252
                            continue;
1253
                        }
1254
                    }
1255
1256
                    // Hiding the gradebook option.
1257
                    if ('show_tabs' === $rowkeys['variable'] && 'my_gradebook' === $rowkeys['subkey']) {
1258
                        continue;
1259
                    }
1260
1261
                    $element = &$form->createElement(
1262
                        'checkbox',
1263
                        $rowkeys['subkey'],
1264
                        '',
1265
                        get_lang($rowkeys['subkeytext'])
1266
                    );
1267
1268
                    if (1 == $row['access_url_changeable']) {
1269
                        // 2. We look into the DB if there is a setting for a specific access_url.
1270
                        $access_url = $_configuration['access_url'];
1271
                        if (empty($access_url)) {
1272
                            $access_url = 1;
1273
                        }
1274
                        $sql = "SELECT selected_value FROM $table_settings_current
1275
                                WHERE
1276
                                    variable='".$rowkeys['variable']."' AND
1277
                                    subkey='".$rowkeys['subkey']."' AND
1278
                                    subkeytext='".$rowkeys['subkeytext']."' AND
1279
                                    access_url =  $access_url";
1280
                        $result_access = Database::query($sql);
1281
                        $row_access = Database::fetch_array($result_access);
1282
                        if ('true' === $row_access['selected_value'] && !$form->isSubmitted()) {
1283
                            $element->setChecked(true);
1284
                        }
1285
                    } else {
1286
                        if ('true' === $rowkeys['selected_value'] && !$form->isSubmitted()) {
1287
                            $element->setChecked(true);
1288
                        }
1289
                    }
1290
                    if ($hide_element) {
1291
                        $element->freeze();
1292
                    }
1293
                    $group[] = $element;
1294
                }
1295
                $form->addGroup(
1296
                    $group,
1297
                    $row['variable'],
1298
                    [get_lang($row['title']), get_lang($row['comment'])],
1299
                    null
1300
                );
1301
                break;
1302
            case 'link':
1303
                $form->addElement(
1304
                    'static',
1305
                    null,
1306
                    [get_lang($row['title']), get_lang($row['comment'])],
1307
                    get_lang('current value').' : '.$row['selected_value'],
1308
                    $hideme
1309
                );
1310
                break;
1311
            case 'select':
1312
                /*
1313
                * To populate the list of options, the select type dynamically calls a function that must be called select_ + the name of the variable being displayed.
1314
                * The functions being called must be added to the file settings.lib.php.
1315
                */
1316
                $form->addElement(
1317
                    'select',
1318
                    $row['variable'],
1319
                    [get_lang($row['title']), get_lang($row['comment'])],
1320
                    call_user_func('select_'.$row['variable']),
1321
                    $hideme
1322
                );
1323
                $default_values[$row['variable']] = $row['selected_value'];
1324
                break;
1325
            case 'custom':
1326
                break;
1327
            case 'select_course':
1328
                $courseSelectOptions = [];
1329
1330
                if (!empty($row['selected_value'])) {
1331
                    $course = $em->find('ChamiloCoreBundle:Course', $row['selected_value']);
1332
1333
                    $courseSelectOptions[$course->getId()] = $course->getTitle();
1334
                }
1335
1336
                $form->addElement(
1337
                    'select_ajax',
1338
                    $row['variable'],
1339
                    [get_lang($row['title']), get_lang($row['comment'])],
1340
                    $courseSelectOptions,
1341
                    ['url' => api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=search_course']
1342
                );
1343
                $default_values[$row['variable']] = $row['selected_value'];
1344
                break;
1345
        }
1346
1347
        switch ($row['variable']) {
1348
            case 'pdf_export_watermark_enable':
1349
                $url = PDF::get_watermark(null);
1350
1351
                if (false != $url) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $url of type string to the boolean false. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
1352
                    $delete_url = '<a href="?delete_watermark">'.get_lang('Remove picture').' '.Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Remove picture')).'</a>';
1353
                    $form->addElement('html', '<div style="max-height:100px; max-width:100px; margin-left:162px; margin-bottom:10px; clear:both;"><img src="'.$url.'" style="margin-bottom:10px;" />'.$delete_url.'</div>');
1354
                }
1355
1356
                $form->addElement('file', 'pdf_export_watermark_path', get_lang('Upload a watermark image'));
1357
                $allowed_picture_types = ['jpg', 'jpeg', 'png', 'gif'];
1358
                $form->addRule(
1359
                    'pdf_export_watermark_path',
1360
                    get_lang('Only PNG, JPG or GIF images allowed').' ('.implode(',', $allowed_picture_types).')',
1361
                    'filetype',
1362
                    $allowed_picture_types
1363
                );
1364
1365
                break;
1366
            case 'timezone_value':
1367
                $timezone = $row['selected_value'];
1368
                if (empty($timezone)) {
1369
                    $timezone = api_get_timezone();
1370
                }
1371
                $form->addLabel('', sprintf(get_lang('The local time in the portal timezone (%s) is %s'), $timezone, api_get_local_time()));
1372
                break;
1373
        }
1374
    } // end for
1375
1376
    if (!empty($settings)) {
1377
        $form->setDefaults($default_values);
1378
    }
1379
    $form->addHtml('<div class="bottom_actions">');
1380
    $form->addButtonSave(get_lang('Save settings'));
1381
    $form->addHtml('</div>');
1382
1383
    return $form;
1384
}
1385
1386
/**
1387
 * Searches a platform setting in all categories except from the Plugins category.
1388
 *
1389
 * @param string $search
1390
 *
1391
 * @return array
1392
 */
1393
function searchSetting($search)
1394
{
1395
    if (empty($search)) {
1396
        return [];
1397
    }
1398
    $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS);
1399
    $sql = "SELECT * FROM $table_settings_current
1400
            WHERE category <> 'Plugins' ORDER BY id ASC ";
1401
    $result = Database::store_result(Database::query($sql), 'ASSOC');
1402
    $settings = [];
1403
1404
    $search = api_strtolower($search);
1405
1406
    if (!empty($result)) {
1407
        foreach ($result as $setting) {
1408
            $found = false;
1409
1410
            $title = api_strtolower(get_lang($setting['title']));
1411
            // try the title
1412
            if (false === strpos($title, $search)) {
1413
                $comment = api_strtolower(get_lang($setting['comment']));
1414
                //Try the comment
1415
                if (false === strpos($comment, $search)) {
1416
                    //Try the variable name
1417
                    if (false === strpos($setting['variable'], $search)) {
1418
                        continue;
1419
                    } else {
1420
                        $found = true;
1421
                    }
1422
                } else {
1423
                    $found = true;
1424
                }
1425
            } else {
1426
                $found = true;
1427
            }
1428
            if ($found) {
1429
                $settings[] = $setting;
1430
            }
1431
        }
1432
    }
1433
1434
    return $settings;
1435
}
1436
/**
1437
 * Helper function to generates a form elements group.
1438
 *
1439
 * @param object $form   The form where the elements group has to be added
1440
 * @param array  $values Values to browse through
1441
 *
1442
 * @return array
1443
 */
1444
function formGenerateElementsGroup($form, $values = [], $elementName)
1445
{
1446
    $group = [];
1447
    if (is_array($values)) {
1448
        foreach ($values as $key => $value) {
1449
            $element = &$form->createElement('radio', $elementName, '', get_lang($value['display_text']), $value['value']);
1450
            $group[] = $element;
1451
        }
1452
    }
1453
1454
    return $group;
1455
}
1456
/**
1457
 * Helper function with allowed file types for CSS.
1458
 *
1459
 * @return array Array of file types (no indexes)
1460
 */
1461
function getAllowedFileTypes()
1462
{
1463
    $allowedFiles = [
1464
        'css',
1465
        'zip',
1466
        'jpeg',
1467
        'jpg',
1468
        'png',
1469
        'gif',
1470
        'ico',
1471
        'psd',
1472
        'xcf',
1473
        'svg',
1474
        'webp',
1475
        'woff',
1476
        'woff2',
1477
    ];
1478
1479
    return $allowedFiles;
1480
}
1481
/**
1482
 * Helper function to set settings in the database.
1483
 *
1484
 * @param array $parameters List of values
1485
 * @param int   $accessUrl  The current access URL
1486
 */
1487
function setConfigurationSettingsInDatabase($parameters, $accessUrl)
1488
{
1489
    api_set_settings_category('Search', 'false', $accessUrl);
1490
    // Save the settings.
1491
    foreach ($parameters as $key => $value) {
1492
        api_set_setting($key, $value, null, null);
1493
    }
1494
}
1495
1496
/**
1497
 * Helper function to show the status of the search settings table.
1498
 *
1499
 * @param array $data Data to show
1500
 */
1501
function showSearchSettingsTable($data)
1502
{
1503
    echo Display::tag('h3', get_lang('Settings'));
1504
    $table = new SortableTableFromArray($data);
1505
    $table->set_header(0, get_lang('Setting'), false);
1506
    $table->set_header(1, get_lang('Status'), false);
1507
    echo $table->display();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $table->display() targeting SortableTable::display() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1508
}
1509
/**
1510
 * Helper function to show status table for each command line tool installed.
1511
 */
1512
function showSearchToolsStatusTable()
1513
{
1514
    //@todo windows support
1515
    if (false == api_is_windows_os()) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1516
        $list_of_programs = ['pdftotext', 'ps2pdf', 'catdoc', 'html2text', 'unrtf', 'catppt', 'xls2csv'];
1517
        foreach ($list_of_programs as $program) {
1518
            $output = [];
1519
            $ret_val = null;
1520
            exec("which $program", $output, $ret_val);
1521
1522
            if (!$output) {
1523
                $output[] = '';
1524
            }
1525
1526
            $icon = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Not installed'));
1527
            if (!empty($output[0])) {
1528
                $icon = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Installed'));
1529
            }
1530
            $data2[] = [$program, $output[0], $icon];
1531
        }
1532
        echo Display::tag('h3', get_lang('Course Program</a>. If your course has no code, whatever the reason, invent one. For instance <i>INNOVATION</i> if the course is about Innovation Managements needed to convert files'));
1533
        $table = new SortableTableFromArray($data2);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $data2 seems to be defined by a foreach iteration on line 1517. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1534
        $table->set_header(0, get_lang('Course Program</a>. If your course has no code, whatever the reason, invent one. For instance <i>INNOVATION</i> if the course is about Innovation Management'), false);
1535
        $table->set_header(1, get_lang('Path'), false);
1536
        $table->set_header(2, get_lang('Status'), false);
1537
        echo $table->display();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $table->display() targeting SortableTable::display() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1538
    } else {
1539
        echo Display::return_message(
1540
            get_lang('You are using Chamilo in a Windows platform, sadly you can\'t convert documents in order to search the content using this tool'),
1541
            'warning'
1542
        );
1543
    }
1544
}
1545
/**
1546
 * Helper function to generate and show CSS Zip download message.
1547
 *
1548
 * @param string $style Style path
1549
 */
1550
function generateCSSDownloadLink($style)
1551
{
1552
    $arch = api_get_path(SYS_ARCHIVE_PATH).$style.'.zip';
1553
    $themeDir = Template::getThemeDir($style);
1554
    $dir = api_get_path(SYS_CSS_PATH).$themeDir;
1555
    $check = Security::check_abs_path(
1556
        $dir,
1557
        api_get_path(SYS_CSS_PATH).'themes'
1558
    );
1559
    if (is_dir($dir) && $check) {
1560
        $zip = new PclZip($arch);
1561
        // Remove path prefix except the style name and put file on disk
1562
        $zip->create($dir, PCLZIP_OPT_REMOVE_PATH, substr($dir, 0, -strlen($style)));
0 ignored issues
show
Bug introduced by
The constant PCLZIP_OPT_REMOVE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1563
        $url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive_path=&archive='.str_replace(api_get_path(SYS_ARCHIVE_PATH), '', $arch);
1564
1565
        //@TODO: use more generic script to download.
1566
        $str = '<a class="btn btn--primary btn-large" href="'.$url.'">'.get_lang('Download the file').'</a>';
1567
        echo Display::return_message($str, 'normal', false);
1568
    } else {
1569
        echo Display::return_message(get_lang('The file was not found'), 'warning');
1570
    }
1571
}
1572
1573
/**
1574
 * Get all settings of one category prepared for display in admin/settings.php.
1575
 *
1576
 * @param string $category
1577
 *
1578
 * @return array
1579
 */
1580
function getCategorySettings($category = '')
1581
{
1582
    $url_id = api_get_current_access_url_id();
1583
    $settings_by_access_list = [];
1584
1585
    if (1 == $url_id) {
1586
        $settings = api_get_settings($category, 'group', $url_id);
1587
    } else {
1588
        $url_info = api_get_access_url($url_id);
1589
        if (1 == $url_info['active']) {
1590
            $categoryToSearch = $category;
1591
            if ('search_setting' == $category) {
1592
                $categoryToSearch = '';
1593
            }
1594
            // The default settings of Chamilo
1595
            $settings = api_get_settings($categoryToSearch, 'group', 1, 0);
1596
            // The settings that are changeable from a particular site.
1597
            $settings_by_access = api_get_settings($categoryToSearch, 'group', $url_id, 1);
1598
1599
            foreach ($settings_by_access as $row) {
1600
                if (empty($row['variable'])) {
1601
                    $row['variable'] = 0;
1602
                }
1603
                if (empty($row['subkey'])) {
1604
                    $row['subkey'] = 0;
1605
                }
1606
                if (empty($row['category'])) {
1607
                    $row['category'] = 0;
1608
                }
1609
1610
                // One more validation if is changeable.
1611
                if (1 == $row['access_url_changeable']) {
1612
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
1613
                } else {
1614
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = [];
1615
                }
1616
            }
1617
        }
1618
    }
1619
1620
    if (isset($category) && 'search_setting' == $category) {
1621
        if (!empty($_REQUEST['search_field'])) {
1622
            $settings = searchSetting($_REQUEST['search_field']);
1623
        }
1624
    }
1625
1626
    return [
1627
        'settings' => $settings,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $settings does not seem to be defined for all execution paths leading up to this point.
Loading history...
1628
        'settings_by_access_list' => $settings_by_access_list,
1629
    ];
1630
}
1631