Passed
Push — master ( 9d7978...5faf0b )
by Julito
10:24
created

Plugin   F

Complexity

Total Complexity 127

Size/Duplication

Total Lines 1002
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 424
dl 0
loc 1002
rs 2
c 0
b 0
f 0
wmc 127

37 Methods

Rating   Name   Duplication   Size   Complexity  
A get_comment() 0 3 1
A get_version() 0 3 1
A get_author() 0 3 1
A get_title() 0 3 1
A getCamelCaseName() 0 5 1
A get_info() 0 27 4
A get_name() 0 7 1
A __construct() 0 8 1
A get_css() 0 12 2
A get_lang_plugin_exists() 0 3 1
A uninstall_course_fields_in_all_courses() 0 9 2
A updateTab() 0 8 1
F getSettingsForm() 0 113 25
A setHasPersonalEvents() 0 3 1
A getAdminUrl() 0 19 4
A getCourseSettings() 0 16 5
A course_install() 0 3 1
A get() 0 16 5
B deleteTab() 0 40 7
A performActionsAfterConfigure() 0 3 1
A manageTab() 0 25 4
A isIconVisibleByDefault() 0 3 1
A renderRegion() 0 3 1
A install_course_fields_in_all_courses() 0 8 2
C get_lang() 0 55 13
A validateCourseSetting() 0 3 1
A course_settings_updated() 0 2 1
B uninstall_course_fields() 0 36 6
B install_course_fields() 0 73 11
A isEnabled() 0 16 4
A get_settings() 0 17 3
A getToolIconVisibilityPerUserStatus() 0 3 1
B addTab() 0 68 5
A doWhenDeletingUser() 0 2 1
A doWhenDeletingSession() 0 2 1
A doWhenDeletingCourse() 0 2 1
A createLinkToCourseTool() 0 48 5

How to fix   Complexity   

Complex Class

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.

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