Passed
Push — 1.11.x ( 229e01...681b6c )
by Julito
09:59
created

AppPlugin::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
/* See license terms in /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * Class AppPlugin.
8
 */
9
class AppPlugin
10
{
11
    public $plugin_regions = [
12
        'main_top',
13
        'main_bottom',
14
        'login_top',
15
        'login_bottom',
16
        'menu_top',
17
        'menu_bottom',
18
        'content_top',
19
        'content_bottom',
20
        'header_main',
21
        'header_center',
22
        'header_left',
23
        'header_right',
24
        'pre_footer',
25
        'footer_left',
26
        'footer_center',
27
        'footer_right',
28
        'menu_administrator',
29
        'course_tool_plugin',
30
    ];
31
32
    public $installedPluginListName = [];
33
    public $installedPluginListObject = [];
34
    private static $instance;
35
36
    /**
37
     * Constructor.
38
     */
39
    public function __construct()
40
    {
41
    }
42
43
    /**
44
     * @return AppPlugin
45
     */
46
    public static function getInstance()
47
    {
48
        if (!isset(self::$instance)) {
49
            self::$instance = new self();
50
        }
51
52
        return self::$instance;
53
    }
54
55
    /**
56
     * Read plugin from path.
57
     *
58
     * @return array
59
     */
60
    public function read_plugins_from_path()
61
    {
62
        /* We scan the plugin directory. Each folder is a potential plugin. */
63
        $pluginPath = api_get_path(SYS_PLUGIN_PATH);
64
        $plugins = [];
65
        $handle = @opendir($pluginPath);
66
        while (false !== ($file = readdir($handle))) {
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $dir_handle of readdir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

66
        while (false !== ($file = readdir(/** @scrutinizer ignore-type */ $handle))) {
Loading history...
67
            if ($file != '.' && $file != '..' && is_dir(api_get_path(SYS_PLUGIN_PATH).$file)) {
68
                $plugins[] = $file;
69
            }
70
        }
71
        @closedir($handle);
0 ignored issues
show
Bug introduced by
Are you sure the usage of closedir($handle) is correct as it 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...
Bug introduced by
It seems like $handle can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

71
        @closedir(/** @scrutinizer ignore-type */ $handle);
Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition for closedir(). 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

71
        /** @scrutinizer ignore-unhandled */ @closedir($handle);

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...
72
        sort($plugins);
73
74
        return $plugins;
75
    }
76
77
    /**
78
     * @return array
79
     */
80
    public function getInstalledPluginListName()
81
    {
82
        if (empty($this->installedPluginListName)) {
83
            $this->installedPluginListName = $this->getInstalledPlugins();
84
        }
85
86
        return $this->installedPluginListName;
87
    }
88
89
    /**
90
     * @return array List of Plugin
91
     */
92
    public function getInstalledPluginListObject()
93
    {
94
        if (empty($this->installedPluginListObject)) {
95
            $this->setInstalledPluginListObject();
96
        }
97
98
        return $this->installedPluginListObject;
99
    }
100
101
    public function setInstalledPluginListObject()
102
    {
103
        $pluginListName = $this->getInstalledPluginListName();
104
        $pluginList = [];
105
        if (!empty($pluginListName)) {
106
            foreach ($pluginListName as $pluginName) {
107
                $pluginInfo = $this->getPluginInfo($pluginName, true);
108
                if (isset($pluginInfo['plugin_class'])) {
109
                    $pluginList[] = $pluginInfo['plugin_class']::create();
110
                }
111
            }
112
        }
113
        $this->installedPluginListObject = $pluginList;
114
    }
115
116
    /**
117
     * @param string $plugin
118
     *
119
     * @return bool
120
     */
121
    public function isInstalled($plugin)
122
    {
123
        $list = self::getInstalledPlugins(false);
0 ignored issues
show
Bug Best Practice introduced by
The method AppPlugin::getInstalledPlugins() is not static, but was called statically. ( Ignorable by Annotation )

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

123
        /** @scrutinizer ignore-call */ 
124
        $list = self::getInstalledPlugins(false);
Loading history...
124
125
        return in_array($plugin, $list);
126
    }
127
128
    /**
129
     * Returns a list of all installed plugins.
130
     *
131
     * @param bool $fromDatabase
132
     *
133
     * @return array
134
     */
135
    public function getInstalledPlugins($fromDatabase = true)
136
    {
137
        static $installedPlugins = null;
138
139
        if ($fromDatabase === false) {
140
            if (is_array($installedPlugins)) {
141
                return $installedPlugins;
142
            }
143
        }
144
145
        if ($fromDatabase || $installedPlugins === null) {
146
            $installedPlugins = [];
147
            $plugins = api_get_settings_params(
148
                [
149
                    'variable = ? AND selected_value = ? AND category = ? ' => ['status', 'installed', 'Plugins'],
150
                ]
151
            );
152
153
            if (!empty($plugins)) {
154
                foreach ($plugins as $row) {
155
                    $installedPlugins[$row['subkey']] = true;
156
                }
157
                $installedPlugins = array_keys($installedPlugins);
158
            }
159
        }
160
161
        return $installedPlugins;
162
    }
163
164
    /**
165
     * Returns a list of all official (delivered with the Chamilo package)
166
     * plugins. This list is maintained manually and updated with every new
167
     * release to avoid hacking.
168
     *
169
     * @return array
170
     */
171
    public function getOfficialPlugins()
172
    {
173
        static $officialPlugins = null;
174
        // Please keep this list alphabetically sorted
175
        $officialPlugins = [
176
            'add_cas_login_button',
177
            'add_cas_logout_button',
178
            'add_facebook_login_button',
179
            'add_shibboleth_login_button',
180
            'advanced_subscription',
181
            'azure_active_directory',
182
            'bbb',
183
            'before_login',
184
            'buycourses',
185
            'card_game',
186
            'clockworksms',
187
            'courseblock',
188
            'coursehomenotify',
189
            'courselegal',
190
            'createdrupaluser',
191
            'customcertificate',
192
            'customfooter',
193
            'dashboard',
194
            'date',
195
            'dictionary',
196
            'embedregistry',
197
            'ext_auth_chamilo_logout_button_behaviour',
198
            'follow_buttons',
199
            'formLogin_hide_unhide',
200
            'google_maps',
201
            'grading_electronic',
202
            'hello_world',
203
            'ims_lti',
204
            'jcapture',
205
            'justification',
206
            'kannelsms',
207
            'keycloak',
208
            'learning_calendar',
209
            'maintenancemode',
210
            'migrationmoodle',
211
            'nosearchindex',
212
            'notebookteacher',
213
            'olpc_peru_filter',
214
            'openmeetings',
215
            'pens',
216
            'questionoptionsevaluation',
217
            'redirection',
218
            'reports',
219
            'resubscription',
220
            'rss',
221
            'search_course',
222
            'sepe',
223
            'share_buttons',
224
            'show_regions',
225
            'show_user_info',
226
            'static',
227
            'studentfollowup',
228
            'surveyexportcsv',
229
            'surveyexporttxt',
230
            'test2pdf',
231
            'tour',
232
            'vchamilo',
233
            'whispeakauth',
234
        ];
235
236
        return $officialPlugins;
237
    }
238
239
    /**
240
     * @param string $pluginName
241
     * @param int    $urlId
242
     */
243
    public function install($pluginName, $urlId = null)
244
    {
245
        $urlId = (int) $urlId;
246
        if (empty($urlId)) {
247
            $urlId = api_get_current_access_url_id();
248
        }
249
250
        api_add_setting(
251
            'installed',
252
            'status',
253
            $pluginName,
254
            'setting',
255
            'Plugins',
256
            $pluginName,
257
            '',
258
            '',
259
            '',
260
            $urlId,
261
            1
262
        );
263
264
        $pluginPath = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/install.php';
265
266
        if (is_file($pluginPath) && is_readable($pluginPath)) {
267
            // Execute the install procedure.
268
269
            require $pluginPath;
270
        }
271
    }
272
273
    /**
274
     * @param string $pluginName
275
     * @param int    $urlId
276
     */
277
    public function uninstall($pluginName, $urlId = null)
278
    {
279
        $urlId = (int) $urlId;
280
        if (empty($urlId)) {
281
            $urlId = api_get_current_access_url_id();
282
        }
283
284
        // First call the custom uninstall to allow full access to global settings
285
        $pluginPath = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/uninstall.php';
286
        if (is_file($pluginPath) && is_readable($pluginPath)) {
287
            // Execute the uninstall procedure.
288
289
            require $pluginPath;
290
        }
291
292
        // Second remove all remaining global settings
293
        api_delete_settings_params(
294
            ['category = ? AND access_url = ? AND subkey = ? ' => ['Plugins', $urlId, $pluginName]]
295
        );
296
    }
297
298
    /**
299
     * @param string $pluginName
300
     *
301
     * @return array
302
     */
303
    public function get_areas_by_plugin($pluginName)
304
    {
305
        $result = api_get_settings('Plugins');
306
        $areas = [];
307
        foreach ($result as $row) {
308
            if ($pluginName == $row['selected_value']) {
309
                $areas[] = $row['variable'];
310
            }
311
        }
312
313
        return $areas;
314
    }
315
316
    /**
317
     * @param string $pluginName
318
     *
319
     * @return bool
320
     */
321
    public function is_valid_plugin($pluginName)
322
    {
323
        if (is_dir(api_get_path(SYS_PLUGIN_PATH).$pluginName)) {
324
            if (is_file(api_get_path(SYS_PLUGIN_PATH).$pluginName.'/index.php')) {
325
                return true;
326
            }
327
        }
328
329
        return false;
330
    }
331
332
    /**
333
     * @return array
334
     */
335
    public function get_plugin_regions()
336
    {
337
        sort($this->plugin_regions);
338
339
        return $this->plugin_regions;
340
    }
341
342
    /**
343
     * @param string   $region
344
     * @param Template $template
345
     * @param bool     $forced
346
     *
347
     * @return string|null
348
     */
349
    public function load_region($region, $template, $forced = false)
350
    {
351
        if ($region == 'course_tool_plugin') {
352
            return '';
353
        }
354
355
        ob_start();
356
        $this->get_all_plugin_contents_by_region($region, $template, $forced);
357
        $content = ob_get_contents();
358
        ob_end_clean();
359
360
        return $content;
361
    }
362
363
    /**
364
     * Loads the translation files inside a plugin if exists.
365
     * It loads by default english see the hello world plugin.
366
     *
367
     * @param string $plugin_name
368
     *
369
     * @todo add caching
370
     */
371
    public function load_plugin_lang_variables($plugin_name)
372
    {
373
        global $language_interface;
374
        $root = api_get_path(SYS_PLUGIN_PATH);
375
        $strings = null;
376
377
        // 1. Loading english if exists
378
        $english_path = $root.$plugin_name."/lang/english.php";
379
380
        if (is_readable($english_path)) {
381
            include $english_path;
382
383
            foreach ($strings as $key => $string) {
0 ignored issues
show
Bug introduced by
The expression $strings of type null is not traversable.
Loading history...
384
                $GLOBALS[$key] = $string;
385
            }
386
        }
387
388
        // 2. Loading the system language
389
        if ($language_interface != 'english') {
390
            $path = $root.$plugin_name."/lang/$language_interface.php";
391
392
            if (is_readable($path)) {
393
                include $path;
394
                if (!empty($strings)) {
395
                    foreach ($strings as $key => $string) {
396
                        $GLOBALS[$key] = $string;
397
                    }
398
                }
399
            } else {
400
                $interfaceLanguageId = api_get_language_id($language_interface);
401
                $interfaceLanguageInfo = api_get_language_info($interfaceLanguageId);
402
                $languageParentId = intval($interfaceLanguageInfo['parent_id']);
403
404
                if ($languageParentId > 0) {
405
                    $languageParentInfo = api_get_language_info($languageParentId);
406
                    $languageParentFolder = $languageParentInfo['dokeos_folder'];
407
408
                    $parentPath = "{$root}{$plugin_name}/lang/{$languageParentFolder}.php";
409
                    if (is_readable($parentPath)) {
410
                        include $parentPath;
411
                        if (!empty($strings)) {
412
                            foreach ($strings as $key => $string) {
413
                                $this->strings[$key] = $string;
0 ignored issues
show
Bug Best Practice introduced by
The property strings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
414
                            }
415
                        }
416
                    }
417
                }
418
            }
419
        }
420
    }
421
422
    /**
423
     * @param string   $region
424
     * @param Template $template
425
     * @param bool     $forced
426
     *
427
     * @return bool
428
     *
429
     * @todo improve this function
430
     */
431
    public function get_all_plugin_contents_by_region($region, $template, $forced = false)
432
    {
433
        global $_plugins;
434
        if (isset($_plugins[$region]) && is_array($_plugins[$region])) {
435
            // Load the plugin information
436
            foreach ($_plugins[$region] as $plugin_name) {
437
                // The plugin_info variable is available inside the plugin index
438
                $plugin_info = $this->getPluginInfo($plugin_name, $forced);
439
440
                // We also know where the plugin is
441
                $plugin_info['current_region'] = $region;
442
443
                // Loading the plugin/XXX/index.php file
444
                $plugin_file = api_get_path(SYS_PLUGIN_PATH)."$plugin_name/index.php";
445
446
                if (file_exists($plugin_file)) {
447
                    //Loading the lang variables of the plugin if exists
448
                    self::load_plugin_lang_variables($plugin_name);
0 ignored issues
show
Bug Best Practice introduced by
The method AppPlugin::load_plugin_lang_variables() is not static, but was called statically. ( Ignorable by Annotation )

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

448
                    self::/** @scrutinizer ignore-call */ 
449
                          load_plugin_lang_variables($plugin_name);
Loading history...
449
450
                    // Printing the plugin index.php file
451
                    require $plugin_file;
452
453
                    // If the variable $_template is set we assign those values to be accessible in Twig
454
                    if (isset($_template)) {
455
                        $_template['plugin_info'] = $plugin_info;
456
                    } else {
457
                        $_template = [];
458
                        $_template['plugin_info'] = $plugin_info;
459
                    }
460
461
                    // Setting the plugin info available in the template if exists.
462
                    $template->assign($plugin_name, $_template);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $_template does not seem to be defined for all execution paths leading up to this point.
Loading history...
463
464
                    // Loading the Twig template plugin files if exists
465
                    $template_list = [];
466
                    if (isset($plugin_info) && isset($plugin_info['templates'])) {
467
                        $template_list = $plugin_info['templates'];
468
                    }
469
470
                    if (!empty($template_list)) {
471
                        foreach ($template_list as $plugin_tpl) {
472
                            if (!empty($plugin_tpl)) {
473
                                $template_plugin_file = "$plugin_name/$plugin_tpl"; // for twig
474
                                $template->display($template_plugin_file, false);
475
                            }
476
                        }
477
                    }
478
                }
479
            }
480
        }
481
482
        return true;
483
    }
484
485
    /**
486
     * Loads plugin info.
487
     *
488
     * @staticvar array $plugin_data
489
     *
490
     * @param string $plugin_name
491
     * @param bool   $forced      load from DB or from the static array
492
     *
493
     * @return array
494
     *
495
     * @todo filter setting_form
496
     */
497
    public function getPluginInfo($plugin_name, $forced = false)
498
    {
499
        $pluginData = Session::read('plugin_data');
500
        if (isset($pluginData[$plugin_name]) && $forced == false) {
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...
501
            return $pluginData[$plugin_name];
502
        } else {
503
            $plugin_file = api_get_path(SYS_PLUGIN_PATH)."$plugin_name/plugin.php";
504
505
            $plugin_info = [];
506
            if (file_exists($plugin_file)) {
507
                require $plugin_file;
508
            }
509
510
            // @todo check if settings are already added
511
            // Extra options
512
            $plugin_settings = api_get_settings_params(
513
                [
514
                    "subkey = ? AND category = ? AND type = ? AND access_url = ?" => [
515
                        $plugin_name,
516
                        'Plugins',
517
                        'setting',
518
                        api_get_current_access_url_id(),
519
                    ],
520
                ]
521
            );
522
523
            $settings_filtered = [];
524
            foreach ($plugin_settings as $item) {
525
                if (!empty($item['selected_value'])) {
526
                    $unserialized = UnserializeApi::unserialize('not_allowed_classes', $item['selected_value'], true);
527
                    if (false !== $unserialized) {
528
                        $item['selected_value'] = $unserialized;
529
                    }
530
                }
531
                $settings_filtered[$item['variable']] = $item['selected_value'];
532
            }
533
            $plugin_info['settings'] = $settings_filtered;
534
            $pluginData[$plugin_name] = $plugin_info;
535
            Session::write('plugin_data', $pluginData);
536
537
            return $plugin_info;
538
        }
539
    }
540
541
    /**
542
     * Get the template list.
543
     *
544
     * @param string $pluginName
545
     *
546
     * @return bool
547
     */
548
    public function get_templates_list($pluginName)
549
    {
550
        $plugin_info = $this->getPluginInfo($pluginName);
551
        if (isset($plugin_info) && isset($plugin_info['templates'])) {
552
            return $plugin_info['templates'];
553
        }
554
555
        return false;
556
    }
557
558
    /**
559
     * Remove all regions of an specific plugin.
560
     *
561
     * @param string $plugin
562
     */
563
    public function remove_all_regions($plugin)
564
    {
565
        $access_url_id = api_get_current_access_url_id();
566
        if (!empty($plugin)) {
567
            api_delete_settings_params(
568
                [
569
                    'category = ? AND type = ? AND access_url = ? AND subkey = ? ' => [
570
                        'Plugins',
571
                        'region',
572
                        $access_url_id,
573
                        $plugin,
574
                    ],
575
                ]
576
            );
577
        }
578
    }
579
580
    /**
581
     * Add a plugin to a region.
582
     *
583
     * @param string $plugin
584
     * @param string $region
585
     */
586
    public function add_to_region($plugin, $region)
587
    {
588
        api_add_setting(
589
            $plugin,
590
            $region,
591
            $plugin,
592
            'region',
593
            'Plugins',
594
            $plugin,
595
            '',
596
            '',
597
            '',
598
            api_get_current_access_url_id(),
599
            1
600
        );
601
    }
602
603
    /**
604
     * @param int $courseId
605
     */
606
    public function install_course_plugins($courseId)
607
    {
608
        $pluginList = $this->getInstalledPluginListObject();
609
610
        if (!empty($pluginList)) {
611
            /** @var Plugin $obj */
612
            foreach ($pluginList as $obj) {
613
                $pluginName = $obj->get_name();
614
                $plugin_path = api_get_path(SYS_PLUGIN_PATH).$pluginName.'/plugin.php';
615
616
                if (file_exists($plugin_path)) {
617
                    require $plugin_path;
618
                    if (isset($plugin_info) && isset($plugin_info['plugin_class']) && $obj->isCoursePlugin) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $plugin_info does not exist. Did you maybe mean $plugin_path?
Loading history...
619
                        $obj->course_install($courseId);
620
                    }
621
                }
622
            }
623
        }
624
    }
625
626
    /**
627
     * Trigger for Plugin::doWhenDeleting[Item] functions.
628
     *
629
     * @param string $itemType
630
     * @param int    $itemId
631
     */
632
    public function performActionsWhenDeletingItem($itemType, $itemId)
633
    {
634
        $pluginList = $this->getInstalledPluginListObject();
635
636
        if (empty($pluginList)) {
637
            return;
638
        }
639
640
        /** @var Plugin $pluginObj */
641
        foreach ($pluginList as $pluginObj) {
642
            switch ($itemType) {
643
                case 'course':
644
                    $pluginObj->doWhenDeletingCourse($itemId);
645
                    break;
646
                case 'session':
647
                    $pluginObj->doWhenDeletingSession($itemId);
648
                    break;
649
                case 'user':
650
                    $pluginObj->doWhenDeletingUser($itemId);
651
                    break;
652
            }
653
        }
654
    }
655
656
    /**
657
     * Add the course settings to the course settings form.
658
     *
659
     * @param FormValidator $form
660
     */
661
    public function add_course_settings_form($form)
662
    {
663
        $pluginList = $this->getInstalledPluginListObject();
664
        /** @var Plugin $obj */
665
        foreach ($pluginList as $obj) {
666
            $plugin_name = $obj->get_name();
667
            $pluginTitle = $obj->get_title();
668
            if (!empty($obj->course_settings)) {
669
                if (is_file(api_get_path(SYS_CODE_PATH).'img/icons/'.ICON_SIZE_SMALL.'/'.$plugin_name.'.png')) {
670
                    $icon = Display::return_icon(
671
                        $plugin_name.'.png',
672
                        Security::remove_XSS($pluginTitle),
673
                        '',
674
                        ICON_SIZE_SMALL
675
                    );
676
                } else {
677
                    $icon = Display::return_icon(
678
                        'plugins.png',
679
                        Security::remove_XSS($pluginTitle),
680
                        '',
681
                        ICON_SIZE_SMALL
682
                    );
683
                }
684
685
                $form->addHtml('<div class="panel panel-default">');
686
                $form->addHtml('
687
                    <div class="panel-heading" role="tab" id="heading-'.$plugin_name.'-settings">
688
                        <h4 class="panel-title">
689
                            <a class="collapsed"
690
                                role="button" data-toggle="collapse" data-parent="#accordion"
691
                                href="#collapse-'.$plugin_name.'-settings" aria-expanded="false"
692
                                aria-controls="collapse-'.$plugin_name.'-settings">
693
                ');
694
                $form->addHtml($icon.' '.$pluginTitle);
695
                $form->addHtml('
696
                            </a>
697
                        </h4>
698
                    </div>
699
                ');
700
                $form->addHtml('
701
                    <div
702
                        id="collapse-'.$plugin_name.'-settings"
703
                        class="panel-collapse collapse" role="tabpanel"
704
                        aria-labelledby="heading-'.$plugin_name.'-settings">
705
                        <div class="panel-body">
706
                ');
707
708
                $groups = [];
709
                foreach ($obj->course_settings as $setting) {
710
                    if ($obj->validateCourseSetting($setting['name']) === false) {
711
                        continue;
712
                    }
713
                    if ($setting['type'] !== 'checkbox') {
714
                        $form->addElement($setting['type'], $setting['name'], $obj->get_lang($setting['name']));
715
                    } else {
716
                        $element = &$form->createElement(
717
                            $setting['type'],
718
                            $setting['name'],
719
                            '',
720
                            $obj->get_lang($setting['name'])
721
                        );
722
723
                        // Check global settings
724
                        $courseSetting = api_get_course_setting($setting['name']);
725
                        if (-1 === $courseSetting) {
726
                            $defaultValue = api_get_plugin_setting($plugin_name, $setting['name']);
727
                            if (!empty($defaultValue)) {
728
                                if ('true' === $defaultValue) {
729
                                    $element->setChecked(true);
730
                                }
731
                            }
732
                        }
733
734
                        if (isset($setting['init_value']) && $setting['init_value'] == 1) {
735
                            $element->setChecked(true);
736
                        }
737
738
                        $form->addElement($element);
739
                        if (isset($setting['group'])) {
740
                            $groups[$setting['group']][] = $element;
741
                        }
742
                    }
743
                }
744
                foreach ($groups as $k => $v) {
745
                    $form->addGroup($groups[$k], $k, [$obj->get_lang($k)]);
746
                }
747
                $form->addButtonSave(get_lang('SaveSettings'));
748
                $form->addHtml('
749
                        </div>
750
                    </div>
751
                ');
752
                $form->addHtml('</div>');
753
            }
754
        }
755
    }
756
757
    /**
758
     * Get all course settings from all installed plugins.
759
     *
760
     * @return array
761
     */
762
    public function getAllPluginCourseSettings()
763
    {
764
        $pluginList = $this->getInstalledPluginListObject();
765
        /** @var Plugin $obj */
766
        $courseSettings = [];
767
        if (!empty($pluginList)) {
768
            foreach ($pluginList as $obj) {
769
                $pluginCourseSetting = $obj->getCourseSettings();
770
                $courseSettings = array_merge($courseSettings, $pluginCourseSetting);
771
            }
772
        }
773
774
        return $courseSettings;
775
    }
776
777
    /**
778
     * When saving the plugin values in the course settings, check whether
779
     * a callback method should be called and send it the updated settings.
780
     *
781
     * @param array $values The new settings the user just saved
782
     */
783
    public function saveCourseSettingsHook($values)
784
    {
785
        $pluginList = $this->getInstalledPluginListObject();
786
787
        /** @var Plugin $obj */
788
        foreach ($pluginList as $obj) {
789
            $settings = $obj->getCourseSettings();
790
            $subValues = [];
791
            if (!empty($settings)) {
792
                foreach ($settings as $v) {
793
                    if (isset($values[$v])) {
794
                        $subValues[$v] = $values[$v];
795
                    }
796
                }
797
            }
798
799
            if (!empty($subValues)) {
800
                $obj->course_settings_updated($subValues);
801
            }
802
        }
803
    }
804
805
    /**
806
     * Get first SMS plugin name.
807
     *
808
     * @return string|bool
809
     */
810
    public function getSMSPluginName()
811
    {
812
        $installedPluginsList = $this->getInstalledPluginListObject();
813
        foreach ($installedPluginsList as $installedPlugin) {
814
            if ($installedPlugin->isMailPlugin) {
815
                return get_class($installedPlugin);
816
            }
817
        }
818
819
        return false;
820
    }
821
822
    /**
823
     * @return SmsPluginLibraryInterface
824
     */
825
    public function getSMSPluginLibrary()
826
    {
827
        $className = $this->getSMSPluginName();
828
        $className = str_replace('Plugin', '', $className);
829
830
        if (class_exists($className)) {
831
            return new $className();
832
        }
833
834
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type SmsPluginLibraryInterface.
Loading history...
835
    }
836
}
837