Passed
Push — master ( a02707...7dc539 )
by Julito
12:00
created

AppPlugin::getAllPluginContentsByRegion()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 46
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 19
nc 9
nop 4
dl 0
loc 46
rs 8.4444
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))) {
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...
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
     * @deprecated
130
     */
131
    public function get_installed_plugins($fromDatabase = true)
132
    {
133
        return $this->getInstalledPlugins($fromDatabase);
134
    }
135
136
    /**
137
     * @param bool $fromDatabase
138
     *
139
     * @return array
140
     */
141
    public function getInstalledPlugins($fromDatabase = true)
142
    {
143
        // @todo restore plugin loading
144
        return [];
145
146
        static $installedPlugins = null;
0 ignored issues
show
Unused Code introduced by
StaticNode is not reachable.

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

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

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

    return false;
}

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

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

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