Completed
Push — master ( 996ef7...cc3037 )
by Julito
29:27
created

settings.lib.php ➔ handleRegions()   F

Complexity

Conditions 13
Paths 336

Size

Total Lines 94
Code Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 67
nc 336
nop 0
dl 0
loc 94
rs 3.7737
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 Symfony\Component\Filesystem\Filesystem;
5
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
6
7
/**
8
 * Library of the settings.php file
9
 *
10
 * @author Julio Montoya <[email protected]>
11
 * @author Guillaume Viguier <[email protected]>
12
 *
13
 * @since Chamilo 1.8.7
14
 * @package chamilo.admin
15
 */
16
17
define('CSS_UPLOAD_PATH', api_get_path(SYS_APP_PATH).'Resources/public/css/themes/');
18
19
/**
20
 * This function allows easy activating and inactivating of regions
21
 * @author Julio Montoya <[email protected]> Beeznest 2012
22
 */
23
function handleRegions()
24
{
25
    if (isset($_POST['submit_plugins'])) {
26
        storeRegions();
27
        // Add event to the system log.
28
        $user_id = api_get_user_id();
29
        $category = $_GET['category'];
30
        Event::addEvent(
31
            LOG_CONFIGURATION_SETTINGS_CHANGE,
32
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
33
            $category,
34
            api_get_utc_datetime(),
0 ignored issues
show
Bug introduced by
It seems like api_get_utc_datetime() can also be of type object<DateTime>; however, Event::addEvent() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
35
            $user_id
36
        );
37
        Display :: display_confirmation_message(get_lang('SettingsStored'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_confirmation_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
38
    }
39
40
    $plugin_obj = new AppPlugin();
41
    $possible_plugins  = $plugin_obj->read_plugins_from_path();
42
    $installed_plugins = $plugin_obj->get_installed_plugins();
43
    $name = isset($_GET['name']) ? $_GET['name'] : '';
44
45
    echo '<form 
46
        name="plugins" 
47
        method="post" 
48
        action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'&name='.Security::remove_XSS($name).'">';
49
    echo '<table class="data_table">';
50
    echo '<tr>';
51
    echo '<th width="400px">';
52
    echo get_lang('Plugin');
53
    echo '</th><th>';
54
    echo get_lang('Regions');
55
    echo '</th>';
56
    echo '</th>';
57
    echo '</tr>';
58
59
    /* We display all the possible plugins and the checkboxes */
60
61
    $plugin_region_list = array();
62
    $my_plugin_list = $plugin_obj->get_plugin_regions();
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 = array();
75
            require $plugin_info_file;
76
            if ($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
87
            $region_list = [];
88
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
            echo Display::select(
103
                'plugin_'.$pluginName.'[]',
104
                $region_list,
105
                $selected_plugins,
106
                array('multiple' => 'multiple', 'style' => 'width:500px'),
107
                true,
108
                get_lang('None')
109
            );
110
            echo '</td></tr>';
111
        }
112
    }
113
    echo '</table>';
114
    echo '<br />';
115
    echo '<button class="btn btn-success" type="submit" name="submit_plugins">'.get_lang('EnablePlugins').'</button></form>';
116
}
117
118
function handleExtensions()
119
{
120
    echo Display::page_subheader(get_lang('ConfigureExtensions'));
121
    echo '<a class="btn btn-success" href="configure_extensions.php?display=ppt2lp" role="button">'.get_lang('Ppt2lp').'</a>';
122
123
}
124
125
/**
126
 * This function allows easy activating and inactivating of plugins
127
 * @todo: a similar function needs to be written to activate or inactivate additional tools.
128
 * @author Patrick Cool <[email protected]>, Ghent University
129
 * @author Julio Montoya <[email protected]> Beeznest 2012
130
 */
131
function handlePlugins($installed = true)
132
{
133
    $plugin_obj = new AppPlugin();
134
    $token = Security::get_token();
135
    if (isset($_REQUEST['action'])) {
136
        $name = $_REQUEST['name'];
137
        $appPlugin = new AppPlugin();
138
        switch ($_REQUEST['action']) {
139
            case 'install':
140
                $appPlugin->install($name);
141
                break;
142
            case 'uninstall':
143
                $appPlugin->uninstall($name);
144
                break;
145
        }
146
147
        // Add event to the system log.
148
        $user_id = api_get_user_id();
149
        $category = $_GET['category'];
150
        Event::addEvent(
151
            LOG_CONFIGURATION_SETTINGS_CHANGE,
152
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
153
            $category,
154
            api_get_utc_datetime(),
0 ignored issues
show
Bug introduced by
It seems like api_get_utc_datetime() can also be of type object<DateTime>; however, Event::addEvent() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
155
            $user_id
156
        );
157
        Display :: display_confirmation_message(get_lang('SettingsStored'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_confirmation_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
158
    }
159
160
    $all_plugins = $plugin_obj->read_plugins_from_path();
161
    $installed_plugins = $plugin_obj->get_installed_plugins();
162
163
    // Plugins NOT installed
164
    echo Display::page_subheader(get_lang('Plugins'));
165
    echo '<form class="form-horizontal" name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'&sec_token=' . $token . '">';
166
    echo '<table class="data_table">';
167
    /*echo '<tr>';
168
    echo '<th>';
169
    echo get_lang('Description');
170
    echo '</th>';
171
    echo '</tr>';*/
172
173
    foreach ($all_plugins as $pluginName) {
174
        $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/plugin.php';
175
        if (file_exists($plugin_info_file)) {
176
            $plugin_info = array();
177
            require $plugin_info_file;
178
179
            echo '<tr>';
180
            if (in_array($pluginName, $installed_plugins)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
181
            } else {
182
                if ($installed) {
183
                    continue;
184
                }
185
            }
186
187
            if ($installed == false) {
188
                if (in_array($pluginName, $installed_plugins)) {
189
                    continue;
190
                }
191
            }
192
193
            // Checkbox
194
            if (in_array($pluginName, $installed_plugins)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
195
                //echo '<input type="checkbox" name="plugin_'.$pluginName.'[]" checked="checked">';
196
            } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
197
                //echo '<input type="checkbox" name="plugin_'.$pluginName.'[]">';
198
            }
199
200
            echo '<td>';
201
            echo '<h4>'.$plugin_info['title'].' <small>v '.$plugin_info['version'].'</small></h4>';
202
            echo '<p>'.$plugin_info['comment'].'</p>';
203
            echo '<p>'.get_lang('Author').': '.$plugin_info['author'].'</p>';
204
            echo '<div class="btn-group">';
205
206
            $readme = '';
207
            if (file_exists(api_get_path(SYS_PLUGIN_PATH).$pluginName.'/readme.txt')) {
208
                $readme = Display::url(
209
                    "<em class='fa fa-file-text-o'></em> readme.txt",
210
                    api_get_path(WEB_PLUGIN_PATH) . $pluginName . "/readme.txt",
211
                    [
212
                        'class' => 'btn btn-default ajax',
213
                        'data-title' => $plugin_info['title'],
214
                        'data-size' => 'lg',
215
                        '_target' => '_blank'
216
                    ]
217
                );
218
            }
219
220
            $readmeFile = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/README.md';
221
            if (file_exists($readmeFile)) {
222
                $readme .= Display::url(
223
                    "<em class='fa fa-file-text-o'></em> README.md",
224
                    api_get_path(WEB_AJAX_PATH).'plugin.ajax.php?a=md_to_html&plugin='.$pluginName,
225
                    [
226
                        'class' => 'btn btn-default ajax',
227
                        'data-title' => $plugin_info['title'],
228
                        'data-size' => 'lg',
229
                        '_target' => '_blank'
230
                    ]
231
                );
232
            }
233
234
            if (in_array($pluginName, $installed_plugins)) {
235
                echo Display::url(
236
                    '<em class="fa fa-cogs"></em> '.get_lang('Configure'), 'configure_plugin.php?name='.$pluginName,
237
                    array('class' => 'btn btn-default')
238
                );
239
                echo Display::url(
240
                    '<em class="fa fa-th-large"></em> '.get_lang('Regions'), 'settings.php?category=Regions&name='.$pluginName,
241
                    array('class' => 'btn btn-default')
242
                );
243
244
                echo $readme;
245
246
                echo Display::url(
247
                    '<em class="fa trash-o fa-trash-o "></em> '.get_lang('Uninstall'), 'settings.php?category=Plugins&action=uninstall&name='.$pluginName,
248
                    array('class' => 'btn btn-danger')
249
                );
250
            } else {
251
                echo Display::url(
252
                    '<em class="fa fa-th-large"></em> '.get_lang('Install'), 'settings.php?category=Plugins&action=install&name='.$pluginName,
253
                    array('class' => 'btn btn-success')
254
                );
255
                echo $readme;
256
            }
257
            echo '</div>';
258
            echo '</td></tr>';
259
        }
260
    }
261
    echo '</table>';
262
263
    /*echo '<div class="form-actions bottom_actions">';
264
    echo '<button class="btn btn-success" type="submit" name="submit_plugins">'.
265
            get_lang('EnablePlugins').'</button>';
266
    echo '</div>';*/
267
    echo '</form>';
268
}
269
270
/**
271
 * This function allows the platform admin to choose the default stylesheet
272
 * @author Patrick Cool <[email protected]>, Ghent University
273
 * @author Julio Montoya <[email protected]>, Chamilo
274
 */
275
function handleStylesheets()
276
{
277
    global $_configuration;
278
279
    // Current style.
280
    $currentstyle = api_get_setting('stylesheets');
281
282
    $is_style_changeable = isStyleChangeable();
283
284
    $form = new FormValidator(
285
        'stylesheet_upload',
286
        'post',
287
        'settings.php?category=Stylesheets#tabs-3'
288
    );
289
    $form->addElement('text', 'name_stylesheet', get_lang('NameStylesheet'),
290
        array('size' => '40', 'maxlength' => '40'));
291
    $form->addRule('name_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
292
    $form->addElement('file', 'new_stylesheet', get_lang('UploadNewStylesheet'));
293
    $allowed_file_types = getAllowedFileTypes();
294
295
    $form->addRule('new_stylesheet', get_lang('InvalidExtension') . ' (' . implode(',', $allowed_file_types) . ')',
296
        'filetype', $allowed_file_types);
297
    $form->addRule('new_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
298
    $form->addButtonUpload(get_lang('Upload'), 'stylesheet_upload');
299
300
    $show_upload_form = false;
301
302
    if (!is_writable(CSS_UPLOAD_PATH)) {
303
        Display::display_error_message(CSS_UPLOAD_PATH.get_lang('IsNotWritable'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
304
    } else {
305
        // Uploading a new stylesheet.
306
        if ($_configuration['access_url'] == 1) {
307
            $show_upload_form = true;
308
        } else {
309
            if ($is_style_changeable) {
310
                $show_upload_form = true;
311
            }
312
        }
313
    }
314
315
    // Stylesheet upload.
316
317
    if (isset($_POST['stylesheet_upload'])) {
318
        if ($form->validate()) {
319
            $values = $form->exportValues();
320
            $picture_element = $form->getElement('new_stylesheet');
321
            $picture = $picture_element->getValue();
322
            $result = uploadStylesheet($values, $picture);
323
324
            // Add event to the system log.
325
            $user_id = api_get_user_id();
326
            $category = $_GET['category'];
327
            Event::addEvent(
328
                LOG_CONFIGURATION_SETTINGS_CHANGE,
329
                LOG_CONFIGURATION_SETTINGS_CATEGORY,
330
                $category,
331
                api_get_utc_datetime(),
0 ignored issues
show
Bug introduced by
It seems like api_get_utc_datetime() can also be of type object<DateTime>; however, Event::addEvent() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
332
                $user_id
333
            );
334
335
            if ($result) {
336
                Display::display_confirmation_message(get_lang('StylesheetAdded'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_confirmation_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
337
            }
338
        }
339
    }
340
341
    $form_change = new FormValidator(
342
        'stylesheet_upload',
343
        'post',
344
        api_get_self().'?category=Stylesheets',
345
        null,
346
        array('id' => 'stylesheets_id')
347
    );
348
349
    $list_of_names  = array();
350
    $selected = '';
351
    $dirpath = '';
352
    $safe_style_dir = '';
353
354
    if ($handle = @opendir(CSS_UPLOAD_PATH)) {
355
        $counter = 1;
356
        while (false !== ($style_dir = readdir($handle))) {
357
            if (substr($style_dir, 0, 1) == '.') {
358
                // Skip directories starting with a '.'
359
                continue;
360
            }
361
            $dirpath = CSS_UPLOAD_PATH.$style_dir;
362
363
            if (is_dir($dirpath)) {
364
                if ($style_dir != '.' && $style_dir != '..') {
365
                    if (isset($_POST['style']) &&
366
                        (isset($_POST['preview']) || isset($_POST['download'])) &&
367
                        $_POST['style'] == $style_dir
368
                    ) {
369
                        $safe_style_dir = $style_dir;
370
                    } else {
371
                        if ($currentstyle == $style_dir || ($style_dir == 'chamilo' && !$currentstyle)) {
372
                            if (isset($_POST['style'])) {
373
                                $selected = Database::escape_string($_POST['style']);
374
                            } else {
375
                                $selected = $style_dir;
376
                            }
377
                        }
378
                    }
379
                    $show_name = ucwords(str_replace('_', ' ', $style_dir));
380
381
                    if ($is_style_changeable) {
382
                        $list_of_names[$style_dir]  = $show_name;
383
                    }
384
                    $counter++;
385
                }
386
            }
387
        }
388
        closedir($handle);
389
    }
390
391
    // Sort styles in alphabetical order.
392
    asort($list_of_names);
393
    $select_list = array();
394
    foreach ($list_of_names as $style_dir => $item) {
395
        $select_list[$style_dir] = $item;
396
    }
397
398
    $styles = &$form_change->addElement('select', 'style', get_lang('NameStylesheet'), $select_list);
399
    $styles->setSelected($selected);
400
401
    if ($form_change->validate()) {
402
        // Submit stylesheets.
403
        if (isset($_POST['save'])) {
404
            storeStylesheets();
405
            Display::display_normal_message(get_lang('Saved'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
406
        }
407
        if (isset($_POST['download'])) {
408
            generateCSSDownloadLink($safe_style_dir);
409
        }
410
    }
411
412
    $logoForm = new FormValidator(
413
        'logo_upload',
414
        'post',
415
        'settings.php?category=Stylesheets#tabs-2'
416
    );
417
418
    $logoForm->addHtml(
419
        Display::return_message(sprintf(get_lang('TheLogoMustBeSizeXAndFormatY'), '250 x 70', 'PNG'), 'info')
420
    );
421
422
    $dir = api_get_path(SYS_PUBLIC_PATH).'css/themes/' . $selected . '/images/';
423
    $url = api_get_path(WEB_CSS_PATH).'themes/' . $selected . '/images/';
424
    $logoFileName = 'header-logo.png';
425
    $newLogoFileName = 'header-logo-custom' . api_get_current_access_url_id() . '.png';
426
    $webPlatformLogoPath = ChamiloApi::getWebPlatformLogoPath();
427
428
    if ($webPlatformLogoPath !== null) {
429
        $logoForm->addLabel(
430
            get_lang('CurrentLogo'),
431
            '<img id="header-logo-custom" src="' . $webPlatformLogoPath . '?' . time() . '">'
432
        );
433
    }
434
435
    $logoForm->addFile('new_logo', get_lang('UpdateLogo'));
436
    $allowedFileTypes = ['png'];
437
438
    if (isset($_POST['logo_reset'])) {
439
        if (is_file($dir.$newLogoFileName)) {
440
            unlink($dir.$newLogoFileName);
441
            echo Display::return_message(get_lang('ResetToTheOriginalLogo'));
442
            echo '<script>'
443
                . '$("#header-logo").attr("src","'.$url.$logoFileName.'");'
444
            . '</script>';
445
        }
446
    } elseif (isset($_POST['logo_upload'])) {
447
        $logoForm->addRule('new_logo', get_lang('InvalidExtension').' ('.implode(',', $allowedFileTypes).')', 'filetype', $allowedFileTypes);
448
        $logoForm->addRule('new_logo', get_lang('ThisFieldIsRequired'), 'required');
449
450
        if ($logoForm->validate()) {
451
            $imageInfo = getimagesize($_FILES['new_logo']['tmp_name']);
452
            $width = $imageInfo[0];
453
            $height = $imageInfo[1];
454
            if ($width <= 250 && $height <= 70) {
455
                if (is_file($dir.$newLogoFileName)) {
456
                    unlink($dir.$newLogoFileName);
457
                }
458
459
                $status = move_uploaded_file($_FILES['new_logo']['tmp_name'], $dir.$newLogoFileName);
460
461
                if ($status) {
462
                    echo Display::return_message(get_lang('NewLogoUpdated'));
463
                    echo '<script>'
464
                            . '$("#header-logo").attr("src","'.$url.$newLogoFileName.'");'
465
                        . '</script>';
466
                } else {
467
                    echo Display::return_message('Error - '.get_lang('UplNoFileUploaded'), 'error');
468
                }
469
            } else {
470
                Display::return_message('Error - '.get_lang('InvalidImageDimensions'), 'error');
471
            }
472
        }
473
    }
474
475
    if ($is_style_changeable) {
476
        $group = [
477
            $form_change->addButtonSave(get_lang('SaveSettings'), 'save', true),
478
            $form_change->addButtonPreview(get_lang('Preview'), 'preview', true),
479
            $form_change->addButtonDownload(get_lang('Download'), 'download', true)
480
        ];
481
482
        $form_change->addGroup($group);
483
484
        $logoGroup = [
485
            $logoForm->addButtonUpload(get_lang('Upload'), 'logo_upload', true),
486
            $logoForm->addButtonCancel(get_lang('Reset'), 'logo_reset', true)
487
        ];
488
489
        $logoForm->addGroup($logoGroup);
490
491
        if ($show_upload_form) {
492
            echo '<script>
493
            $(function() {
494
                $( "#tabs" ).tabs();
495
            });
496
            </script>';
497
            echo Display::tabs(
498
                array(get_lang('Update'),get_lang('UpdateLogo'), get_lang('UploadNewStylesheet')),
499
                array($form_change->return_form(), $logoForm->returnForm(), $form->returnForm())
0 ignored issues
show
Deprecated Code introduced by
The method FormValidator::return_form() has been deprecated with message: use returnForm()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
500
            );
501
        } else {
502
            $form_change->display();
503
        }
504
505
        //Little hack to update the logo image in update form when submiting
506
        if (isset($_POST['logo_reset'])) {
507
            echo '<script>'
508
                    . '$("#header-logo-custom").attr("src","'.$url.$logoFileName.'");'
509
                . '</script>';
510
        } elseif (isset($_POST['logo_upload']) && is_file($dir.$newLogoFileName)) {
511
            echo '<script>'
512
                    . '$("#header-logo-custom").attr("src","'.$url.$newLogoFileName.'");'
513
                . '</script>';
514
        }
515
    } else {
516
        $form_change->freeze();
517
    }
518
}
519
520
/**
521
 * Creates the folder (if needed) and uploads the stylesheet in it
522
 * @param array $values the values of the form
523
 * @param array $picture the values of the uploaded file
524
 * @return bool
525
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
526
 * @version May 2008
527
 * @since v1.8.5
528
 */
529
function uploadStylesheet($values, $picture)
530
{
531
    $result = false;
532
    // Valid name for the stylesheet folder.
533
    $style_name = api_preg_replace('/[^A-Za-z0-9]/', '', $values['name_stylesheet']);
534
    $cssToUpload = CSS_UPLOAD_PATH;
535
536
    // Create the folder if needed.
537
538
    if (!is_dir($cssToUpload.$style_name.'/')) {
539
        mkdir($cssToUpload.$style_name.'/', api_get_permissions_for_new_directories());
540
    }
541
542
    $info = pathinfo($picture['name']);
543
544
    if ($info['extension'] == 'zip') {
545
        // Try to open the file and extract it in the theme.
546
        $zip = new ZipArchive();
547
        if ($zip->open($picture['tmp_name'])) {
548
            // Make sure all files inside the zip are images or css.
549
            $num_files = $zip->numFiles;
550
            $valid = true;
551
            $single_directory = true;
552
            $invalid_files = array();
553
554
            $allowedFiles = getAllowedFileTypes();
555
556
            for ($i = 0; $i < $num_files; $i++) {
557
                $file = $zip->statIndex($i);
558
                if (substr($file['name'], -1) != '/') {
559
                    $path_parts = pathinfo($file['name']);
560
                    if (!in_array($path_parts['extension'], $allowedFiles)) {
561
                        $valid = false;
562
                        $invalid_files[] = $file['name'];
563
                    }
564
                }
565
566
                if (strpos($file['name'], '/') === false) {
567
                    $single_directory = false;
568
                }
569
            }
570
            if (!$valid) {
571
                $error_string = '<ul>';
572
                foreach ($invalid_files as $invalid_file) {
573
                    $error_string .= '<li>'.$invalid_file.'</li>';
574
                }
575
                $error_string .= '</ul>';
576
                Display::display_error_message(
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
577
                    get_lang('ErrorStylesheetFilesExtensionsInsideZip').$error_string,
578
                    false
579
                );
580
            } else {
581
                // If the zip does not contain a single directory, extract it.
582
                if (!$single_directory) {
583
                    // Extract zip file.
584
                    $zip->extractTo($cssToUpload.$style_name.'/');
585
                    $result = true;
586
                } else {
587
                    $extraction_path = $cssToUpload.$style_name.'/';
588
                    for ($i = 0; $i < $num_files; $i++) {
589
                        $entry = $zip->getNameIndex($i);
590
                        if (substr($entry, -1) == '/') {
591
                            continue;
592
                        }
593
594
                        $pos_slash = strpos($entry, '/');
595
                        $entry_without_first_dir = substr($entry, $pos_slash + 1);
596
                        // If there is still a slash, we need to make sure the directories are created.
597
                        if (strpos($entry_without_first_dir, '/') !== false) {
598
                            if (!is_dir($extraction_path.dirname($entry_without_first_dir))) {
599
                                // Create it.
600
                                @mkdir($extraction_path.dirname($entry_without_first_dir), $mode = 0777, true);
601
                            }
602
                        }
603
604
                        $fp = $zip->getStream($entry);
605
                        $ofp = fopen($extraction_path.dirname($entry_without_first_dir).'/'.basename($entry), 'w');
606
607
                        while (!feof($fp)) {
608
                            fwrite($ofp, fread($fp, 8192));
609
                        }
610
611
                        fclose($fp);
612
                        fclose($ofp);
613
                    }
614
                    $result = true;
615
                }
616
            }
617
            $zip->close();
618
        } else {
619
            Display::display_error_message(get_lang('ErrorReadingZip').$info['extension'], false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
620
        }
621
    } else {
622
        // Simply move the file.
623
        move_uploaded_file($picture['tmp_name'], $cssToUpload.$style_name.'/'.$picture['name']);
624
        $result = true;
625
    }
626
627
    if ($result) {
628
        $fs = new Filesystem();
629
        $fs->mirror($cssToUpload, api_get_path(SYS_PATH).'web/css/themes/');
630
    }
631
632
    return $result;
633
}
634
635
/**
636
 * Store plugin regions.
637
 */
638
function storeRegions()
639
{
640
    $plugin_obj = new AppPlugin();
641
642
    // Get a list of all current 'Plugins' settings
643
    $installed_plugins = $plugin_obj->get_installed_plugins();
644
645
    $shortlist_installed = array();
646
    if (!empty($installed_plugins)) {
647
        foreach ($installed_plugins as $plugin) {
648
            if (isset($plugin['subkey'])) {
649
                $shortlist_installed[] = $plugin['subkey'];
650
            }
651
        }
652
    }
653
    $shortlist_installed = array_flip(array_flip($shortlist_installed));
654
655
    $plugin_list = $plugin_obj->read_plugins_from_path();
656
657
    foreach ($plugin_list as $plugin) {
658
        if (isset($_POST['plugin_'.$plugin])) {
659
            $areas_to_installed = $_POST['plugin_'.$plugin];
660
            if (!empty($areas_to_installed)) {
661
                $plugin_obj->remove_all_regions($plugin);
662
                foreach ($areas_to_installed as $region) {
663
                    if (!empty($region) && $region != '-1' ) {
664
                        $plugin_obj->add_to_region($plugin, $region);
665
                    }
666
                }
667
            }
668
        }
669
    }
670
}
671
672
/**
673
 * This function allows easy activating and inactivating of plugins
674
 * @author Patrick Cool <[email protected]>, Ghent University
675
 */
676
function storePlugins()
677
{
678
    $appPlugin = new AppPlugin();
679
680
    // Get a list of all current 'Plugins' settings
681
    $plugin_list = $appPlugin->read_plugins_from_path();
682
683
    var_dump($plugin_list);exit;
0 ignored issues
show
Security Debugging Code introduced by
var_dump($plugin_list); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
684
    $installed_plugins = array();
0 ignored issues
show
Unused Code introduced by
$installed_plugins = array(); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
685
686
    foreach ($plugin_list as $plugin) {
687
        if (isset($_POST['plugin_'.$plugin])) {
688
            $appPlugin->install($plugin);
689
            $installed_plugins[] = $plugin;
690
        }
691
    }
692
693
    if (!empty($installed_plugins)) {
694
        $remove_plugins = array_diff($plugin_list, $installed_plugins);
695
    } else {
696
        $remove_plugins = $plugin_list;
697
    }
698
699
    /*foreach ($remove_plugins as $plugin) {
700
        $appPlugin->uninstall($plugin);
701
    }*/
702
}
703
704
/**
705
 * This function allows the platform admin to choose which should be the default stylesheet
706
 * @author Patrick Cool <[email protected]>, Ghent University
707
 */
708
function storeStylesheets()
709
{
710
    // Insert the stylesheet.
711
    if (isStyle($_POST['style'])) {
712
        api_set_setting(
713
            'stylesheets',
714
            $_POST['style'],
715
            null,
716
            'stylesheets',
717
            api_get_current_access_url_id()
718
        );
719
    }
720
    return true;
721
}
722
723
/**
724
 * This function checks if the given style is a recognize style that exists in the css directory as
725
 * a standalone directory.
726
 * @param string    Style
727
 * @return bool     True if this style is recognized, false otherwise
728
 */
729
function isStyle($style)
730
{
731
    $dir = CSS_UPLOAD_PATH;
732
    $dirs = scandir($dir);
733
    $style = str_replace(array('/', '\\'), array('', ''), $style); // Avoid slashes or backslashes.
734
    if (in_array($style, $dirs) && is_dir($dir.$style)) {
735
        return true;
736
    }
737
    return false;
738
}
739
740
/**
741
 * Search options
742
 * TODO: support for multiple site. aka $_configuration['access_url'] == 1
743
 * @author Marco Villegas <[email protected]>
744
 */
745
function handleSearch()
746
{
747
    global $SettingsStored, $_configuration;
748
749
    require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
750
    $search_enabled = api_get_setting('search_enabled');
751
752
    $form = new FormValidator('search-options', 'post', api_get_self().'?category=Search');
753
    $values = api_get_settings_options('search_enabled');
754
    $form->addElement('header', null, get_lang('SearchEnabledTitle'));
755
756
    $group = formGenerateElementsGroup($form, $values, 'search_enabled');
757
758
    //SearchEnabledComment
759
    $form->addGroup($group, 'search_enabled', array(get_lang('SearchEnabledTitle'), get_lang('SearchEnabledComment')), null, false);
760
761
    $search_enabled = api_get_setting('search_enabled');
762
763 View Code Duplication
    if ($form->validate()) {
764
        $formValues = $form->exportValues();
765
        setConfigurationSettingsInDatabase($formValues, $_configuration['access_url']);
766
        $search_enabled = $formValues['search_enabled'];
767
        Display::display_confirmation_message($SettingsStored);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_confirmation_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
768
    }
769
    $specific_fields = get_specific_field_list();
770
771
    if ($search_enabled == 'true') {
772
        $values = api_get_settings_options('search_show_unlinked_results');
773
774
        $group = formGenerateElementsGroup($form, $values, 'search_show_unlinked_results');
775
        $form->addGroup($group, 'search_show_unlinked_results', array(get_lang('SearchShowUnlinkedResultsTitle'),get_lang('SearchShowUnlinkedResultsComment')), null, false);
776
        $default_values['search_show_unlinked_results'] = api_get_setting('search_show_unlinked_results');
777
778
        $sf_values = array();
779
        foreach ($specific_fields as $sf) {
780
            $sf_values[$sf['code']] = $sf['name'];
781
        }
782
        $url =  Display::div(Display::url(get_lang('AddSpecificSearchField'), 'specific_fields.php'), array('class'=>'sectioncomment'));
783
        if (empty($sf_values)) {
784
            $form->addElement('label', [get_lang('SearchPrefilterPrefix'), $url]);
785
        } else {
786
            $form->addElement('select', 'search_prefilter_prefix', array(get_lang('SearchPrefilterPrefix'), $url), $sf_values, '');
787
            $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix');
788
        }
789
    }
790
791
    $default_values['search_enabled'] = $search_enabled;
792
793
    $form->addButtonSave(get_lang('Save'));
794
    $form->setDefaults($default_values);
795
796
    echo '<div id="search-options-form">';
797
    $form->display();
798
    echo '</div>';
799
800
    if ($search_enabled == 'true') {
801
        $xapianPath = api_get_path(SYS_UPLOAD_PATH).'plugins/xapian/searchdb';
802
803
        /*
804
        @todo Test the Xapian connection
805
        if (extension_loaded('xapian')) {
806
            require_once 'xapian.php';
807
            try {
808
                $db = new XapianDatabase($xapianPath.'/');
809
            } catch (Exception $e) {
810
                var_dump($e->getMessage());
811
            }
812
813
            require_once api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php';
814
            require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
815
            require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
816
817
            $indexable = new IndexableChunk();
818
            $indexable->addValue("content", 'Test');
819
820
            $di = new ChamiloIndexer();
821
            $di->connectDb(NULL, NULL, 'english');
822
            $di->addChunk($indexable);
823
            $did = $di->index();
824
        }
825
        */
826
827
        $xapianLoaded = Display::return_icon('bullet_green.png', get_lang('Ok'));
828
        $dir_exists = Display::return_icon('bullet_green.png', get_lang('Ok'));
829
        $dir_is_writable = Display::return_icon('bullet_green.png', get_lang('Ok'));
830
        $specific_fields_exists = Display::return_icon('bullet_green.png', get_lang('Ok'));
831
832
        //Testing specific fields
833
        if (empty($specific_fields)) {
834
            $specific_fields_exists = Display::return_icon('bullet_red.png', get_lang('AddSpecificSearchField'));
835
        }
836
        //Testing xapian extension
837
        if (!extension_loaded('xapian')) {
838
            $xapianLoaded = Display::return_icon('bullet_red.png', get_lang('Error'));
839
        }
840
        //Testing xapian searchdb path
841
        if (!is_dir($xapianPath)) {
842
            $dir_exists = Display::return_icon('bullet_red.png', get_lang('Error'));
843
        }
844
        //Testing xapian searchdb path is writable
845
        if (!is_writable($xapianPath)) {
846
            $dir_is_writable = Display::return_icon('bullet_red.png', get_lang('Error'));
847
        }
848
849
        $data = array();
850
        $data[] = array(get_lang('XapianModuleInstalled'), $xapianLoaded);
851
        $data[] = array(get_lang('DirectoryExists').' - '.$xapianPath, $dir_exists);
852
        $data[] = array(get_lang('IsWritable').' - '.$xapianPath, $dir_is_writable);
853
        $data[] = array(get_lang('SpecificSearchFieldsAvailable'), $specific_fields_exists);
854
855
        showSearchSettingsTable($data);
856
        showSearchToolsStatusTable();
857
    }
858
}
859
860
/**
861
 * Wrapper for the templates
862
 *
863
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
864
 * @author Julio Montoya.
865
 * @version August 2008
866
 * @since v1.8.6
867
 */
868
function handleTemplates()
869
{
870
    /* Drive-by fix to avoid undefined var warnings, without repeating
871
     * isset() combos all over the place. */
872
    $action = isset($_GET['action']) ? $_GET['action'] : "invalid";
873
874
    if ($action != 'add') {
875
        echo '<div class="actions" style="margin-left: 1px;">';
876
        echo '<a href="settings.php?category=Templates&action=add">'.
877
                Display::return_icon('new_template.png', get_lang('AddTemplate'),'',ICON_SIZE_MEDIUM).'</a>';
878
        echo '</div>';
879
    }
880
881
    if ($action == 'add' || ($action == 'edit' && is_numeric($_GET['id']))) {
882
        addEditTemplate();
883
884
        // Add event to the system log.
885
        $user_id = api_get_user_id();
886
        $category = $_GET['category'];
887
        Event::addEvent(
888
            LOG_CONFIGURATION_SETTINGS_CHANGE,
889
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
890
            $category,
891
            api_get_utc_datetime(),
0 ignored issues
show
Bug introduced by
It seems like api_get_utc_datetime() can also be of type object<DateTime>; however, Event::addEvent() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
892
            $user_id
893
        );
894
    } else {
895
        if ($action == 'delete' && is_numeric($_GET['id'])) {
896
            deleteTemplate($_GET['id']);
897
898
            // Add event to the system log
899
            $user_id = api_get_user_id();
900
            $category = $_GET['category'];
901
            Event::addEvent(
902
                LOG_CONFIGURATION_SETTINGS_CHANGE,
903
                LOG_CONFIGURATION_SETTINGS_CATEGORY,
904
                $category,
905
                api_get_utc_datetime(),
0 ignored issues
show
Bug introduced by
It seems like api_get_utc_datetime() can also be of type object<DateTime>; however, Event::addEvent() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
906
                $user_id
907
            );
908
        }
909
        displayTemplates();
910
    }
911
}
912
913
/**
914
 * Display a sortable table with all the templates that the platform administrator has defined.
915
 *
916
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
917
 * @version August 2008
918
 * @since v1.8.6
919
 */
920
function displayTemplates()
921
{
922
    $table = new SortableTable('templates', 'getNumberOfTemplates', 'getTemplateData', 1);
923
    $table->set_additional_parameters(array('category' => Security::remove_XSS($_GET['category'])));
924
    $table->set_header(0, get_lang('Image'), true, array('style' => 'width: 101px;'));
925
    $table->set_header(1, get_lang('Title'));
926
    $table->set_header(2, get_lang('Actions'), false, array('style' => 'width:50px;'));
927
    $table->set_column_filter(2, 'actionsFilter');
928
    $table->set_column_filter(0, 'searchImageFilter');
929
    $table->display();
930
}
931
932
/**
933
 * Gets the number of templates that are defined by the platform admin.
934
 *
935
 * @return integer
936
 *
937
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
938
 * @version August 2008
939
 * @since v1.8.6
940
 */
941 View Code Duplication
function getNumberOfTemplates()
942
{
943
    // Database table definition.
944
    $table_system_template = Database :: get_main_table('system_template');
945
946
    // The sql statement.
947
    $sql = "SELECT COUNT(id) AS total FROM $table_system_template";
948
    $result = Database::query($sql);
949
    $row = Database::fetch_array($result);
950
951
    // Returning the number of templates.
952
    return $row['total'];
953
}
954
955
/**
956
 * Gets all the template data for the sortable table.
957
 *
958
 * @param integer $from the start of the limit statement
959
 * @param integer $number_of_items the number of elements that have to be retrieved from the database
960
 * @param integer $column the column that is
961
 * @param string $direction the sorting direction (ASC or DESC�
962
 * @return array
963
 *
964
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
965
 * @version August 2008
966
 * @since v1.8.6
967
 */
968
function getTemplateData($from, $number_of_items, $column, $direction)
969
{
970
    // Database table definition.
971
    $table_system_template = Database :: get_main_table('system_template');
972
973
    // The sql statement.
974
    $sql = "SELECT image as col0, title as col1, id as col2 FROM $table_system_template";
975
    $sql .= " ORDER BY col$column $direction ";
976
    $sql .= " LIMIT $from,$number_of_items";
977
    $result = Database::query($sql);
978
    $return = array();
979
    while ($row = Database::fetch_array($result)) {
980
        $row['1'] = get_lang($row['1']);
981
        $return[] = $row;
982
    }
983
    // Returning all the information for the sortable table.
984
    return $return;
985
}
986
987
/**
988
 * display the edit and delete icons in the sortable table
989
 *
990
 * @param integer $id the id of the template
991
 * @return string code for the link to edit and delete the template
992
 *
993
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
994
 * @version August 2008
995
 * @since v1.8.6
996
 */
997
function actionsFilter($id) {
998
    $return = '<a href="settings.php?category=Templates&action=edit&id='.Security::remove_XSS($id).'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>';
999
    $return .= '<a href="settings.php?category=Templates&action=delete&id='.Security::remove_XSS($id).'" onClick="javascript:if(!confirm('."'".get_lang('ConfirmYourChoice')."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>';
1000
    return $return;
1001
}
1002
1003
/**
1004
 * Display the image of the template in the sortable table
1005
 *
1006
 * @param string $image the image
1007
 * @return string code for the image
1008
 *
1009
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1010
 * @version August 2008
1011
 * @since v1.8.6
1012
 */
1013
function searchImageFilter($image)
1014
{
1015
    if (!empty($image)) {
1016
        return '<img src="'.api_get_path(WEB_APP_PATH).'home/default_platform_document/template_thumb/'.$image.'" alt="'.get_lang('TemplatePreview').'"/>';
1017
    } else {
1018
        return '<img src="'.api_get_path(WEB_APP_PATH).'home/default_platform_document/template_thumb/noimage.gif" alt="'.get_lang('NoTemplatePreview').'"/>';
1019
    }
1020
}
1021
1022
/**
1023
 * Add (or edit) a template. This function displays the form and also takes
1024
 * care of uploading the image and storing the information in the database
1025
 *
1026
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1027
 * @version August 2008
1028
 * @since v1.8.6
1029
 */
1030
function addEditTemplate()
1031
{
1032
    // Initialize the object.
1033
    $id = isset($_GET['id']) ? '&id='.Security::remove_XSS($_GET['id']) : '';
1034
    $form = new FormValidator('template', 'post', 'settings.php?category=Templates&action='.Security::remove_XSS($_GET['action']).$id);
1035
1036
    // Setting the form elements: the header.
1037
    if ($_GET['action'] == 'add') {
1038
        $title = get_lang('AddTemplate');
1039
    } else {
1040
        $title = get_lang('EditTemplate');
1041
    }
1042
    $form->addElement('header', '', $title);
1043
1044
    // Setting the form elements: the title of the template.
1045
    $form->addText('title', get_lang('Title'), false);
1046
1047
    // Setting the form elements: the content of the template (wysiwyg editor).
1048
    $form->addElement('html_editor', 'template_text', get_lang('Text'), null, array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
1049
1050
    // Setting the form elements: the form to upload an image to be used with the template.
1051
    $form->addElement('file','template_image',get_lang('Image'),'');
1052
1053
    // Setting the form elements: a little bit information about the template image.
1054
    $form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
1055
1056
    // Getting all the information of the template when editing a template.
1057
    if ($_GET['action'] == 'edit') {
1058
        // Database table definition.
1059
        $table_system_template = Database :: get_main_table('system_template');
1060
        $sql = "SELECT * FROM $table_system_template WHERE id = ".intval($_GET['id'])."";
1061
        $result = Database::query($sql);
1062
        $row = Database::fetch_array($result);
1063
1064
        $defaults['template_id']    = intval($_GET['id']);
1065
        $defaults['template_text']  = $row['content'];
1066
        // Forcing get_lang().
1067
        $defaults['title']          = get_lang($row['title']);
1068
1069
        // Adding an extra field: a hidden field with the id of the template we are editing.
1070
        $form->addElement('hidden', 'template_id');
1071
1072
        // Adding an extra field: a preview of the image that is currently used.
1073
        if (!empty($row['image'])) {
1074
            $form->addElement('static', 'template_image_preview', '',
1075
                '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/' . $row['image'] . '" alt="' . get_lang('TemplatePreview') . '"/>');
1076
        } else {
1077
            $form->addElement('static', 'template_image_preview', '',
1078
                '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/noimage.gif" alt="' . get_lang('NoTemplatePreview') . '"/>');
1079
        }
1080
1081
        // Setting the information of the template that we are editing.
1082
        $form->setDefaults($defaults);
1083
    }
1084
    // Setting the form elements: the submit button.
1085
    $form->addButtonSave(get_lang('Ok'), 'submit');
1086
1087
    // Setting the rules: the required fields.
1088
    $form->addRule('template_image', get_lang('ThisFieldIsRequired'), 'required');
1089
    $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
1090
    $form->addRule('template_text', get_lang('ThisFieldIsRequired'), 'required');
1091
1092
    // if the form validates (complies to all rules) we save the information, else we display the form again (with error message if needed)
1093
    if ($form->validate()) {
1094
1095
        $check = Security::check_token('post');
1096
        if ($check) {
1097
            // Exporting the values.
1098
            $values = $form->exportValues();
1099
            // Upload the file.
1100
            if (!empty($_FILES['template_image']['name'])) {
1101
                $upload_ok = process_uploaded_file($_FILES['template_image']);
1102
1103
                if ($upload_ok) {
1104
                    // Try to add an extension to the file if it hasn't one.
1105
                    $new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']), $_FILES['template_image']['type']);
1106
1107
                    // The upload directory.
1108
                    $upload_dir = api_get_path(SYS_APP_PATH).'home/default_platform_document/template_thumb/';
1109
1110
                    // Create the directory if it does not exist.
1111
                    if (!is_dir($upload_dir)) {
1112
                        mkdir($upload_dir, api_get_permissions_for_new_directories());
1113
                    }
1114
1115
                    // Resize the preview image to max default and upload.
1116
                    $temp = new Image($_FILES['template_image']['tmp_name']);
1117
                    $picture_info = $temp->get_image_info();
1118
1119
                    $max_width_for_picture = 100;
1120
1121
                    if ($picture_info['width'] > $max_width_for_picture) {
1122
                        $temp->resize($max_width_for_picture);
1123
                    }
1124
                    $temp->send_image($upload_dir.$new_file_name);
1125
                }
1126
            }
1127
1128
            // Store the information in the database (as insert or as update).
1129
            $table_system_template = Database :: get_main_table('system_template');
1130
            if ($_GET['action'] == 'add') {
1131
                $content_template =  Security::remove_XSS($values['template_text'], COURSEMANAGERLOWSECURITY);
1132
                $params = [
1133
                    'title' =>  $values['title'],
1134
                    'content' => $content_template,
1135
                    'image' => $new_file_name
1136
                ];
1137
                Database::insert($table_system_template, $params);
1138
1139
                // Display a feedback message.
1140
                Display::display_confirmation_message(get_lang('TemplateAdded'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_confirmation_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1141
                echo '<a href="settings.php?category=Templates&action=add">'.Display::return_icon('new_template.png', get_lang('AddTemplate'),'',ICON_SIZE_MEDIUM).'</a>';
1142
            } else {
1143
                $content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>'.Database::escape_string($values['template_text']).'</body>';
1144
                $sql = "UPDATE $table_system_template set title = '".Database::escape_string($values['title'])."', content = '".$content_template."'";
1145
                if (!empty($new_file_name)) {
1146
                    $sql .= ", image = '".Database::escape_string($new_file_name)."'";
1147
                }
1148
                $sql .= " WHERE id = ".intval($_GET['id'])."";
1149
                Database::query($sql);
1150
1151
                // Display a feedback message.
1152
                Display::display_confirmation_message(get_lang('TemplateEdited'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_confirmation_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1153
            }
1154
        }
1155
        Security::clear_token();
1156
        displayTemplates();
1157
    } else {
1158
        $token = Security::get_token();
1159
        $form->addElement('hidden','sec_token');
1160
        $form->setConstants(array('sec_token' => $token));
1161
        // Display the form.
1162
        $form->display();
1163
    }
1164
}
1165
1166
/**
1167
 * Delete a template
1168
 *
1169
 * @param integer $id the id of the template that has to be deleted
1170
 *
1171
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1172
 * @version August 2008
1173
 * @since v1.8.6
1174
 */
1175
function deleteTemplate($id)
1176
{
1177
    // First we remove the image.
1178
    $table_system_template = Database :: get_main_table('system_template');
1179
    $sql = "SELECT * FROM $table_system_template WHERE id = ".intval($id)."";
1180
    $result = Database::query($sql);
1181
    $row = Database::fetch_array($result);
1182
    if (!empty($row['image'])) {
1183
        @unlink(api_get_path(SYS_APP_PATH).'home/default_platform_document/template_thumb/'.$row['image']);
1184
    }
1185
1186
    // Now we remove it from the database.
1187
    $sql = "DELETE FROM $table_system_template WHERE id = ".intval($id)."";
1188
    Database::query($sql);
1189
1190
    // Display a feedback message.
1191
    Display::display_confirmation_message(get_lang('TemplateDeleted'));
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_confirmation_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1192
}
1193
1194
/**
1195
 * Returns the list of timezone identifiers used to populate the select
1196
 * This function is called through a call_user_func() in the generate_settings_form function.
1197
 * @return array List of timezone identifiers
1198
 *
1199
 * @author Guillaume Viguier <[email protected]>
1200
 * @since Chamilo 1.8.7
1201
 */
1202
function select_timezone_value()
1203
{
1204
    return api_get_timezones();
1205
}
1206
1207
/**
1208
 * Returns an array containing the list of options used to populate the gradebook_number_decimals variable
1209
 * This function is called through a call_user_func() in the generate_settings_form function.
1210
 * @return array List of gradebook_number_decimals options
1211
 *
1212
 * @author Guillaume Viguier <[email protected]>
1213
 */
1214
function select_gradebook_number_decimals() {
1215
    return array('0', '1', '2');
1216
}
1217
1218
/**
1219
 * Get the options for a select element to select gradebook default grade model
1220
 * @return array
1221
 */
1222
function select_gradebook_default_grade_model_id()
1223
{
1224
    $grade_model = new GradeModel();
1225
    $models = $grade_model->get_all();
1226
    $options = array();
1227
    $options[-1] = get_lang('None');
1228
1229
    if (!empty($models)) {
1230
        foreach ($models as $model) {
1231
            $options[$model['id']] = $model['name'];
1232
        }
1233
    }
1234
1235
    return $options;
1236
}
1237
1238
/**
1239
 * @param array $settings
1240
 * @param array $settings_by_access_list
1241
 *
1242
 * @return FormValidator
1243
 *
1244
 * @throws \Doctrine\ORM\ORMException
1245
 * @throws \Doctrine\ORM\OptimisticLockException
1246
 * @throws \Doctrine\ORM\TransactionRequiredException
1247
 */
1248
function generateSettingsForm($settings, $settings_by_access_list)
1249
{
1250
    return;
1251
    global $_configuration, $settings_to_avoid, $convert_byte_to_mega_list;
0 ignored issues
show
Unused Code introduced by
global $_configuration, ...vert_byte_to_mega_list; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1252
    $multipleAccessUrl = api_get_configuration_value('multiple_access_urls');
1253
    $em = Database::getManager();
1254
    $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1255
1256
    $form = new FormValidator('settings', 'post', 'settings.php?category='.Security::remove_XSS($_GET['category']));
1257
1258
    $form->addElement(
1259
        'hidden',
1260
        'search_field',
1261
        (!empty($_GET['search_field']) ? Security::remove_XSS($_GET['search_field']) : null)
1262
    );
1263
1264
    $url_id = api_get_current_access_url_id();
1265
    /*
1266
    if (!empty($_configuration['multiple_access_urls']) && api_is_global_platform_admin() && $url_id == 1) {
1267
        $group = array();
1268
        $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll'));
1269
        $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll'));
1270
        $form->addGroup($group, 'buttons_in_action_right');
1271
    }*/
1272
1273
    $default_values = array();
1274
    $url_info = api_get_access_url($url_id);
1275
    $i = 0;
1276
    $addedSettings = [];
1277
    foreach ($settings as $row) {
1278
1279
        if (!empty($row['variable']) &&
1280
            in_array($row['variable'], array_keys($settings_to_avoid))
1281
        ) {
1282
            continue;
1283
        }
1284
1285
        if (!empty($row['variable']) &&
1286
            in_array($row['variable'], $addedSettings)
1287
        ) {
1288
            continue;
1289
        }
1290
1291
        $addedSettings[] = $row['variable'];
1292
1293
        if (!empty($multipleAccessUrl)) {
1294
            if (api_is_global_platform_admin()) {
1295
                if ($row['access_url_locked'] == 0) {
1296
                    if ($url_id == 1) {
1297
                        if ($row['access_url_changeable'] == '1') {
1298
                            $form->addElement(
1299
                                'html',
1300
                                '<div class="pull-right"><a class="share_this_setting" data_status = "0"  data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
1301
                                Display::return_icon('shared_setting.png', get_lang('ChangeSharedSetting') , null, ICON_SIZE_MEDIUM).'</a></div>'
1302
                            );
1303
                        } else {
1304
                            $form->addElement(
1305
                                'html',
1306
                                '<div class="pull-right"><a class="share_this_setting" data_status = "1" data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
1307
                                Display::return_icon('shared_setting_na.png', get_lang('ChangeSharedSetting'), null, ICON_SIZE_MEDIUM ).'</a></div>'
1308
                            );
1309
                        }
1310
                    } else {
1311
                        if ($row['access_url_changeable'] == '1') {
1312
                            $form->addElement(
1313
                                'html',
1314
                                '<div class="pull-right">'.
1315
                                Display::return_icon('shared_setting.png', get_lang('ChangeSharedSetting'), null, ICON_SIZE_MEDIUM ).'</div>'
1316
                            );
1317
                        } else {
1318
                            $form->addElement(
1319
                                'html',
1320
                                '<div class="pull-right">'.
1321
                                Display::return_icon('shared_setting_na.png', get_lang('ChangeSharedSetting'), null, ICON_SIZE_MEDIUM ).'</div>'
1322
                            );
1323
                        }
1324
                    }
1325
                }
1326
            }
1327
        }
1328
1329
        $hideme = array();
1330
        $hide_element = false;
1331
1332
        if ($_configuration['access_url'] != 1) {
1333
            if ($row['access_url_changeable'] == 0) {
1334
                // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element.
1335
                $hide_element = true;
1336
                $hideme = array('disabled');
1337
            } elseif ($url_info['active'] == 1) {
1338
                // We show the elements.
1339
                if (empty($row['variable'])) {
1340
                    $row['variable'] = 0;
1341
                }
1342
                if (empty($row['subkey'])) {
1343
                    $row['subkey'] = 0;
1344
                }
1345
                if (empty($row['category'])) {
1346
                    $row['category'] = 0;
1347
                }
1348
                if (isset($settings_by_access_list[$row['variable']]) &&
1349
                    is_array($settings_by_access_list[$row['variable']][$row['subkey']][$row['category']])) {
1350
                    // We are sure that the other site have a selected value.
1351
                    if ($settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value'] != '') {
1352
                        $row['selected_value'] = $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value'];
1353
                    }
1354
                }
1355
                // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
1356
            }
1357
        }
1358
1359
        switch ($row['type']) {
1360
            case 'textfield':
1361
                if (in_array($row['variable'], $convert_byte_to_mega_list)) {
1362
                    $form->addElement(
1363
                        'text',
1364
                        $row['variable'],
1365
                        array(
1366
                            get_lang($row['title']),
1367
                            get_lang($row['comment']),
1368
                            get_lang('MB')
1369
                        ),
1370
                        array('maxlength' => '8')
1371
                    );
1372
                    $form->applyFilter($row['variable'], 'html_filter');
1373
                    $default_values[$row['variable']] = round($row['selected_value']/1024/1024, 1);
1374
                } elseif ($row['variable'] == 'account_valid_duration') {
1375
                    $form->addElement(
1376
                        'text',
1377
                        $row['variable'],
1378
                        array(
1379
                            get_lang($row['title']),
1380
                            get_lang($row['comment']),
1381
                        ),
1382
                        array('maxlength' => '5')
1383
                    );
1384
                    $form->applyFilter($row['variable'], 'html_filter');
1385
                    $default_values[$row['variable']] = $row['selected_value'];
1386
1387
                    // For platform character set selection: Conversion of the textfield to a select box with valid values.
1388
                } elseif ($row['variable'] == 'platform_charset') {
1389
                    continue;
1390
                } else {
1391
                    $hideme['class'] = 'col-md-4';
1392
                    $form->addElement(
1393
                        'text',
1394
                        $row['variable'],
1395
                        array(
1396
                            get_lang($row['title']),
1397
                            get_lang($row['comment'])
1398
                        ),
1399
                        $hideme
1400
                    );
1401
                    $form->applyFilter($row['variable'],'html_filter');
1402
                    $default_values[$row['variable']] = $row['selected_value'];
1403
                }
1404
                break;
1405
            case 'textarea':
1406
                if ($row['variable'] == 'header_extra_content') {
1407
                    $file = api_get_path(SYS_PATH).api_get_home_path().'header_extra_content.txt';
1408
                    $value = '';
1409
                    if (file_exists($file)) {
1410
                        $value = file_get_contents($file);
1411
                    }
1412
                    $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
1413
                    $default_values[$row['variable']] = $value;
1414
                } elseif ($row['variable'] == 'footer_extra_content') {
1415
                    $file = api_get_path(SYS_PATH).api_get_home_path().'footer_extra_content.txt';
1416
                    $value = '';
1417
                    if (file_exists($file)) {
1418
                        $value = file_get_contents($file);
1419
                    }
1420
                    $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
1421
                    $default_values[$row['variable']] = $value;
1422
                } else {
1423
                    $form->addElement('textarea', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])) , array('rows'=>'10'), $hideme);
1424
                    $default_values[$row['variable']] = $row['selected_value'];
1425
                }
1426
                break;
1427
            case 'radio':
1428
                $values = api_get_settings_options($row['variable']);
1429
                $group = array ();
1430 View Code Duplication
                if (is_array($values)) {
1431
                    foreach ($values as $key => $value) {
1432
                        $element = &$form->createElement(
1433
                            'radio',
1434
                            $row['variable'],
1435
                            '',
1436
                            get_lang($value['display_text']),
1437
                            $value['value']
1438
                        );
1439
                        if ($hide_element) {
1440
                            $element->freeze();
1441
                        }
1442
                        $group[] = $element;
1443
                    }
1444
                }
1445
                $form->addGroup(
1446
                    $group,
1447
                    $row['variable'],
1448
                    array(get_lang($row['title']), get_lang($row['comment'])),
1449
                    null,
1450
                    false
1451
                );
1452
                $default_values[$row['variable']] = $row['selected_value'];
1453
                break;
1454
            case 'checkbox':
1455
                // 1. We collect all the options of this variable.
1456
                $sql = "SELECT * FROM $table_settings_current
1457
                        WHERE variable='".$row['variable']."' AND access_url =  1";
1458
1459
                $result = Database::query($sql);
1460
                $group = array ();
1461
                while ($rowkeys = Database::fetch_array($result)) {
1462
                    // Profile tab option should be hidden when the social tool is enabled.
1463
                    if (api_get_setting('allow_social_tool') == 'true') {
1464
                        if ($rowkeys['variable'] === 'show_tabs' && $rowkeys['subkey'] === 'my_profile') {
1465
                            continue;
1466
                        }
1467
                    }
1468
1469
                    // Hiding the gradebook option.
1470
                    if ($rowkeys['variable'] === 'show_tabs' && $rowkeys['subkey'] === 'my_gradebook') {
1471
                        continue;
1472
                    }
1473
1474
                    $element = &$form->createElement(
1475
                        'checkbox',
1476
                        $rowkeys['subkey'],
1477
                        '',
1478
                        get_lang($rowkeys['subkeytext'])
1479
                    );
1480
1481
                    if ($row['access_url_changeable'] == 1) {
1482
                        // 2. We look into the DB if there is a setting for a specific access_url.
1483
                        $access_url = $_configuration['access_url'];
1484
                        if (empty($access_url)) {
1485
                            $access_url = 1;
1486
                        }
1487
                        $sql = "SELECT selected_value FROM $table_settings_current
1488
                                WHERE
1489
                                    variable='".$rowkeys['variable']."' AND
1490
                                    subkey='".$rowkeys['subkey']."' AND
1491
                                    subkeytext='".$rowkeys['subkeytext']."' AND
1492
                                    access_url =  $access_url";
1493
                        $result_access = Database::query($sql);
1494
                        $row_access = Database::fetch_array($result_access);
1495
                        if ($row_access['selected_value'] === 'true' && !$form->isSubmitted()) {
1496
                            $element->setChecked(true);
1497
                        }
1498
                    } else {
1499
                        if ($rowkeys['selected_value'] === 'true' && !$form->isSubmitted()) {
1500
                            $element->setChecked(true);
1501
                        }
1502
                    }
1503
                    if ($hide_element) {
1504
                        $element->freeze();
1505
                    }
1506
                    $group[] = $element;
1507
                }
1508
                $form->addGroup(
1509
                    $group,
1510
                    $row['variable'],
1511
                    array(get_lang($row['title']), get_lang($row['comment'])),
1512
                    null
1513
                );
1514
                break;
1515
            case 'link':
1516
                $form->addElement('static', null, array(get_lang($row['title']), get_lang($row['comment'])),
1517
                    get_lang('CurrentValue') . ' : ' . $row['selected_value'], $hideme);
1518
                break;
1519
            case 'select':
1520
                /*
1521
                * 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.
1522
                * The functions being called must be added to the file settings.lib.php.
1523
                */
1524
                $form->addElement(
1525
                    'select',
1526
                    $row['variable'],
1527
                    array(get_lang($row['title']), get_lang($row['comment'])),
1528
                    call_user_func('select_'.$row['variable']),
1529
                    $hideme
1530
                );
1531
                $default_values[$row['variable']] = $row['selected_value'];
1532
                break;
1533
            case 'custom':
1534
                break;
1535
            case 'select_course':
1536
                $courseSelectOptions = [];
1537
1538
                if (!empty($row['selected_value'])) {
1539
                    $course = $em->find('ChamiloCoreBundle:Course', $row['selected_value']);
1540
1541
                    $courseSelectOptions[$course->getId()] = $course->getTitle();
1542
                }
1543
1544
                $form->addElement(
1545
                    'select_ajax',
1546
                    $row['variable'],
1547
                    [get_lang($row['title']), get_lang($row['comment'])],
1548
                    $courseSelectOptions,
1549
                    ['url' => api_get_path(WEB_AJAX_PATH) . 'course.ajax.php?a=search_course']
1550
                );
1551
                $default_values[$row['variable']] = $row['selected_value'];
1552
                break;
1553
        }
1554
1555
        switch ($row['variable']) {
1556
            case 'pdf_export_watermark_enable':
1557
                $url =  PDF::get_watermark(null);
1558
1559
                if ($url != false) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $url of type string|false against false; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
1560
                    $delete_url = '<a href="?delete_watermark">'.get_lang('DelImage').' '.Display::return_icon('delete.png',get_lang('DelImage')).'</a>';
1561
                    $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>');
1562
                }
1563
1564
                $form->addElement('file', 'pdf_export_watermark_path', get_lang('AddWaterMark'));
1565
                $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
1566
                $form->addRule('pdf_export_watermark_path', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
1567
1568
                break;
1569
            case 'timezone_value':
1570
                $timezone = $row['selected_value'];
1571
                if (empty($timezone)) {
1572
                    $timezone = api_get_timezone();
1573
                }
1574
                $form->addLabel('', sprintf(get_lang('LocalTimeUsingPortalTimezoneXIsY'), $timezone, api_get_local_time()));
1575
                break;
1576
        }
1577
    } // end for
1578
1579
    if (!empty($settings)) {
1580
        $form->setDefaults($default_values);
1581
    }
1582
    $form->addHtml('<div class="bottom_actions">');
1583
    $form->addButtonSave(get_lang('SaveSettings'));
1584
    $form->addHtml('</div>');
1585
    return $form;
1586
}
1587
1588
/**
1589
 * Searches a platform setting in all categories except from the Plugins category
1590
 * @param string $search
1591
 * @return array
1592
 */
1593
function searchSetting($search)
1594
{
1595
    if (empty($search)) {
1596
        return array();
1597
    }
1598
    $table_settings_current = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1599
    $sql = "SELECT * FROM $table_settings_current
1600
            WHERE category <> 'Plugins' ORDER BY id ASC ";
1601
    $result = Database::store_result(Database::query($sql), 'ASSOC');
0 ignored issues
show
Bug introduced by
It seems like \Database::query($sql) can be null; however, store_result() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1602
    $settings = array();
1603
1604
    $search = api_strtolower($search);
1605
1606
    if (!empty($result)) {
1607
        foreach ($result as $setting) {
1608
            $found = false;
1609
1610
            $title = api_strtolower(get_lang($setting['title']));
1611
            // try the title
1612
            if (strpos($title, $search) === false) {
1613
                $comment = api_strtolower(get_lang($setting['comment']));
1614
                //Try the comment
1615
                if (strpos($comment, $search) === false) {
1616
                    //Try the variable name
1617
                    if (strpos($setting['variable'], $search) === false) {
1618
                        continue;
1619
                    } else {
1620
                        $found = true;
1621
                    }
1622
                } else {
1623
                    $found = true;
1624
                }
1625
1626
            } else {
1627
                $found = true;
1628
            }
1629
            if ($found) {
1630
                $settings[] = $setting;
1631
            }
1632
        }
1633
    }
1634
    return $settings;
1635
}
1636
/**
1637
 * Helper function to generates a form elements group
1638
 * @param object $form The form where the elements group has to be added
1639
 * @param array $values Values to browse through
1640
 * @return array
1641
 */
1642
function formGenerateElementsGroup($form, $values = array(), $elementName)
1643
{
1644
    $group = array();
1645 View Code Duplication
    if (is_array($values)) {
1646
        foreach ($values as $key => $value) {
1647
            $element = &$form->createElement('radio', $elementName, '', get_lang($value['display_text']), $value['value']);
1648
            $group[] = $element;
1649
        }
1650
    }
1651
    return $group;
1652
}
1653
/**
1654
 * Helper function with allowed file types for CSS
1655
 * @return  array Array of file types (no indexes)
1656
 */
1657
function getAllowedFileTypes()
1658
{
1659
    $allowedFiles = array(
1660
        'css',
1661
        'zip',
1662
        'jpeg',
1663
        'jpg',
1664
        'png',
1665
        'gif',
1666
        'ico',
1667
        'psd',
1668
        'xcf',
1669
        'svg',
1670
        'webp',
1671
        'woff',
1672
        'woff2'
1673
    );
1674
    return $allowedFiles;
1675
}
1676
/**
1677
 * Helper function to set settings in the database
1678
 * @param   array   $parameters     List of values
1679
 * @param   int     $accessUrl      The current access URL
1680
 * @return  void
1681
 */
1682
function setConfigurationSettingsInDatabase($parameters, $accessUrl)
1683
{
1684
    $r = api_set_settings_category('Search', 'false', $accessUrl);
1685
    // Save the settings.
1686
    foreach ($parameters as $key => $value) {
1687
        $result = api_set_setting($key, $value, null, null);
1688
    }
1689
}
1690
1691
/**
1692
 * Helper function to show the status of the search settings table
1693
 * @param   array   $data   Data to show
1694
 * @return void
1695
 */
1696
function showSearchSettingsTable($data)
1697
{
1698
    echo Display::tag('h3', get_lang('Settings'));
1699
    $table = new SortableTableFromArray($data);
1700
    $table->set_header(0, get_lang('Setting'), false);
1701
    $table->set_header(1, get_lang('Status'), false);
1702
    echo $table->display();
1703
}
1704
/**
1705
 * Helper function to show status table for each command line tool installed
1706
 * @return void
1707
 */
1708
function showSearchToolsStatusTable()
1709
{
1710
    //@todo windows support
1711
    if (api_is_windows_os() == false) {
1712
        $list_of_programs = array('pdftotext', 'ps2pdf', 'catdoc', 'html2text', 'unrtf', 'catppt', 'xls2csv');
1713
1714
        foreach($list_of_programs as $program) {
1715
            $output = [];
1716
            $ret_val = null;
1717
            exec("which $program", $output, $ret_val);
1718
1719
            if (!$output) {
1720
                $output[] = '';
1721
            }
1722
1723
            $icon = Display::return_icon('bullet_red.png', get_lang('NotInstalled'));
1724
            if (!empty($output[0])) {
1725
                $icon = Display::return_icon('bullet_green.png', get_lang('Installed'));
1726
            }
1727
            $data2[]= array($program, $output[0], $icon);
1728
        }
1729
        echo Display::tag('h3', get_lang('ProgramsNeededToConvertFiles'));
1730
        $table = new SortableTableFromArray($data2);
1731
        $table->set_header(0, get_lang('Program'), false);
1732
        $table->set_header(1, get_lang('Path'), false);
1733
        $table->set_header(2, get_lang('Status'), false);
1734
        echo $table->display();
1735
    } else {
1736
        Display::display_warning_message(
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_warning_message() has been deprecated with message: use Display::addFlash with Display::return_message

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1737
            get_lang('YouAreUsingChamiloInAWindowsPlatformSadlyYouCantConvertDocumentsInOrderToSearchTheContentUsingThisTool')
1738
        );
1739
    }
1740
}
1741
/**
1742
 * Helper function to generate and show CSS Zip download message
1743
 * @param   string $style Style path
1744
 * @return void
1745
 */
1746
function generateCSSDownloadLink($style)
1747
{
1748
    $arch = api_get_path(SYS_ARCHIVE_PATH).$style.'.zip';
1749
    $dir = api_get_path(SYS_CSS_PATH).'themes/'.$style;
1750
    if (is_dir($dir)) {
1751
        $zip = new PclZip($arch);
1752
        // Remove path prefix except the style name and put file on disk
1753
        $zip->create($dir, PCLZIP_OPT_REMOVE_PATH, substr($dir,0,-strlen($style)));
1754
        //@TODO: use more generic script to download.
1755
        $str = '<a class="btn btn-primary btn-large" href="' . api_get_path(WEB_CODE_PATH) . 'course_info/download.php?archive=' . str_replace(api_get_path(SYS_ARCHIVE_PATH), '', $arch) . '">'.get_lang('ClickHereToDownloadTheFile').'</a>';
1756
        Display::display_normal_message($str, false);
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_normal_message() has been deprecated with message: use Display::addFlash with Display::return_message($message, 'normal');

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1757
    } else {
1758
        Display::addFlash(Display::return_message(get_lang('FileNotFound'), 'warning'));
1759
    }
1760
}
1761
/**
1762
 * Helper function to tell if the style is changeable in the current URL
1763
 * @return bool $changeable Whether the style can be changed in this URL or not
1764
 */
1765
function isStyleChangeable() {
1766
    global $_configuration;
1767
    $changeable = false;
1768
    if ($_configuration['access_url'] != 1) {
1769
        $style_info = api_get_settings('stylesheets', '', 1, 0);
1770
        $url_info = api_get_access_url($_configuration['access_url']);
1771
        if ($style_info[0]['access_url_changeable'] == 1 && $url_info['active'] == 1) {
1772
            $changeable = true;
1773
        }
1774
    } else {
1775
        $changeable = true;
1776
    }
1777
    return $changeable;
1778
}