Passed
Pull Request — master (#4645)
by Yannick
12:39 queued 05:14
created

deleteTemplateImage()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 11
rs 10
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
5
use Chamilo\CoreBundle\Entity\SystemTemplate;
6
use ChamiloSession as Session;
7
use Symfony\Component\Filesystem\Filesystem;
8
use Chamilo\CoreBundle\Framework\Container;
9
use Chamilo\CoreBundle\Entity\Asset;
10
use Chamilo\CoreBundle\Component\Utils\ActionIcon;
11
use Chamilo\CoreBundle\Component\Utils\ObjectIcon;
12
use Chamilo\CoreBundle\Component\Utils\StateIcon;
13
14
/**
15
 * Library of the settings.php file.
16
 *
17
 * @author Julio Montoya <[email protected]>
18
 * @author Guillaume Viguier <[email protected]>
19
 *
20
 * @since Chamilo 1.8.7
21
 */
22
define('CSS_UPLOAD_PATH', api_get_path(SYS_PATH).'Resources/public/css/themes/');
23
24
/**
25
 * This function allows easy activating and inactivating of regions.
26
 *
27
 * @author Julio Montoya <[email protected]> Beeznest 2012
28
 */
29
function handleRegions()
30
{
31
    if (isset($_POST['submit_plugins'])) {
32
        storeRegions();
33
        // Add event to the system log.
34
        $user_id = api_get_user_id();
35
        $category = $_GET['category'];
36
        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

36
        Event::/** @scrutinizer ignore-call */ 
37
               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...
37
            LOG_CONFIGURATION_SETTINGS_CHANGE,
38
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
39
            $category,
40
            api_get_utc_datetime(),
41
            $user_id
42
        );
43
        echo Display::return_message(get_lang('The settings have been stored'), 'confirmation');
44
    }
45
46
    $plugin_obj = new AppPlugin();
47
    $installed_plugins = $plugin_obj->getInstalledPlugins();
48
49
    echo '<form name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'">';
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($_GET['category']) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

49
    echo '<form name="plugins" method="post" action="'.api_get_self().'?category='./** @scrutinizer ignore-type */ Security::remove_XSS($_GET['category']).'">';
Loading history...
50
    echo '<table class="data_table">';
51
    echo '<tr>';
52
    echo '<th width="400px">';
53
    echo get_lang('Plugin');
54
    echo '</th><th>';
55
    echo get_lang('Regions');
56
    echo '</th>';
57
    echo '</th>';
58
    echo '</tr>';
59
60
    /* We display all the possible plugins and the checkboxes */
61
    $plugin_region_list = [];
62
    $my_plugin_list = $plugin_obj->getPluginRegions();
63
    foreach ($my_plugin_list as $plugin_item) {
64
        $plugin_region_list[$plugin_item] = $plugin_item;
65
    }
66
67
    // Removing course tool
68
    unset($plugin_region_list['course_tool_plugin']);
69
70
    foreach ($installed_plugins as $pluginName) {
71
        $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/plugin.php';
72
73
        if (file_exists($plugin_info_file)) {
74
            $plugin_info = [];
75
            require $plugin_info_file;
76
            if (isset($_GET['name']) && $_GET['name'] === $pluginName) {
77
                echo '<tr class="row_selected">';
78
            } else {
79
                echo '<tr>';
80
            }
81
            echo '<td>';
82
            echo '<h4>'.$plugin_info['title'].' <small>v'.$plugin_info['version'].'</small></h4>';
83
            echo '<p>'.$plugin_info['comment'].'</p>';
84
            echo '</td><td>';
85
            $selected_plugins = $plugin_obj->get_areas_by_plugin($pluginName);
86
            $region_list = [];
87
            $isAdminPlugin = isset($plugin_info['is_admin_plugin']) && $plugin_info['is_admin_plugin'];
88
            $isCoursePlugin = isset($plugin_info['is_course_plugin']) && $plugin_info['is_course_plugin'];
89
90
            if (!$isAdminPlugin && !$isCoursePlugin) {
91
                $region_list = $plugin_region_list;
92
            } else {
93
                if ($isAdminPlugin) {
94
                    $region_list['menu_administrator'] = 'menu_administrator';
95
                }
96
                if ($isCoursePlugin) {
97
                    $region_list['course_tool_plugin'] = 'course_tool_plugin';
98
                }
99
            }
100
101
            echo Display::select(
102
                'plugin_'.$pluginName.'[]',
103
                $region_list,
104
                $selected_plugins,
105
                ['multiple' => 'multiple', 'style' => 'width:500px'],
106
                true,
107
                get_lang('none')
108
            );
109
            echo '</td></tr>';
110
        }
111
    }
112
    echo '</table>';
113
    echo '<br />';
114
    echo '<button class="btn btn--success" type="submit" name="submit_plugins">'.get_lang('Enable the selected plugins').'</button></form>';
115
}
116
117
function handleExtensions()
118
{
119
    echo Display::page_subheader(get_lang('Configure extensions'));
120
    echo '<a class="btn btn--success" href="configure_extensions.php?display=ppt2lp" role="button">'.get_lang('Chamilo RAPID').'</a>';
121
}
122
123
/**
124
 * This function allows easy activating and inactivating of plugins.
125
 *
126
 * @todo: a similar function needs to be written to activate or inactivate additional tools.
127
 *
128
 * @author Patrick Cool <[email protected]>, Ghent University
129
 * @author Julio Montoya <[email protected]> Beeznest 2012
130
 */
131
function handlePlugins()
132
{
133
    Session::erase('plugin_data');
134
    $plugin_obj = new AppPlugin();
135
    $token = Security::get_token();
136
    if (isset($_POST['submit_plugins'])) {
137
        storePlugins();
138
        // Add event to the system log.
139
        $user_id = api_get_user_id();
140
        $category = $_GET['category'];
141
        Event::addEvent(
142
            LOG_CONFIGURATION_SETTINGS_CHANGE,
143
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
144
            $category,
145
            api_get_utc_datetime(),
146
            $user_id
147
        );
148
        echo Display::return_message(get_lang('The settings have been stored'), 'confirmation');
149
    }
150
151
    $all_plugins = $plugin_obj->read_plugins_from_path();
152
    $installed_plugins = $plugin_obj->getInstalledPlugins();
153
154
    // Plugins NOT installed
155
    echo Display::page_subheader(get_lang('Plugins'));
156
    echo '<form class="form-horizontal" name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'&sec_token='.$token.'">';
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($_GET['category']) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

156
    echo '<form class="form-horizontal" name="plugins" method="post" action="'.api_get_self().'?category='./** @scrutinizer ignore-type */ Security::remove_XSS($_GET['category']).'&sec_token='.$token.'">';
Loading history...
157
    echo '<table class="table table-hover table-striped table-bordered table-fixed">';
158
    echo '<thead class="bg-gray-50">';
159
    echo '<tr>';
160
    echo '<th width="20px" class="px-6 py-2 uppercase font-normal leading-normal mt-0 mb-2 text-gray-500">';
161
    echo get_lang('Action');
162
    echo '</th><th class="px-6 py-2 uppercase font-normal leading-normal mt-0 mb-2 text-gray-500">';
163
    echo get_lang('Description');
164
    echo '</th>';
165
    echo '</tr>';
166
    echo '</thead>';
167
168
    /*$plugin_list = array();
169
    $my_plugin_list = $plugin_obj->get_plugin_regions();
170
    foreach($my_plugin_list as $plugin_item) {
171
        $plugin_list[$plugin_item] = $plugin_item;
172
    }*/
173
    $installed = '';
174
    $notInstalled = '';
175
    foreach ($all_plugins as $pluginName) {
176
        $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/plugin.php';
177
        if (file_exists($plugin_info_file)) {
178
            $plugin_info = [];
179
            require $plugin_info_file;
180
181
            $pluginRow = '';
182
183
            if (in_array($pluginName, $installed_plugins)) {
184
                $pluginRow .= '<tr class="row_selected whitespace-nowrap">';
185
            } else {
186
                $pluginRow .= '<tr class="whitespace-nowrap">';
187
            }
188
            $pluginRow .= '<td class="px-6 py-4 text-sm text-gray-500">';
189
            // Checkbox
190
            if (in_array($pluginName, $installed_plugins)) {
191
                $pluginRow .= '<input type="checkbox" name="plugin_'.$pluginName.'[]" checked="checked" class="border rounded">';
192
            } else {
193
                $pluginRow .= '<input type="checkbox" name="plugin_'.$pluginName.'[]" class="border rounded">';
194
            }
195
            $pluginRow .= '</td><td class="px-6 py-4 text-sm text-gray-500">';
196
            $pluginRow .= '<h3 class="text-3xl font-normal leading-normal mt-0 mb-2">'.$plugin_info['title'].' <small>v '.$plugin_info['version'].'</small></h3>';
197
            $pluginRow .= '<p>'.$plugin_info['comment'].'</p>';
198
            $pluginRow .= '<p>'.get_lang('Author').': '.$plugin_info['author'].'</p>';
199
200
            $pluginRow .= '<div class="btn-group btn-group-sm mt-4">';
201
            if (in_array($pluginName, $installed_plugins)) {
202
                $pluginRow .= Display::url(
203
                    '<em class="fa fa-cogs"></em> '.get_lang('Configure'),
204
                    'configure_plugin.php?name='.$pluginName,
205
                    ['class' => 'btn btn--primary']
206
                );
207
                $pluginRow .= Display::url(
208
                    '<em class="fa fa-th-large"></em> '.get_lang('Regions'),
209
                    'settings.php?category=Regions&name='.$pluginName,
210
                    ['class' => 'btn btn--primary']
211
                );
212
            }
213
214
            if (file_exists(api_get_path(SYS_PLUGIN_PATH).$pluginName.'/readme.txt')) {
215
                $pluginRow .= Display::url(
216
                    "<em class='fa fa-file-text-o'></em> readme.txt",
217
                    api_get_path(WEB_PLUGIN_PATH).$pluginName."/readme.txt",
218
                    [
219
                        'class' => 'btn btn-blue ajax',
220
                        'data-title' => $plugin_info['title'],
221
                        'data-size' => 'lg',
222
                        '_target' => '_blank',
223
                    ]
224
                );
225
            }
226
227
            $readmeFile = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/README.md';
228
            if (file_exists($readmeFile)) {
229
                $pluginRow .= Display::url(
230
                    "<em class='fa fa-file-text-o'></em> README.md",
231
                    api_get_path(WEB_AJAX_PATH).'plugin.ajax.php?a=md_to_html&plugin='.$pluginName,
232
                    [
233
                        'class' => 'btn btn-blue ajax',
234
                        'data-title' => $plugin_info['title'],
235
                        'data-size' => 'lg',
236
                        '_target' => '_blank',
237
                    ]
238
                );
239
            }
240
241
            $pluginRow .= '</div>';
242
            $pluginRow .= '</td></tr>';
243
244
            if (in_array($pluginName, $installed_plugins)) {
245
                $installed .= $pluginRow;
246
            } else {
247
                $notInstalled .= $pluginRow;
248
            }
249
        }
250
    }
251
    echo '<tbody class="bg-white">';
252
    echo $installed;
253
    echo $notInstalled;
254
    echo '</tbody>';
255
    echo '</table>';
256
257
    echo '<div class="form-actions bottom_actions">';
258
    echo '<button class="btn btn--primary" type="submit" name="submit_plugins">';
259
    echo '<i class="fa fa-check" aria-hidden="true"></i> ';
260
    echo get_lang('Enable the selected plugins').'</button>';
261
    echo '</div>';
262
    echo '</form>';
263
}
264
265
/**
266
 * This function allows the platform admin to choose the default stylesheet.
267
 *
268
 * @author Patrick Cool <[email protected]>, Ghent University
269
 * @author Julio Montoya <[email protected]>, Chamilo
270
 */
271
function handleStylesheets()
272
{
273
    $is_style_changeable = isStyleChangeable();
274
    $allowedFileTypes = ['png'];
275
276
    $form = new FormValidator(
277
        'stylesheet_upload',
278
        'post',
279
        'settings.php?category=Stylesheets#tabs-3'
280
    );
281
    $form->addElement(
282
        'text',
283
        'name_stylesheet',
284
        get_lang('Name of the stylesheet'),
285
        ['size' => '40', 'maxlength' => '40']
286
    );
287
    $form->addRule(
288
        'name_stylesheet',
289
        get_lang('Required field'),
290
        'required'
291
    );
292
    $form->addElement(
293
        'file',
294
        'new_stylesheet',
295
        get_lang('New stylesheet file')
296
    );
297
    $allowed_file_types = getAllowedFileTypes();
298
299
    $form->addRule(
300
        'new_stylesheet',
301
        get_lang('Invalid extension').' ('.implode(',', $allowed_file_types).')',
302
        'filetype',
303
        $allowed_file_types
304
    );
305
    $form->addRule(
306
        'new_stylesheet',
307
        get_lang('Required field'),
308
        'required'
309
    );
310
    $form->addButtonUpload(get_lang('Upload'), 'stylesheet_upload');
311
312
    $show_upload_form = false;
313
    $urlId = api_get_current_access_url_id();
314
315
    if (!is_writable(CSS_UPLOAD_PATH)) {
316
        echo Display::return_message(
317
            CSS_UPLOAD_PATH.get_lang('is not writeable'),
318
            'error',
319
            false
320
        );
321
    } else {
322
        // Uploading a new stylesheet.
323
        if (1 == $urlId) {
324
            $show_upload_form = true;
325
        } else {
326
            if ($is_style_changeable) {
327
                $show_upload_form = true;
328
            }
329
        }
330
    }
331
332
    // Stylesheet upload.
333
    if (isset($_POST['stylesheet_upload'])) {
334
        if ($form->validate()) {
335
            $values = $form->exportValues();
336
            $picture_element = $form->getElement('new_stylesheet');
337
            $picture = $picture_element->getValue();
338
            $result = uploadStylesheet($values, $picture);
339
340
            // Add event to the system log.
341
            $user_id = api_get_user_id();
342
            $category = $_GET['category'];
343
            Event::addEvent(
344
                LOG_CONFIGURATION_SETTINGS_CHANGE,
345
                LOG_CONFIGURATION_SETTINGS_CATEGORY,
346
                $category,
347
                api_get_utc_datetime(),
348
                $user_id
349
            );
350
351
            if ($result) {
352
                echo Display::return_message(get_lang('The stylesheet has been added'));
353
            }
354
        }
355
    }
356
357
    // Current style.
358
    $selected = $currentStyle = api_get_setting('stylesheets');
359
    $styleFromDatabase = api_get_settings_params_simple(
360
        ['variable = ? AND access_url = ?' => ['stylesheets', api_get_current_access_url_id()]]
361
    );
362
    if ($styleFromDatabase) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $styleFromDatabase of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
363
        $selected = $currentStyle = $styleFromDatabase['selected_value'];
364
    }
365
366
    if (isset($_POST['preview'])) {
367
        $selected = $currentStyle = Security::remove_XSS($_POST['style']);
368
    }
369
370
    $themeDir = Template::getThemeDir($selected);
371
    $dir = api_get_path(SYS_PUBLIC_PATH).'css/'.$themeDir.'/images/';
372
    $url = api_get_path(WEB_CSS_PATH).'/'.$themeDir.'/images/';
373
    $logoFileName = 'header-logo.png';
374
    $newLogoFileName = 'header-logo-custom'.api_get_current_access_url_id().'.png';
375
    $webPlatformLogoPath = ChamiloApi::getPlatformLogoPath($selected);
376
377
    $logoForm = new FormValidator(
378
        'logo_upload',
379
        'post',
380
        'settings.php?category=Stylesheets#tabs-2'
381
    );
382
383
    $logoForm->addHtml(
384
        Display::return_message(
385
            sprintf(
386
                get_lang('The logo must be of %s px in size and in %s format'),
387
                '250 x 70',
388
                'PNG'
389
            ),
390
            'info'
391
        )
392
    );
393
394
    if (null !== $webPlatformLogoPath) {
395
        $logoForm->addLabel(
396
            get_lang('Current logo'),
397
            '<img id="header-logo-custom" src="'.$webPlatformLogoPath.'?'.time().'">'
398
        );
399
    }
400
    $logoForm->addFile('new_logo', get_lang('Update logo'));
401
    if ($is_style_changeable) {
402
        $logoGroup = [
403
            $logoForm->addButtonUpload(get_lang('Upload'), 'logo_upload', true),
404
            $logoForm->addButtonCancel(get_lang('Reset'), 'logo_reset', true),
405
        ];
406
407
        $logoForm->addGroup($logoGroup);
408
    }
409
410
    if (isset($_POST['logo_reset'])) {
411
        if (is_file($dir.$newLogoFileName)) {
412
            unlink($dir.$newLogoFileName);
413
            echo Display::return_message(get_lang('Original logo recovered'));
414
            echo '<script>'
415
                .'$("#header-logo").attr("src","'.$url.$logoFileName.'");'
416
            .'</script>';
417
        }
418
    } elseif (isset($_POST['logo_upload'])) {
419
        $logoForm->addRule(
420
            'new_logo',
421
            get_lang('Invalid extension').' ('.implode(',', $allowedFileTypes).')',
422
            'filetype',
423
            $allowedFileTypes
424
        );
425
        $logoForm->addRule(
426
            'new_logo',
427
            get_lang('Required field'),
428
            'required'
429
        );
430
431
        if ($logoForm->validate()) {
432
            $imageInfo = getimagesize($_FILES['new_logo']['tmp_name']);
433
            $width = $imageInfo[0];
434
            $height = $imageInfo[1];
435
            if ($width <= 250 && $height <= 70) {
436
                if (is_file($dir.$newLogoFileName)) {
437
                    unlink($dir.$newLogoFileName);
438
                }
439
440
                $status = move_uploaded_file(
441
                    $_FILES['new_logo']['tmp_name'],
442
                    $dir.$newLogoFileName
443
                );
444
445
                if ($status) {
446
                    echo Display::return_message(get_lang('New logo uploaded'));
447
                    echo '<script>'
448
                         .'$("#header-logo").attr("src","'.$url.$newLogoFileName.'");'
449
                         .'</script>';
450
                } else {
451
                    echo Display::return_message('Error - '.get_lang('No file was uploaded.'), 'error');
452
                }
453
            } else {
454
                Display::return_message('Error - '.get_lang('Image dimensions do not match the requirements. Please check the suggestions next to the image field.'), 'error');
455
            }
456
        }
457
    }
458
459
    if (isset($_POST['download'])) {
460
        generateCSSDownloadLink($selected);
461
    }
462
463
    $form_change = new FormValidator(
464
        'stylesheet_upload',
465
        'post',
466
        api_get_self().'?category=Stylesheets',
467
        null,
468
        ['id' => 'stylesheets_id']
469
    );
470
471
    $styles = $form_change->addSelectTheme(
472
        'style',
473
        get_lang('Name of the stylesheet')
474
    );
475
    $styles->setSelected($currentStyle);
476
477
    if ($is_style_changeable) {
478
        $group = [
479
            $form_change->addButtonSave(get_lang('Save settings'), 'save', true),
480
            $form_change->addButtonPreview(get_lang('Preview'), 'preview', true),
481
            $form_change->addButtonDownload(get_lang('Download'), 'download', true),
482
        ];
483
484
        $form_change->addGroup($group);
485
486
        if ($show_upload_form) {
487
            echo Display::tabs(
488
                [get_lang('Update'), get_lang('Update logo'), get_lang('New stylesheet file')],
489
                [$form_change->returnForm(), $logoForm->returnForm(), $form->returnForm()]
490
            );
491
        } else {
492
            $form_change->display();
493
        }
494
495
        // Little hack to update the logo image in update form when submiting
496
        if (isset($_POST['logo_reset'])) {
497
            echo '<script>'
498
                    .'$("#header-logo-custom").attr("src","'.$url.$logoFileName.'");'
499
                .'</script>';
500
        } elseif (isset($_POST['logo_upload']) && is_file($dir.$newLogoFileName)) {
501
            echo '<script>'
502
                    .'$("#header-logo-custom").attr("src","'.$url.$newLogoFileName.'");'
503
                .'</script>';
504
        }
505
    } else {
506
        $form_change->freeze();
507
    }
508
}
509
510
/**
511
 * Creates the folder (if needed) and uploads the stylesheet in it.
512
 *
513
 * @param array $values  the values of the form
514
 * @param array $picture the values of the uploaded file
515
 *
516
 * @return bool
517
 *
518
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
519
 *
520
 * @version May 2008
521
 *
522
 * @since v1.8.5
523
 */
524
function uploadStylesheet($values, $picture)
525
{
526
    $result = false;
527
    // Valid name for the stylesheet folder.
528
    $style_name = api_preg_replace('/[^A-Za-z0-9]/', '', $values['name_stylesheet']);
529
    if (empty($style_name) || is_array($style_name)) {
530
        // The name of the uploaded stylesheet doesn't have the expected format
531
        return $result;
532
    }
533
    $cssToUpload = CSS_UPLOAD_PATH;
534
535
    // Check if a virtual instance vchamilo is used
536
    $virtualInstanceTheme = api_get_configuration_value('virtual_css_theme_folder');
537
    if (!empty($virtualInstanceTheme)) {
538
        $cssToUpload = $cssToUpload.$virtualInstanceTheme.'/';
539
    }
540
541
    // Create the folder if needed.
542
    if (!is_dir($cssToUpload.$style_name.'/')) {
543
        mkdir($cssToUpload.$style_name.'/', api_get_permissions_for_new_directories());
544
    }
545
546
    $info = pathinfo($picture['name']);
547
548
    if ('zip' == $info['extension']) {
549
        // Try to open the file and extract it in the theme.
550
        $zip = new ZipArchive();
551
        if ($zip->open($picture['tmp_name'])) {
552
            // Make sure all files inside the zip are images or css.
553
            $num_files = $zip->numFiles;
554
            $valid = true;
555
            $single_directory = true;
556
            $invalid_files = [];
557
558
            $allowedFiles = getAllowedFileTypes();
559
560
            for ($i = 0; $i < $num_files; $i++) {
561
                $file = $zip->statIndex($i);
562
                if ('/' != substr($file['name'], -1)) {
563
                    $path_parts = pathinfo($file['name']);
564
                    if (!in_array($path_parts['extension'], $allowedFiles)) {
565
                        $valid = false;
566
                        $invalid_files[] = $file['name'];
567
                    }
568
                }
569
570
                if (false === strpos($file['name'], '/')) {
571
                    $single_directory = false;
572
                }
573
            }
574
            if (!$valid) {
575
                $error_string = '<ul>';
576
                foreach ($invalid_files as $invalid_file) {
577
                    $error_string .= '<li>'.$invalid_file.'</li>';
578
                }
579
                $error_string .= '</ul>';
580
                echo Display::return_message(
581
                    get_lang('The only accepted extensions in the ZIP file are .jp(e)g, .png, .gif and .css.').$error_string,
582
                    'error',
583
                    false
584
                );
585
            } else {
586
                // If the zip does not contain a single directory, extract it.
587
                if (!$single_directory) {
588
                    // Extract zip file.
589
                    $zip->extractTo($cssToUpload.$style_name.'/');
590
                    $result = true;
591
                } else {
592
                    $extraction_path = $cssToUpload.$style_name.'/';
593
                    $mode = api_get_permissions_for_new_directories();
594
                    for ($i = 0; $i < $num_files; $i++) {
595
                        $entry = $zip->getNameIndex($i);
596
                        if ('/' == substr($entry, -1)) {
597
                            continue;
598
                        }
599
600
                        $pos_slash = strpos($entry, '/');
601
                        $entry_without_first_dir = substr($entry, $pos_slash + 1);
602
                        // If there is still a slash, we need to make sure the directories are created.
603
                        if (false !== strpos($entry_without_first_dir, '/')) {
604
                            if (!is_dir($extraction_path.dirname($entry_without_first_dir))) {
605
                                // Create it.
606
                                @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

606
                                /** @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...
607
                            }
608
                        }
609
610
                        $fp = $zip->getStream($entry);
611
                        $ofp = fopen($extraction_path.dirname($entry_without_first_dir).'/'.basename($entry), 'w');
612
613
                        while (!feof($fp)) {
614
                            fwrite($ofp, fread($fp, 8192));
615
                        }
616
617
                        fclose($fp);
618
                        fclose($ofp);
619
                    }
620
                    $result = true;
621
                }
622
            }
623
            $zip->close();
624
        } else {
625
            echo Display::return_message(get_lang('Error reading ZIP file').$info['extension'], 'error', false);
626
        }
627
    } else {
628
        // Simply move the file.
629
        move_uploaded_file($picture['tmp_name'], $cssToUpload.$style_name.'/'.$picture['name']);
630
        $result = true;
631
    }
632
633
    if ($result) {
634
        $fs = new Filesystem();
635
        $fs->mirror(
636
            CSS_UPLOAD_PATH,
637
            api_get_path(SYS_PATH).'web/css/themes/',
638
            null,
639
            ['override' => true]
640
        );
641
    }
642
643
    return $result;
644
}
645
646
/**
647
 * Store plugin regions.
648
 */
649
function storeRegions()
650
{
651
    $plugin_obj = new AppPlugin();
652
653
    // Get a list of all current 'Plugins' settings
654
    $installed_plugins = $plugin_obj->getInstalledPlugins();
655
    $shortlist_installed = [];
656
    if (!empty($installed_plugins)) {
657
        foreach ($installed_plugins as $plugin) {
658
            if (isset($plugin['subkey'])) {
659
                $shortlist_installed[] = $plugin['subkey'];
660
            }
661
        }
662
    }
663
664
    $plugin_list = $plugin_obj->read_plugins_from_path();
665
666
    foreach ($plugin_list as $plugin) {
667
        if (isset($_POST['plugin_'.$plugin])) {
668
            $areas_to_installed = $_POST['plugin_'.$plugin];
669
            if (!empty($areas_to_installed)) {
670
                $plugin_obj->removeAllRegions($plugin);
671
                foreach ($areas_to_installed as $region) {
672
                    if (!empty($region) && '-1' != $region) {
673
                        $plugin_obj->add_to_region($plugin, $region);
674
                    }
675
                }
676
            }
677
        }
678
    }
679
}
680
681
/**
682
 * This function allows easy activating and inactivating of plugins.
683
 *
684
 * @author Patrick Cool <[email protected]>, Ghent University
685
 */
686
function storePlugins()
687
{
688
    $appPlugin = new AppPlugin();
689
    // Get a list of all current 'Plugins' settings
690
    $plugin_list = $appPlugin->read_plugins_from_path();
691
    $installed_plugins = [];
692
693
    foreach ($plugin_list as $plugin) {
694
        if (isset($_POST['plugin_'.$plugin])) {
695
            $appPlugin->install($plugin);
696
            $installed_plugins[] = $plugin;
697
        }
698
    }
699
700
    if (!empty($installed_plugins)) {
701
        $remove_plugins = array_diff($plugin_list, $installed_plugins);
702
    } else {
703
        $remove_plugins = $plugin_list;
704
    }
705
706
    foreach ($remove_plugins as $plugin) {
707
        $appPlugin->uninstall($plugin);
708
    }
709
}
710
711
/**
712
 * This function allows the platform admin to choose which should be the default stylesheet.
713
 *
714
 * @author Patrick Cool <[email protected]>, Ghent University
715
 */
716
function storeStylesheets()
717
{
718
    // Insert the stylesheet.
719
    if (isStyle($_POST['style'])) {
720
        api_set_setting(
721
            'stylesheets',
722
            $_POST['style'],
723
            null,
724
            'stylesheets',
725
            api_get_current_access_url_id()
726
        );
727
    }
728
729
    return true;
730
}
731
732
/**
733
 * This function checks if the given style is a recognize style that exists in the css directory as
734
 * a standalone directory.
735
 *
736
 * @param string $style
737
 *
738
 * @return bool True if this style is recognized, false otherwise
739
 */
740
function isStyle($style)
741
{
742
    $themeList = api_get_themes();
743
744
    return in_array($style, array_keys($themeList));
745
}
746
747
/**
748
 * Search options
749
 * TODO: support for multiple site. aka $_configuration['access_url'] == 1.
750
 *
751
 * @author Marco Villegas <[email protected]>
752
 */
753
function handleSearch()
754
{
755
    global $SettingsStored, $_configuration;
756
757
    $search_enabled = api_get_setting('search_enabled');
758
759
    $form = new FormValidator(
760
        'search-options',
761
        'post',
762
        api_get_self().'?category=Search'
763
    );
764
    $values = api_get_settings_options('search_enabled');
765
    $form->addElement('header', null, get_lang('Fulltext search'));
766
767
    $group = formGenerateElementsGroup($form, $values, 'search_enabled');
768
769
    // SearchEnabledComment
770
    $form->addGroup(
771
        $group,
772
        'search_enabled',
773
        [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.')],
774
        null,
775
        false
776
    );
777
778
    $search_enabled = api_get_setting('search_enabled');
779
780
    if ($form->validate()) {
781
        $formValues = $form->exportValues();
782
        setConfigurationSettingsInDatabase($formValues, $_configuration['access_url']);
783
        $search_enabled = $formValues['search_enabled'];
784
        echo Display::return_message($SettingsStored, 'confirm');
785
    }
786
    $specific_fields = get_specific_field_list();
787
788
    if ('true' == $search_enabled) {
789
        $values = api_get_settings_options('search_show_unlinked_results');
790
        $group = formGenerateElementsGroup(
791
            $form,
792
            $values,
793
            'search_show_unlinked_results'
794
        );
795
        $form->addGroup(
796
            $group,
797
            'search_show_unlinked_results',
798
            [
799
                get_lang('Full-text search: show unlinked results'),
800
                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?'),
801
            ],
802
            null,
803
            false
804
        );
805
        $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...
806
807
        $sf_values = [];
808
        foreach ($specific_fields as $sf) {
809
            $sf_values[$sf['code']] = $sf['name'];
810
        }
811
        $url = Display::div(
812
            Display::url(
813
                get_lang('Add a specific search field'),
814
                'specific_fields.php'
815
            ),
816
            ['class' => 'sectioncomment']
817
        );
818
        if (empty($sf_values)) {
819
            $form->addElement('label', [get_lang('Specific Field for prefilter'), $url]);
820
        } else {
821
            $form->addElement(
822
                'select',
823
                'search_prefilter_prefix',
824
                [get_lang('Specific Field for prefilter'), $url],
825
                $sf_values,
826
                ''
827
            );
828
            $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix');
829
        }
830
    }
831
832
    $default_values['search_enabled'] = $search_enabled;
833
834
    $form->addButtonSave(get_lang('Save'));
835
    $form->setDefaults($default_values);
836
837
    echo '<div id="search-options-form">';
838
    $form->display();
839
    echo '</div>';
840
841
    if ('true' == $search_enabled) {
842
        //$xapianPath = api_get_path(SYS_UPLOAD_PATH).'plugins/xapian/searchdb';
843
844
        /*
845
        @todo Test the Xapian connection
846
        if (extension_loaded('xapian')) {
847
            require_once 'xapian.php';
848
            try {
849
                $db = new XapianDatabase($xapianPath.'/');
850
            } catch (Exception $e) {
851
                var_dump($e->getMessage());
852
            }
853
854
            require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
855
            require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
856
            require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
857
858
            $indexable = new IndexableChunk();
859
            $indexable->addValue("content", 'Test');
860
861
            $di = new ChamiloIndexer();
862
            $di->connectDb(NULL, NULL, 'english');
863
            $di->addChunk($indexable);
864
            $did = $di->index();
865
        }
866
        */
867
868
        $xapianLoaded = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Validate'));
869
        $dir_exists = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Validate'));
870
        $dir_is_writable = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Validate'));
871
        $specific_fields_exists = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Validate'));
872
873
        //Testing specific fields
874
        if (empty($specific_fields)) {
875
            $specific_fields_exists = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Add a specific search field')
876
            );
877
        }
878
        //Testing xapian extension
879
        if (!extension_loaded('xapian')) {
880
            $xapianLoaded = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Error'));
881
        }
882
        //Testing xapian searchdb path
883
        if (!is_dir($xapianPath)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $xapianPath seems to be never defined.
Loading history...
884
            $dir_exists = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Error'));
885
        }
886
        //Testing xapian searchdb path is writable
887
        if (!is_writable($xapianPath)) {
888
            $dir_is_writable = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Error'));
889
        }
890
891
        $data = [];
892
        $data[] = [get_lang('Xapian module installed'), $xapianLoaded];
893
        $data[] = [get_lang('The directory exists').' - '.$xapianPath, $dir_exists];
894
        $data[] = [get_lang('Is writable').' - '.$xapianPath, $dir_is_writable];
895
        $data[] = [get_lang('Available custom search fields'), $specific_fields_exists];
896
897
        showSearchSettingsTable($data);
898
        showSearchToolsStatusTable();
899
    }
900
}
901
902
/**
903
 * Wrapper for the templates.
904
 *
905
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
906
 * @author Julio Montoya.
907
 *
908
 * @version August 2008
909
 *
910
 * @since v1.8.6
911
 */
912
function handleTemplates()
913
{
914
    /* Drive-by fix to avoid undefined var warnings, without repeating
915
     * isset() combos all over the place. */
916
    $action = isset($_GET['action']) ? $_GET['action'] : "invalid";
917
918
    if ('add' != $action) {
919
        echo '<div class="actions" style="margin-left: 1px;">';
920
        echo '<a href="settings.php?category=Templates&action=add">'.
921
                Display::getMdiIcon(ObjectIcon::TEMPLATE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add a template')).'</a>';
922
        echo '</div>';
923
    }
924
925
    if ('add' == $action || ('edit' == $action && is_numeric($_GET['id']))) {
926
        addEditTemplate();
927
928
        // Add event to the system log.
929
        $user_id = api_get_user_id();
930
        $category = $_GET['category'];
931
        Event::addEvent(
932
            LOG_CONFIGURATION_SETTINGS_CHANGE,
933
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
934
            $category,
935
            api_get_utc_datetime(),
936
            $user_id
937
        );
938
    } else {
939
        if ('delete' == $action && is_numeric($_GET['id'])) {
940
            deleteTemplate($_GET['id']);
941
942
            // Add event to the system log
943
            $user_id = api_get_user_id();
944
            $category = $_GET['category'];
945
            Event::addEvent(
946
                LOG_CONFIGURATION_SETTINGS_CHANGE,
947
                LOG_CONFIGURATION_SETTINGS_CATEGORY,
948
                $category,
949
                api_get_utc_datetime(),
950
                $user_id
951
            );
952
        }
953
        displayTemplates();
954
    }
955
}
956
957
/**
958
 * Display a sortable table with all the templates that the platform administrator has defined.
959
 *
960
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
961
 *
962
 * @version August 2008
963
 *
964
 * @since v1.8.6
965
 */
966
function displayTemplates()
967
{
968
    $table = new SortableTable(
969
        'templates',
970
        'getNumberOfTemplates',
971
        'getTemplateData',
972
        1
973
    );
974
    $table->set_additional_parameters(
975
        ['category' => Security::remove_XSS($_GET['category'])]
976
    );
977
    $table->set_header(0, get_lang('Image'), true, ['style' => 'width: 101px;']);
978
    $table->set_header(1, get_lang('Title'));
979
    $table->set_header(2, get_lang('Detail'), false, ['style' => 'width:50px;']);
980
    $table->set_column_filter(2, 'actionsFilter');
981
    $table->set_column_filter(0, 'searchImageFilter');
982
    $table->display();
983
}
984
985
/**
986
 * Gets the number of templates that are defined by the platform admin.
987
 *
988
 * @return int
989
 *
990
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
991
 *
992
 * @version August 2008
993
 *
994
 * @since v1.8.6
995
 */
996
function getNumberOfTemplates()
997
{
998
    // Database table definition.
999
    $table = Database::get_main_table('system_template');
1000
1001
    // The sql statement.
1002
    $sql = "SELECT COUNT(id) AS total FROM $table";
1003
    $result = Database::query($sql);
1004
    $row = Database::fetch_array($result);
1005
1006
    // Returning the number of templates.
1007
    return $row['total'];
1008
}
1009
1010
/**
1011
 * Gets all the template data for the sortable table.
1012
 *
1013
 * @param int    $from            the start of the limit statement
1014
 * @param int    $number_of_items the number of elements that have to be retrieved from the database
1015
 * @param int    $column          the column that is
1016
 * @param string $direction       the sorting direction (ASC or DESC)
1017
 *
1018
 * @return array
1019
 *
1020
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1021
 *
1022
 * @version August 2008
1023
 *
1024
 * @since v1.8.6
1025
 */
1026
function getTemplateData($from, $number_of_items, $column, $direction)
1027
{
1028
    // Database table definition.
1029
    $table_system_template = Database::get_main_table('system_template');
1030
1031
    $from = (int) $from;
1032
    $number_of_items = (int) $number_of_items;
1033
    $column = (int) $column;
1034
    $direction = !in_array(strtolower(trim($direction)), ['asc', 'desc']) ? 'asc' : $direction;
1035
    // The sql statement.
1036
    $sql = "SELECT id as col0, title as col1, id as col2 FROM $table_system_template";
1037
    $sql .= " ORDER BY col$column $direction ";
1038
    $sql .= " LIMIT $from,$number_of_items";
1039
    $result = Database::query($sql);
1040
    $return = [];
1041
    while ($row = Database::fetch_array($result)) {
1042
        $row['1'] = get_lang($row['1']);
1043
        $return[] = $row;
1044
    }
1045
    // Returning all the information for the sortable table.
1046
    return $return;
1047
}
1048
1049
/**
1050
 * display the edit and delete icons in the sortable table.
1051
 *
1052
 * @param int $id the id of the template
1053
 *
1054
 * @return string code for the link to edit and delete the template
1055
 *
1056
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1057
 *
1058
 * @version August 2008
1059
 *
1060
 * @since v1.8.6
1061
 */
1062
function actionsFilter($id)
1063
{
1064
    $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>';
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($id) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

1064
    $return = '<a href="settings.php?category=Templates&action=edit&id='./** @scrutinizer ignore-type */ Security::remove_XSS($id).'">'.Display::getMdiIcon(ActionIcon::EDIT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Edit')).'</a>';
Loading history...
1065
    $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>';
1066
1067
    return $return;
1068
}
1069
1070
/**
1071
 * Display the image of the template in the sortable table.
1072
 *
1073
 * @param string $image the image
1074
 *
1075
 * @return string code for the image
1076
 *
1077
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1078
 *
1079
 * @version August 2008
1080
 *
1081
 * @since v1.8.6
1082
 */
1083
function searchImageFilter($id)
1084
{
1085
    $em = Database::getManager();
1086
1087
    /** @var SystemTemplate $template */
1088
    $template = $em->find('ChamiloCoreBundle:SystemTemplate', $id);
1089
1090
    $assetRepo = Container::getAssetRepository();
1091
    $imageUrl = $assetRepo->getAssetUrl($template->getImage());
1092
1093
    if (!empty($imageUrl)) {
1094
        return '<img src="'.$imageUrl.'" alt="'.get_lang('Template preview').'"/>';
1095
    } else {
1096
        return '<img src="'.api_get_path(WEB_PUBLIC_PATH).'img/template_thumb/noimage.gif" alt="'.get_lang('NoTemplate preview').'"/>';
1097
    }
1098
}
1099
1100
/**
1101
 * Add (or edit) a template. This function displays the form and also takes
1102
 * care of uploading the image and storing the information in the database.
1103
 *
1104
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1105
 *
1106
 * @version August 2008
1107
 *
1108
 * @since v1.8.6
1109
 */
1110
function addEditTemplate()
1111
{
1112
    $em = Database::getManager();
1113
    $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
1114
1115
    $assetRepo = Container::getAssetRepository();
1116
1117
    /** @var SystemTemplate $template */
1118
    $template = $id ? $em->find('ChamiloCoreBundle:SystemTemplate', $id) : new SystemTemplate();
1119
1120
    $form = new FormValidator(
1121
        'template',
1122
        'post',
1123
        'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).'&id='.$id
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($_GET['action']) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

1123
        'settings.php?category=Templates&action='./** @scrutinizer ignore-type */ Security::remove_XSS($_GET['action']).'&id='.$id
Loading history...
1124
    );
1125
1126
    // Setting the form elements: the header.
1127
    if ('add' == $_GET['action']) {
1128
        $title = get_lang('Add a template');
1129
    } else {
1130
        $title = get_lang('Template edition');
1131
    }
1132
    $form->addElement('header', '', $title);
1133
1134
    // Setting the form elements: the title of the template.
1135
    $form->addText('title', get_lang('Title'), false);
1136
    $form->addText('comment', get_lang('Description'), false);
1137
1138
    // Setting the form elements: the content of the template (wysiwyg editor).
1139
    $form->addHtmlEditor(
1140
        'template_text',
1141
        get_lang('Text'),
1142
        true,
1143
        true,
1144
        ['ToolbarSet' => 'Documents', 'Width' => '100%', 'Height' => '400']
1145
    );
1146
1147
    // Setting the form elements: the form to upload an image to be used with the template.
1148
    if (!$template->hasImage()) {
1149
        // Picture
1150
        $form->addFile(
1151
            'template_image',
1152
            get_lang('Add image'),
1153
            ['id' => 'picture', 'class' => 'picture-form', 'crop_image' => true, 'crop_ratio' => '1 / 1']
1154
        );
1155
        $allowedPictureTypes = api_get_supported_image_extensions(false);
1156
        $form->addRule('template_image', get_lang('Only PNG, JPG or GIF images allowed').' ('.implode(',', $allowedPictureTypes).')', 'filetype', $allowedPictureTypes);
1157
    }
1158
1159
    // Setting the form elements: a little bit information about the template image.
1160
    $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'));
1161
1162
    // Getting all the information of the template when editing a template.
1163
    if ('edit' == $_GET['action']) {
1164
        $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...
1165
        $defaults['template_text'] = $template->getContent();
1166
        // Forcing get_lang().
1167
        $defaults['title'] = $template->getTitle();
1168
        $defaults['comment'] = $template->getComment();
1169
1170
        // Adding an extra field: a hidden field with the id of the template we are editing.
1171
        $form->addElement('hidden', 'template_id');
1172
1173
        // Adding an extra field: a preview of the image that is currently used.
1174
1175
        if ($template->hasImage()) {
1176
            $imageUrl = $assetRepo->getAssetUrl($template->getImage());
1177
            $form->addElement(
1178
                'static',
1179
                'template_image_preview',
1180
                '',
1181
                '<img src="'.$imageUrl
1182
                    .'" alt="'.get_lang('Template preview')
1183
                    .'"/>'
1184
            );
1185
            $form->addCheckBox('delete_image', null, get_lang('Delete picture'));
1186
        } else {
1187
            $form->addElement(
1188
                'static',
1189
                'template_image_preview',
1190
                '',
1191
                '<img src="'.api_get_path(WEB_PUBLIC_PATH).'img/template_thumb/noimage.gif" alt="'.get_lang('NoTemplate preview').'"/>'
1192
            );
1193
        }
1194
1195
        // Setting the information of the template that we are editing.
1196
        $form->setDefaults($defaults);
1197
    }
1198
    // Setting the form elements: the submit button.
1199
    $form->addButtonSave(get_lang('Validate'), 'submit');
1200
1201
    // Setting the rules: the required fields.
1202
    if (!$template->hasImage()) {
1203
        $form->addRule(
1204
            'template_image',
1205
            get_lang('Required field'),
1206
            'required'
1207
        );
1208
        $form->addRule('title', get_lang('Required field'), 'required');
1209
    }
1210
1211
    // if the form validates (complies to all rules) we save the information,
1212
    // else we display the form again (with error message if needed)
1213
    if ($form->validate()) {
1214
        $check = Security::check_token('post');
1215
1216
        if ($check) {
1217
            // Exporting the values.
1218
            $values = $form->exportValues();
1219
            $asset = null;
1220
            if (isset($values['delete_image']) && !empty($id)) {
1221
                deleteTemplateImage($id);
1222
            }
1223
1224
            // Upload the file.
1225
            if (!empty($_FILES['template_image']['name'])) {
1226
                $picture = $_FILES['template_image'];
1227
                if (!empty($picture['name'])) {
1228
                    $asset = (new Asset())
1229
                        ->setCategory(Asset::SYSTEM_TEMPLATE)
1230
                        ->setTitle($picture['name'])
1231
                    ;
1232
                    if (!empty($values['picture_crop_result'])) {
1233
                        $asset->setCrop($values['picture_crop_result']);
1234
                    }
1235
                    $asset = $assetRepo->createFromRequest($asset, $picture);
1236
                }
1237
            }
1238
1239
            // Store the information in the database (as insert or as update).
1240
            $bootstrap = api_get_bootstrap_and_font_awesome();
1241
            $viewport = '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
1242
1243
            if ('add' == $_GET['action']) {
1244
                $templateContent = '<head>'.$viewport.'<title>'.$values['title'].'</title>'.$bootstrap.'</head>'
1245
                    .$values['template_text'];
1246
                $template
1247
                    ->setTitle($values['title'])
1248
                    ->setComment(Security::remove_XSS($values['comment']))
1249
                    ->setContent(Security::remove_XSS($templateContent, COURSEMANAGERLOWSECURITY))
1250
                    ->setImage($asset);
1251
                $em->persist($template);
1252
                $em->flush();
1253
1254
                // Display a feedback message.
1255
                echo Display::return_message(
1256
                    get_lang('Template added'),
1257
                    'confirm'
1258
                );
1259
                echo '<a href="settings.php?category=Templates&action=add">'.
1260
                    Display::getMdiIcon(ObjectIcon::TEMPLATE, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add a template')).
1261
                    '</a>';
1262
            } else {
1263
                $templateContent = '<head>'.$viewport.'<title>'.$values['title'].'</title>'.$bootstrap.'</head>'
1264
                    .$values['template_text'];
1265
1266
                $template
1267
                    ->setTitle($values['title'])
1268
                    ->setContent(Security::remove_XSS($templateContent, COURSEMANAGERLOWSECURITY));
1269
1270
                if ($asset) {
1271
                    $template->setImage($asset);
1272
                }
1273
1274
                $em->persist($template);
1275
                $em->flush();
1276
1277
                // Display a feedback message.
1278
                echo Display::return_message(get_lang('Template edited'), 'confirm');
1279
            }
1280
        }
1281
        Security::clear_token();
1282
        displayTemplates();
1283
    } else {
1284
        $token = Security::get_token();
1285
        $form->addElement('hidden', 'sec_token');
1286
        $form->setConstants(['sec_token' => $token]);
1287
        // Display the form.
1288
        $form->display();
1289
    }
1290
}
1291
1292
/**
1293
 * Deletes the template picture as asset.
1294
 *
1295
 * @param int $id
1296
 */
1297
function deleteTemplateImage($id)
1298
{
1299
    $em = Database::getManager();
1300
1301
    /** @var SystemTemplate $template */
1302
    $template = $em->find('ChamiloCoreBundle:SystemTemplate', $id);
1303
1304
    if ($template && $template->hasImage()) {
1305
        $image = $template->getImage();
1306
        $em->remove($image);
1307
        $em->flush();
1308
    }
1309
}
1310
1311
/**
1312
 * Delete a template.
1313
 *
1314
 * @param int $id the id of the template that has to be deleted
1315
 *
1316
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1317
 *
1318
 * @version August 2008
1319
 *
1320
 * @since v1.8.6
1321
 */
1322
function deleteTemplate($id)
1323
{
1324
    $id = intval($id);
1325
    // First we remove the image.
1326
    $table = Database::get_main_table('system_template');
1327
    $sql = "SELECT * FROM $table WHERE id = $id";
1328
    $result = Database::query($sql);
1329
    $row = Database::fetch_array($result);
1330
    if (!empty($row['image'])) {
1331
        @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

1331
        /** @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...
1332
    }
1333
1334
    // Now we remove it from the database.
1335
    $sql = "DELETE FROM $table WHERE id = $id";
1336
    Database::query($sql);
1337
1338
    deleteTemplateImage($id);
1339
1340
    // Display a feedback message.
1341
    echo Display::return_message(get_lang('Template deleted'), 'confirm');
1342
}
1343
1344
/**
1345
 * @param array $settings
1346
 * @param array $settings_by_access_list
1347
 *
1348
 * @throws \Doctrine\ORM\ORMException
1349
 * @throws \Doctrine\ORM\OptimisticLockException
1350
 * @throws \Doctrine\ORM\TransactionRequiredException
1351
 *
1352
 * @return FormValidator
1353
 */
1354
function generateSettingsForm($settings, $settings_by_access_list)
1355
{
1356
    global $_configuration, $settings_to_avoid, $convert_byte_to_mega_list;
1357
    $em = Database::getManager();
1358
    $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1359
1360
    $form = new FormValidator(
1361
        'settings',
1362
        'post',
1363
        'settings.php?category='.Security::remove_XSS($_GET['category'])
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($_GET['category']) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

1363
        'settings.php?category='./** @scrutinizer ignore-type */ Security::remove_XSS($_GET['category'])
Loading history...
1364
    );
1365
1366
    $form->addElement(
1367
        'hidden',
1368
        'search_field',
1369
        (!empty($_GET['search_field']) ? Security::remove_XSS($_GET['search_field']) : null)
1370
    );
1371
1372
    $url_id = api_get_current_access_url_id();
1373
    /*
1374
    if (!empty($_configuration['multiple_access_urls']) && api_is_global_platform_admin() && $url_id == 1) {
1375
        $group = array();
1376
        $group[] = $form->createElement('button', 'mark_all', get_lang('Select all'));
1377
        $group[] = $form->createElement('button', 'unmark_all', get_lang('Unselect all'));
1378
        $form->addGroup($group, 'buttons_in_action_right');
1379
    }*/
1380
1381
    $default_values = [];
1382
    $url_info = api_get_access_url($url_id);
1383
    $i = 0;
1384
    $addedSettings = [];
1385
    foreach ($settings as $row) {
1386
        if (in_array($row['variable'], array_keys($settings_to_avoid))) {
1387
            continue;
1388
        }
1389
1390
        if (in_array($row['variable'], $addedSettings)) {
1391
            continue;
1392
        }
1393
1394
        $addedSettings[] = $row['variable'];
1395
1396
        if (!empty($_configuration['multiple_access_urls'])) {
1397
            if (api_is_global_platform_admin()) {
1398
                if (0 == $row['access_url_locked']) {
1399
                    if (1 == $url_id) {
1400
                        if ('1' == $row['access_url_changeable']) {
1401
                            $form->addElement(
1402
                                'html',
1403
                                '<div class="float-right"><a class="share_this_setting" data_status = "0"  data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
1404
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</a></div>'
1405
                            );
1406
                        } else {
1407
                            $form->addElement(
1408
                                'html',
1409
                                '<div class="float-right"><a class="share_this_setting" data_status = "1" data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
1410
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon-disabled', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</a></div>'
1411
                            );
1412
                        }
1413
                    } else {
1414
                        if ('1' == $row['access_url_changeable']) {
1415
                            $form->addElement(
1416
                                'html',
1417
                                '<div class="float-right">'.
1418
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</div>'
1419
                            );
1420
                        } else {
1421
                            $form->addElement(
1422
                                'html',
1423
                                '<div class="float-right">'.
1424
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon-disabled', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</div>'
1425
                            );
1426
                        }
1427
                    }
1428
                }
1429
            }
1430
        }
1431
1432
        $hideme = [];
1433
        $hide_element = false;
1434
1435
        if (1 != $_configuration['access_url']) {
1436
            if (0 == $row['access_url_changeable']) {
1437
                // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element.
1438
                $hide_element = true;
1439
                $hideme = ['disabled'];
1440
            } elseif (1 == $url_info['active']) {
1441
                // We show the elements.
1442
                if (empty($row['variable'])) {
1443
                    $row['variable'] = 0;
1444
                }
1445
                if (empty($row['subkey'])) {
1446
                    $row['subkey'] = 0;
1447
                }
1448
                if (empty($row['category'])) {
1449
                    $row['category'] = 0;
1450
                }
1451
                if (isset($settings_by_access_list[$row['variable']]) &&
1452
                    isset($settings_by_access_list[$row['variable']][$row['subkey']]) &&
1453
                    is_array($settings_by_access_list[$row['variable']][$row['subkey']][$row['category']])
1454
                ) {
1455
                    // We are sure that the other site have a selected value.
1456
                    if ('' != $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value']) {
1457
                        $row['selected_value'] = $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value'];
1458
                    }
1459
                }
1460
                // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
1461
            }
1462
        }
1463
1464
        switch ($row['type']) {
1465
            case 'textfield':
1466
                if (in_array($row['variable'], $convert_byte_to_mega_list)) {
1467
                    $form->addElement(
1468
                        'text',
1469
                        $row['variable'],
1470
                        [
1471
                            get_lang($row['title']),
1472
                            get_lang($row['comment']),
1473
                            get_lang('MB'),
1474
                        ],
1475
                        ['maxlength' => '8', 'aria-label' => get_lang($row['title'])]
1476
                    );
1477
                    $form->applyFilter($row['variable'], 'html_filter');
1478
                    $default_values[$row['variable']] = round($row['selected_value'] / 1024 / 1024, 1);
1479
                } elseif ('account_valid_duration' == $row['variable']) {
1480
                    $form->addElement(
1481
                        'text',
1482
                        $row['variable'],
1483
                        [
1484
                            get_lang($row['title']),
1485
                            get_lang($row['comment']),
1486
                        ],
1487
                        ['maxlength' => '5', 'aria-label' => get_lang($row['title'])]
1488
                    );
1489
                    $form->applyFilter($row['variable'], 'html_filter');
1490
1491
                    // For platform character set selection:
1492
                    // Conversion of the textfield to a select box with valid values.
1493
                    $default_values[$row['variable']] = $row['selected_value'];
1494
                } elseif ('platform_charset' == $row['variable']) {
1495
                    break;
1496
                } else {
1497
                    $hideme['class'] = 'col-md-4';
1498
                    $hideme['aria-label'] = get_lang($row['title']);
1499
                    $form->addElement(
1500
                        'text',
1501
                        $row['variable'],
1502
                        [
1503
                            get_lang($row['title']),
1504
                            get_lang($row['comment']),
1505
                        ],
1506
                        $hideme
1507
                    );
1508
                    $form->applyFilter($row['variable'], 'html_filter');
1509
                    $default_values[$row['variable']] = $row['selected_value'];
1510
                }
1511
                break;
1512
            case 'textarea':
1513
                if ('header_extra_content' == $row['variable']) {
1514
                    $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

1514
                    $file = /** @scrutinizer ignore-call */ api_get_home_path().'header_extra_content.txt';
Loading history...
1515
                    $value = '';
1516
                    if (file_exists($file)) {
1517
                        $value = file_get_contents($file);
1518
                    }
1519
                    $form->addElement(
1520
                        'textarea',
1521
                        $row['variable'],
1522
                        [get_lang($row['title']), get_lang($row['comment'])],
1523
                        ['rows' => '10', 'id' => $row['variable']],
1524
                        $hideme
1525
                    );
1526
                    $default_values[$row['variable']] = $value;
1527
                } elseif ('footer_extra_content' == $row['variable']) {
1528
                    $file = api_get_home_path().'footer_extra_content.txt';
1529
                    $value = '';
1530
                    if (file_exists($file)) {
1531
                        $value = file_get_contents($file);
1532
                    }
1533
                    $form->addElement(
1534
                        'textarea',
1535
                        $row['variable'],
1536
                        [get_lang($row['title']), get_lang($row['comment'])],
1537
                        ['rows' => '10', 'id' => $row['variable']],
1538
                        $hideme
1539
                    );
1540
                    $default_values[$row['variable']] = $value;
1541
                } else {
1542
                    $form->addElement(
1543
                        'textarea',
1544
                        $row['variable'],
1545
                        [get_lang($row['title']),
1546
                        get_lang($row['comment']), ],
1547
                        ['rows' => '10', 'id' => $row['variable']],
1548
                        $hideme
1549
                    );
1550
                    $default_values[$row['variable']] = $row['selected_value'];
1551
                }
1552
                break;
1553
            case 'radio':
1554
                $values = api_get_settings_options($row['variable']);
1555
                $group = [];
1556
                if (is_array($values)) {
1557
                    foreach ($values as $key => $value) {
1558
                        $element = &$form->createElement(
1559
                            'radio',
1560
                            $row['variable'],
1561
                            '',
1562
                            get_lang($value['display_text']),
1563
                            $value['value']
1564
                        );
1565
                        if ($hide_element) {
1566
                            $element->freeze();
1567
                        }
1568
                        $group[] = $element;
1569
                    }
1570
                }
1571
                $form->addGroup(
1572
                    $group,
1573
                    $row['variable'],
1574
                    [get_lang($row['title']), get_lang($row['comment'])],
1575
                    null,
1576
                    false
1577
                );
1578
                $default_values[$row['variable']] = $row['selected_value'];
1579
                break;
1580
            case 'checkbox':
1581
                // 1. We collect all the options of this variable.
1582
                $sql = "SELECT * FROM $table_settings_current
1583
                        WHERE variable='".$row['variable']."' AND access_url =  1";
1584
1585
                $result = Database::query($sql);
1586
                $group = [];
1587
                while ($rowkeys = Database::fetch_array($result)) {
1588
                    // Profile tab option should be hidden when the social tool is enabled.
1589
                    if ('true' == api_get_setting('allow_social_tool')) {
1590
                        if ('show_tabs' === $rowkeys['variable'] && 'my_profile' === $rowkeys['subkey']) {
1591
                            continue;
1592
                        }
1593
                    }
1594
1595
                    // Hiding the gradebook option.
1596
                    if ('show_tabs' === $rowkeys['variable'] && 'my_gradebook' === $rowkeys['subkey']) {
1597
                        continue;
1598
                    }
1599
1600
                    $element = &$form->createElement(
1601
                        'checkbox',
1602
                        $rowkeys['subkey'],
1603
                        '',
1604
                        get_lang($rowkeys['subkeytext'])
1605
                    );
1606
1607
                    if (1 == $row['access_url_changeable']) {
1608
                        // 2. We look into the DB if there is a setting for a specific access_url.
1609
                        $access_url = $_configuration['access_url'];
1610
                        if (empty($access_url)) {
1611
                            $access_url = 1;
1612
                        }
1613
                        $sql = "SELECT selected_value FROM $table_settings_current
1614
                                WHERE
1615
                                    variable='".$rowkeys['variable']."' AND
1616
                                    subkey='".$rowkeys['subkey']."' AND
1617
                                    subkeytext='".$rowkeys['subkeytext']."' AND
1618
                                    access_url =  $access_url";
1619
                        $result_access = Database::query($sql);
1620
                        $row_access = Database::fetch_array($result_access);
1621
                        if ('true' === $row_access['selected_value'] && !$form->isSubmitted()) {
1622
                            $element->setChecked(true);
1623
                        }
1624
                    } else {
1625
                        if ('true' === $rowkeys['selected_value'] && !$form->isSubmitted()) {
1626
                            $element->setChecked(true);
1627
                        }
1628
                    }
1629
                    if ($hide_element) {
1630
                        $element->freeze();
1631
                    }
1632
                    $group[] = $element;
1633
                }
1634
                $form->addGroup(
1635
                    $group,
1636
                    $row['variable'],
1637
                    [get_lang($row['title']), get_lang($row['comment'])],
1638
                    null
1639
                );
1640
                break;
1641
            case 'link':
1642
                $form->addElement(
1643
                    'static',
1644
                    null,
1645
                    [get_lang($row['title']), get_lang($row['comment'])],
1646
                    get_lang('current value').' : '.$row['selected_value'],
1647
                    $hideme
1648
                );
1649
                break;
1650
            case 'select':
1651
                /*
1652
                * 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.
1653
                * The functions being called must be added to the file settings.lib.php.
1654
                */
1655
                $form->addElement(
1656
                    'select',
1657
                    $row['variable'],
1658
                    [get_lang($row['title']), get_lang($row['comment'])],
1659
                    call_user_func('select_'.$row['variable']),
1660
                    $hideme
1661
                );
1662
                $default_values[$row['variable']] = $row['selected_value'];
1663
                break;
1664
            case 'custom':
1665
                break;
1666
            case 'select_course':
1667
                $courseSelectOptions = [];
1668
1669
                if (!empty($row['selected_value'])) {
1670
                    $course = $em->find('ChamiloCoreBundle:Course', $row['selected_value']);
1671
1672
                    $courseSelectOptions[$course->getId()] = $course->getTitle();
1673
                }
1674
1675
                $form->addElement(
1676
                    'select_ajax',
1677
                    $row['variable'],
1678
                    [get_lang($row['title']), get_lang($row['comment'])],
1679
                    $courseSelectOptions,
1680
                    ['url' => api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=search_course']
1681
                );
1682
                $default_values[$row['variable']] = $row['selected_value'];
1683
                break;
1684
        }
1685
1686
        switch ($row['variable']) {
1687
            case 'pdf_export_watermark_enable':
1688
                $url = PDF::get_watermark(null);
1689
1690
                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...
1691
                    $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>';
1692
                    $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>');
1693
                }
1694
1695
                $form->addElement('file', 'pdf_export_watermark_path', get_lang('Upload a watermark image'));
1696
                $allowed_picture_types = ['jpg', 'jpeg', 'png', 'gif'];
1697
                $form->addRule(
1698
                    'pdf_export_watermark_path',
1699
                    get_lang('Only PNG, JPG or GIF images allowed').' ('.implode(',', $allowed_picture_types).')',
1700
                    'filetype',
1701
                    $allowed_picture_types
1702
                );
1703
1704
                break;
1705
            case 'timezone_value':
1706
                $timezone = $row['selected_value'];
1707
                if (empty($timezone)) {
1708
                    $timezone = api_get_timezone();
1709
                }
1710
                $form->addLabel('', sprintf(get_lang('The local time in the portal timezone (%s) is %s'), $timezone, api_get_local_time()));
1711
                break;
1712
        }
1713
    } // end for
1714
1715
    if (!empty($settings)) {
1716
        $form->setDefaults($default_values);
1717
    }
1718
    $form->addHtml('<div class="bottom_actions">');
1719
    $form->addButtonSave(get_lang('Save settings'));
1720
    $form->addHtml('</div>');
1721
1722
    return $form;
1723
}
1724
1725
/**
1726
 * Searches a platform setting in all categories except from the Plugins category.
1727
 *
1728
 * @param string $search
1729
 *
1730
 * @return array
1731
 */
1732
function searchSetting($search)
1733
{
1734
    if (empty($search)) {
1735
        return [];
1736
    }
1737
    $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1738
    $sql = "SELECT * FROM $table_settings_current
1739
            WHERE category <> 'Plugins' ORDER BY id ASC ";
1740
    $result = Database::store_result(Database::query($sql), 'ASSOC');
1741
    $settings = [];
1742
1743
    $search = api_strtolower($search);
1744
1745
    if (!empty($result)) {
1746
        foreach ($result as $setting) {
1747
            $found = false;
1748
1749
            $title = api_strtolower(get_lang($setting['title']));
1750
            // try the title
1751
            if (false === strpos($title, $search)) {
1752
                $comment = api_strtolower(get_lang($setting['comment']));
1753
                //Try the comment
1754
                if (false === strpos($comment, $search)) {
1755
                    //Try the variable name
1756
                    if (false === strpos($setting['variable'], $search)) {
1757
                        continue;
1758
                    } else {
1759
                        $found = true;
1760
                    }
1761
                } else {
1762
                    $found = true;
1763
                }
1764
            } else {
1765
                $found = true;
1766
            }
1767
            if ($found) {
1768
                $settings[] = $setting;
1769
            }
1770
        }
1771
    }
1772
1773
    return $settings;
1774
}
1775
/**
1776
 * Helper function to generates a form elements group.
1777
 *
1778
 * @param object $form   The form where the elements group has to be added
1779
 * @param array  $values Values to browse through
1780
 *
1781
 * @return array
1782
 */
1783
function formGenerateElementsGroup($form, $values = [], $elementName)
1784
{
1785
    $group = [];
1786
    if (is_array($values)) {
1787
        foreach ($values as $key => $value) {
1788
            $element = &$form->createElement('radio', $elementName, '', get_lang($value['display_text']), $value['value']);
1789
            $group[] = $element;
1790
        }
1791
    }
1792
1793
    return $group;
1794
}
1795
/**
1796
 * Helper function with allowed file types for CSS.
1797
 *
1798
 * @return array Array of file types (no indexes)
1799
 */
1800
function getAllowedFileTypes()
1801
{
1802
    $allowedFiles = [
1803
        'css',
1804
        'zip',
1805
        'jpeg',
1806
        'jpg',
1807
        'png',
1808
        'gif',
1809
        'ico',
1810
        'psd',
1811
        'xcf',
1812
        'svg',
1813
        'webp',
1814
        'woff',
1815
        'woff2',
1816
    ];
1817
1818
    return $allowedFiles;
1819
}
1820
/**
1821
 * Helper function to set settings in the database.
1822
 *
1823
 * @param array $parameters List of values
1824
 * @param int   $accessUrl  The current access URL
1825
 */
1826
function setConfigurationSettingsInDatabase($parameters, $accessUrl)
1827
{
1828
    api_set_settings_category('Search', 'false', $accessUrl);
1829
    // Save the settings.
1830
    foreach ($parameters as $key => $value) {
1831
        api_set_setting($key, $value, null, null);
1832
    }
1833
}
1834
1835
/**
1836
 * Helper function to show the status of the search settings table.
1837
 *
1838
 * @param array $data Data to show
1839
 */
1840
function showSearchSettingsTable($data)
1841
{
1842
    echo Display::tag('h3', get_lang('Settings'));
1843
    $table = new SortableTableFromArray($data);
1844
    $table->set_header(0, get_lang('Setting'), false);
1845
    $table->set_header(1, get_lang('Status'), false);
1846
    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...
1847
}
1848
/**
1849
 * Helper function to show status table for each command line tool installed.
1850
 */
1851
function showSearchToolsStatusTable()
1852
{
1853
    //@todo windows support
1854
    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...
1855
        $list_of_programs = ['pdftotext', 'ps2pdf', 'catdoc', 'html2text', 'unrtf', 'catppt', 'xls2csv'];
1856
        foreach ($list_of_programs as $program) {
1857
            $output = [];
1858
            $ret_val = null;
1859
            exec("which $program", $output, $ret_val);
1860
1861
            if (!$output) {
1862
                $output[] = '';
1863
            }
1864
1865
            $icon = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Not installed'));
1866
            if (!empty($output[0])) {
1867
                $icon = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Installed'));
1868
            }
1869
            $data2[] = [$program, $output[0], $icon];
1870
        }
1871
        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'));
1872
        $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 1856. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1873
        $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);
1874
        $table->set_header(1, get_lang('Path'), false);
1875
        $table->set_header(2, get_lang('Status'), false);
1876
        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...
1877
    } else {
1878
        echo Display::return_message(
1879
            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'),
1880
            'warning'
1881
        );
1882
    }
1883
}
1884
/**
1885
 * Helper function to generate and show CSS Zip download message.
1886
 *
1887
 * @param string $style Style path
1888
 */
1889
function generateCSSDownloadLink($style)
1890
{
1891
    $arch = api_get_path(SYS_ARCHIVE_PATH).$style.'.zip';
1892
    $themeDir = Template::getThemeDir($style);
1893
    $dir = api_get_path(SYS_CSS_PATH).$themeDir;
1894
    $check = Security::check_abs_path(
1895
        $dir,
1896
        api_get_path(SYS_CSS_PATH).'themes'
1897
    );
1898
    if (is_dir($dir) && $check) {
1899
        $zip = new PclZip($arch);
1900
        // Remove path prefix except the style name and put file on disk
1901
        $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...
1902
        $url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive_path=&archive='.str_replace(api_get_path(SYS_ARCHIVE_PATH), '', $arch);
1903
1904
        //@TODO: use more generic script to download.
1905
        $str = '<a class="btn btn--primary btn-large" href="'.$url.'">'.get_lang('Download the file').'</a>';
1906
        echo Display::return_message($str, 'normal', false);
1907
    } else {
1908
        echo Display::return_message(get_lang('The file was not found'), 'warning');
1909
    }
1910
}
1911
1912
/**
1913
 * Helper function to tell if the style is changeable in the current URL.
1914
 *
1915
 * @return bool $changeable Whether the style can be changed in this URL or not
1916
 */
1917
function isStyleChangeable()
1918
{
1919
    $changeable = false;
1920
    $urlId = api_get_current_access_url_id();
1921
    if ($urlId) {
1922
        $style_info = api_get_settings('stylesheets', '', 1, 0);
1923
        $url_info = api_get_access_url($urlId);
1924
        if (1 == $style_info[0]['access_url_changeable'] && 1 == $url_info['active']) {
1925
            $changeable = true;
1926
        }
1927
    } else {
1928
        $changeable = true;
1929
    }
1930
1931
    return $changeable;
1932
}
1933
1934
/**
1935
 * Get all settings of one category prepared for display in admin/settings.php.
1936
 *
1937
 * @param string $category
1938
 *
1939
 * @return array
1940
 */
1941
function getCategorySettings($category = '')
1942
{
1943
    $url_id = api_get_current_access_url_id();
1944
    $settings_by_access_list = [];
1945
1946
    if (1 == $url_id) {
1947
        $settings = api_get_settings($category, 'group', $url_id);
1948
    } else {
1949
        $url_info = api_get_access_url($url_id);
1950
        if (1 == $url_info['active']) {
1951
            $categoryToSearch = $category;
1952
            if ('search_setting' == $category) {
1953
                $categoryToSearch = '';
1954
            }
1955
            // The default settings of Chamilo
1956
            $settings = api_get_settings($categoryToSearch, 'group', 1, 0);
1957
            // The settings that are changeable from a particular site.
1958
            $settings_by_access = api_get_settings($categoryToSearch, 'group', $url_id, 1);
1959
1960
            foreach ($settings_by_access as $row) {
1961
                if (empty($row['variable'])) {
1962
                    $row['variable'] = 0;
1963
                }
1964
                if (empty($row['subkey'])) {
1965
                    $row['subkey'] = 0;
1966
                }
1967
                if (empty($row['category'])) {
1968
                    $row['category'] = 0;
1969
                }
1970
1971
                // One more validation if is changeable.
1972
                if (1 == $row['access_url_changeable']) {
1973
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
1974
                } else {
1975
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = [];
1976
                }
1977
            }
1978
        }
1979
    }
1980
1981
    if (isset($category) && 'search_setting' == $category) {
1982
        if (!empty($_REQUEST['search_field'])) {
1983
            $settings = searchSetting($_REQUEST['search_field']);
1984
        }
1985
    }
1986
1987
    return [
1988
        '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...
1989
        'settings_by_access_list' => $settings_by_access_list,
1990
    ];
1991
}
1992