Passed
Push — master ( 0085e5...a02707 )
by Julito
10:26
created

Plugin::getLangFromFile()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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