Completed
Push — 1.10.x ( 90a383...61feb9 )
by Angel Fernando Quiroz
39:29
created

settings.lib.php ➔ handle_regions()   D

Complexity

Conditions 13
Paths 168

Size

Total Lines 84
Code Lines 60

Duplication

Lines 14
Ratio 16.67 %

Importance

Changes 0
Metric Value
cc 13
eloc 60
nc 168
nop 0
dl 14
loc 84
rs 4.6605
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
/**
5
 * Library of the settings.php file
6
 *
7
 * @author Julio Montoya <[email protected]>
8
 * @author Guillaume Viguier <[email protected]>
9
 *
10
 * @since Chamilo 1.8.7
11
 * @package chamilo.admin
12
 */
13
14
define('CSS_UPLOAD_PATH', api_get_path(SYS_APP_PATH) . 'Resources/public/css/themes/');
15
16
use Symfony\Component\Filesystem\Filesystem;
17
18
/**
19
 * This function allows easy activating and inactivating of regions
20
 * @author Julio Montoya <[email protected]> Beeznest 2012
21
 */
22
function handle_regions()
23
{
24 View Code Duplication
    if (isset($_POST['submit_plugins'])) {
25
        store_regions();
26
        // Add event to the system log.
27
        $user_id = api_get_user_id();
28
        $category = $_GET['category'];
29
        Event::addEvent(
30
            LOG_CONFIGURATION_SETTINGS_CHANGE,
31
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
32
            $category,
33
            api_get_utc_datetime(),
34
            $user_id
35
        );
36
        Display:: display_confirmation_message(get_lang('SettingsStored'));
37
    }
38
39
    $plugin_obj = new AppPlugin();
40
    $possible_plugins = $plugin_obj->read_plugins_from_path();
41
    $installed_plugins = $plugin_obj->get_installed_plugins();
42
43
    echo '<form name="plugins" method="post" action="' . api_get_self() . '?category=' . Security::remove_XSS($_GET['category']) . '">';
44
    echo '<table class="data_table">';
45
    echo '<tr>';
46
    echo '<th width="400px">';
47
    echo get_lang('Plugin');
48
    echo '</th><th>';
49
    echo get_lang('Regions');
50
    echo '</th>';
51
    echo '</th>';
52
    echo '</tr>';
53
54
    /* We display all the possible plugins and the checkboxes */
55
56
    $plugin_region_list = array();
57
    $my_plugin_list = $plugin_obj->get_plugin_regions();
58
    foreach ($my_plugin_list as $plugin_item) {
59
        $plugin_region_list[$plugin_item] = $plugin_item;
60
    }
61
62
    // Removing course tool
63
    unset($plugin_region_list['course_tool_plugin']);
64
65
    foreach ($installed_plugins as $plugin) {
66
        $plugin_info_file = api_get_path(SYS_PLUGIN_PATH) . $plugin . '/plugin.php';
67
68
        if (file_exists($plugin_info_file)) {
69
            $plugin_info = array();
70
            require $plugin_info_file;
71
            if (isset($_GET['name']) && $_GET['name'] == $plugin) {
72
                echo '<tr class="row_selected">';
73
            } else {
74
                echo '<tr>';
75
            }
76
            echo '<td>';
77
            echo '<h4>' . $plugin_info['title'] . ' <small>v' . $plugin_info['version'] . '</small></h4>';
78
            echo '<p>' . $plugin_info['comment'] . '</p>';
79
            echo '</td><td>';
80
            $selected_plugins = $plugin_obj->get_areas_by_plugin($plugin);
81
82
            $region_list = [];
83
84
            $isAdminPlugin = isset($plugin_info['is_admin_plugin']) && $plugin_info['is_admin_plugin'];
85
            $isCoursePlugin = isset($plugin_info['is_course_plugin']) && $plugin_info['is_course_plugin'];
86
87
            if (!$isAdminPlugin && !$isCoursePlugin) {
88
                $region_list = $plugin_region_list;
89
            } else {
90
                if ($isAdminPlugin) {
91
                    $region_list['menu_administrator'] = 'menu_administrator';
92
                }
93
                if ($isCoursePlugin) {
94
                    $region_list['course_tool_plugin'] = 'course_tool_plugin';
95
                }
96
            }
97
            echo Display::select('plugin_' . $plugin . '[]', $region_list, $selected_plugins,
98
                array('multiple' => 'multiple', 'style' => 'width:500px'), true, get_lang('None'));
99
            echo '</td></tr>';
100
        }
101
    }
102
    echo '</table>';
103
    echo '<br />';
104
    echo '<button class="btn btn-success" type="submit" name="submit_plugins">' . get_lang('EnablePlugins') . '</button></form>';
105
}
106
107
function handle_extensions()
108
{
109
    echo Display::page_subheader(get_lang('ConfigureExtensions'));
110
    echo '<a class="btn btn-success" href="configure_extensions.php?display=ppt2lp" role="button">' . get_lang('Ppt2lp') . '</a>';
111
112
}
113
114
/**
115
 * This function allows easy activating and inactivating of plugins
116
 * @todo: a similar function needs to be written to activate or inactivate additional tools.
117
 * @author Patrick Cool <[email protected]>, Ghent University
118
 * @author Julio Montoya <[email protected]> Beeznest 2012
119
 */
120
function handle_plugins()
121
{
122
    $plugin_obj = new AppPlugin();
123
    $token = Security::get_token();
124 View Code Duplication
    if (isset($_POST['submit_plugins'])) {
125
        store_plugins();
126
        // Add event to the system log.
127
        $user_id = api_get_user_id();
128
        $category = $_GET['category'];
129
        Event::addEvent(
130
            LOG_CONFIGURATION_SETTINGS_CHANGE,
131
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
132
            $category,
133
            api_get_utc_datetime(),
134
            $user_id
135
        );
136
        Display:: display_confirmation_message(get_lang('SettingsStored'));
137
    }
138
139
    $all_plugins = $plugin_obj->read_plugins_from_path();
140
    $installed_plugins = $plugin_obj->get_installed_plugins();
141
142
    //Plugins NOT installed
143
    echo Display::page_subheader(get_lang('Plugins'));
144
    echo '<form class="form-horizontal" name="plugins" method="post" action="' . api_get_self() . '?category=' . Security::remove_XSS($_GET['category']) . '&sec_token=' . $token . '">';
145
    echo '<table class="data_table">';
146
    echo '<tr>';
147
    echo '<th width="20px">';
148
    echo get_lang('Action');
149
    echo '</th><th>';
150
    echo get_lang('Description');
151
    echo '</th>';
152
    echo '</tr>';
153
154
    $plugin_list = array();
155
    $my_plugin_list = $plugin_obj->get_plugin_regions();
156
    foreach ($my_plugin_list as $plugin_item) {
157
        $plugin_list[$plugin_item] = $plugin_item;
158
    }
159
160
    foreach ($all_plugins as $plugin) {
161
        $plugin_info_file = api_get_path(SYS_PLUGIN_PATH) . $plugin . '/plugin.php';
162
163
        if (file_exists($plugin_info_file)) {
164
            $plugin_info = array();
165
            require $plugin_info_file;
166
167
            if (in_array($plugin, $installed_plugins)) {
168
                echo '<tr class="row_selected">';
169
            } else {
170
                echo '<tr>';
171
            }
172
            echo '<td>';
173
            //Checkbox
174
            if (in_array($plugin, $installed_plugins)) {
175
                echo '<input type="checkbox" name="plugin_' . $plugin . '[]" checked="checked">';
176
177
            } else {
178
                echo '<input type="checkbox" name="plugin_' . $plugin . '[]">';
179
            }
180
            echo '</td><td>';
181
182
            echo '<h4>' . $plugin_info['title'] . ' <small>v ' . $plugin_info['version'] . '</small></h4>';
183
            echo '<p>' . $plugin_info['comment'] . '</p>';
184
            echo '<p>' . get_lang('Author') . ': ' . $plugin_info['author'] . '</p>';
185
186
            echo '<div class="btn-group">';
187
            if (in_array($plugin, $installed_plugins)) {
188
                echo Display::url('<em class="fa fa-cogs"></em> ' . get_lang('Configure'),
189
                    'configure_plugin.php?name=' . $plugin, array('class' => 'btn btn-default'));
190
                echo Display::url('<em class="fa fa-th-large"></em> ' . get_lang('Regions'),
191
                    'settings.php?category=Regions&name=' . $plugin, array('class' => 'btn btn-default'));
192
            }
193
194
            if (file_exists(api_get_path(SYS_PLUGIN_PATH) . $plugin . '/readme.txt')) {
195
                echo Display::url(
196
                    "<em class='fa fa-file-text-o'></em> readme.txt",
197
                    api_get_path(WEB_PLUGIN_PATH) . $plugin . "/readme.txt",
198
                    [
199
                        'class' => 'btn btn-default ajax',
200
                        'data-title' => $plugin_info['title'],
201
                        'data-size' => 'lg',
202
                        '_target' => '_blank'
203
                    ]
204
                );
205
            }
206
            echo '</div>';
207
            echo '</td></tr>';
208
        }
209
    }
210
    echo '</table>';
211
212
    echo '<div class="form-actions bottom_actions">';
213
    echo '<button class="btn btn-success" type="submit" name="submit_plugins">' .
214
        get_lang('EnablePlugins') . '</button>';
215
    echo '</div>';
216
    echo '</form>';
217
}
218
219
/**
220
 * This function allows the platform admin to choose the default stylesheet
221
 * @author Patrick Cool <[email protected]>, Ghent University
222
 * @author Julio Montoya <[email protected]>, Chamilo
223
 */
224
function handle_stylesheets()
225
{
226
    global $_configuration;
227
228
    // Current style.
229
    $currentstyle = api_get_setting('stylesheets');
230
231
    $is_style_changeable = false;
232
233
    if ($_configuration['access_url'] != 1) {
234
        $style_info = api_get_settings('stylesheets', '', 1, 0);
235
        $url_info = api_get_access_url($_configuration['access_url']);
236
        if ($style_info[0]['access_url_changeable'] == 1 && $url_info['active'] == 1) {
237
            $is_style_changeable = true;
238
        }
239
    } else {
240
        $is_style_changeable = true;
241
    }
242
243
    $form = new FormValidator(
244
        'stylesheet_upload',
245
        'post',
246
        'settings.php?category=Stylesheets#tabs-3'
247
    );
248
    $form->addElement('text', 'name_stylesheet', get_lang('NameStylesheet'),
249
        array('size' => '40', 'maxlength' => '40'));
250
    $form->addRule('name_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
251
    $form->addElement('file', 'new_stylesheet', get_lang('UploadNewStylesheet'));
252
    $allowed_file_types = array(
253
        'css',
254
        'zip',
255
        'jpeg',
256
        'jpg',
257
        'png',
258
        'gif',
259
        'ico',
260
        'psd',
261
        'xcf',
262
        'svg',
263
        'webp',
264
        'woff',
265
        'woff2'
266
    );
267
268
    $form->addRule('new_stylesheet', get_lang('InvalidExtension') . ' (' . implode(',', $allowed_file_types) . ')',
269
        'filetype', $allowed_file_types);
270
    $form->addRule('new_stylesheet', get_lang('ThisFieldIsRequired'), 'required');
271
    $form->addButtonUpload(get_lang('Upload'), 'stylesheet_upload');
272
273
    $show_upload_form = false;
274
275
    if (!is_writable(CSS_UPLOAD_PATH)) {
276
        Display::display_error_message(CSS_UPLOAD_PATH . get_lang('IsNotWritable'));
277
    } else {
278
        // Uploading a new stylesheet.
279
        if ($_configuration['access_url'] == 1) {
280
            $show_upload_form = true;
281
        } else {
282
            if ($is_style_changeable) {
283
                $show_upload_form = true;
284
            }
285
        }
286
    }
287
288
    // Stylesheet upload.
289
290
    if (isset($_POST['stylesheet_upload'])) {
291
        if ($form->validate()) {
292
            $values = $form->exportValues();
293
            $picture_element = $form->getElement('new_stylesheet');
294
            $picture = $picture_element->getValue();
295
            $result = upload_stylesheet($values, $picture);
296
297
            // Add event to the system log.
298
            $user_id = api_get_user_id();
299
            $category = $_GET['category'];
300
            Event::addEvent(
301
                LOG_CONFIGURATION_SETTINGS_CHANGE,
302
                LOG_CONFIGURATION_SETTINGS_CATEGORY,
303
                $category,
304
                api_get_utc_datetime(),
305
                $user_id
306
            );
307
308
            if ($result) {
309
                Display::display_confirmation_message(get_lang('StylesheetAdded'));
310
            }
311
        }
312
    }
313
314
    $form_change = new FormValidator(
315
        'stylesheet_upload',
316
        'post',
317
        api_get_self() . '?category=Stylesheets',
318
        null,
319
        array('id' => 'stylesheets_id')
320
    );
321
322
    $list_of_names = array();
323
    $selected = '';
324
    $dirpath = '';
325
    $safe_style_dir = '';
326
327
    if ($handle = @opendir(CSS_UPLOAD_PATH)) {
328
        $counter = 1;
329
        while (false !== ($style_dir = readdir($handle))) {
330
            if (substr($style_dir, 0, 1) == '.') {
331
                // Skip directories starting with a '.'
332
                continue;
333
            }
334
            $dirpath = CSS_UPLOAD_PATH . $style_dir;
335
336
            if (is_dir($dirpath)) {
337
                if ($style_dir != '.' && $style_dir != '..') {
338
                    if (isset($_POST['style']) &&
339
                        (isset($_POST['preview']) || isset($_POST['download'])) &&
340
                        $_POST['style'] == $style_dir
341
                    ) {
342
                        $safe_style_dir = $style_dir;
343
                    } else {
344
                        if ($currentstyle == $style_dir || ($style_dir == 'chamilo' && !$currentstyle)) {
345
                            if (isset($_POST['style'])) {
346
                                $selected = Database::escape_string($_POST['style']);
347
                            } else {
348
                                $selected = $style_dir;
349
                            }
350
                        }
351
                    }
352
                    $show_name = ucwords(str_replace('_', ' ', $style_dir));
353
354
                    if ($is_style_changeable) {
355
                        $list_of_names[$style_dir] = $show_name;
356
                    }
357
                    $counter++;
358
                }
359
            }
360
        }
361
        closedir($handle);
362
    }
363
364
    // Sort styles in alphabetical order.
365
    asort($list_of_names);
366
    $select_list = array();
367
    foreach ($list_of_names as $style_dir => $item) {
368
        $select_list[$style_dir] = $item;
369
    }
370
371
    $styles = &$form_change->addElement('select', 'style', get_lang('NameStylesheet'), $select_list);
372
    $styles->setSelected($selected);
373
374
    if ($form_change->validate()) {
375
        // Submit stylesheets.
376
        if (isset($_POST['save'])) {
377
            store_stylesheets();
378
            Display::display_normal_message(get_lang('Saved'));
379
        }
380
        if (isset($_POST['download'])) {
381
            $arch = api_get_path(SYS_ARCHIVE_PATH) . $safe_style_dir . '.zip';
382
            $dir = api_get_path(SYS_CSS_PATH) . 'themes/' . $safe_style_dir;
383
            if (is_dir($dir)) {
384
                $zip = new PclZip($arch);
385
                // Remove path prefix except the style name and put file on disk
386
                $zip->create($dir, PCLZIP_OPT_REMOVE_PATH, substr($dir, 0, -strlen($safe_style_dir)));
387
                //@TODO: use more generic script to download.
388
                $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),
389
                        '', $arch) . '">' . get_lang('ClickHereToDownloadTheFile') . '</a>';
390
                Display::display_normal_message($str, false);
391
            } else {
392
                Display::addFlash(Display::return_message(get_lang('FileNotFound'), 'warning'));
393
            }
394
        }
395
    }
396
397
    $logoForm = new FormValidator(
398
        'logo_upload',
399
        'post',
400
        'settings.php?category=Stylesheets#tabs-2'
401
    );
402
403
    $logoForm->addHtml(Display::return_message(sprintf(get_lang('TheLogoMustBeSizeXAndFormatY'), '250 x 70', 'PNG'),
404
        'info'));
405
406
    $dir = api_get_path(SYS_PUBLIC_PATH) . 'css/themes/' . $selected . '/images/';
407
    $url = api_get_path(WEB_CSS_PATH) . 'themes/' . $selected . '/images/';
408
    $logoFileName = 'header-logo.png';
409
    $newLogoFileName = 'header-logo-custom.png';
410
411
    if (is_file($dir . $newLogoFileName)) {
412
        $logoForm->addLabel(get_lang('CurrentLogo'),
413
            '<img id="header-logo-custom" src="' . $url . $newLogoFileName . '?' . time() . '">');
414
    } else {
415
        $logoForm->addLabel(get_lang('CurrentLogo'),
416
            '<img id="header-logo-custom" src="' . $url . $logoFileName . '?' . time() . '">');
417
    }
418
419
    $logoForm->addFile('new_logo', get_lang('UpdateLogo'));
420
    $allowedFileTypes = ['png'];
421
422
    if (isset($_POST['logo_reset'])) {
423
        if (is_file($dir . $newLogoFileName)) {
424
            unlink($dir . $newLogoFileName);
425
            Display::display_normal_message(get_lang('ResetToTheOriginalLogo'));
426
            echo '<script>'
427
                . '$("#header-logo").attr("src","' . $url . $logoFileName . '");'
428
                . '</script>';
429
        }
430
    } elseif (isset($_POST['logo_upload'])) {
431
432
        $logoForm->addRule('new_logo', get_lang('InvalidExtension') . ' (' . implode(',', $allowedFileTypes) . ')',
433
            'filetype', $allowedFileTypes);
434
        $logoForm->addRule('new_logo', get_lang('ThisFieldIsRequired'), 'required');
435
436
        if ($logoForm->validate()) {
437
438
            $imageInfo = getimagesize($_FILES['new_logo']['tmp_name']);
439
            $width = $imageInfo[0];
440
            $height = $imageInfo[1];
441
            if ($width <= 250 && $height <= 70) {
442
                if (is_file($dir . $newLogoFileName)) {
443
                    unlink($dir . $newLogoFileName);
444
                }
445
446
                $status = move_uploaded_file($_FILES['new_logo']['tmp_name'], $dir . $newLogoFileName);
447
448
                if ($status) {
449
                    Display::display_normal_message(get_lang('NewLogoUpdated'));
450
                    echo '<script>'
451
                        . '$("#header-logo").attr("src","' . $url . $newLogoFileName . '");'
452
                        . '</script>';
453
                } else {
454
                    Display::display_error_message('Error - ' . get_lang('UplNoFileUploaded'));
455
                }
456
            } else {
457
                Display::display_error_message('Error - ' . get_lang('InvalidImageDimensions'));
458
            }
459
        }
460
    }
461
462
    if ($is_style_changeable) {
463
        $group = [
464
            $form_change->addButtonSave(get_lang('SaveSettings'), 'save', true),
465
            $form_change->addButtonPreview(get_lang('Preview'), 'preview', true),
466
            $form_change->addButtonDownload(get_lang('Download'), 'download', true)
467
        ];
468
469
        $form_change->addGroup($group);
470
471
        $logoGroup = [
472
            $logoForm->addButtonUpload(get_lang('Upload'), 'logo_upload', true),
473
            $logoForm->addButtonCancel(get_lang('Reset'), 'logo_reset', true)
474
        ];
475
476
        $logoForm->addGroup($logoGroup);
477
478
        if ($show_upload_form) {
479
            echo '<script>
480
            $(function() {
481
                $( "#tabs" ).tabs();
482
            });
483
            </script>';
484
            echo Display::tabs(
485
                array(get_lang('Update'), get_lang('UpdateLogo'), get_lang('UploadNewStylesheet')),
486
                array($form_change->return_form(), $logoForm->return_form(), $form->return_form())
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...
487
            );
488
        } else {
489
            $form_change->display();
490
        }
491
492
        //Little hack to update the logo image in update form when submiting
493
        if (isset($_POST['logo_reset'])) {
494
            echo '<script>'
495
                . '$("#header-logo-custom").attr("src","' . $url . $logoFileName . '");'
496
                . '</script>';
497
        } elseif (isset($_POST['logo_upload']) && is_file($dir . $newLogoFileName)) {
498
            echo '<script>'
499
                . '$("#header-logo-custom").attr("src","' . $url . $newLogoFileName . '");'
500
                . '</script>';
501
        }
502
    } else {
503
        $form_change->freeze();
504
    }
505
}
506
507
/**
508
 * Creates the folder (if needed) and uploads the stylesheet in it
509
 *
510
 * @param array $values the values of the form
511
 * @param array $picture the values of the uploaded file
512
 *
513
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
514
 * @version May 2008
515
 * @since Dokeos 1.8.5
516
 */
517
function upload_stylesheet($values, $picture)
518
{
519
    $result = false;
520
    // Valid name for the stylesheet folder.
521
    $style_name = api_preg_replace('/[^A-Za-z0-9]/', '', $values['name_stylesheet']);
522
    $cssToUpload = CSS_UPLOAD_PATH;
523
524
    // Create the folder if needed.
525
526
    if (!is_dir($cssToUpload . $style_name . '/')) {
527
        mkdir($cssToUpload . $style_name . '/', api_get_permissions_for_new_directories());
528
    }
529
530
    $info = pathinfo($picture['name']);
531
532
    if ($info['extension'] == 'zip') {
533
        // Try to open the file and extract it in the theme.
534
        $zip = new ZipArchive();
535
        if ($zip->open($picture['tmp_name'])) {
536
            // Make sure all files inside the zip are images or css.
537
            $num_files = $zip->numFiles;
538
            $valid = true;
539
            $single_directory = true;
540
            $invalid_files = array();
541
542
            $allowedFiles = array(
543
                'jpg',
544
                'jpeg',
545
                'png',
546
                'gif',
547
                'css',
548
                'ico',
549
                'psd',
550
                'woff',
551
                'woff2',
552
                'xcf',
553
                'svg',
554
                'webp'
555
            );
556
557
            for ($i = 0; $i < $num_files; $i++) {
558
                $file = $zip->statIndex($i);
559
                if (substr($file['name'], -1) != '/') {
560
                    $path_parts = pathinfo($file['name']);
561
                    if (!in_array($path_parts['extension'], $allowedFiles)) {
562
                        $valid = false;
563
                        $invalid_files[] = $file['name'];
564
                    }
565
                }
566
567
                if (strpos($file['name'], '/') === false) {
568
                    $single_directory = false;
569
                }
570
            }
571
            if (!$valid) {
572
                $error_string = '<ul>';
573
                foreach ($invalid_files as $invalid_file) {
574
                    $error_string .= '<li>' . $invalid_file . '</li>';
575
                }
576
                $error_string .= '</ul>';
577
                Display::display_error_message(
578
                    get_lang('ErrorStylesheetFilesExtensionsInsideZip') . $error_string,
579
                    false
580
                );
581
            } else {
582
                // If the zip does not contain a single directory, extract it.
583
                if (!$single_directory) {
584
                    // Extract zip file.
585
                    $zip->extractTo($cssToUpload . $style_name . '/');
586
                    $result = true;
587
                } else {
588
                    $extraction_path = $cssToUpload . $style_name . '/';
589
                    for ($i = 0; $i < $num_files; $i++) {
590
                        $entry = $zip->getNameIndex($i);
591
                        if (substr($entry, -1) == '/') {
592
                            continue;
593
                        }
594
595
                        $pos_slash = strpos($entry, '/');
596
                        $entry_without_first_dir = substr($entry, $pos_slash + 1);
597
                        // If there is still a slash, we need to make sure the directories are created.
598
                        if (strpos($entry_without_first_dir, '/') !== false) {
599
                            if (!is_dir($extraction_path . dirname($entry_without_first_dir))) {
600
                                // Create it.
601
                                @mkdir($extraction_path . dirname($entry_without_first_dir), $mode = 0777, true);
602
                            }
603
                        }
604
605
                        $fp = $zip->getStream($entry);
606
                        $ofp = fopen($extraction_path . dirname($entry_without_first_dir) . '/' . basename($entry),
607
                            'w');
608
609
                        while (!feof($fp)) {
610
                            fwrite($ofp, fread($fp, 8192));
611
                        }
612
613
                        fclose($fp);
614
                        fclose($ofp);
615
                    }
616
                    $result = true;
617
                }
618
            }
619
            $zip->close();
620
        } else {
621
            Display::display_error_message(get_lang('ErrorReadingZip') . $info['extension'], false);
622
        }
623
    } else {
624
        // Simply move the file.
625
        move_uploaded_file($picture['tmp_name'], $cssToUpload . $style_name . '/' . $picture['name']);
626
        $result = true;
627
    }
628
629
    if ($result) {
630
        $fs = new Filesystem();
631
        $fs->mirror($cssToUpload, api_get_path(SYS_PATH) . 'web/css/themes/');
632
    }
633
634
    return $result;
635
}
636
637
/**
638
 * Store plugin regions.
639
 */
640
function store_regions()
641
{
642
    $plugin_obj = new AppPlugin();
643
644
    // Get a list of all current 'Plugins' settings
645
    $installed_plugins = $plugin_obj->get_installed_plugins();
646
647
    $shortlist_installed = array();
648
    if (!empty($installed_plugins)) {
649
        foreach ($installed_plugins as $plugin) {
650
            if (isset($plugin['subkey'])) {
651
                $shortlist_installed[] = $plugin['subkey'];
652
            }
653
        }
654
    }
655
    $shortlist_installed = array_flip(array_flip($shortlist_installed));
656
657
    $plugin_list = $plugin_obj->read_plugins_from_path();
658
659
    foreach ($plugin_list as $plugin) {
660
        if (isset($_POST['plugin_' . $plugin])) {
661
            $areas_to_installed = $_POST['plugin_' . $plugin];
662
            if (!empty($areas_to_installed)) {
663
                $plugin_obj->remove_all_regions($plugin);
664
                foreach ($areas_to_installed as $region) {
665
                    if (!empty($region) && $region != '-1') {
666
                        $plugin_obj->add_to_region($plugin, $region);
667
                    }
668
                }
669
            }
670
        }
671
    }
672
}
673
674
/**
675
 * This function allows easy activating and inactivating of plugins
676
 * @author Patrick Cool <[email protected]>, Ghent University
677
 */
678
function store_plugins()
679
{
680
    $appPlugin = new AppPlugin();
681
682
    // Get a list of all current 'Plugins' settings
683
    $plugin_list = $appPlugin->read_plugins_from_path();
684
685
    $installed_plugins = array();
686
687
    foreach ($plugin_list as $plugin) {
688
        if (isset($_POST['plugin_' . $plugin])) {
689
            $appPlugin->install($plugin);
690
            $installed_plugins[] = $plugin;
691
        }
692
    }
693
694
    if (!empty($installed_plugins)) {
695
        $remove_plugins = array_diff($plugin_list, $installed_plugins);
696
    } else {
697
        $remove_plugins = $plugin_list;
698
    }
699
700
    foreach ($remove_plugins as $plugin) {
701
        $appPlugin->uninstall($plugin);
702
    }
703
}
704
705
/**
706
 * This function allows the platform admin to choose which should be the default stylesheet
707
 * @author Patrick Cool <[email protected]>, Ghent University
708
 */
709
function store_stylesheets()
710
{
711
    // Insert the stylesheet.
712
    if (is_style($_POST['style'])) {
713
        api_set_setting(
714
            'stylesheets',
715
            $_POST['style'],
716
            null,
717
            'stylesheets',
718
            api_get_current_access_url_id()
719
        );
720
    }
721
    return true;
722
}
723
724
/**
725
 * This function checks if the given style is a recognize style that exists in the css directory as
726
 * a standalone directory.
727
 * @param string    Style
728
 * @return bool     True if this style is recognized, false otherwise
729
 */
730
function is_style($style)
731
{
732
    $dir = CSS_UPLOAD_PATH;
733
    $dirs = scandir($dir);
734
    $style = str_replace(array('/', '\\'), array('', ''), $style); // Avoid slashes or backslashes.
735
    if (in_array($style, $dirs) && is_dir($dir . $style)) {
736
        return true;
737
    }
738
    return false;
739
}
740
741
/**
742
 * Search options
743
 * TODO: support for multiple site. aka $_configuration['access_url'] == 1
744
 * @author Marco Villegas <[email protected]>
745
 */
746
function handle_search()
747
{
748
    global $SettingsStored, $_configuration;
749
750
    require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
751
    $search_enabled = api_get_setting('search_enabled');
752
753
    $form = new FormValidator('search-options', 'post', api_get_self() . '?category=Search');
754
    $values = api_get_settings_options('search_enabled');
755
    $form->addElement('header', null, get_lang('SearchEnabledTitle'));
756
757
    $group = array();
758
    if (is_array($values)) {
759 View Code Duplication
        foreach ($values as $key => $value) {
760
            $element = &$form->createElement('radio', 'search_enabled', '', get_lang($value['display_text']),
761
                $value['value']);
762
            $group[] = $element;
763
        }
764
    }
765
    //SearchEnabledComment
766
    $form->addGroup($group, 'search_enabled', array(get_lang('SearchEnabledTitle'), get_lang('SearchEnabledComment')),
767
        '<br />', false);
768
769
    $search_enabled = api_get_setting('search_enabled');
770
771
    if ($form->validate()) {
772
        $formvalues = $form->exportValues();
773
        $r = api_set_settings_category('Search', 'false', $_configuration['access_url']);
774
        // Save the settings.
775
        foreach ($formvalues as $key => $value) {
776
            $result = api_set_setting($key, $value, null, null);
777
        }
778
        $search_enabled = $formvalues['search_enabled'];
779
        Display::display_confirmation_message($SettingsStored);
780
    }
781
    $specific_fields = get_specific_field_list();
782
783
    if ($search_enabled == 'true') {
784
        $values = api_get_settings_options('search_show_unlinked_results');
785
        $group = array();
786 View Code Duplication
        foreach ($values as $key => $value) {
787
            $element = &$form->createElement('radio', 'search_show_unlinked_results', '',
788
                get_lang($value['display_text']), $value['value']);
789
            $group[] = $element;
790
        }
791
        $form->addGroup($group, 'search_show_unlinked_results',
792
            array(get_lang('SearchShowUnlinkedResultsTitle'), get_lang('SearchShowUnlinkedResultsComment')), '', false);
793
        $default_values['search_show_unlinked_results'] = api_get_setting('search_show_unlinked_results');
794
795
        $sf_values = array();
796
        foreach ($specific_fields as $sf) {
797
            $sf_values[$sf['code']] = $sf['name'];
798
        }
799
        $group = array();
800
        $url = Display::div(Display::url(get_lang('AddSpecificSearchField'), 'specific_fields.php'),
801
            array('class' => 'sectioncomment'));
802
        if (empty($sf_values)) {
803
            $form->addElement('label', [get_lang('SearchPrefilterPrefix'), $url]);
804
        } else {
805
            $form->addElement('select', 'search_prefilter_prefix', array(get_lang('SearchPrefilterPrefix'), $url),
806
                $sf_values, '');
807
            $default_values['search_prefilter_prefix'] = api_get_setting('search_prefilter_prefix');
808
        }
809
    }
810
811
    $default_values['search_enabled'] = $search_enabled;
812
813
    $form->addButtonSave(get_lang('Save'));
814
    $form->setDefaults($default_values);
815
816
    echo '<div id="search-options-form">';
817
    $form->display();
818
    echo '</div>';
819
820
    if ($search_enabled == 'true') {
821
        $xapian_path = api_get_path(SYS_UPLOAD_PATH) . 'plugins/xapian/searchdb';
822
823
        /*
824
        @todo Test the Xapian connection
825
        if (extension_loaded('xapian')) {
826
            require_once 'xapian.php';
827
            try {
828
                $db = new XapianDatabase($xapian_path.'/');
829
            } catch (Exception $e) {
830
                var_dump($e->getMessage());
831
            }
832
833
            require_once api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php';
834
            require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
835
            require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
836
837
            $indexable = new IndexableChunk();
838
            $indexable->addValue("content", 'Test');
839
840
            $di = new DokeosIndexer();
841
            $di->connectDb(NULL, NULL, 'english');
842
            $di->addChunk($indexable);
843
            $did = $di->index();
844
        }
845
        */
846
847
        $xapian_loaded = Display::return_icon('bullet_green.png', get_lang('Ok'));
848
        $dir_exists = Display::return_icon('bullet_green.png', get_lang('Ok'));
849
        $dir_is_writable = Display::return_icon('bullet_green.png', get_lang('Ok'));
850
        $specific_fields_exists = Display::return_icon('bullet_green.png', get_lang('Ok'));
851
852
        //Testing specific fields
853
        if (empty($specific_fields)) {
854
            $specific_fields_exists = Display::return_icon('bullet_red.png', get_lang('AddSpecificSearchField'));
855
        }
856
        //Testing xapian extension
857
        if (!extension_loaded('xapian')) {
858
            $xapian_loaded = Display::return_icon('bullet_red.png', get_lang('Error'));
859
        }
860
        //Testing xapian searchdb path
861
        if (!is_dir($xapian_path)) {
862
            $dir_exists = Display::return_icon('bullet_red.png', get_lang('Error'));
863
        }
864
        //Testing xapian searchdb path is writable
865
        if (!is_writable($xapian_path)) {
866
            $dir_is_writable = Display::return_icon('bullet_red.png', get_lang('Error'));
867
        }
868
869
        $data[] = array(get_lang('XapianModuleInstalled'), $xapian_loaded);
870
        $data[] = array(get_lang('DirectoryExists') . ' - ' . $xapian_path, $dir_exists);
871
        $data[] = array(get_lang('IsWritable') . ' - ' . $xapian_path, $dir_is_writable);
872
        $data[] = array(get_lang('SpecificSearchFieldsAvailable'), $specific_fields_exists);
873
874
        echo Display::tag('h3', get_lang('Settings'));
875
        $table = new SortableTableFromArray($data);
876
        $table->set_header(0, get_lang('Setting'), false);
877
        $table->set_header(1, get_lang('Status'), false);
878
        echo $table->display();
879
880
        //@todo windows support
881
        if (api_is_windows_os() == false) {
882
            $list_of_programs = array('pdftotext', 'ps2pdf', 'catdoc', 'html2text', 'unrtf', 'catppt', 'xls2csv');
883
884
            foreach ($list_of_programs as $program) {
885
                $output = [];
886
                $ret_val = null;
887
                exec("which $program", $output, $ret_val);
888
889
                if (!$output) {
890
                    $output[] = '';
891
                }
892
893
                $icon = Display::return_icon('bullet_red.png', get_lang('NotInstalled'));
894
                if (!empty($output[0])) {
895
                    $icon = Display::return_icon('bullet_green.png', get_lang('Installed'));
896
                }
897
                $data2[] = array($program, $output[0], $icon);
898
            }
899
            echo Display::tag('h3', get_lang('ProgramsNeededToConvertFiles'));
900
            $table = new SortableTableFromArray($data2);
901
            $table->set_header(0, get_lang('Program'), false);
902
            $table->set_header(1, get_lang('Path'), false);
903
            $table->set_header(2, get_lang('Status'), false);
904
            echo $table->display();
905
        } else {
906
            Display::display_warning_message(
907
                get_lang('YouAreUsingChamiloInAWindowsPlatformSadlyYouCantConvertDocumentsInOrderToSearchTheContentUsingThisTool')
908
            );
909
        }
910
    }
911
}
912
913
/**
914
 * Wrapper for the templates
915
 *
916
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
917
 * @author Julio Montoya.
918
 * @version August 2008
919
 * @since Dokeos 1.8.6
920
 */
921
function handle_templates()
922
{
923
    /* Drive-by fix to avoid undefined var warnings, without repeating
924
     * isset() combos all over the place. */
925
    $action = isset($_GET['action']) ? $_GET['action'] : "invalid";
926
927
    if ($action != 'add') {
928
        echo '<div class="actions" style="margin-left: 1px;">';
929
        echo '<a href="settings.php?category=Templates&action=add">' .
930
            Display::return_icon('new_template.png', get_lang('AddTemplate'), '', ICON_SIZE_MEDIUM) . '</a>';
931
        echo '</div>';
932
    }
933
934
    if ($action == 'add' || ($action == 'edit' && is_numeric($_GET['id']))) {
935
        add_edit_template();
936
937
        // Add event to the system log.
938
        $user_id = api_get_user_id();
939
        $category = $_GET['category'];
940
        Event::addEvent(
941
            LOG_CONFIGURATION_SETTINGS_CHANGE,
942
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
943
            $category,
944
            api_get_utc_datetime(),
945
            $user_id
946
        );
947
    } else {
948
        if ($action == 'delete' && is_numeric($_GET['id'])) {
949
            delete_template($_GET['id']);
950
951
            // Add event to the system log
952
            $user_id = api_get_user_id();
953
            $category = $_GET['category'];
954
            Event::addEvent(
955
                LOG_CONFIGURATION_SETTINGS_CHANGE,
956
                LOG_CONFIGURATION_SETTINGS_CATEGORY,
957
                $category,
958
                api_get_utc_datetime(),
959
                $user_id
960
            );
961
        }
962
        display_templates();
963
    }
964
}
965
966
/**
967
 * Display a sortable table with all the templates that the platform administrator has defined.
968
 *
969
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
970
 * @version August 2008
971
 * @since Dokeos 1.8.6
972
 */
973
function display_templates()
974
{
975
    $table = new SortableTable('templates', 'get_number_of_templates', 'get_template_data', 1);
976
    $table->set_additional_parameters(array('category' => Security::remove_XSS($_GET['category'])));
977
    $table->set_header(0, get_lang('Image'), true, array('style' => 'width: 101px;'));
978
    $table->set_header(1, get_lang('Title'));
979
    $table->set_header(2, get_lang('Actions'), false, array('style' => 'width:50px;'));
980
    $table->set_column_filter(2, 'actions_filter');
981
    $table->set_column_filter(0, 'image_filter');
982
    $table->display();
983
}
984
985
/**
986
 * Gets the number of templates that are defined by the platform admin.
987
 *
988
 * @return integer
989
 *
990
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
991
 * @version August 2008
992
 * @since Dokeos 1.8.6
993
 */
994
function get_number_of_templates()
995
{
996
    // Database table definition.
997
    $table_system_template = Database:: get_main_table('system_template');
998
999
    // The sql statement.
1000
    $sql = "SELECT COUNT(id) AS total FROM $table_system_template";
1001
    $result = Database::query($sql);
1002
    $row = Database::fetch_array($result);
1003
1004
    // Returning the number of templates.
1005
    return $row['total'];
1006
}
1007
1008
/**
1009
 * Gets all the template data for the sortable table.
1010
 *
1011
 * @param integer $from the start of the limit statement
1012
 * @param integer $number_of_items the number of elements that have to be retrieved from the database
1013
 * @param integer $column the column that is
1014
 * @param string $direction the sorting direction (ASC or DESC�
1015
 * @return array
1016
 *
1017
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1018
 * @version August 2008
1019
 * @since Dokeos 1.8.6
1020
 */
1021
function get_template_data($from, $number_of_items, $column, $direction)
1022
{
1023
    // Database table definition.
1024
    $table_system_template = Database:: get_main_table('system_template');
1025
1026
    // The sql statement.
1027
    $sql = "SELECT image as col0, title as col1, id as col2 FROM $table_system_template";
1028
    $sql .= " ORDER BY col$column $direction ";
1029
    $sql .= " LIMIT $from,$number_of_items";
1030
    $result = Database::query($sql);
1031
    $return = array();
1032
    while ($row = Database::fetch_array($result)) {
1033
        $row['1'] = get_lang($row['1']);
1034
        $return[] = $row;
1035
    }
1036
    // Returning all the information for the sortable table.
1037
    return $return;
1038
}
1039
1040
/**
1041
 * display the edit and delete icons in the sortable table
1042
 *
1043
 * @param integer $id the id of the template
1044
 * @return string code for the link to edit and delete the template
1045
 *
1046
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1047
 * @version August 2008
1048
 * @since Dokeos 1.8.6
1049
 */
1050
function actions_filter($id)
1051
{
1052
    $return = '<a href="settings.php?category=Templates&action=edit&id=' . Security::remove_XSS($id) . '">' . Display::return_icon('edit.png',
1053
            get_lang('Edit'), '', ICON_SIZE_SMALL) . '</a>';
1054
    $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',
1055
            get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
1056
    return $return;
1057
}
1058
1059
/**
1060
 * Display the image of the template in the sortable table
1061
 *
1062
 * @param string $image the image
1063
 * @return string code for the image
1064
 *
1065
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1066
 * @version August 2008
1067
 * @since Dokeos 1.8.6
1068
 */
1069
function image_filter($image)
1070
{
1071
    if (!empty($image)) {
1072
        return '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/' . $image . '" alt="' . get_lang('TemplatePreview') . '"/>';
1073
    } else {
1074
        return '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/noimage.gif" alt="' . get_lang('NoTemplatePreview') . '"/>';
1075
    }
1076
}
1077
1078
/**
1079
 * Add (or edit) a template. This function displays the form and also takes
1080
 * care of uploading the image and storing the information in the database
1081
 *
1082
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1083
 * @version August 2008
1084
 * @since Dokeos 1.8.6
1085
 */
1086
function add_edit_template()
1087
{
1088
    // Initialize the object.
1089
    $id = isset($_GET['id']) ? '&id=' . Security::remove_XSS($_GET['id']) : '';
1090
    $form = new FormValidator('template', 'post',
1091
        'settings.php?category=Templates&action=' . Security::remove_XSS($_GET['action']) . $id);
1092
1093
    // Setting the form elements: the header.
1094
    if ($_GET['action'] == 'add') {
1095
        $title = get_lang('AddTemplate');
1096
    } else {
1097
        $title = get_lang('EditTemplate');
1098
    }
1099
    $form->addElement('header', '', $title);
1100
1101
    // Setting the form elements: the title of the template.
1102
    $form->addText('title', get_lang('Title'), false);
1103
1104
    // Setting the form elements: the content of the template (wysiwyg editor).
1105
    $form->addElement('html_editor', 'template_text', get_lang('Text'), null,
1106
        array('ToolbarSet' => 'AdminTemplates', 'Width' => '100%', 'Height' => '400'));
1107
1108
    // Setting the form elements: the form to upload an image to be used with the template.
1109
    $form->addElement('file', 'template_image', get_lang('Image'), '');
1110
1111
    // Setting the form elements: a little bit information about the template image.
1112
    $form->addElement('static', 'file_comment', '', get_lang('TemplateImageComment100x70'));
1113
1114
    // Getting all the information of the template when editing a template.
1115
    if ($_GET['action'] == 'edit') {
1116
        // Database table definition.
1117
        $table_system_template = Database:: get_main_table('system_template');
1118
        $sql = "SELECT * FROM $table_system_template WHERE id = " . intval($_GET['id']) . "";
1119
        $result = Database::query($sql);
1120
        $row = Database::fetch_array($result);
1121
1122
        $defaults['template_id'] = intval($_GET['id']);
1123
        $defaults['template_text'] = $row['content'];
1124
        // Forcing get_lang().
1125
        $defaults['title'] = get_lang($row['title']);
1126
1127
        // Adding an extra field: a hidden field with the id of the template we are editing.
1128
        $form->addElement('hidden', 'template_id');
1129
1130
        // Adding an extra field: a preview of the image that is currently used.
1131
        if (!empty($row['image'])) {
1132
            $form->addElement('static', 'template_image_preview', '',
1133
                '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/' . $row['image'] . '" alt="' . get_lang('TemplatePreview') . '"/>');
1134
        } else {
1135
            $form->addElement('static', 'template_image_preview', '',
1136
                '<img src="' . api_get_path(WEB_APP_PATH) . 'home/default_platform_document/template_thumb/noimage.gif" alt="' . get_lang('NoTemplatePreview') . '"/>');
1137
        }
1138
1139
        // Setting the information of the template that we are editing.
1140
        $form->setDefaults($defaults);
1141
    }
1142
    // Setting the form elements: the submit button.
1143
    $form->addButtonSave(get_lang('Ok'), 'submit');
1144
1145
    // Setting the rules: the required fields.
1146
    $form->addRule('template_image', get_lang('ThisFieldIsRequired'), 'required');
1147
    $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
1148
    $form->addRule('template_text', get_lang('ThisFieldIsRequired'), 'required');
1149
1150
    // if the form validates (complies to all rules) we save the information, else we display the form again (with error message if needed)
1151
    if ($form->validate()) {
1152
1153
        $check = Security::check_token('post');
1154
        if ($check) {
1155
            // Exporting the values.
1156
            $values = $form->exportValues();
1157
            // Upload the file.
1158
            if (!empty($_FILES['template_image']['name'])) {
1159
                $upload_ok = process_uploaded_file($_FILES['template_image']);
1160
1161
                if ($upload_ok) {
1162
                    // Try to add an extension to the file if it hasn't one.
1163
                    $new_file_name = add_ext_on_mime(stripslashes($_FILES['template_image']['name']),
1164
                        $_FILES['template_image']['type']);
1165
1166
                    // The upload directory.
1167
                    $upload_dir = api_get_path(SYS_APP_PATH) . 'home/default_platform_document/template_thumb/';
1168
1169
                    // Create the directory if it does not exist.
1170
                    if (!is_dir($upload_dir)) {
1171
                        mkdir($upload_dir, api_get_permissions_for_new_directories());
1172
                    }
1173
1174
                    // Resize the preview image to max default and upload.
1175
                    $temp = new Image($_FILES['template_image']['tmp_name']);
1176
                    $picture_info = $temp->get_image_info();
1177
1178
                    $max_width_for_picture = 100;
1179
1180
                    if ($picture_info['width'] > $max_width_for_picture) {
1181
                        $temp->resize($max_width_for_picture);
1182
                    }
1183
                    $temp->send_image($upload_dir . $new_file_name);
1184
                }
1185
            }
1186
1187
            // Store the information in the database (as insert or as update).
1188
            $table_system_template = Database:: get_main_table('system_template');
1189
            if ($_GET['action'] == 'add') {
1190
                $content_template = Security::remove_XSS($values['template_text'], COURSEMANAGERLOWSECURITY);
1191
                $params = [
1192
                    'title' => $values['title'],
1193
                    'content' => $content_template,
1194
                    'image' => $new_file_name
1195
                ];
1196
                Database::insert($table_system_template, $params);
1197
1198
                // Display a feedback message.
1199
                Display::display_confirmation_message(get_lang('TemplateAdded'));
1200
                echo '<a href="settings.php?category=Templates&action=add">' . Display::return_icon('new_template.png',
1201
                        get_lang('AddTemplate'), '', ICON_SIZE_MEDIUM) . '</a>';
1202
            } else {
1203
                $content_template = '<head>{CSS}<style type="text/css">.text{font-weight: normal;}</style></head><body>' . Database::escape_string($values['template_text']) . '</body>';
1204
                $sql = "UPDATE $table_system_template set title = '" . Database::escape_string($values['title']) . "', content = '" . $content_template . "'";
1205
                if (!empty($new_file_name)) {
1206
                    $sql .= ", image = '" . Database::escape_string($new_file_name) . "'";
1207
                }
1208
                $sql .= " WHERE id = " . intval($_GET['id']) . "";
1209
                Database::query($sql);
1210
1211
                // Display a feedback message.
1212
                Display::display_confirmation_message(get_lang('TemplateEdited'));
1213
            }
1214
        }
1215
        Security::clear_token();
1216
        display_templates();
1217
    } else {
1218
        $token = Security::get_token();
1219
        $form->addElement('hidden', 'sec_token');
1220
        $form->setConstants(array('sec_token' => $token));
1221
        // Display the form.
1222
        $form->display();
1223
    }
1224
}
1225
1226
/**
1227
 * Delete a template
1228
 *
1229
 * @param integer $id the id of the template that has to be deleted
1230
 *
1231
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
1232
 * @version August 2008
1233
 * @since Dokeos 1.8.6
1234
 */
1235
function delete_template($id)
1236
{
1237
    // First we remove the image.
1238
    $table_system_template = Database:: get_main_table('system_template');
1239
    $sql = "SELECT * FROM $table_system_template WHERE id = " . intval($id) . "";
1240
    $result = Database::query($sql);
1241
    $row = Database::fetch_array($result);
1242
    if (!empty($row['image'])) {
1243
        @unlink(api_get_path(SYS_APP_PATH) . 'home/default_platform_document/template_thumb/' . $row['image']);
1244
    }
1245
1246
    // Now we remove it from the database.
1247
    $sql = "DELETE FROM $table_system_template WHERE id = " . intval($id) . "";
1248
    Database::query($sql);
1249
1250
    // Display a feedback message.
1251
    Display::display_confirmation_message(get_lang('TemplateDeleted'));
1252
}
1253
1254
/**
1255
 * Returns the list of timezone identifiers used to populate the select
1256
 * This function is called through a call_user_func() in the generate_settings_form function.
1257
 * @return array List of timezone identifiers
1258
 *
1259
 * @author Guillaume Viguier <[email protected]>
1260
 * @since Chamilo 1.8.7
1261
 */
1262
function select_timezone_value()
1263
{
1264
    return api_get_timezones();
1265
}
1266
1267
/**
1268
 * Returns an array containing the list of options used to populate the gradebook_number_decimals variable
1269
 * This function is called through a call_user_func() in the generate_settings_form function.
1270
 * @return string[] List of gradebook_number_decimals options
1271
 *
1272
 * @author Guillaume Viguier <[email protected]>
1273
 */
1274
function select_gradebook_number_decimals()
1275
{
1276
    return array('0', '1', '2');
1277
}
1278
1279
function select_gradebook_default_grade_model_id()
1280
{
1281
    $grade_model = new GradeModel();
1282
    $models = $grade_model->get_all();
1283
    $options = array();
1284
    $options[-1] = get_lang('None');
1285
    if (!empty($models)) {
1286
        foreach ($models as $model) {
1287
            $options[$model['id']] = $model['name'];
1288
        }
1289
    }
1290
    return $options;
1291
}
1292
1293
/**
1294
 * Updates the gradebook score custom values using the scoredisplay class of the
1295
 * gradebook module
1296
 *
1297
 * @param array List of gradebook score custom values
1298
 *
1299
 * @author Guillaume Viguier <[email protected]>
1300
 */
1301
function update_gradebook_score_display_custom_values($values)
1302
{
1303
    $scoredisplay = ScoreDisplay::instance();
1304
    $scores = $values['gradebook_score_display_custom_values_endscore'];
1305
    $displays = $values['gradebook_score_display_custom_values_displaytext'];
1306
    $nr_displays = count($displays);
1307
    $final = array();
1308
    for ($i = 1; $i < $nr_displays; $i++) {
1309
        if (!empty($scores[$i]) && !empty($displays[$i])) {
1310
            $final[$i]['score'] = $scores[$i];
1311
            $final[$i]['display'] = $displays[$i];
1312
        }
1313
    }
1314
    $scoredisplay->update_custom_score_display_settings($final);
1315
}
1316
1317
function generate_settings_form($settings, $settings_by_access_list)
1318
{
1319
    global $_configuration, $settings_to_avoid, $convert_byte_to_mega_list;
1320
    $table_settings_current = Database:: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1321
1322
    $form = new FormValidator('settings', 'post', 'settings.php?category=' . Security::remove_XSS($_GET['category']));
1323
1324
    $form->addElement('hidden', 'search_field',
1325
        (!empty($_GET['search_field']) ? Security::remove_XSS($_GET['search_field']) : null));
1326
1327
    $url_id = api_get_current_access_url_id();
1328
1329
    if (!empty($_configuration['multiple_access_urls']) && api_is_global_platform_admin() && $url_id == 1) {
1330
        $group = array();
1331
        $group[] = $form->createElement('button', 'mark_all', get_lang('MarkAll'));
1332
        $group[] = $form->createElement('button', 'unmark_all', get_lang('UnmarkAll'));
1333
        $form->addGroup($group, 'buttons_in_action_right');
1334
    }
1335
1336
    $default_values = array();
1337
    $url_info = api_get_access_url($url_id);
1338
    $i = 0;
1339
    $addedSettings = [];
1340
    foreach ($settings as $row) {
1341
        if (in_array($row['variable'], array_keys($settings_to_avoid))) {
1342
            continue;
1343
        }
1344
1345
        if (in_array($row['variable'], $addedSettings)) {
1346
            continue;
1347
        }
1348
1349
        $addedSettings[] = $row['variable'];
1350
1351
        if (!empty($_configuration['multiple_access_urls'])) {
1352
            if (api_is_global_platform_admin()) {
1353
                if ($row['access_url_locked'] == 0) {
1354
                    if ($url_id == 1) {
1355
                        if ($row['access_url_changeable'] == '1') {
1356
                            $form->addElement('html',
1357
                                '<div style="float: right;"><a class="share_this_setting" data_status = "0"  data_to_send = "' . $row['variable'] . '" href="javascript:void(0);">' .
1358
                                Display::return_icon('shared_setting.png',
1359
                                    get_lang('ChangeSharedSetting')) . '</a></div>');
1360
                        } else {
1361
                            $form->addElement('html',
1362
                                '<div style="float: right;"><a class="share_this_setting" data_status = "1" data_to_send = "' . $row['variable'] . '" href="javascript:void(0);">' .
1363
                                Display::return_icon('shared_setting_na.png',
1364
                                    get_lang('ChangeSharedSetting')) . '</a></div>');
1365
                        }
1366
                    } else {
1367
                        if ($row['access_url_changeable'] == '1') {
1368
                            $form->addElement('html', '<div style="float: right;">' .
1369
                                Display::return_icon('shared_setting.png', get_lang('ChangeSharedSetting')) . '</div>');
1370
                        } else {
1371
                            $form->addElement('html', '<div style="float: right;">' .
1372
                                Display::return_icon('shared_setting_na.png',
1373
                                    get_lang('ChangeSharedSetting')) . '</div>');
1374
                        }
1375
                    }
1376
                }
1377
            }
1378
        }
1379
1380
        $hideme = array();
1381
        $hide_element = false;
1382
1383
        if ($_configuration['access_url'] != 1) {
1384
            if ($row['access_url_changeable'] == 0) {
1385
                // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element.
1386
                $hide_element = true;
1387
                $hideme = array('disabled');
1388
            } elseif ($url_info['active'] == 1) {
1389
                // We show the elements.
1390
                if (empty($row['variable'])) {
1391
                    $row['variable'] = 0;
1392
                }
1393
                if (empty($row['subkey'])) {
1394
                    $row['subkey'] = 0;
1395
                }
1396
                if (empty($row['category'])) {
1397
                    $row['category'] = 0;
1398
                }
1399
1400
                if (is_array($settings_by_access_list[$row['variable']] [$row['subkey']] [$row['category']])) {
1401
                    // We are sure that the other site have a selected value.
1402
                    if ($settings_by_access_list[$row['variable']] [$row['subkey']] [$row['category']]['selected_value'] != '') {
1403
                        $row['selected_value'] = $settings_by_access_list[$row['variable']] [$row['subkey']] [$row['category']]['selected_value'];
1404
                    }
1405
                }
1406
                // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
1407
            }
1408
        }
1409
1410
        switch ($row['type']) {
1411
            case 'textfield':
1412
                if (in_array($row['variable'], $convert_byte_to_mega_list)) {
1413
                    $form->addElement(
1414
                        'text',
1415
                        $row['variable'],
1416
                        array(
1417
                            get_lang($row['title']),
1418
                            get_lang($row['comment']),
1419
                            get_lang('MB'),
1420
                        ),
1421
                        array('maxlength' => '8')
1422
                    );
1423
                    $form->applyFilter($row['variable'], 'html_filter');
1424
                    $default_values[$row['variable']] = round($row['selected_value'] / 1024 / 1024, 1);
1425
                } elseif ($row['variable'] == 'account_valid_duration') {
1426
                    $form->addElement(
1427
                        'text',
1428
                        $row['variable'],
1429
                        array(
1430
                            get_lang($row['title']),
1431
                            get_lang($row['comment']),
1432
                        ),
1433
                        array('maxlength' => '5')
1434
                    );
1435
                    $form->applyFilter($row['variable'], 'html_filter');
1436
                    $default_values[$row['variable']] = $row['selected_value'];
1437
1438
                    // For platform character set selection: Conversion of the textfield to a select box with valid values.
1439
                } elseif ($row['variable'] == 'platform_charset') {
1440
                    continue;
1441
                } else {
1442
                    $hideme['class'] = 'col-md-4';
1443
                    $form->addElement(
1444
                        'text',
1445
                        $row['variable'],
1446
                        array(
1447
                            get_lang($row['title']),
1448
                            get_lang($row['comment']),
1449
                        ),
1450
                        $hideme
1451
                    );
1452
                    $form->applyFilter($row['variable'], 'html_filter');
1453
                    $default_values[$row['variable']] = $row['selected_value'];
1454
                }
1455
                break;
1456
            case 'textarea':
1457
                if ($row['variable'] == 'header_extra_content') {
1458
                    $file = api_get_path(SYS_PATH) . api_get_home_path() . 'header_extra_content.txt';
1459
                    $value = '';
1460
                    if (file_exists($file)) {
1461
                        $value = file_get_contents($file);
1462
                    }
1463
                    $form->addElement('textarea', $row['variable'],
1464
                        array(get_lang($row['title']), get_lang($row['comment'])), array('rows' => '10'), $hideme);
1465
                    $default_values[$row['variable']] = $value;
1466
                } elseif ($row['variable'] == 'footer_extra_content') {
1467
                    $file = api_get_path(SYS_PATH) . api_get_home_path() . 'footer_extra_content.txt';
1468
                    $value = '';
1469
                    if (file_exists($file)) {
1470
                        $value = file_get_contents($file);
1471
                    }
1472
                    $form->addElement('textarea', $row['variable'],
1473
                        array(get_lang($row['title']), get_lang($row['comment'])), array('rows' => '10'), $hideme);
1474
                    $default_values[$row['variable']] = $value;
1475
                } else {
1476
                    $form->addElement('textarea', $row['variable'],
1477
                        array(get_lang($row['title']), get_lang($row['comment'])), array('rows' => '10'), $hideme);
1478
                    $default_values[$row['variable']] = $row['selected_value'];
1479
                }
1480
                break;
1481
            case 'radio':
1482
                $values = api_get_settings_options($row['variable']);
1483
                $group = array();
1484
                if (is_array($values)) {
1485
                    foreach ($values as $key => $value) {
1486
                        $element = &$form->createElement(
1487
                            'radio',
1488
                            $row['variable'],
1489
                            '',
1490
                            get_lang($value['display_text']),
1491
                            $value['value']
1492
                        );
1493
                        if ($hide_element) {
1494
                            $element->freeze();
1495
                        }
1496
                        $group[] = $element;
1497
                    }
1498
                }
1499
                $form->addGroup(
1500
                    $group,
1501
                    $row['variable'],
1502
                    array(get_lang($row['title']), get_lang($row['comment'])),
1503
                    '',
1504
                    false
1505
                );
1506
                $default_values[$row['variable']] = $row['selected_value'];
1507
                break;
1508
            case 'checkbox';
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
1509
                // 1. We collect all the options of this variable.
1510
                $sql = "SELECT * FROM $table_settings_current
1511
                        WHERE variable='" . $row['variable'] . "' AND access_url =  1";
1512
1513
                $result = Database::query($sql);
1514
                $group = array();
1515
                while ($rowkeys = Database::fetch_array($result)) {
1516
                    // Profile tab option should be hidden when the social tool is enabled.
1517
                    if (api_get_setting('allow_social_tool') == 'true') {
1518
                        if ($rowkeys['variable'] == 'show_tabs' && $rowkeys['subkey'] == 'my_profile') {
1519
                            continue;
1520
                        }
1521
                    }
1522
1523
                    // Hiding the gradebook option.
1524
                    if ($rowkeys['variable'] == 'show_tabs' && $rowkeys['subkey'] == 'my_gradebook') {
1525
                        continue;
1526
                    }
1527
1528
                    $element = &$form->createElement(
1529
                        'checkbox',
1530
                        $rowkeys['subkey'],
1531
                        '',
1532
                        get_lang($rowkeys['subkeytext'])
1533
                    );
1534
1535
                    if ($row['access_url_changeable'] == 1) {
1536
                        // 2. We look into the DB if there is a setting for a specific access_url.
1537
                        $access_url = $_configuration['access_url'];
1538
                        if (empty($access_url)) {
1539
                            $access_url = 1;
1540
                        }
1541
                        $sql = "SELECT selected_value FROM $table_settings_current
1542
                                WHERE
1543
                                    variable='" . $rowkeys['variable'] . "' AND
1544
                                    subkey='" . $rowkeys['subkey'] . "' AND
1545
                                    subkeytext='" . $rowkeys['subkeytext'] . "' AND
1546
                                    access_url =  $access_url";
1547
                        $result_access = Database::query($sql);
1548
                        $row_access = Database::fetch_array($result_access);
1549
                        if ($row_access['selected_value'] == 'true' && !$form->isSubmitted()) {
1550
                            $element->setChecked(true);
1551
                        }
1552
                    } else {
1553
                        if ($rowkeys['selected_value'] == 'true' && !$form->isSubmitted()) {
1554
                            $element->setChecked(true);
1555
                        }
1556
                    }
1557
                    if ($hide_element) {
1558
                        $element->freeze();
1559
                    }
1560
                    $group[] = $element;
1561
                }
1562
                $form->addGroup(
1563
                    $group,
1564
                    $row['variable'],
1565
                    array(get_lang($row['title']), get_lang($row['comment'])),
1566
                    ''
1567
                );
1568
                break;
1569
            case 'link':
1570
                $form->addElement('static', null, array(get_lang($row['title']), get_lang($row['comment'])),
1571
                    get_lang('CurrentValue') . ' : ' . $row['selected_value'], $hideme);
1572
                break;
1573
            case 'select':
1574
                /*
1575
                * 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.
1576
                * The functions being called must be added to the file settings.lib.php.
1577
                */
1578
                $form->addElement('select', $row['variable'], array(get_lang($row['title']), get_lang($row['comment'])),
1579
                    call_user_func('select_' . $row['variable']), $hideme);
1580
                $default_values[$row['variable']] = $row['selected_value'];
1581
                break;
1582
            case 'custom':
1583
                break;
1584
        }
1585
1586
        switch ($row['variable']) {
1587
            case 'pdf_export_watermark_enable':
1588
                $url = PDF::get_watermark(null);
1589
1590
                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...
1591
                    $delete_url = '<a href="?delete_watermark">' . get_lang('DelImage') . ' ' . Display::return_icon('delete.png',
1592
                            get_lang('DelImage')) . '</a>';
1593
                    $form->addElement('html',
1594
                        '<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>');
1595
                }
1596
1597
                $form->addElement('file', 'pdf_export_watermark_path', get_lang('AddWaterMark'));
1598
                $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
1599
                $form->addRule('pdf_export_watermark_path',
1600
                    get_lang('OnlyImagesAllowed') . ' (' . implode(',', $allowed_picture_types) . ')', 'filetype',
1601
                    $allowed_picture_types);
1602
1603
                break;
1604
            case 'timezone_value':
1605
                $timezone = $row['selected_value'];
1606
                if (empty($timezone)) {
1607
                    $timezone = _api_get_timezone();
1608
                }
1609
                $form->addElement('html',
1610
                    sprintf(get_lang('LocalTimeUsingPortalTimezoneXIsY'), $timezone, api_get_local_time()));
1611
                break;
1612
        }
1613
    } // end for
1614
1615
    if (!empty($settings)) {
1616
        $form->setDefaults($default_values);
1617
    }
1618
    $form->addHtml('<div class="bottom_actions">');
1619
    $form->addButtonSave(get_lang('SaveSettings'));
1620
    $form->addHtml('</div>');
1621
    return $form;
1622
}
1623
1624
/**
1625
 * Searches a platform setting in all categories except from the Plugins category
1626
 * @param string $search
1627
 * @return array
1628
 */
1629
function search_setting($search)
1630
{
1631
    if (empty($search)) {
1632
        return array();
1633
    }
1634
    $table_settings_current = Database:: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
1635
    $sql = "SELECT * FROM $table_settings_current
1636
            WHERE category <> 'Plugins' ORDER BY id ASC ";
1637
    $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...
1638
    $settings = array();
1639
1640
    $search = api_strtolower($search);
1641
1642
    if (!empty($result)) {
1643
        foreach ($result as $setting) {
1644
            $found = false;
1645
1646
            $title = api_strtolower(get_lang($setting['title']));
1647
            // try the title
1648
            if (strpos($title, $search) === false) {
1649
                $comment = api_strtolower(get_lang($setting['comment']));
1650
                //Try the comment
1651
                if (strpos($comment, $search) === false) {
1652
                    //Try the variable name
1653
                    if (strpos($setting['variable'], $search) === false) {
1654
                        continue;
1655
                    } else {
1656
                        $found = true;
1657
                    }
1658
                } else {
1659
                    $found = true;
1660
                }
1661
1662
            } else {
1663
                $found = true;
1664
            }
1665
            if ($found) {
1666
                $settings[] = $setting;
1667
            }
1668
        }
1669
    }
1670
    return $settings;
1671
}
1672