handleSearch()   C
last analyzed

Complexity

Conditions 10
Paths 102

Size

Total Lines 146
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 80
nc 102
nop 0
dl 0
loc 146
rs 6.5563
c 0
b 0
f 0

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\Course;
6
use Chamilo\CoreBundle\Entity\Plugin as PluginEntity;
7
use Chamilo\CoreBundle\Entity\SystemTemplate;
8
use ChamiloSession as Session;
9
use Symfony\Component\Filesystem\Filesystem;
10
use Chamilo\CoreBundle\Framework\Container;
11
use Chamilo\CoreBundle\Entity\Asset;
12
use Chamilo\CoreBundle\Component\Utils\ActionIcon;
13
use Chamilo\CoreBundle\Component\Utils\ObjectIcon;
14
use Chamilo\CoreBundle\Component\Utils\StateIcon;
15
16
/**
17
 * Library of the settings.php file.
18
 *
19
 * @author Julio Montoya <[email protected]>
20
 * @author Guillaume Viguier <[email protected]>
21
 *
22
 * @since Chamilo 1.8.7
23
 */
24
define('CSS_UPLOAD_PATH', api_get_path(SYMFONY_SYS_PATH).'var/themes/');
25
26
/**
27
 * This function allows easy activating and inactivating of regions.
28
 *
29
 * @author Julio Montoya <[email protected]> Beeznest 2012
30
 */
31
function handleRegions()
32
{
33
    if (isset($_POST['submit_plugins'])) {
34
        storeRegions();
35
        // Add event to the system log.
36
        $user_id = api_get_user_id();
37
        $category = $_GET['category'];
38
        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

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

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

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

1181
                    $file = /** @scrutinizer ignore-call */ api_get_home_path().'header_extra_content.txt';
Loading history...
1182
                    $value = '';
1183
                    if (file_exists($file)) {
1184
                        $value = file_get_contents($file);
1185
                    }
1186
                    $form->addElement(
1187
                        'textarea',
1188
                        $row['variable'],
1189
                        [get_lang($row['title']), get_lang($row['comment'])],
1190
                        ['rows' => '10', 'id' => $row['variable']],
1191
                        $hideme
1192
                    );
1193
                    $default_values[$row['variable']] = $value;
1194
                } elseif ('footer_extra_content' == $row['variable']) {
1195
                    $file = api_get_home_path().'footer_extra_content.txt';
1196
                    $value = '';
1197
                    if (file_exists($file)) {
1198
                        $value = file_get_contents($file);
1199
                    }
1200
                    $form->addElement(
1201
                        'textarea',
1202
                        $row['variable'],
1203
                        [get_lang($row['title']), get_lang($row['comment'])],
1204
                        ['rows' => '10', 'id' => $row['variable']],
1205
                        $hideme
1206
                    );
1207
                    $default_values[$row['variable']] = $value;
1208
                } else {
1209
                    $form->addElement(
1210
                        'textarea',
1211
                        $row['variable'],
1212
                        [get_lang($row['title']),
1213
                        get_lang($row['comment']), ],
1214
                        ['rows' => '10', 'id' => $row['variable']],
1215
                        $hideme
1216
                    );
1217
                    $default_values[$row['variable']] = $row['selected_value'];
1218
                }
1219
                break;
1220
            case 'radio':
1221
                $values = api_get_settings_options($row['variable']);
1222
                $group = [];
1223
                if (is_array($values)) {
1224
                    foreach ($values as $key => $value) {
1225
                        $element = &$form->createElement(
1226
                            'radio',
1227
                            $row['variable'],
1228
                            '',
1229
                            get_lang($value['display_text']),
1230
                            $value['value']
1231
                        );
1232
                        if ($hide_element) {
1233
                            $element->freeze();
1234
                        }
1235
                        $group[] = $element;
1236
                    }
1237
                }
1238
                $form->addGroup(
1239
                    $group,
1240
                    $row['variable'],
1241
                    [get_lang($row['title']), get_lang($row['comment'])],
1242
                    null,
1243
                    false
1244
                );
1245
                $default_values[$row['variable']] = $row['selected_value'];
1246
                break;
1247
            case 'checkbox':
1248
                // 1. We collect all the options of this variable.
1249
                $sql = "SELECT * FROM $table_settings_current
1250
                        WHERE variable='".$row['variable']."' AND access_url =  1";
1251
1252
                $result = Database::query($sql);
1253
                $group = [];
1254
                while ($rowkeys = Database::fetch_array($result)) {
1255
                    // Profile tab option should be hidden when the social tool is enabled.
1256
                    if ('true' == api_get_setting('allow_social_tool')) {
1257
                        if ('show_tabs' === $rowkeys['variable'] && 'my_profile' === $rowkeys['subkey']) {
1258
                            continue;
1259
                        }
1260
                    }
1261
1262
                    // Hiding the gradebook option.
1263
                    if ('show_tabs' === $rowkeys['variable'] && 'my_gradebook' === $rowkeys['subkey']) {
1264
                        continue;
1265
                    }
1266
1267
                    $element = &$form->createElement(
1268
                        'checkbox',
1269
                        $rowkeys['subkey'],
1270
                        '',
1271
                        get_lang($rowkeys['subkeytext'])
1272
                    );
1273
1274
                    if (1 == $row['access_url_changeable']) {
1275
                        // 2. We look into the DB if there is a setting for a specific access_url.
1276
                        $access_url = $_configuration['access_url'];
1277
                        if (empty($access_url)) {
1278
                            $access_url = 1;
1279
                        }
1280
                        $sql = "SELECT selected_value FROM $table_settings_current
1281
                                WHERE
1282
                                    variable='".$rowkeys['variable']."' AND
1283
                                    subkey='".$rowkeys['subkey']."' AND
1284
                                    subkeytext='".$rowkeys['subkeytext']."' AND
1285
                                    access_url =  $access_url";
1286
                        $result_access = Database::query($sql);
1287
                        $row_access = Database::fetch_array($result_access);
1288
                        if ('true' === $row_access['selected_value'] && !$form->isSubmitted()) {
1289
                            $element->setChecked(true);
1290
                        }
1291
                    } else {
1292
                        if ('true' === $rowkeys['selected_value'] && !$form->isSubmitted()) {
1293
                            $element->setChecked(true);
1294
                        }
1295
                    }
1296
                    if ($hide_element) {
1297
                        $element->freeze();
1298
                    }
1299
                    $group[] = $element;
1300
                }
1301
                $form->addGroup(
1302
                    $group,
1303
                    $row['variable'],
1304
                    [get_lang($row['title']), get_lang($row['comment'])],
1305
                    null
1306
                );
1307
                break;
1308
            case 'link':
1309
                $form->addElement(
1310
                    'static',
1311
                    null,
1312
                    [get_lang($row['title']), get_lang($row['comment'])],
1313
                    get_lang('current value').' : '.$row['selected_value'],
1314
                    $hideme
1315
                );
1316
                break;
1317
            case 'select':
1318
                /*
1319
                * 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.
1320
                * The functions being called must be added to the file settings.lib.php.
1321
                */
1322
                $form->addElement(
1323
                    'select',
1324
                    $row['variable'],
1325
                    [get_lang($row['title']), get_lang($row['comment'])],
1326
                    call_user_func('select_'.$row['variable']),
1327
                    $hideme
1328
                );
1329
                $default_values[$row['variable']] = $row['selected_value'];
1330
                break;
1331
            case 'custom':
1332
                break;
1333
            case 'select_course':
1334
                $courseSelectOptions = [];
1335
1336
                if (!empty($row['selected_value'])) {
1337
                    $course = $em->find(Course::class, $row['selected_value']);
1338
1339
                    $courseSelectOptions[$course->getId()] = $course->getTitle();
1340
                }
1341
1342
                $form->addElement(
1343
                    'select_ajax',
1344
                    $row['variable'],
1345
                    [get_lang($row['title']), get_lang($row['comment'])],
1346
                    $courseSelectOptions,
1347
                    ['url' => api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=search_course']
1348
                );
1349
                $default_values[$row['variable']] = $row['selected_value'];
1350
                break;
1351
        }
1352
1353
        switch ($row['variable']) {
1354
            case 'pdf_export_watermark_enable':
1355
                $url = PDF::get_watermark(null);
1356
1357
                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...
1358
                    $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>';
1359
                    $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>');
1360
                }
1361
1362
                $form->addElement('file', 'pdf_export_watermark_path', get_lang('Upload a watermark image'));
1363
                $allowed_picture_types = ['jpg', 'jpeg', 'png', 'gif'];
1364
                $form->addRule(
1365
                    'pdf_export_watermark_path',
1366
                    get_lang('Only PNG, JPG or GIF images allowed').' ('.implode(',', $allowed_picture_types).')',
1367
                    'filetype',
1368
                    $allowed_picture_types
1369
                );
1370
1371
                break;
1372
            case 'timezone_value':
1373
                $timezone = $row['selected_value'];
1374
                if (empty($timezone)) {
1375
                    $timezone = api_get_timezone();
1376
                }
1377
                $form->addLabel('', sprintf(get_lang('The local time in the portal timezone (%s) is %s'), $timezone, api_get_local_time()));
1378
                break;
1379
        }
1380
    } // end for
1381
1382
    if (!empty($settings)) {
1383
        $form->setDefaults($default_values);
1384
    }
1385
    $form->addHtml('<div class="bottom_actions">');
1386
    $form->addButtonSave(get_lang('Save settings'));
1387
    $form->addHtml('</div>');
1388
1389
    return $form;
1390
}
1391
1392
/**
1393
 * Searches a platform setting in all categories except from the Plugins category.
1394
 *
1395
 * @param string $search
1396
 *
1397
 * @return array
1398
 */
1399
function searchSetting($search)
1400
{
1401
    if (empty($search)) {
1402
        return [];
1403
    }
1404
    $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS);
1405
    $sql = "SELECT * FROM $table_settings_current
1406
            WHERE category <> 'Plugins' ORDER BY id ASC ";
1407
    $result = Database::store_result(Database::query($sql), 'ASSOC');
1408
    $settings = [];
1409
1410
    $search = api_strtolower($search);
1411
1412
    if (!empty($result)) {
1413
        foreach ($result as $setting) {
1414
            $found = false;
1415
1416
            $title = api_strtolower(get_lang($setting['title']));
1417
            // try the title
1418
            if (false === strpos($title, $search)) {
1419
                $comment = api_strtolower(get_lang($setting['comment']));
1420
                //Try the comment
1421
                if (false === strpos($comment, $search)) {
1422
                    //Try the variable name
1423
                    if (false === strpos($setting['variable'], $search)) {
1424
                        continue;
1425
                    } else {
1426
                        $found = true;
1427
                    }
1428
                } else {
1429
                    $found = true;
1430
                }
1431
            } else {
1432
                $found = true;
1433
            }
1434
            if ($found) {
1435
                $settings[] = $setting;
1436
            }
1437
        }
1438
    }
1439
1440
    return $settings;
1441
}
1442
/**
1443
 * Helper function to generates a form elements group.
1444
 *
1445
 * @param object $form   The form where the elements group has to be added
1446
 * @param array  $values Values to browse through
1447
 *
1448
 * @return array
1449
 */
1450
function formGenerateElementsGroup($form, $values = [], $elementName)
1451
{
1452
    $group = [];
1453
    if (is_array($values)) {
1454
        foreach ($values as $key => $value) {
1455
            $element = &$form->createElement('radio', $elementName, '', get_lang($value['display_text']), $value['value']);
1456
            $group[] = $element;
1457
        }
1458
    }
1459
1460
    return $group;
1461
}
1462
/**
1463
 * Helper function with allowed file types for CSS.
1464
 *
1465
 * @return array Array of file types (no indexes)
1466
 */
1467
function getAllowedFileTypes()
1468
{
1469
    $allowedFiles = [
1470
        'css',
1471
        'zip',
1472
        'jpeg',
1473
        'jpg',
1474
        'png',
1475
        'gif',
1476
        'ico',
1477
        'psd',
1478
        'xcf',
1479
        'svg',
1480
        'webp',
1481
        'woff',
1482
        'woff2',
1483
    ];
1484
1485
    return $allowedFiles;
1486
}
1487
/**
1488
 * Helper function to set settings in the database.
1489
 *
1490
 * @param array $parameters List of values
1491
 * @param int   $accessUrl  The current access URL
1492
 */
1493
function setConfigurationSettingsInDatabase($parameters, $accessUrl)
1494
{
1495
    api_set_settings_category('Search', 'false', $accessUrl);
1496
    // Save the settings.
1497
    foreach ($parameters as $key => $value) {
1498
        api_set_setting($key, $value, null, null);
1499
    }
1500
}
1501
1502
/**
1503
 * Helper function to show the status of the search settings table.
1504
 *
1505
 * @param array $data Data to show
1506
 */
1507
function showSearchSettingsTable($data)
1508
{
1509
    echo Display::tag('h3', get_lang('Settings'));
1510
    $table = new SortableTableFromArray($data);
1511
    $table->set_header(0, get_lang('Setting'), false);
1512
    $table->set_header(1, get_lang('Status'), false);
1513
    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...
1514
}
1515
/**
1516
 * Helper function to show status table for each command line tool installed.
1517
 */
1518
function showSearchToolsStatusTable()
1519
{
1520
    //@todo windows support
1521
    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...
1522
        $list_of_programs = ['pdftotext', 'ps2pdf', 'catdoc', 'html2text', 'unrtf', 'catppt', 'xls2csv'];
1523
        foreach ($list_of_programs as $program) {
1524
            $output = [];
1525
            $ret_val = null;
1526
            exec("which $program", $output, $ret_val);
1527
1528
            if (!$output) {
1529
                $output[] = '';
1530
            }
1531
1532
            $icon = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Not installed'));
1533
            if (!empty($output[0])) {
1534
                $icon = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Installed'));
1535
            }
1536
            $data2[] = [$program, $output[0], $icon];
1537
        }
1538
        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'));
1539
        $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 1523. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1540
        $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);
1541
        $table->set_header(1, get_lang('Path'), false);
1542
        $table->set_header(2, get_lang('Status'), false);
1543
        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...
1544
    } else {
1545
        echo Display::return_message(
1546
            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'),
1547
            'warning'
1548
        );
1549
    }
1550
}
1551
/**
1552
 * Helper function to generate and show CSS Zip download message.
1553
 *
1554
 * @param string $style Style path
1555
 */
1556
function generateCSSDownloadLink($style)
1557
{
1558
    $arch = api_get_path(SYS_ARCHIVE_PATH).$style.'.zip';
1559
    $themeDir = Template::getThemeDir($style);
1560
    $dir = api_get_path(SYS_CSS_PATH).$themeDir;
1561
    $check = Security::check_abs_path(
1562
        $dir,
1563
        api_get_path(SYS_CSS_PATH).'themes'
1564
    );
1565
    if (is_dir($dir) && $check) {
1566
        $zip = new PclZip($arch);
1567
        // Remove path prefix except the style name and put file on disk
1568
        $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...
1569
        $url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive_path=&archive='.str_replace(api_get_path(SYS_ARCHIVE_PATH), '', $arch);
1570
1571
        //@TODO: use more generic script to download.
1572
        $str = '<a class="btn btn--primary btn-large" href="'.$url.'">'.get_lang('Download the file').'</a>';
1573
        echo Display::return_message($str, 'normal', false);
1574
    } else {
1575
        echo Display::return_message(get_lang('The file was not found'), 'warning');
1576
    }
1577
}
1578
1579
/**
1580
 * Get all settings of one category prepared for display in admin/settings.php.
1581
 *
1582
 * @param string $category
1583
 *
1584
 * @return array
1585
 */
1586
function getCategorySettings($category = '')
1587
{
1588
    $url_id = api_get_current_access_url_id();
1589
    $settings_by_access_list = [];
1590
1591
    if (1 == $url_id) {
1592
        $settings = api_get_settings($category, 'group', $url_id);
1593
    } else {
1594
        $url_info = api_get_access_url($url_id);
1595
        if (1 == $url_info['active']) {
1596
            $categoryToSearch = $category;
1597
            if ('search_setting' == $category) {
1598
                $categoryToSearch = '';
1599
            }
1600
            // The default settings of Chamilo
1601
            $settings = api_get_settings($categoryToSearch, 'group', 1, 0);
1602
            // The settings that are changeable from a particular site.
1603
            $settings_by_access = api_get_settings($categoryToSearch, 'group', $url_id, 1);
1604
1605
            foreach ($settings_by_access as $row) {
1606
                if (empty($row['variable'])) {
1607
                    $row['variable'] = 0;
1608
                }
1609
                if (empty($row['subkey'])) {
1610
                    $row['subkey'] = 0;
1611
                }
1612
                if (empty($row['category'])) {
1613
                    $row['category'] = 0;
1614
                }
1615
1616
                // One more validation if is changeable.
1617
                if (1 == $row['access_url_changeable']) {
1618
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
1619
                } else {
1620
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = [];
1621
                }
1622
            }
1623
        }
1624
    }
1625
1626
    if (isset($category) && 'search_setting' == $category) {
1627
        if (!empty($_REQUEST['search_field'])) {
1628
            $settings = searchSetting($_REQUEST['search_field']);
1629
        }
1630
    }
1631
1632
    return [
1633
        '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...
1634
        'settings_by_access_list' => $settings_by_access_list,
1635
    ];
1636
}
1637