searchImageFilter()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

Loading history...
37
            LOG_CONFIGURATION_SETTINGS_CHANGE,
38
            LOG_CONFIGURATION_SETTINGS_CATEGORY,
39
            $category,
40
            api_get_utc_datetime(),
41
            $user_id
42
        );
43
        echo Display::return_message(get_lang('The settings have been stored'), 'confirmation');
44
    }
45
46
    $plugin_obj = new AppPlugin();
47
    $installed_plugins = $plugin_obj->getInstalledPlugins();
48
49
    echo '<form name="plugins" method="post" action="'.api_get_self().'?category='.Security::remove_XSS($_GET['category']).'">';
50
    echo '<table class="data_table">';
51
    echo '<tr>';
52
    echo '<th width="400px">';
53
    echo get_lang('Plugin');
54
    echo '</th><th>';
55
    echo get_lang('Regions');
56
    echo '</th>';
57
    echo '</th>';
58
    echo '</tr>';
59
60
    /* We display all the possible plugins and the checkboxes */
61
    $plugin_region_list = [];
62
    $my_plugin_list = $plugin_obj->getPluginRegions();
63
    foreach ($my_plugin_list as $plugin_item) {
64
        $plugin_region_list[$plugin_item] = $plugin_item;
65
    }
66
67
    // Removing course tool
68
    unset($plugin_region_list['course_tool_plugin']);
69
70
    foreach ($installed_plugins as $pluginName) {
71
        $plugin_info_file = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/plugin.php';
72
73
        if (file_exists($plugin_info_file)) {
74
            $plugin_info = [];
75
            require $plugin_info_file;
76
            if (isset($_GET['name']) && $_GET['name'] === $pluginName) {
77
                echo '<tr class="row_selected">';
78
            } else {
79
                echo '<tr>';
80
            }
81
            echo '<td>';
82
            echo '<h4>'.$plugin_info['title'].' <small>v'.$plugin_info['version'].'</small></h4>';
83
            echo '<p>'.$plugin_info['comment'].'</p>';
84
            echo '</td><td>';
85
            $selected_plugins = $plugin_obj->get_areas_by_plugin($pluginName);
86
            $region_list = [];
87
            $isAdminPlugin = isset($plugin_info['is_admin_plugin']) && $plugin_info['is_admin_plugin'];
88
            $isCoursePlugin = isset($plugin_info['is_course_plugin']) && $plugin_info['is_course_plugin'];
89
90
            if (!$isAdminPlugin && !$isCoursePlugin) {
91
                $region_list = $plugin_region_list;
92
            } else {
93
                if ($isAdminPlugin) {
94
                    $region_list['menu_administrator'] = 'menu_administrator';
95
                }
96
                if ($isCoursePlugin) {
97
                    $region_list['course_tool_plugin'] = 'course_tool_plugin';
98
                }
99
            }
100
101
            echo Display::select(
102
                'plugin_'.$pluginName.'[]',
103
                $region_list,
104
                $selected_plugins,
105
                ['multiple' => 'multiple', 'style' => 'width:500px'],
106
                true,
107
                get_lang('none')
108
            );
109
            echo '</td></tr>';
110
        }
111
    }
112
    echo '</table>';
113
    echo '<br />';
114
    echo '<button class="btn btn--success" type="submit" name="submit_plugins">'.get_lang('Enable the selected plugins').'</button></form>';
115
}
116
117
function handleExtensions()
118
{
119
    echo Display::page_subheader(get_lang('Configure extensions'));
120
    echo '<a class="btn btn--success" href="configure_extensions.php?display=ppt2lp" role="button">'.get_lang('Chamilo RAPID').'</a>';
121
}
122
123
/**
124
 * This function allows easy activating and inactivating of plugins.
125
 *
126
 * @todo: a similar function needs to be written to activate or inactivate additional tools.
127
 *
128
 * @author Patrick Cool <[email protected]>, Ghent University
129
 * @author Julio Montoya <[email protected]> Beeznest 2012
130
 */
131
function handlePlugins()
132
{
133
    Session::erase('plugin_data');
134
    $pluginRepo = Container::getPluginRepository();
135
136
    $allPlugins = (new AppPlugin())->read_plugins_from_path();
137
138
    // Header
139
    echo '<div class="mb-4 flex items-center justify-between">';
140
    echo '<h2 class="text-2xl font-semibold text-gray-90">'.get_lang('Manage plugins').'</h2>';
141
    echo '<p class="text-gray-50 text-sm">'.get_lang('Install, activate or deactivate plugins easily.').'</p>';
142
    echo '</div>';
143
144
    echo '<table class="w-full border border-gray-25 rounded-lg shadow-md">';
145
    echo '<thead>';
146
    echo '<tr class="bg-gray-10 text-left">';
147
    echo '<th class="p-3 border-b border-gray-25">'.get_lang('Plugin').'</th>';
148
    echo '<th class="p-3 border-b border-gray-25">'.get_lang('Version').'</th>';
149
    echo '<th class="p-3 border-b border-gray-25">'.get_lang('Status').'</th>';
150
    echo '<th class="p-3 border-b border-gray-25 text-center">'.get_lang('Actions').'</th>';
151
    echo '</tr>';
152
    echo '</thead>';
153
    echo '<tbody>';
154
155
    foreach ($allPlugins as $pluginName) {
156
        $pluginInfoFile = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/plugin.php';
157
        if (!file_exists($pluginInfoFile)) {
158
            continue;
159
        }
160
161
        $plugin_info = [];
162
        try {
163
            require $pluginInfoFile;
164
        } catch (\Throwable $e) {
165
            error_log('[plugins] failed to read '.$pluginName.' metadata: '.$e->getMessage());
166
            $plugin_info = ['title' => $pluginName, 'version' => 'n/a'];
167
        }
168
169
        $plugin = $pluginRepo->findOneByTitle($pluginName);
170
        $pluginConfiguration = $plugin?->getConfigurationsByAccessUrl(Container::getAccessUrlUtil()->getCurrent());
171
        $isInstalled = $plugin && $plugin->isInstalled();
172
        $isEnabled   = $plugin && $pluginConfiguration && $pluginConfiguration->isActive();
173
174
        // Status badge
175
        $statusBadge = $isInstalled
176
            ? ($isEnabled
177
                ? '<span class="badge badge--success">'.get_lang('Enabled').'</span>'
178
                : '<span class="badge badge--warning">'.get_lang('Disabled').'</span>')
179
            : '<span class="badge badge--default">'.get_lang('Not installed').'</span>';
180
181
        echo '<tr class="border-t border-gray-25 hover:bg-gray-15 transition duration-200">';
182
        echo '<td class="p-3 font-medium">'.htmlspecialchars($plugin_info['title'] ?? $pluginName, ENT_QUOTES).'</td>';
183
        echo '<td class="p-3">'.htmlspecialchars($plugin_info['version'] ?? '0.0.0', ENT_QUOTES).'</td>';
184
        echo '<td class="p-3">'.$statusBadge.'</td>';
185
        echo '<td class="p-3 text-center"><div class="flex justify-center gap-2">';
186
187
        if ($isInstalled) {
188
            $toggleAction = $isEnabled ? 'disable' : 'enable';
189
            $toggleText   = $isEnabled ? get_lang('Disable') : get_lang('Enable');
190
            $toggleColor  = $isEnabled ? 'btn--plain' : 'btn--warning';
191
            $toggleIcon   = $isEnabled ? 'mdi mdi-toggle-switch-off-outline' : 'mdi mdi-toggle-switch-outline';
192
193
            echo '<button class="plugin-action btn btn--sm '.$toggleColor.'"
194
                    data-plugin="'.htmlspecialchars($pluginName, ENT_QUOTES).'" data-action="'.$toggleAction.'">
195
                    <i class="'.$toggleIcon.'"></i> '.$toggleText.'
196
                  </button>';
197
198
            echo '<button class="plugin-action btn btn--sm btn--danger"
199
                    data-plugin="'.htmlspecialchars($pluginName, ENT_QUOTES).'" data-action="uninstall">
200
                    <i class="mdi mdi-trash-can-outline"></i> '.get_lang('Uninstall').'
201
                  </button>';
202
203
            // Show "Configure" only if the plugin is ENABLED and actually has editable settings.
204
            if ($isEnabled && plugin_has_editable_settings($pluginName)) {
205
                $configureUrl = '/main/admin/configure_plugin.php?'.http_build_query(['plugin' => $pluginName]);
206
                echo Display::url(
207
                    get_lang('Configure'),
208
                    $configureUrl,
209
                    ['class' => 'btn btn--info btn--sm']
210
                );
211
            }
212
        } else {
213
            echo '<button class="plugin-action btn btn--sm btn--success"
214
                    data-plugin="'.htmlspecialchars($pluginName, ENT_QUOTES).'" data-action="install">
215
                    <i class="mdi mdi-download"></i> '.get_lang('Install').'
216
                  </button>';
217
        }
218
219
        echo '</div></td></tr>';
220
    }
221
222
    echo '</tbody></table>';
223
224
    echo '<div id="page-loader" class="hidden fixed inset-0 bg-black/30 z-40">
225
            <div class="absolute inset-0 flex items-center justify-center">
226
              <div class="text-white text-sm text-center">
227
                <i class="mdi mdi-loading mdi-spin text-3xl block mb-2"></i>
228
                '.get_lang('Processing').'…
229
              </div>
230
            </div>
231
          </div>';
232
233
    echo '<script>
234
(function($){
235
  function showToast(message, type) {
236
    var bg = type === "success" ? "bg-green-600" : (type === "warning" ? "bg-yellow-600" : "bg-red-600");
237
    var $toast = $("<div/>", {
238
      class: "fixed top-4 right-4 z-50 text-white px-4 py-3 rounded shadow " + bg,
239
      text: message
240
    }).appendTo("body");
241
    setTimeout(function(){ $toast.fadeOut(300, function(){ $(this).remove(); }); }, 3500);
242
  }
243
  function actionLabel(a) {
244
    switch(a){
245
      case "install": return "'.get_lang('Installing').'";
246
      case "uninstall": return "'.get_lang('Uninstalling').'";
247
      case "enable": return "'.get_lang('Enabling').'";
248
      case "disable": return "'.get_lang('Disabling').'";
249
      default: return "'.get_lang('Processing').'";
250
    }
251
  }
252
  function showPageLoader(show){ $("#page-loader").toggleClass("hidden", !show); }
253
254
  $(document).ready(function () {
255
    $(".plugin-action").on("click", function () {
256
      var $btn = $(this);
257
      if ($btn.data("busy")) return;
258
259
      var pluginName = $btn.data("plugin");
260
      var action = $btn.data("action");
261
      var originalHtml = $btn.html();
262
263
      $btn.data("busy", true)
264
          .attr("aria-busy", "true")
265
          .addClass("opacity-60 cursor-not-allowed")
266
          .html(\'<i class="mdi mdi-loading mdi-spin"></i> \' + actionLabel(action) + "...");
267
      $.ajax({
268
        type: "POST",
269
        url: "'.api_get_path(WEB_AJAX_PATH).'plugin.ajax.php",
270
        data: { a: action, plugin: pluginName },
271
        dataType: "json",
272
        timeout: 120000,
273
        beforeSend: function(){ showToast(actionLabel(action) + "…", "warning"); },
274
        success: function(data){
275
          if (data && data.success) {
276
            showToast("'.get_lang('Done').': " + action.toUpperCase(), "success");
277
            setTimeout(function(){ location.reload(); }, 500);
278
          } else {
279
            var msg = (data && (data.error || data.message)) ? (data.error || data.message) : "'.get_lang('Error').'";
280
            showToast("'.get_lang('Error').': " + msg, "error");
281
            $btn.html(originalHtml);
282
          }
283
        },
284
        error: function(xhr){
285
          var msg = "'.get_lang('Request failed').'";
286
          try {
287
            var j = JSON.parse(xhr.responseText);
288
            if (j && (j.error || j.message)) msg = j.error || j.message;
289
          } catch(e) {}
290
          showToast("'.get_lang('Error').': " + msg, "error");
291
          $btn.html(originalHtml);
292
        },
293
        complete: function(){
294
          $btn.data("busy", false)
295
              .removeAttr("aria-busy")
296
              .removeClass("opacity-60 cursor-not-allowed");
297
        }
298
      });
299
    });
300
  });
301
})(jQuery);
302
</script>';
303
}
304
305
/**
306
 * Determine if a plugin exposes editable settings (excluding legacy enable/active toggles).
307
 * Used to decide whether the "Configure" button should be shown.
308
 */
309
function plugin_has_editable_settings(string $pluginName): bool
310
{
311
    static $cache = [];
312
    if (array_key_exists($pluginName, $cache)) {
313
        return $cache[$pluginName];
314
    }
315
316
    $has = false;
317
318
    try {
319
        $app  = new AppPlugin();
320
        $info = $app->getPluginInfo($pluginName, true) ?? [];
321
322
        // Collect fields from Plugin object or from 'settings' array
323
        if (!empty($info['obj']) && $info['obj'] instanceof Plugin) {
324
            $fields = (array) $info['obj']->getFieldNames();
325
        } elseif (!empty($info['settings']) && is_array($info['settings'])) {
326
            $fields = array_keys($info['settings']);
327
        } else {
328
            $fields = [];
329
        }
330
331
        // Strip legacy toggles; these do not qualify as "configurable settings".
332
        // Keep this list broad to cover plugins that added their own toggle names.
333
        $legacyToggles = [
334
            'tool_enable',
335
            'enable_onlyoffice_plugin',
336
            'enabled',
337
            'enable',
338
            'active',
339
            'is_active',
340
        ];
341
        $fields = array_values(array_diff($fields, $legacyToggles));
342
343
        // Final decision: at least one real field
344
        $has = count($fields) > 0;
345
    } catch (\Throwable $e) {
346
        // Fail closed: if metadata lookup fails, do not show Configure
347
        $has = false;
348
    }
349
350
    return $cache[$pluginName] = $has;
351
}
352
353
/**
354
 * Creates the folder (if needed) and uploads the stylesheet in it.
355
 *
356
 * @param array $values  the values of the form
357
 * @param array $picture the values of the uploaded file
358
 *
359
 * @return bool
360
 *
361
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
362
 *
363
 * @version May 2008
364
 *
365
 * @since v1.8.5
366
 */
367
function uploadStylesheet($values, $picture)
368
{
369
    $result = false;
370
    // Valid name for the stylesheet folder.
371
    $style_name = api_preg_replace('/[^A-Za-z0-9]/', '', $values['name_stylesheet']);
372
    if (empty($style_name) || is_array($style_name)) {
373
        // The name of the uploaded stylesheet doesn't have the expected format
374
        return $result;
375
    }
376
    $cssToUpload = CSS_UPLOAD_PATH;
377
378
    // Check if a virtual instance vchamilo is used
379
    $virtualInstanceTheme = api_get_configuration_value('virtual_css_theme_folder');
380
    if (!empty($virtualInstanceTheme)) {
381
        $cssToUpload = $cssToUpload.$virtualInstanceTheme.'/';
382
    }
383
384
    // Create the folder if needed.
385
    if (!is_dir($cssToUpload.$style_name.'/')) {
386
        mkdir($cssToUpload.$style_name.'/', api_get_permissions_for_new_directories());
387
    }
388
389
    $info = pathinfo($picture['name']);
390
391
    if ('zip' == $info['extension']) {
392
        // Try to open the file and extract it in the theme.
393
        $zip = new ZipArchive();
394
        if ($zip->open($picture['tmp_name'])) {
395
            // Make sure all files inside the zip are images or css.
396
            $num_files = $zip->numFiles;
397
            $valid = true;
398
            $single_directory = true;
399
            $invalid_files = [];
400
401
            $allowedFiles = getAllowedFileTypes();
402
403
            for ($i = 0; $i < $num_files; $i++) {
404
                $file = $zip->statIndex($i);
405
                if ('/' != substr($file['name'], -1)) {
406
                    $path_parts = pathinfo($file['name']);
407
                    if (!in_array($path_parts['extension'], $allowedFiles)) {
408
                        $valid = false;
409
                        $invalid_files[] = $file['name'];
410
                    }
411
                }
412
413
                if (false === strpos($file['name'], '/')) {
414
                    $single_directory = false;
415
                }
416
            }
417
            if (!$valid) {
418
                $error_string = '<ul>';
419
                foreach ($invalid_files as $invalid_file) {
420
                    $error_string .= '<li>'.$invalid_file.'</li>';
421
                }
422
                $error_string .= '</ul>';
423
                echo Display::return_message(
424
                    get_lang('The only accepted extensions in the ZIP file are .jp(e)g, .png, .gif and .css.').$error_string,
425
                    'error',
426
                    false
427
                );
428
            } else {
429
                // If the zip does not contain a single directory, extract it.
430
                if (!$single_directory) {
431
                    // Extract zip file.
432
                    $zip->extractTo($cssToUpload.$style_name.'/');
433
                    $result = true;
434
                } else {
435
                    $extraction_path = $cssToUpload.$style_name.'/';
436
                    $mode = api_get_permissions_for_new_directories();
437
                    for ($i = 0; $i < $num_files; $i++) {
438
                        $entry = $zip->getNameIndex($i);
439
                        if ('/' == substr($entry, -1)) {
440
                            continue;
441
                        }
442
443
                        $pos_slash = strpos($entry, '/');
444
                        $entry_without_first_dir = substr($entry, $pos_slash + 1);
445
                        // If there is still a slash, we need to make sure the directories are created.
446
                        if (false !== strpos($entry_without_first_dir, '/')) {
447
                            if (!is_dir($extraction_path.dirname($entry_without_first_dir))) {
448
                                // Create it.
449
                                @mkdir($extraction_path.dirname($entry_without_first_dir), $mode, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
Bug introduced by
The constant SYS_APP_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1119
    }
1120
1121
    // Now we remove it from the database.
1122
    $sql = "DELETE FROM $table WHERE id = $id";
1123
    Database::query($sql);
1124
1125
    deleteTemplateImage($id);
1126
1127
    // Display a feedback message.
1128
    echo Display::return_message(get_lang('Template deleted'), 'confirm');
1129
}
1130
1131
/**
1132
 * @param array $settings
1133
 * @param array $settings_by_access_list
1134
 *
1135
 * @throws \Doctrine\ORM\ORMException
1136
 * @throws \Doctrine\ORM\OptimisticLockException
1137
 * @throws \Doctrine\ORM\TransactionRequiredException
1138
 *
1139
 * @return FormValidator
1140
 */
1141
function generateSettingsForm($settings, $settings_by_access_list)
1142
{
1143
    global $_configuration, $settings_to_avoid, $convert_byte_to_mega_list;
1144
    $em = Database::getManager();
1145
    $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS);
1146
1147
    $form = new FormValidator(
1148
        'settings',
1149
        'post',
1150
        'settings.php?category='.Security::remove_XSS($_GET['category'])
1151
    );
1152
1153
    $form->addElement(
1154
        'hidden',
1155
        'search_field',
1156
        (!empty($_GET['search_field']) ? Security::remove_XSS($_GET['search_field']) : null)
1157
    );
1158
1159
    $url_id = api_get_current_access_url_id();
1160
1161
    $default_values = [];
1162
    $url_info = api_get_access_url($url_id);
1163
    $i = 0;
1164
    $addedSettings = [];
1165
    foreach ($settings as $row) {
1166
        if (in_array($row['variable'], array_keys($settings_to_avoid))) {
1167
            continue;
1168
        }
1169
1170
        if (in_array($row['variable'], $addedSettings)) {
1171
            continue;
1172
        }
1173
1174
        $addedSettings[] = $row['variable'];
1175
1176
        if (api_get_multiple_access_url()) {
1177
            if (api_is_global_platform_admin()) {
1178
                if (0 == $row['access_url_locked']) {
1179
                    if (1 == $url_id) {
1180
                        if ('1' == $row['access_url_changeable']) {
1181
                            $form->addElement(
1182
                                'html',
1183
                                '<div class="float-right"><a class="share_this_setting" data_status = "0"  data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
1184
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</a></div>'
1185
                            );
1186
                        } else {
1187
                            $form->addElement(
1188
                                'html',
1189
                                '<div class="float-right"><a class="share_this_setting" data_status = "1" data_to_send = "'.$row['variable'].'" href="javascript:void(0);">'.
1190
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon-disabled', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</a></div>'
1191
                            );
1192
                        }
1193
                    } else {
1194
                        if ('1' == $row['access_url_changeable']) {
1195
                            $form->addElement(
1196
                                'html',
1197
                                '<div class="float-right">'.
1198
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</div>'
1199
                            );
1200
                        } else {
1201
                            $form->addElement(
1202
                                'html',
1203
                                '<div class="float-right">'.
1204
                                Display::getMdiIcon(StateIcon::SHARED_VISIBILITY, 'ch-tool-icon-disabled', null, ICON_SIZE_MEDIUM, get_lang('Change setting visibility for the other portals')).'</div>'
1205
                            );
1206
                        }
1207
                    }
1208
                }
1209
            }
1210
        }
1211
1212
        $hideme = [];
1213
        $hide_element = false;
1214
1215
        if (1 != $_configuration['access_url']) {
1216
            if (0 == $row['access_url_changeable']) {
1217
                // We hide the element in other cases (checkbox, radiobutton) we 'freeze' the element.
1218
                $hide_element = true;
1219
                $hideme = ['disabled'];
1220
            } elseif (1 == $url_info['active']) {
1221
                // We show the elements.
1222
                if (empty($row['variable'])) {
1223
                    $row['variable'] = 0;
1224
                }
1225
                if (empty($row['subkey'])) {
1226
                    $row['subkey'] = 0;
1227
                }
1228
                if (empty($row['category'])) {
1229
                    $row['category'] = 0;
1230
                }
1231
                if (isset($settings_by_access_list[$row['variable']]) &&
1232
                    isset($settings_by_access_list[$row['variable']][$row['subkey']]) &&
1233
                    is_array($settings_by_access_list[$row['variable']][$row['subkey']][$row['category']])
1234
                ) {
1235
                    // We are sure that the other site have a selected value.
1236
                    if ('' != $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value']) {
1237
                        $row['selected_value'] = $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']]['selected_value'];
1238
                    }
1239
                }
1240
                // There is no else{} statement because we load the default $row['selected_value'] of the main Chamilo site.
1241
            }
1242
        }
1243
1244
        switch ($row['type']) {
1245
            case 'textfield':
1246
                if (in_array($row['variable'], $convert_byte_to_mega_list)) {
1247
                    $form->addElement(
1248
                        'text',
1249
                        $row['variable'],
1250
                        [
1251
                            get_lang($row['title']),
1252
                            get_lang($row['comment']),
1253
                            get_lang('MB'),
1254
                        ],
1255
                        ['maxlength' => '8', 'aria-label' => get_lang($row['title'])]
1256
                    );
1257
                    $form->applyFilter($row['variable'], 'html_filter');
1258
                    $default_values[$row['variable']] = round($row['selected_value'] / 1024 / 1024, 1);
1259
                } elseif ('account_valid_duration' == $row['variable']) {
1260
                    $form->addElement(
1261
                        'text',
1262
                        $row['variable'],
1263
                        [
1264
                            get_lang($row['title']),
1265
                            get_lang($row['comment']),
1266
                        ],
1267
                        ['maxlength' => '5', 'aria-label' => get_lang($row['title'])]
1268
                    );
1269
                    $form->applyFilter($row['variable'], 'html_filter');
1270
1271
                    // For platform character set selection:
1272
                    // Conversion of the textfield to a select box with valid values.
1273
                    $default_values[$row['variable']] = $row['selected_value'];
1274
                } elseif ('platform_charset' == $row['variable']) {
1275
                    break;
1276
                } else {
1277
                    $hideme['class'] = 'col-md-4';
1278
                    $hideme['aria-label'] = get_lang($row['title']);
1279
                    $form->addElement(
1280
                        'text',
1281
                        $row['variable'],
1282
                        [
1283
                            get_lang($row['title']),
1284
                            get_lang($row['comment']),
1285
                        ],
1286
                        $hideme
1287
                    );
1288
                    $form->applyFilter($row['variable'], 'html_filter');
1289
                    $default_values[$row['variable']] = $row['selected_value'];
1290
                }
1291
                break;
1292
            case 'textarea':
1293
                if ('header_extra_content' == $row['variable']) {
1294
                    $file = api_get_home_path().'header_extra_content.txt';
0 ignored issues
show
Bug introduced by
The function api_get_home_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

1294
                    $file = /** @scrutinizer ignore-call */ api_get_home_path().'header_extra_content.txt';
Loading history...
1295
                    $value = '';
1296
                    if (file_exists($file)) {
1297
                        $value = file_get_contents($file);
1298
                    }
1299
                    $form->addElement(
1300
                        'textarea',
1301
                        $row['variable'],
1302
                        [get_lang($row['title']), get_lang($row['comment'])],
1303
                        ['rows' => '10', 'id' => $row['variable']],
1304
                        $hideme
1305
                    );
1306
                    $default_values[$row['variable']] = $value;
1307
                } elseif ('footer_extra_content' == $row['variable']) {
1308
                    $file = api_get_home_path().'footer_extra_content.txt';
1309
                    $value = '';
1310
                    if (file_exists($file)) {
1311
                        $value = file_get_contents($file);
1312
                    }
1313
                    $form->addElement(
1314
                        'textarea',
1315
                        $row['variable'],
1316
                        [get_lang($row['title']), get_lang($row['comment'])],
1317
                        ['rows' => '10', 'id' => $row['variable']],
1318
                        $hideme
1319
                    );
1320
                    $default_values[$row['variable']] = $value;
1321
                } else {
1322
                    $form->addElement(
1323
                        'textarea',
1324
                        $row['variable'],
1325
                        [get_lang($row['title']),
1326
                        get_lang($row['comment']), ],
1327
                        ['rows' => '10', 'id' => $row['variable']],
1328
                        $hideme
1329
                    );
1330
                    $default_values[$row['variable']] = $row['selected_value'];
1331
                }
1332
                break;
1333
            case 'radio':
1334
                $values = api_get_settings_options($row['variable']);
1335
                $group = [];
1336
                if (is_array($values)) {
1337
                    foreach ($values as $key => $value) {
1338
                        $element = &$form->createElement(
1339
                            'radio',
1340
                            $row['variable'],
1341
                            '',
1342
                            get_lang($value['display_text']),
1343
                            $value['value']
1344
                        );
1345
                        if ($hide_element) {
1346
                            $element->freeze();
1347
                        }
1348
                        $group[] = $element;
1349
                    }
1350
                }
1351
                $form->addGroup(
1352
                    $group,
1353
                    $row['variable'],
1354
                    [get_lang($row['title']), get_lang($row['comment'])],
1355
                    null,
1356
                    false
1357
                );
1358
                $default_values[$row['variable']] = $row['selected_value'];
1359
                break;
1360
            case 'checkbox':
1361
                // 1. We collect all the options of this variable.
1362
                $sql = "SELECT * FROM $table_settings_current
1363
                        WHERE variable='".$row['variable']."' AND access_url =  1";
1364
1365
                $result = Database::query($sql);
1366
                $group = [];
1367
                while ($rowkeys = Database::fetch_array($result)) {
1368
                    // Profile tab option should be hidden when the social tool is enabled.
1369
                    if ('true' == api_get_setting('allow_social_tool')) {
1370
                        if ('show_tabs' === $rowkeys['variable'] && 'my_profile' === $rowkeys['subkey']) {
1371
                            continue;
1372
                        }
1373
                    }
1374
1375
                    // Hiding the gradebook option.
1376
                    if ('show_tabs' === $rowkeys['variable'] && 'my_gradebook' === $rowkeys['subkey']) {
1377
                        continue;
1378
                    }
1379
1380
                    $element = &$form->createElement(
1381
                        'checkbox',
1382
                        $rowkeys['subkey'],
1383
                        '',
1384
                        get_lang($rowkeys['subkeytext'])
1385
                    );
1386
1387
                    if (1 == $row['access_url_changeable']) {
1388
                        // 2. We look into the DB if there is a setting for a specific access_url.
1389
                        $access_url = $_configuration['access_url'];
1390
                        if (empty($access_url)) {
1391
                            $access_url = 1;
1392
                        }
1393
                        $sql = "SELECT selected_value FROM $table_settings_current
1394
                                WHERE
1395
                                    variable='".$rowkeys['variable']."' AND
1396
                                    subkey='".$rowkeys['subkey']."' AND
1397
                                    subkeytext='".$rowkeys['subkeytext']."' AND
1398
                                    access_url =  $access_url";
1399
                        $result_access = Database::query($sql);
1400
                        $row_access = Database::fetch_array($result_access);
1401
                        if ('true' === $row_access['selected_value'] && !$form->isSubmitted()) {
1402
                            $element->setChecked(true);
1403
                        }
1404
                    } else {
1405
                        if ('true' === $rowkeys['selected_value'] && !$form->isSubmitted()) {
1406
                            $element->setChecked(true);
1407
                        }
1408
                    }
1409
                    if ($hide_element) {
1410
                        $element->freeze();
1411
                    }
1412
                    $group[] = $element;
1413
                }
1414
                $form->addGroup(
1415
                    $group,
1416
                    $row['variable'],
1417
                    [get_lang($row['title']), get_lang($row['comment'])],
1418
                    null
1419
                );
1420
                break;
1421
            case 'link':
1422
                $form->addElement(
1423
                    'static',
1424
                    null,
1425
                    [get_lang($row['title']), get_lang($row['comment'])],
1426
                    get_lang('current value').' : '.$row['selected_value'],
1427
                    $hideme
1428
                );
1429
                break;
1430
            case 'select':
1431
                /*
1432
                * 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.
1433
                * The functions being called must be added to the file settings.lib.php.
1434
                */
1435
                $form->addElement(
1436
                    'select',
1437
                    $row['variable'],
1438
                    [get_lang($row['title']), get_lang($row['comment'])],
1439
                    call_user_func('select_'.$row['variable']),
1440
                    $hideme
1441
                );
1442
                $default_values[$row['variable']] = $row['selected_value'];
1443
                break;
1444
            case 'custom':
1445
                break;
1446
            case 'select_course':
1447
                $courseSelectOptions = [];
1448
1449
                if (!empty($row['selected_value'])) {
1450
                    $course = $em->find(Course::class, $row['selected_value']);
1451
1452
                    $courseSelectOptions[$course->getId()] = $course->getTitle();
1453
                }
1454
1455
                $form->addElement(
1456
                    'select_ajax',
1457
                    $row['variable'],
1458
                    [get_lang($row['title']), get_lang($row['comment'])],
1459
                    $courseSelectOptions,
1460
                    ['url' => api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=search_course']
1461
                );
1462
                $default_values[$row['variable']] = $row['selected_value'];
1463
                break;
1464
        }
1465
1466
        switch ($row['variable']) {
1467
            case 'pdf_export_watermark_enable':
1468
                $url = PDF::get_watermark(null);
1469
1470
                if (false != $url) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $url of type string to the boolean false. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
1471
                    $delete_url = '<a href="?delete_watermark">'.get_lang('Remove picture').' '.Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Remove picture')).'</a>';
1472
                    $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>');
1473
                }
1474
1475
                $form->addElement('file', 'pdf_export_watermark_path', get_lang('Upload a watermark image'));
1476
                $allowed_picture_types = ['jpg', 'jpeg', 'png', 'gif'];
1477
                $form->addRule(
1478
                    'pdf_export_watermark_path',
1479
                    get_lang('Only PNG, JPG or GIF images allowed').' ('.implode(',', $allowed_picture_types).')',
1480
                    'filetype',
1481
                    $allowed_picture_types
1482
                );
1483
1484
                break;
1485
            case 'timezone_value':
1486
                $timezone = $row['selected_value'];
1487
                if (empty($timezone)) {
1488
                    $timezone = api_get_timezone();
1489
                }
1490
                $form->addLabel('', sprintf(get_lang('The local time in the portal timezone (%s) is %s'), $timezone, api_get_local_time()));
1491
                break;
1492
        }
1493
    } // end for
1494
1495
    if (!empty($settings)) {
1496
        $form->setDefaults($default_values);
1497
    }
1498
    $form->addHtml('<div class="bottom_actions">');
1499
    $form->addButtonSave(get_lang('Save settings'));
1500
    $form->addHtml('</div>');
1501
1502
    return $form;
1503
}
1504
1505
/**
1506
 * Searches a platform setting in all categories except from the Plugins category.
1507
 *
1508
 * @param string $search
1509
 *
1510
 * @return array
1511
 */
1512
function searchSetting($search)
1513
{
1514
    if (empty($search)) {
1515
        return [];
1516
    }
1517
    $table_settings_current = Database::get_main_table(TABLE_MAIN_SETTINGS);
1518
    $sql = "SELECT * FROM $table_settings_current
1519
            WHERE category <> 'Plugins' ORDER BY id ASC ";
1520
    $result = Database::store_result(Database::query($sql), 'ASSOC');
1521
    $settings = [];
1522
1523
    $search = api_strtolower($search);
1524
1525
    if (!empty($result)) {
1526
        foreach ($result as $setting) {
1527
            $found = false;
1528
1529
            $title = api_strtolower(get_lang($setting['title']));
1530
            // try the title
1531
            if (false === strpos($title, $search)) {
1532
                $comment = api_strtolower(get_lang($setting['comment']));
1533
                //Try the comment
1534
                if (false === strpos($comment, $search)) {
1535
                    //Try the variable name
1536
                    if (false === strpos($setting['variable'], $search)) {
1537
                        continue;
1538
                    } else {
1539
                        $found = true;
1540
                    }
1541
                } else {
1542
                    $found = true;
1543
                }
1544
            } else {
1545
                $found = true;
1546
            }
1547
            if ($found) {
1548
                $settings[] = $setting;
1549
            }
1550
        }
1551
    }
1552
1553
    return $settings;
1554
}
1555
/**
1556
 * Helper function to generates a form elements group.
1557
 *
1558
 * @param object $form   The form where the elements group has to be added
1559
 * @param array  $values Values to browse through
1560
 *
1561
 * @return array
1562
 */
1563
function formGenerateElementsGroup($form, $values = [], $elementName)
1564
{
1565
    $group = [];
1566
    if (is_array($values)) {
1567
        foreach ($values as $key => $value) {
1568
            $element = &$form->createElement('radio', $elementName, '', get_lang($value['display_text']), $value['value']);
1569
            $group[] = $element;
1570
        }
1571
    }
1572
1573
    return $group;
1574
}
1575
/**
1576
 * Helper function with allowed file types for CSS.
1577
 *
1578
 * @return array Array of file types (no indexes)
1579
 */
1580
function getAllowedFileTypes()
1581
{
1582
    $allowedFiles = [
1583
        'css',
1584
        'zip',
1585
        'jpeg',
1586
        'jpg',
1587
        'png',
1588
        'gif',
1589
        'ico',
1590
        'psd',
1591
        'xcf',
1592
        'svg',
1593
        'webp',
1594
        'woff',
1595
        'woff2',
1596
    ];
1597
1598
    return $allowedFiles;
1599
}
1600
/**
1601
 * Helper function to set settings in the database.
1602
 *
1603
 * @param array $parameters List of values
1604
 * @param int   $accessUrl  The current access URL
1605
 */
1606
function setConfigurationSettingsInDatabase($parameters, $accessUrl)
1607
{
1608
    api_set_settings_category('Search', 'false', $accessUrl);
1609
    // Save the settings.
1610
    foreach ($parameters as $key => $value) {
1611
        api_set_setting($key, $value, null, null);
1612
    }
1613
}
1614
1615
/**
1616
 * Helper function to show the status of the search settings table.
1617
 *
1618
 * @param array $data Data to show
1619
 */
1620
function showSearchSettingsTable($data)
1621
{
1622
    echo Display::tag('h3', get_lang('Settings'));
1623
    $table = new SortableTableFromArray($data);
1624
    $table->set_header(0, get_lang('Setting'), false);
1625
    $table->set_header(1, get_lang('Status'), false);
1626
    echo $table->display();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $table->display() targeting SortableTable::display() seems to always return null.

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

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

}

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

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

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

Loading history...
1627
}
1628
/**
1629
 * Helper function to show status table for each command line tool installed.
1630
 */
1631
function showSearchToolsStatusTable()
1632
{
1633
    //@todo windows support
1634
    if (false == api_is_windows_os()) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
1635
        $list_of_programs = ['pdftotext', 'ps2pdf', 'catdoc', 'html2text', 'unrtf', 'catppt', 'xls2csv'];
1636
        foreach ($list_of_programs as $program) {
1637
            $output = [];
1638
            $ret_val = null;
1639
            exec("which $program", $output, $ret_val);
1640
1641
            if (!$output) {
1642
                $output[] = '';
1643
            }
1644
1645
            $icon = Display::getMdiIcon(StateIcon::CLOSED_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Not installed'));
1646
            if (!empty($output[0])) {
1647
                $icon = Display::getMdiIcon(StateIcon::OPEN_VISIBILITY, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Installed'));
1648
            }
1649
            $data2[] = [$program, $output[0], $icon];
1650
        }
1651
        echo Display::tag('h3', get_lang('Programs needed to convert files'));
1652
        $table = new SortableTableFromArray($data2);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $data2 seems to be defined by a foreach iteration on line 1636. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1653
        $table->set_header(0, get_lang('Software program'), false);
1654
        $table->set_header(1, get_lang('Path'), false);
1655
        $table->set_header(2, get_lang('Status'), false);
1656
        echo $table->display();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $table->display() targeting SortableTable::display() seems to always return null.

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

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

}

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

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

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

Loading history...
1657
    } else {
1658
        echo Display::return_message(
1659
            get_lang('You are using Chamilo in a Windows platform, sadly you can\'t convert documents in order to search the content using this tool'),
1660
            'warning'
1661
        );
1662
    }
1663
}
1664
/**
1665
 * Helper function to generate and show CSS Zip download message.
1666
 *
1667
 * @param string $style Style path
1668
 */
1669
function generateCSSDownloadLink($style)
1670
{
1671
    $arch = api_get_path(SYS_ARCHIVE_PATH).$style.'.zip';
1672
    $themeDir = Template::getThemeDir($style);
1673
    $dir = api_get_path(SYS_CSS_PATH).$themeDir;
1674
    $check = Security::check_abs_path(
1675
        $dir,
1676
        api_get_path(SYS_CSS_PATH).'themes'
1677
    );
1678
    if (is_dir($dir) && $check) {
1679
        $zip = new PclZip($arch);
1680
        // Remove path prefix except the style name and put file on disk
1681
        $zip->create($dir, PCLZIP_OPT_REMOVE_PATH, substr($dir, 0, -strlen($style)));
0 ignored issues
show
Bug introduced by
The constant PCLZIP_OPT_REMOVE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1682
        $url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive_path=&archive='.str_replace(api_get_path(SYS_ARCHIVE_PATH), '', $arch);
1683
1684
        //@TODO: use more generic script to download.
1685
        $str = '<a class="btn btn--primary btn-large" href="'.$url.'">'.get_lang('Download the file').'</a>';
1686
        echo Display::return_message($str, 'normal', false);
1687
    } else {
1688
        echo Display::return_message(get_lang('The file was not found'), 'warning');
1689
    }
1690
}
1691
1692
/**
1693
 * Get all settings of one category prepared for display in admin/settings.php.
1694
 *
1695
 * @param string $category
1696
 *
1697
 * @return array
1698
 */
1699
function getCategorySettings($category = '')
1700
{
1701
    $url_id = api_get_current_access_url_id();
1702
    $settings_by_access_list = [];
1703
1704
    if (1 == $url_id) {
1705
        $settings = api_get_settings($category, 'group', $url_id);
1706
    } else {
1707
        $url_info = api_get_access_url($url_id);
1708
        if (1 == $url_info['active']) {
1709
            $categoryToSearch = $category;
1710
            if ('search_setting' == $category) {
1711
                $categoryToSearch = '';
1712
            }
1713
            // The default settings of Chamilo
1714
            $settings = api_get_settings($categoryToSearch, 'group', 1, 0);
1715
            // The settings that are changeable from a particular site.
1716
            $settings_by_access = api_get_settings($categoryToSearch, 'group', $url_id, 1);
1717
1718
            foreach ($settings_by_access as $row) {
1719
                if (empty($row['variable'])) {
1720
                    $row['variable'] = 0;
1721
                }
1722
                if (empty($row['subkey'])) {
1723
                    $row['subkey'] = 0;
1724
                }
1725
                if (empty($row['category'])) {
1726
                    $row['category'] = 0;
1727
                }
1728
1729
                // One more validation if is changeable.
1730
                if (1 == $row['access_url_changeable']) {
1731
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = $row;
1732
                } else {
1733
                    $settings_by_access_list[$row['variable']][$row['subkey']][$row['category']] = [];
1734
                }
1735
            }
1736
        }
1737
    }
1738
1739
    if (isset($category) && 'search_setting' == $category) {
1740
        if (!empty($_REQUEST['search_field'])) {
1741
            $settings = searchSetting($_REQUEST['search_field']);
1742
        }
1743
    }
1744
1745
    return [
1746
        'settings' => $settings,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $settings does not seem to be defined for all execution paths leading up to this point.
Loading history...
1747
        'settings_by_access_list' => $settings_by_access_list,
1748
    ];
1749
}
1750