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

Plugin::course_settings_updated()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
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
279
                    $element = $result->createElement(
280
                        $type,
281
                        $name,
282
                        '',
283
                        $this->get_lang($name),
284
                        $selectedValue
285
                    );
286
                    $element->_attributes['value'] = 'true';
287
                    $checkboxGroup[] = $element;
288
                    break;
289
                case 'select':
290
                    $result->addElement(
291
                        $type,
292
                        $name,
293
                        [$this->get_lang($name), $help],
294
                        $options,
295
                        $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...
296
                    );
297
                    break;
298
            }
299
        }
300
301
        if (!empty($checkboxGroup)) {
302
            $result->addGroup(
303
                $checkboxGroup,
304
                null,
305
                ['', $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...
306
                //[$this->get_lang('sms_types'), $help]
307
            );
308
        }
309
        $result->setDefaults($defaults);
310
        $result->addButtonSave($this->get_lang('Save'), 'submit_button');
311
312
        return $result;
313
    }
314
315
    /**
316
     * Returns the value of a given plugin global setting.
317
     *
318
     * @param string $name of the plugin
319
     *
320
     * @return string Value of the plugin
321
     */
322
    public function get($name)
323
    {
324
        $settings = $this->get_settings();
325
        foreach ($settings as $setting) {
326
            if ($setting['variable'] == $this->get_name().'_'.$name) {
327
                $unserialized = UnserializeApi::unserialize('not_allowed_classes', $setting['selected_value'], true);
328
329
                if (!empty($setting['selected_value']) &&
330
                    false !== $unserialized
331
                ) {
332
                    $setting['selected_value'] = $unserialized;
333
                }
334
335
                return $setting['selected_value'];
336
            }
337
        }
338
339
        return false;
340
    }
341
342
    /**
343
     * Returns an array with the global settings for this plugin.
344
     *
345
     * @param bool $forceFromDB Optional. Force get settings from the database
346
     *
347
     * @return array Plugin settings as an array
348
     */
349
    public function get_settings($forceFromDB = false)
350
    {
351
        if (empty($this->settings) || $forceFromDB) {
352
            $settings = api_get_settings_params(
353
                [
354
                    "subkey = ? AND category = ? AND type = ? AND access_url = ?" => [
355
                        $this->get_name(),
356
                        'Plugins',
357
                        'setting',
358
                        api_get_current_access_url_id(),
359
                    ],
360
                ]
361
            );
362
            $this->settings = $settings;
363
        }
364
365
        return $this->settings;
366
    }
367
368
    /**
369
     * Tells whether language variables are defined for this plugin or not.
370
     *
371
     * @param string $name System name of the plugin
372
     *
373
     * @return bool True if the plugin has language variables defined, false otherwise
374
     */
375
    public function get_lang_plugin_exists($name)
376
    {
377
        return isset($this->strings[$name]);
378
    }
379
380
    /**
381
     * Hook for the get_lang() function to check for plugin-defined language terms.
382
     *
383
     * @param string $name of the language variable we are looking for
384
     *
385
     * @return string The translated language term of the plugin
386
     */
387
    public function get_lang($name)
388
    {
389
        // Check whether the language strings for the plugin have already been
390
        // loaded. If so, no need to load them again.
391
        if (is_null($this->strings)) {
392
            $language_interface = api_get_interface_language();
393
            $root = api_get_path(SYS_PLUGIN_PATH);
394
            $plugin_name = $this->get_name();
395
396
            $interfaceLanguageId = api_get_language_id($language_interface);
397
            if (empty($interfaceLanguageId)) {
398
                $language_interface = api_get_setting('platformLanguage');
399
                $interfaceLanguageId = api_get_language_id($language_interface);
400
            }
401
            $interfaceLanguageInfo = api_get_language_info($interfaceLanguageId);
402
            $languageParentId = !empty($interfaceLanguageInfo['parent_id']) ? (int) $interfaceLanguageInfo['parent_id'] : 0;
403
404
            // 1. Loading english if exists
405
            $english_path = $root.$plugin_name."/lang/english.php";
406
407
            if (is_readable($english_path)) {
408
                $strings = [];
409
                include $english_path;
410
                $this->strings = $strings;
411
            }
412
413
            $path = $root.$plugin_name."/lang/$language_interface.php";
414
            // 2. Loading the system language
415
            if (is_readable($path)) {
416
                include $path;
417
                if (!empty($strings)) {
418
                    foreach ($strings as $key => $string) {
419
                        $this->strings[$key] = $string;
420
                    }
421
                }
422
            } elseif ($languageParentId > 0) {
423
                $languageParentInfo = api_get_language_info($languageParentId);
424
                $languageParentFolder = $languageParentInfo['dokeos_folder'];
425
426
                $parentPath = "{$root}{$plugin_name}/lang/{$languageParentFolder}.php";
427
                if (is_readable($parentPath)) {
428
                    include $parentPath;
429
                    if (!empty($strings)) {
430
                        foreach ($strings as $key => $string) {
431
                            $this->strings[$key] = $string;
432
                        }
433
                    }
434
                }
435
            }
436
        }
437
        if (isset($this->strings[$name])) {
438
            return $this->strings[$name];
439
        }
440
441
        return get_lang($name);
442
    }
443
444
    /**
445
     * Caller for the install_course_fields() function.
446
     *
447
     * @param int  $courseId
448
     * @param bool $addToolLink Whether to add a tool link on the course homepage
449
     */
450
    public function course_install($courseId, $addToolLink = true)
451
    {
452
        $this->install_course_fields($courseId, $addToolLink);
453
    }
454
455
    /**
456
     * Add course settings and, if not asked otherwise, add a tool link on the course homepage.
457
     *
458
     * @param int  $courseId      Course integer ID
459
     * @param bool $add_tool_link Whether to add a tool link or not
460
     *                            (some tools might just offer a configuration section and act on the backend)
461
     *
462
     * @return bool|null False on error, null otherwise
463
     */
464
    public function install_course_fields($courseId, $add_tool_link = true)
465
    {
466
        $plugin_name = $this->get_name();
467
        $t_course = Database::get_course_table(TABLE_COURSE_SETTING);
468
        $courseId = (int) $courseId;
469
470
        if (empty($courseId)) {
471
            return false;
472
        }
473
474
        // Adding course settings.
475
        if (!empty($this->course_settings)) {
476
            foreach ($this->course_settings as $setting) {
477
                $variable = $setting['name'];
478
                $value = '';
479
                if (isset($setting['init_value'])) {
480
                    $value = $setting['init_value'];
481
                }
482
483
                $pluginGlobalValue = api_get_plugin_setting($plugin_name, $variable);
484
                if (null !== $pluginGlobalValue) {
485
                    $value = 1;
486
                }
487
488
                $type = 'textfield';
489
                if (isset($setting['type'])) {
490
                    $type = $setting['type'];
491
                }
492
493
                if (isset($setting['group'])) {
494
                    $group = $setting['group'];
495
                    $sql = "SELECT value
496
                            FROM $t_course
497
                            WHERE
498
                                c_id = $courseId AND
499
                                variable = '".Database::escape_string($group)."' AND
500
                                subkey = '".Database::escape_string($variable)."'
501
                            ";
502
                    $result = Database::query($sql);
503
                    if (!Database::num_rows($result)) {
504
                        $params = [
505
                            'c_id' => $courseId,
506
                            'variable' => $group,
507
                            'subkey' => $variable,
508
                            'value' => $value,
509
                            'category' => 'plugins',
510
                            'type' => $type,
511
                            'title' => '',
512
                        ];
513
                        Database::insert($t_course, $params);
514
                    }
515
                } else {
516
                    $sql = "SELECT value FROM $t_course
517
                            WHERE c_id = $courseId AND variable = '$variable' ";
518
                    $result = Database::query($sql);
519
                    if (!Database::num_rows($result)) {
520
                        $params = [
521
                            'c_id' => $courseId,
522
                            'variable' => $variable,
523
                            'subkey' => $plugin_name,
524
                            'value' => $value,
525
                            'category' => 'plugins',
526
                            'type' => $type,
527
                            'title' => '',
528
                        ];
529
                        Database::insert($t_course, $params);
530
                    }
531
                }
532
            }
533
        }
534
535
        // Stop here if we don't want a tool link on the course homepage
536
        if (!$add_tool_link || $this->addCourseTool == false) {
537
            return true;
538
        }
539
540
        // Add an icon in the table tool list
541
        $this->createLinkToCourseTool($plugin_name, $courseId);
542
    }
543
544
    /**
545
     * Delete the fields added to the course settings page and the link to the
546
     * tool on the course's homepage.
547
     *
548
     * @param int $courseId
549
     *
550
     * @return false|null
551
     */
552
    public function uninstall_course_fields($courseId)
553
    {
554
        $courseId = (int) $courseId;
555
556
        if (empty($courseId)) {
557
            return false;
558
        }
559
        $pluginName = $this->get_name();
560
561
        $t_course = Database::get_course_table(TABLE_COURSE_SETTING);
562
        $t_tool = Database::get_course_table(TABLE_TOOL_LIST);
563
564
        if (!empty($this->course_settings)) {
565
            foreach ($this->course_settings as $setting) {
566
                $variable = Database::escape_string($setting['name']);
567
                if (!empty($setting['group'])) {
568
                    $variable = Database::escape_string($setting['group']);
569
                }
570
                if (empty($variable)) {
571
                    continue;
572
                }
573
                $sql = "DELETE FROM $t_course
574
                        WHERE c_id = $courseId AND variable = '$variable'";
575
                Database::query($sql);
576
            }
577
        }
578
579
        $pluginName = Database::escape_string($pluginName);
580
        $sql = "DELETE FROM $t_tool
581
                WHERE c_id = $courseId AND
582
                (
583
                  name = '$pluginName' OR
584
                  name = '$pluginName:student' OR
585
                  name = '$pluginName:teacher'
586
                )";
587
        Database::query($sql);
588
    }
589
590
    /**
591
     * Install the course fields and tool link of this plugin in all courses.
592
     *
593
     * @param bool $add_tool_link Whether we want to add a plugin link on the course homepage
594
     */
595
    public function install_course_fields_in_all_courses($add_tool_link = true)
596
    {
597
        // Update existing courses to add plugin settings
598
        $table = Database::get_main_table(TABLE_MAIN_COURSE);
599
        $sql = "SELECT id FROM $table ORDER BY id";
600
        $res = Database::query($sql);
601
        while ($row = Database::fetch_assoc($res)) {
602
            $this->install_course_fields($row['id'], $add_tool_link);
603
        }
604
    }
605
606
    /**
607
     * Uninstall the plugin settings fields from all courses.
608
     */
609
    public function uninstall_course_fields_in_all_courses()
610
    {
611
        // Update existing courses to add conference settings
612
        $table = Database::get_main_table(TABLE_MAIN_COURSE);
613
        $sql = "SELECT id FROM $table
614
                ORDER BY id";
615
        $res = Database::query($sql);
616
        while ($row = Database::fetch_assoc($res)) {
617
            $this->uninstall_course_fields($row['id']);
618
        }
619
    }
620
621
    /**
622
     * @return array
623
     */
624
    public function getCourseSettings()
625
    {
626
        $settings = [];
627
        if (is_array($this->course_settings)) {
628
            foreach ($this->course_settings as $item) {
629
                if (isset($item['group'])) {
630
                    if (!in_array($item['group'], $settings)) {
631
                        $settings[] = $item['group'];
632
                    }
633
                } else {
634
                    $settings[] = $item['name'];
635
                }
636
            }
637
        }
638
639
        return $settings;
640
    }
641
642
    /**
643
     * Method to be extended when changing the setting in the course
644
     * configuration should trigger the use of a callback method.
645
     *
646
     * @param array $values sent back from the course configuration script
647
     */
648
    public function course_settings_updated($values = [])
649
    {
650
    }
651
652
    /**
653
     * Add a tab to platform.
654
     *
655
     * @param string $tabName
656
     * @param string $url
657
     * @param string $userFilter Optional. Filter tab type
658
     *
659
     * @return false|string
660
     */
661
    public function addTab($tabName, $url, $userFilter = null)
662
    {
663
        $sql = "SELECT * FROM settings_current
664
                WHERE
665
                    variable = 'show_tabs' AND
666
                    subkey LIKE 'custom_tab_%'";
667
        $result = Database::query($sql);
668
        $customTabsNum = Database::num_rows($result);
669
670
        $tabNum = $customTabsNum + 1;
671
672
        // Avoid Tab Name Spaces
673
        $tabNameNoSpaces = preg_replace('/\s+/', '', $tabName);
674
        $subkeytext = "Tabs".$tabNameNoSpaces;
675
676
        // Check if it is already added
677
        $checkCondition = [
678
            'where' => [
679
                    "variable = 'show_tabs' AND subkeytext = ?" => [
680
                        $subkeytext,
681
                    ],
682
                ],
683
        ];
684
685
        $checkDuplicate = Database::select('*', 'settings_current', $checkCondition);
686
        if (!empty($checkDuplicate)) {
687
            return false;
688
        }
689
690
        // End Check
691
        $subkey = 'custom_tab_'.$tabNum;
692
693
        if (!empty($userFilter)) {
694
            switch ($userFilter) {
695
                case self::TAB_FILTER_NO_STUDENT:
696
                case self::TAB_FILTER_ONLY_STUDENT:
697
                    $subkey .= $userFilter;
698
                    break;
699
            }
700
        }
701
702
        $currentUrlId = api_get_current_access_url_id();
703
        $attributes = [
704
            'variable' => 'show_tabs',
705
            'subkey' => $subkey,
706
            'type' => 'checkbox',
707
            'category' => 'Platform',
708
            'selected_value' => 'true',
709
            'title' => $tabName,
710
            'comment' => $url,
711
            'subkeytext' => $subkeytext,
712
            'access_url' => $currentUrlId,
713
            'access_url_changeable' => 1,
714
            'access_url_locked' => 0,
715
        ];
716
        $resp = Database::insert('settings_current', $attributes);
717
718
        // Save the id
719
        $settings = $this->get_settings();
720
        $setData = [
721
            'comment' => $subkey,
722
        ];
723
        $whereCondition = [
724
            'id = ?' => key($settings),
725
        ];
726
        Database::update('settings_current', $setData, $whereCondition);
727
728
        return $resp;
729
    }
730
731
    /**
732
     * Delete a tab to chamilo's platform.
733
     *
734
     * @param string $key
735
     *
736
     * @return bool $resp Transaction response
737
     */
738
    public function deleteTab($key)
739
    {
740
        $table = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
741
        $sql = "SELECT *
742
                FROM $table
743
                WHERE variable = 'show_tabs'
744
                AND subkey <> '$key'
745
                AND subkey like 'custom_tab_%'
746
                ";
747
        $resp = $result = Database::query($sql);
748
        $customTabsNum = Database::num_rows($result);
749
750
        if (!empty($key)) {
751
            $whereCondition = [
752
                'variable = ? AND subkey = ?' => ['show_tabs', $key],
753
            ];
754
            $resp = Database::delete('settings_current', $whereCondition);
755
756
            //if there is more than one tab
757
            //re enumerate them
758
            if (!empty($customTabsNum) && $customTabsNum > 0) {
759
                $tabs = Database::store_result($result, 'ASSOC');
760
                $i = 1;
761
                foreach ($tabs as $row) {
762
                    $newSubKey = "custom_tab_$i";
763
764
                    if (strpos($row['subkey'], self::TAB_FILTER_NO_STUDENT) !== false) {
765
                        $newSubKey .= self::TAB_FILTER_NO_STUDENT;
766
                    } elseif (strpos($row['subkey'], self::TAB_FILTER_ONLY_STUDENT) !== false) {
767
                        $newSubKey .= self::TAB_FILTER_ONLY_STUDENT;
768
                    }
769
770
                    $attributes = ['subkey' => $newSubKey];
771
                    $this->updateTab($row['subkey'], $attributes);
772
                    $i++;
773
                }
774
            }
775
        }
776
777
        return $resp;
778
    }
779
780
    /**
781
     * Update the tabs attributes.
782
     *
783
     * @param string $key
784
     * @param array  $attributes
785
     *
786
     * @return bool
787
     */
788
    public function updateTab($key, $attributes)
789
    {
790
        $whereCondition = [
791
            'variable = ? AND subkey = ?' => ['show_tabs', $key],
792
        ];
793
        $resp = Database::update('settings_current', $attributes, $whereCondition);
794
795
        return $resp;
796
    }
797
798
    /**
799
     * This method shows or hides plugin's tab.
800
     *
801
     * @param bool   $showTab  Shows or hides the main menu plugin tab
802
     * @param string $filePath Plugin starter file path
803
     */
804
    public function manageTab($showTab, $filePath = 'index.php')
805
    {
806
        $langString = str_replace('Plugin', '', get_class($this));
807
        $pluginName = strtolower($langString);
808
        $pluginUrl = 'plugin/'.$pluginName.'/'.$filePath;
809
810
        if ($showTab === 'true') {
811
            $tabAdded = $this->addTab($langString, $pluginUrl);
812
            if ($tabAdded) {
813
                // The page must be refreshed to show the recently created tab
814
                echo "<script>location.href = '".Security::remove_XSS($_SERVER['REQUEST_URI'])."';</script>";
815
            }
816
        } else {
817
            $settingsCurrentTable = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
818
            $conditions = [
819
                'where' => [
820
                    "variable = 'show_tabs' AND title = ? AND comment = ? " => [
821
                        $langString,
822
                        $pluginUrl,
823
                    ],
824
                ],
825
            ];
826
            $result = Database::select('subkey', $settingsCurrentTable, $conditions);
827
            if (!empty($result)) {
828
                $this->deleteTab($result[0]['subkey']);
829
            }
830
        }
831
    }
832
833
    /**
834
     * @param string $variable
835
     *
836
     * @return bool
837
     */
838
    public function validateCourseSetting($variable)
839
    {
840
        return true;
841
    }
842
843
    /**
844
     * @param string $region
845
     *
846
     * @return string
847
     */
848
    public function renderRegion($region)
849
    {
850
        return '';
851
    }
852
853
    /**
854
     * Returns true if the plugin is installed, false otherwise.
855
     *
856
     * @return bool True if plugin is installed/enabled, false otherwise
857
     */
858
    public function isEnabled()
859
    {
860
        $settings = api_get_settings_params_simple(
861
            [
862
                "subkey = ? AND category = ? AND type = ? AND variable = 'status' " => [
863
                    $this->get_name(),
864
                    'Plugins',
865
                    'setting',
866
                ],
867
            ]
868
        );
869
        if (is_array($settings) && isset($settings['selected_value']) && $settings['selected_value'] == 'installed') {
870
            return true;
871
        }
872
873
        return false;
874
    }
875
876
    /**
877
     * Allow make some actions after configure the plugin parameters
878
     * This function is called from main/admin/configure_plugin.php page
879
     * when saving the plugin parameters.
880
     *
881
     * @return \Plugin
882
     */
883
    public function performActionsAfterConfigure()
884
    {
885
        return $this;
886
    }
887
888
    /**
889
     * This function allows to change the visibility of the icon inside a course
890
     * :student tool will be visible only for students
891
     * :teacher tool will be visible only for teachers
892
     * If nothing it's set then tool will be visible for both as a normal icon.
893
     *
894
     * @return string
895
     */
896
    public function getToolIconVisibilityPerUserStatus()
897
    {
898
        return '';
899
    }
900
901
    /**
902
     * Default tool icon visibility.
903
     *
904
     * @return bool
905
     */
906
    public function isIconVisibleByDefault()
907
    {
908
        return true;
909
    }
910
911
    /**
912
     * Get the admin URL for the plugin if Plugin::isAdminPlugin is true.
913
     *
914
     * @return string
915
     */
916
    public function getAdminUrl()
917
    {
918
        if (!$this->isAdminPlugin) {
919
            return '';
920
        }
921
922
        $name = $this->get_name();
923
        $sysPath = api_get_path(SYS_PLUGIN_PATH).$name;
924
        $webPath = api_get_path(WEB_PLUGIN_PATH).$name;
925
926
        if (file_exists("$sysPath/admin.php")) {
927
            return "$webPath/admin.php";
928
        }
929
930
        if (file_exists("$sysPath/start.php")) {
931
            return "$webPath/start.php";
932
        }
933
934
        return '';
935
    }
936
937
    /**
938
     * @param bool $value
939
     */
940
    public function setHasPersonalEvents($value)
941
    {
942
        $this->hasPersonalEvents = $value;
943
    }
944
945
    /**
946
     * Overwrite to perform some actions when deleting a user.
947
     *
948
     * @param int $userId
949
     */
950
    public function doWhenDeletingUser($userId)
951
    {
952
    }
953
954
    /**
955
     * Overwrite to perform some actions when deleting a course.
956
     *
957
     * @param int $courseId
958
     */
959
    public function doWhenDeletingCourse($courseId)
960
    {
961
    }
962
963
    /**
964
     * Overwrite to perform some actions when deleting a session.
965
     *
966
     * @param int $sessionId
967
     */
968
    public function doWhenDeletingSession($sessionId)
969
    {
970
    }
971
972
    /**
973
     * Add an link for a course tool.
974
     *
975
     * @param string $name     The tool name
976
     * @param int    $courseId The course ID
977
     * @param string $iconName Optional. Icon file name
978
     * @param string $link     Optional. Link URL
979
     *
980
     * @return CTool|null
981
     */
982
    protected function createLinkToCourseTool(
983
        $name,
984
        $courseId,
985
        $iconName = null,
986
        $link = null
987
    ) {
988
        if (!$this->addCourseTool) {
989
            return null;
990
        }
991
992
        $visibilityPerStatus = $this->getToolIconVisibilityPerUserStatus();
993
        $visibility = $this->isIconVisibleByDefault();
994
995
        $em = Database::getManager();
996
997
        /** @var CTool $tool */
998
        $tool = $em
999
            ->getRepository('ChamiloCourseBundle:CTool')
1000
            ->findOneBy([
1001
                'name' => $name,
1002
                'cId' => $courseId,
1003
                'category' => 'plugin',
1004
            ]);
1005
1006
        if (!$tool) {
0 ignored issues
show
introduced by
$tool is of type Chamilo\CourseBundle\Entity\CTool, thus it always evaluated to true.
Loading history...
1007
            $cToolId = AddCourse::generateToolId($courseId);
1008
            $pluginName = $this->get_name();
1009
1010
            $tool = new CTool();
1011
            $tool
1012
                ->setId($cToolId)
1013
                ->setCId($courseId)
1014
                ->setName($name.$visibilityPerStatus)
1015
                ->setLink($link ?: "$pluginName/start.php")
1016
                ->setImage($iconName ?: "$pluginName.png")
1017
                ->setVisibility($visibility)
1018
                ->setAdmin(0)
1019
                ->setAddress('squaregrey.gif')
1020
                ->setAddedTool(false)
1021
                ->setTarget('_self')
1022
                ->setCategory('plugin')
1023
                ->setSessionId(0);
1024
1025
            $em->persist($tool);
1026
            $em->flush();
1027
        }
1028
1029
        return $tool;
1030
    }
1031
}
1032