Test Setup Failed
Push — master ( 4e700f...c7183e )
by Julito
63:12
created

Plugin   D

Complexity

Total Complexity 104

Size/Duplication

Total Lines 827
Duplicated Lines 7.86 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
dl 65
loc 827
rs 4
c 0
b 0
f 0
wmc 104
lcom 1
cbo 7

30 Methods

Rating   Name   Duplication   Size   Complexity  
A course_install() 0 4 1
A __construct() 0 9 1
B get_info() 0 28 4
A get_name() 0 8 1
A getCamelCaseName() 0 5 1
A get_title() 0 4 1
A get_comment() 0 4 1
A get_version() 0 4 1
A get_author() 0 4 1
A get_css() 0 13 2
F get_settings_form() 4 91 20
A get() 0 11 3
A get_settings() 0 13 3
A get_lang_plugin_exists() 0 4 1
C get_lang() 0 38 7
C install_course_fields() 25 74 11
B createLinkToCourseTool() 0 41 5
B uninstall_course_fields() 0 32 6
A install_course_fields_in_all_courses() 10 10 2
A uninstall_course_fields_in_all_courses() 11 11 2
B getCourseSettings() 0 17 5
A course_settings_updated() 0 4 1
B addTab() 0 70 5
C deleteTab() 0 42 7
A updateTab() 0 9 1
B manageTab() 15 28 4
A validateCourseSetting() 0 4 1
A renderRegion() 0 4 1
A isEnabled() 0 12 4
A performActionsAfterConfigure() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Plugin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Plugin, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CTool;
5
6
/**
7
 * Class Plugin
8
 * Base class for plugins
9
 *
10
 * This class has to be extended by every plugin. It defines basic methods
11
 * to install/uninstall and get information about a plugin
12
 *
13
 * @author    Julio Montoya <[email protected]>
14
 * @author    Yannick Warnier <[email protected]>
15
 * @author    Laurent Opprecht    <[email protected]>
16
 * @copyright 2012 University of Geneva
17
 * @license   GNU General Public License - http://www.gnu.org/copyleft/gpl.html
18
 *
19
 */
20
class Plugin
21
{
22
    protected $version = '';
23
    protected $author = '';
24
    protected $fields = [];
25
    private $settings = [];
26
    // Translation strings.
27
    private $strings = null;
28
    public $isCoursePlugin = false;
29
    public $isAdminPlugin = false;
30
    public $isMailPlugin = false;
31
    // Adds icon in the course home
32
    public $addCourseTool = true;
33
34
    /**
35
     * When creating a new course, these settings are added to the course, in
36
     * the course_info/infocours.php
37
     * To show the plugin course icons you need to add these icons:
38
     * main/img/icons/22/plugin_name.png
39
     * main/img/icons/64/plugin_name.png
40
     * main/img/icons/64/plugin_name_na.png
41
     * @example
42
     * $course_settings = array(
43
    array('name' => 'big_blue_button_welcome_message',  'type' => 'text'),
44
    array('name' => 'big_blue_button_record_and_store', 'type' => 'checkbox')
45
    );
46
     */
47
    public $course_settings = array();
48
    /**
49
     * This indicates whether changing the setting should execute the callback
50
     * function.
51
     */
52
    public $course_settings_callback = false;
53
54
    const TAB_FILTER_NO_STUDENT = '::no-student';
55
    const TAB_FILTER_ONLY_STUDENT = '::only-student';
56
57
    /**
58
     * Default constructor for the plugin class. By default, it only sets
59
     * a few attributes of the object
60
     * @param string $version   of this plugin
61
     * @param string $author    of this plugin
62
     * @param array  $settings  settings to be proposed to configure the plugin
63
     */
64
    protected function __construct($version, $author, $settings = array())
65
    {
66
        $this->version = $version;
67
        $this->author = $author;
68
        $this->fields = $settings;
69
70
        global $language_files;
71
        $language_files[] = 'plugin_'.$this->get_name();
72
    }
73
74
    /**
75
     * Gets an array of information about this plugin (name, version, ...)
76
     * @return  array Array of information elements about this plugin
77
     */
78
    public function get_info()
79
    {
80
        $result = array();
81
        $result['obj'] = $this;
82
        $result['title'] = $this->get_title();
83
        $result['comment'] = $this->get_comment();
84
        $result['version'] = $this->get_version();
85
        $result['author'] = $this->get_author();
86
        $result['plugin_class'] = get_class($this);
87
        $result['is_course_plugin'] = $this->isCoursePlugin;
88
        $result['is_admin_plugin'] = $this->isAdminPlugin;
89
        $result['is_mail_plugin'] = $this->isMailPlugin;
90
91
        if ($form = $this->get_settings_form()) {
92
            $result['settings_form'] = $form;
93
94
            foreach ($this->fields as $name => $type) {
95
                $value = $this->get($name);
96
97
                if (is_array($type)) {
98
                    $value = $type['options'];
99
                }
100
                $result[$name] = $value;
101
            }
102
        }
103
104
        return $result;
105
    }
106
107
    /**
108
     * Returns the "system" name of the plugin in lowercase letters
109
     * @return string
110
     */
111
    public function get_name()
112
    {
113
        $result = get_class($this);
114
        $result = str_replace('Plugin', '', $result);
115
        $result = strtolower($result);
116
117
        return $result;
118
    }
119
120
    /**
121
     * @return string
122
     */
123
    public function getCamelCaseName()
124
    {
125
        $result = get_class($this);
126
        return str_replace('Plugin', '', $result);
127
    }
128
129
    /**
130
     * Returns the title of the plugin
131
     * @return string
132
     */
133
    public function get_title()
134
    {
135
        return $this->get_lang('plugin_title');
136
    }
137
138
    /**
139
     * Returns the description of the plugin
140
     * @return string
141
     */
142
    public function get_comment()
143
    {
144
        return $this->get_lang('plugin_comment');
145
    }
146
147
    /**
148
     * Returns the version of the plugin
149
     * @return string
150
     */
151
    public function get_version()
152
    {
153
        return $this->version;
154
    }
155
156
    /**
157
     * Returns the author of the plugin
158
     * @return string
159
     */
160
    public function get_author()
161
    {
162
        return $this->author;
163
    }
164
165
    /**
166
     * Returns the contents of the CSS defined by the plugin
167
     * @return string
168
     */
169
    public function get_css()
170
    {
171
        $name = $this->get_name();
172
        $path = api_get_path(SYS_PLUGIN_PATH)."$name/resources/$name.css";
173
        if (!is_readable($path)) {
174
            return '';
175
        }
176
        $css = array();
177
        $css[] = file_get_contents($path);
178
        $result = implode($css);
179
180
        return $result;
181
    }
182
183
    /**
184
     * Returns an HTML form (generated by FormValidator) of the plugin settings
185
     * @return FormValidator FormValidator-generated form
186
     */
187
    public function get_settings_form()
188
    {
189
        $result = new FormValidator($this->get_name());
190
191
        $defaults = array();
192
        $checkboxGroup = array();
193
        $checkboxCollection = array();
194
195
        if ($checkboxNames = array_keys($this->fields, 'checkbox')) {
196
            $pluginInfoCollection = api_get_settings('Plugins');
197
            foreach ($pluginInfoCollection as $pluginInfo) {
198
                if (array_search($pluginInfo['title'], $checkboxNames) !== false) {
199
                    $checkboxCollection[$pluginInfo['title']] = $pluginInfo;
200
                }
201
            }
202
        }
203
204
        foreach ($this->fields as $name => $type) {
205
            $options = null;
206 View Code Duplication
            if (is_array($type) && isset($type['type']) && $type['type'] === 'select') {
207
                $options = $type['options'];
208
                $type = $type['type'];
209
            }
210
211
            $value = $this->get($name);
212
            $defaults[$name] = $value;
213
            $type = isset($type) ? $type : 'text';
214
215
            $help = null;
216
            if ($this->get_lang_plugin_exists($name.'_help')) {
217
                $help = $this->get_lang($name.'_help');
218
                if ($name === "show_main_menu_tab") {
219
                    $pluginName = strtolower(str_replace('Plugin', '', get_class($this)));
220
                    $pluginUrl = api_get_path(WEB_PATH)."plugin/$pluginName/index.php";
221
                    $pluginUrl = "<a href=$pluginUrl>$pluginUrl</a>";
222
                    $help = sprintf($help, $pluginUrl);
223
                }
224
            }
225
226
            switch ($type) {
227
                case 'html':
228
                    $result->addElement('html', $this->get_lang($name));
229
                    break;
230
                case 'wysiwyg':
231
                    $result->addHtmlEditor($name, $this->get_lang($name), false);
232
                    break;
233
                case 'text':
234
                    $result->addElement($type, $name, array($this->get_lang($name), $help));
235
                    break;
236
                case 'boolean':
237
                    $group = array();
238
                    $group[] = $result->createElement('radio', $name, '', get_lang('Yes'), 'true');
239
                    $group[] = $result->createElement('radio', $name, '', get_lang('No'), 'false');
240
                    $result->addGroup($group, null, array($this->get_lang($name), $help));
241
                    break;
242
                case 'checkbox':
243
                    $selectedValue = null;
244
                    if (isset($checkboxCollection[$name])) {
245
                        if ($checkboxCollection[$name]['selected_value'] === 'true') {
246
                            $selectedValue = 'checked';
247
                        }
248
                    }
249
                    $element = $result->createElement(
250
                        $type,
251
                        $name,
252
                        '',
253
                        $this->get_lang($name),
254
                        $selectedValue
255
                    );
256
                    $element->_attributes['value'] = 'true';
257
                    $checkboxGroup[] = $element;
258
                    break;
259
                case 'select':
260
                    $result->addElement(
261
                        $type,
262
                        $name,
263
                        array($this->get_lang($name), $help),
264
                        $options
265
                    );
266
                    break;
267
            }
268
        }
269
270
        if (!empty($checkboxGroup)) {
271
            $result->addGroup($checkboxGroup, null, array($this->get_lang('sms_types'), $help));
272
        }
273
        $result->setDefaults($defaults);
274
        $result->addButtonSave($this->get_lang('Save'), 'submit_button');
275
276
        return $result;
277
    }
278
279
    /**
280
     * Returns the value of a given plugin global setting
281
     * @param string $name of the plugin
282
     *
283
     * @return string Value of the plugin
284
     */
285
    public function get($name)
286
    {
287
        $settings = $this->get_settings();
288
        foreach ($settings as $setting) {
289
            if ($setting['variable'] == $this->get_name().'_'.$name) {
290
                return $setting['selected_value'];
291
            }
292
        }
293
294
        return false;
295
    }
296
297
    /**
298
     * Returns an array with the global settings for this plugin
299
     * @param bool $forceFromDB Optional. Force get settings from the database
300
     * @return array Plugin settings as an array
301
     */
302
    public function get_settings($forceFromDB = false)
303
    {
304
        if (empty($this->settings) || $forceFromDB) {
305
            $settings = api_get_settings_params(
306
                array(
307
                    "subkey = ? AND category = ? AND type = ? " => array($this->get_name(), 'Plugins', 'setting')
308
                )
309
            );
310
            $this->settings = $settings;
311
        }
312
313
        return $this->settings;
314
    }
315
316
    /**
317
     * Tells whether language variables are defined for this plugin or not
318
     * @param string $name System name of the plugin
319
     *
320
     * @return bool True if the plugin has language variables defined, false otherwise
321
     */
322
    public function get_lang_plugin_exists($name)
323
    {
324
        return isset($this->strings[$name]);
325
    }
326
327
    /**
328
     * Hook for the get_lang() function to check for plugin-defined language terms
329
     * @param string $name of the language variable we are looking for
330
     *
331
     * @return string The translated language term of the plugin
332
     */
333
    public function get_lang($name)
334
    {
335
        // Check whether the language strings for the plugin have already been
336
        // loaded. If so, no need to load them again.
337
338
        if (is_null($this->strings)) {
339
            $root = api_get_path(SYS_PLUGIN_PATH);
340
            $plugin_name = $this->get_name();
341
342
            $language_interface = api_get_language_isocode();
343
344
            //1. Loading english if exists
345
            $english_path = $root.$plugin_name."/lang/en.php";
346
347
            if (is_readable($english_path)) {
348
                $strings = array();
349
                include $english_path;
350
                $this->strings = $strings;
351
            }
352
353
            $path = $root.$plugin_name."/lang/$language_interface.php";
354
            // 2. Loading the system language
355
            if (is_readable($path)) {
356
                include $path;
357
                if (!empty($strings)) {
358
                    foreach ($strings as $key => $string) {
359
                        $this->strings[$key] = $string;
360
                    }
361
                }
362
            }
363
        }
364
365
        if (isset($this->strings[$name])) {
366
            return $this->strings[$name];
367
        }
368
369
        return get_lang($name);
370
    }
371
372
    /**
373
     * Caller for the install_course_fields() function
374
     * @param int $courseId
375
     *
376
     * @param boolean $addToolLink Whether to add a tool link on the course homepage
377
     *
378
     * @return void
379
     */
380
    public function course_install($courseId, $addToolLink = true)
381
    {
382
        $this->install_course_fields($courseId, $addToolLink);
383
    }
384
385
    /**
386
     * Add course settings and, if not asked otherwise, add a tool link on the course homepage
387
     * @param int $courseId Course integer ID
388
     * @param boolean $add_tool_link Whether to add a tool link or not
389
     * (some tools might just offer a configuration section and act on the backend)
390
     *
391
     * @return boolean|null  False on error, null otherwise
392
     */
393
    public function install_course_fields($courseId, $add_tool_link = true)
394
    {
395
        $plugin_name = $this->get_name();
396
        $t_course = Database::get_course_table(TABLE_COURSE_SETTING);
397
        $courseId = (int) $courseId;
398
399
        if (empty($courseId)) {
400
            return false;
401
        }
402
403
        // Adding course settings.
404
        if (!empty($this->course_settings)) {
405
            foreach ($this->course_settings as $setting) {
406
                $variable = $setting['name'];
407
                $value = '';
408
                if (isset($setting['init_value'])) {
409
                    $value = $setting['init_value'];
410
                }
411
412
                $type = 'textfield';
413
                if (isset($setting['type'])) {
414
                    $type = $setting['type'];
415
                }
416
417
                if (isset($setting['group'])) {
418
                    $group = $setting['group'];
419
                    $sql = "SELECT value
420
                            FROM $t_course
421
                            WHERE
422
                                c_id = $courseId AND
423
                                variable = '".Database::escape_string($group)."' AND
424
                                subkey = '".Database::escape_string($variable)."'
425
                            ";
426
                    $result = Database::query($sql);
427 View Code Duplication
                    if (!Database::num_rows($result)) {
428
                        $params = [
429
                            'c_id' => $courseId,
430
                            'variable' => $group,
431
                            'subkey' => $variable,
432
                            'value' => $value,
433
                            'category' => 'plugins',
434
                            'type' => $type,
435
                            'title' => ''
436
                        ];
437
                        Database::insert($t_course, $params);
438
                    }
439
                } else {
440
                    $sql = "SELECT value FROM $t_course
441
                            WHERE c_id = $courseId AND variable = '$variable' ";
442
                    $result = Database::query($sql);
443 View Code Duplication
                    if (!Database::num_rows($result)) {
444
                        $params = [
445
                            'c_id' => $courseId,
446
                            'variable' => $variable,
447
                            'subkey' => $plugin_name,
448
                            'value' => $value,
449
                            'category' => 'plugins',
450
                            'type' => $type,
451
                            'title' => ''
452
                        ];
453
                        Database::insert($t_course, $params);
454
                    }
455
                }
456
            }
457
        }
458
459
        // Stop here if we don't want a tool link on the course homepage
460
        if (!$add_tool_link || $this->addCourseTool == false) {
461
            return true;
462
        }
463
464
        //Add an icon in the table tool list
465
        $this->createLinkToCourseTool($plugin_name, $courseId);
466
    }
467
468
    /**
469
     * Add an link for a course tool
470
     * @param string $name The tool name
471
     * @param int $courseId The course ID
472
     * @param string $iconName Optional. Icon file name
473
     * @param string $link Optional. Link URL
474
     * @return \Chamilo\CourseBundle\Entity\CTool|null
475
     */
476
    protected function createLinkToCourseTool($name, $courseId, $iconName = null, $link = null)
477
    {
478
        if (!$this->addCourseTool) {
479
            return null;
480
        }
481
482
        $em = Database::getManager();
483
484
        /** @var CTool $tool */
485
        $tool = $em
486
            ->getRepository('ChamiloCourseBundle:CTool')
487
            ->findOneBy([
488
                'name' => $name,
489
                'cId' => $courseId
490
            ]);
491
492
        if (!$tool) {
493
            $cToolId = AddCourse::generateToolId($courseId);
494
            $pluginName = $this->get_name();
495
496
            $tool = new CTool();
497
            $tool
498
                ->setId($cToolId)
499
                ->setCId($courseId)
500
                ->setName($name)
501
                ->setLink($link ?: "$pluginName/start.php")
502
                ->setImage($iconName ?: "$pluginName.png")
503
                ->setVisibility(true)
504
                ->setAdmin(0)
505
                ->setAddress('squaregrey.gif')
506
                ->setAddedTool(false)
507
                ->setTarget('_self')
508
                ->setCategory('plugin')
509
                ->setSessionId(0);
510
511
            $em->persist($tool);
512
            $em->flush();
513
        }
514
515
        return $tool;
516
    }
517
518
    /**
519
     * Delete the fields added to the course settings page and the link to the
520
     * tool on the course's homepage
521
     * @param int $courseId
522
     *
523
     * @return false|null
524
     */
525
    public function uninstall_course_fields($courseId)
526
    {
527
        $courseId = intval($courseId);
528
529
        if (empty($courseId)) {
530
            return false;
531
        }
532
        $plugin_name = $this->get_name();
533
534
        $t_course = Database::get_course_table(TABLE_COURSE_SETTING);
535
        $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
536
537
        if (!empty($this->course_settings)) {
538
            foreach ($this->course_settings as $setting) {
539
                $variable = Database::escape_string($setting['name']);
540
                if (!empty($setting['group'])) {
541
                    $variable = Database::escape_string($setting['group']);
542
                }
543
                if (empty($variable)) {
544
                    continue;
545
                }
546
                $sql = "DELETE FROM $t_course
547
                        WHERE c_id = $courseId AND variable = '$variable'";
548
                Database::query($sql);
549
            }
550
        }
551
552
        $plugin_name = Database::escape_string($plugin_name);
553
        $sql = "DELETE FROM $t_tool
554
                WHERE c_id = $courseId AND name = '$plugin_name'";
555
        Database::query($sql);
556
    }
557
558
    /**
559
     * Install the course fields and tool link of this plugin in all courses
560
     * @param boolean $add_tool_link Whether we want to add a plugin link on the course homepage
561
     *
562
     * @return void
563
     */
564 View Code Duplication
    public function install_course_fields_in_all_courses($add_tool_link = true)
565
    {
566
        // Update existing courses to add plugin settings
567
        $t_courses = Database::get_main_table(TABLE_MAIN_COURSE);
568
        $sql = "SELECT id FROM $t_courses ORDER BY id";
569
        $res = Database::query($sql);
570
        while ($row = Database::fetch_assoc($res)) {
571
            $this->install_course_fields($row['id'], $add_tool_link);
572
        }
573
    }
574
575
    /**
576
     * Uninstall the plugin settings fields from all courses
577
     * @return void
578
     */
579 View Code Duplication
    public function uninstall_course_fields_in_all_courses()
580
    {
581
        // Update existing courses to add conference settings
582
        $t_courses = Database::get_main_table(TABLE_MAIN_COURSE);
583
        $sql = "SELECT id FROM $t_courses
584
                ORDER BY id";
585
        $res = Database::query($sql);
586
        while ($row = Database::fetch_assoc($res)) {
587
            $this->uninstall_course_fields($row['id']);
588
        }
589
    }
590
591
    /**
592
     * @return array
593
     */
594
    public function getCourseSettings()
595
    {
596
        $settings = array();
597
        if (is_array($this->course_settings)) {
598
            foreach ($this->course_settings as $item) {
599
                if (isset($item['group'])) {
600
                    if (!in_array($item['group'], $settings)) {
601
                        $settings[] = $item['group'];
602
                    }
603
                } else {
604
                    $settings[] = $item['name'];
605
                }
606
            }
607
        }
608
609
        return $settings;
610
    }
611
612
    /**
613
     * Method to be extended when changing the setting in the course
614
     * configuration should trigger the use of a callback method
615
     * @param array $values sent back from the course configuration script
616
     *
617
     * @return void
618
     */
619
    public function course_settings_updated($values = array())
620
    {
621
622
    }
623
624
    /**
625
     * Add a tab to platform
626
     * @param string $tabName
627
     * @param string $url
628
     * @param string $userFilter Optional. Filter tab type
629
     * @return false|string
630
     */
631
    public function addTab($tabName, $url, $userFilter = null)
632
    {
633
        $sql = "SELECT * FROM settings_current
634
                WHERE
635
                    variable = 'show_tabs' AND
636
                    subkey LIKE 'custom_tab_%'";
637
        $result = Database::query($sql);
638
        $customTabsNum = Database::num_rows($result);
639
640
        $tabNum = $customTabsNum + 1;
641
642
        // Avoid Tab Name Spaces
643
        $tabNameNoSpaces = preg_replace('/\s+/', '', $tabName);
644
        $subkeytext = "Tabs".$tabNameNoSpaces;
645
646
        // Check if it is already added
647
        $checkCondition = array(
648
            'where' =>
649
                array(
650
                    "variable = 'show_tabs' AND subkeytext = ?" => array(
651
                        $subkeytext
652
                    )
653
                )
654
        );
655
656
        $checkDuplicate = Database::select('*', 'settings_current', $checkCondition);
657
        if (!empty($checkDuplicate)) {
658
            return false;
659
        }
660
661
        // End Check
662
        $subkey = 'custom_tab_'.$tabNum;
663
664
        if (!empty($userFilter)) {
665
            switch ($userFilter) {
666
                case self::TAB_FILTER_NO_STUDENT:
667
                    //no break
668
                case self::TAB_FILTER_ONLY_STUDENT:
669
                    $subkey .= $userFilter;
670
                    break;
671
            }
672
        }
673
674
        $attributes = array(
675
            'variable' => 'show_tabs',
676
            'subkey' => $subkey,
677
            'type' => 'checkbox',
678
            'category' => 'Platform',
679
            'selected_value' => 'true',
680
            'title' => $tabName,
681
            'comment' => $url,
682
            'subkeytext' => $subkeytext,
683
            'access_url' => 1,
684
            'access_url_changeable' => 0,
685
            'access_url_locked' => 0
686
        );
687
        $resp = Database::insert('settings_current', $attributes);
688
689
        // Save the id
690
        $settings = $this->get_settings();
691
        $setData = array(
692
            'comment' => $subkey
693
        );
694
        $whereCondition = array(
695
            'id = ?' => key($settings)
696
        );
697
        Database::update('settings_current', $setData, $whereCondition);
698
699
        return $resp;
700
    }
701
702
    /**
703
     * Delete a tab to chamilo's platform
704
     * @param string $key
705
     * @return boolean $resp Transaction response
706
     */
707
    public function deleteTab($key)
708
    {
709
        $t = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
710
        $sql = "SELECT *
711
                FROM $t
712
                WHERE variable = 'show_tabs'
713
                AND subkey <> '$key'
714
                AND subkey like 'custom_tab_%'
715
                ";
716
        $resp = $result = Database::query($sql);
717
        $customTabsNum = Database::num_rows($result);
718
719
        if (!empty($key)) {
720
            $whereCondition = array(
721
                'variable = ? AND subkey = ?' => array('show_tabs', $key)
722
            );
723
            $resp = Database::delete('settings_current', $whereCondition);
724
725
            //if there is more than one tab
726
            //re enumerate them
727
            if (!empty($customTabsNum) && $customTabsNum > 0) {
728
                $tabs = Database::store_result($result, 'ASSOC');
729
                $i = 1;
730
                foreach ($tabs as $row) {
731
                    $newSubKey = "custom_tab_$i";
732
733
                    if (strpos($row['subkey'], self::TAB_FILTER_NO_STUDENT) !== false) {
734
                        $newSubKey .= self::TAB_FILTER_NO_STUDENT;
735
                    } elseif (strpos($row['subkey'], self::TAB_FILTER_ONLY_STUDENT) !== false) {
736
                        $newSubKey .= self::TAB_FILTER_ONLY_STUDENT;
737
                    }
738
739
                    $attributes = ['subkey' => $newSubKey];
740
741
                    $this->updateTab($row['subkey'], $attributes);
742
                    $i++;
743
                }
744
            }
745
        }
746
747
        return $resp;
748
    }
749
750
    /**
751
     * Update the tabs attributes
752
     * @param string $key
753
     * @param array  $attributes
754
     *
755
     * @return boolean
756
     */
757
    public function updateTab($key, $attributes)
758
    {
759
        $whereCondition = array(
760
            'variable = ? AND subkey = ?' => array('show_tabs', $key)
761
        );
762
        $resp = Database::update('settings_current', $attributes, $whereCondition);
763
764
        return $resp;
765
    }
766
767
    /**
768
     * This method shows or hides plugin's tab
769
     * @param boolean $showTab Shows or hides the main menu plugin tab
770
     * @param string $filePath Plugin starter file path
771
     */
772
    public function manageTab($showTab, $filePath = 'index.php')
773
    {
774
        $langString = str_replace('Plugin', '', get_class($this));
775
        $pluginName = strtolower($langString);
776
        $pluginUrl = 'plugin/'.$pluginName.'/'.$filePath;
777
778
        if ($showTab === 'true') {
779
            $tabAdded = $this->addTab($langString, $pluginUrl);
780
            if ($tabAdded) {
781
                // The page must be refreshed to show the recently created tab
782
                echo "<script>location.href = '".Security::remove_XSS($_SERVER['REQUEST_URI'])."';</script>";
783
            }
784 View Code Duplication
        } else {
785
            $settingsCurrentTable = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
786
            $conditions = array(
787
                'where' => array(
788
                    "variable = 'show_tabs' AND title = ? AND comment = ? " => array(
789
                        $langString,
790
                        $pluginUrl
791
                    )
792
                )
793
            );
794
            $result = Database::select('subkey', $settingsCurrentTable, $conditions);
795
            if (!empty($result)) {
796
                $this->deleteTab($result[0]['subkey']);
797
            }
798
        }
799
    }
800
801
    /**
802
     * @param string $variable
803
     * @return bool
804
     */
805
    public function validateCourseSetting($variable)
806
    {
807
        return true;
808
    }
809
810
    /**
811
     * @param string $region
812
     * @return string
813
     */
814
    public function renderRegion($region)
815
    {
816
        return '';
817
    }
818
819
    /**
820
     * Returns true if the plugin is installed, false otherwise
821
     * @return bool True if plugin is installed/enabled, false otherwise
822
     */
823
    public function isEnabled()
824
    {
825
        $settings = api_get_settings_params_simple(
826
            array(
827
                "subkey = ? AND category = ? AND type = ? AND variable = 'status' " => array($this->get_name(), 'Plugins', 'setting')
828
            )
829
        );
830
        if (is_array($settings) && isset($settings['selected_value']) && $settings['selected_value'] == 'installed') {
831
            return true;
832
        }
833
        return false;
834
    }
835
836
    /**
837
     * Allow make some actions after configure the plugin parameters
838
     * This function is called from main/admin/configure_plugin.php page
839
     * when saving the plugin parameters
840
     * @return \Plugin
841
     */
842
    public function performActionsAfterConfigure()
843
    {
844
        return $this;
845
    }
846
}
847