Passed
Push — master ( 2c1297...2ffb1a )
by Julito
10:51
created

CourseHome   F

Complexity

Total Complexity 303

Size/Duplication

Total Lines 1803
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1042
dl 0
loc 1803
rs 1.432
c 1
b 0
f 0
wmc 303

23 Methods

Rating   Name   Duplication   Size   Complexity  
A getCourseAdminBlocks() 0 30 1
A toolsIconsAction() 0 30 4
A show_session_data() 0 40 4
A getTool() 0 11 1
F get_tools_category() 0 291 49
A show_navigation_menu() 0 58 5
A getUserBlocks() 0 13 5
A getPublishedLpCategoryFromLink() 0 10 2
F show_tool_2column() 0 222 56
A getDisableIcon() 0 5 1
A getCustomWebIconPath() 0 6 1
B deleteIcon() 0 31 9
F show_tools_category() 0 331 61
A translate_tool_name() 0 30 6
B getToolIcon() 0 38 7
F show_tool_3column() 0 237 51
B updateTool() 0 51 6
B getCourseToolBar() 0 43 7
A getCustomSysIconPath() 0 9 2
B getStudentBlocks() 0 46 7
A getCoachBlocks() 0 30 4
B filterPluginTools() 0 46 11
A getPublishedLpIdFromLink() 0 12 3

How to fix   Complexity   

Complex Class

Complex classes like CourseHome 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 CourseHome, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CLpCategory;
5
use Chamilo\CourseBundle\Entity\CTool;
6
7
/**
8
 * Class CourseHome.
9
 */
10
class CourseHome
11
{
12
    /**
13
     * Gets the html content to show in the 3 column view.
14
     *
15
     * @param string $cat
16
     * @param int    $userId
17
     *
18
     * @return string
19
     */
20
    public static function show_tool_3column($cat, $userId = null)
21
    {
22
        $_user = api_get_user_info($userId);
23
24
        $TBL_ACCUEIL = Database::get_course_table(TABLE_TOOL_LIST);
25
        $TABLE_TOOLS = Database::get_main_table(TABLE_MAIN_COURSE_MODULE);
26
27
        $numcols = 3;
28
        $table = new HTML_Table('width="100%"');
29
        $all_tools = [];
30
31
        $course_id = api_get_course_int_id();
32
        $studentView = api_is_student_view_active();
33
34
        switch ($cat) {
35
            case 'Basic':
36
                $condition_display_tools = ' WHERE a.c_id = '.$course_id.' AND  a.link=t.link AND t.position="basic" ';
37
                if ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) &&
38
                    !$studentView
39
                ) {
40
                    $condition_display_tools = ' WHERE 
41
                        a.c_id = '.$course_id.' AND 
42
                        a.link=t.link AND
43
                         (t.position="basic" OR a.name = "'.TOOL_TRACKING.'") 
44
                    ';
45
                }
46
47
                $sql = "SELECT a.*, t.image img, t.row, t.column  
48
                        FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
49
                        $condition_display_tools ORDER BY t.row, t.column";
50
                break;
51
            case 'External':
52
                if (api_is_allowed_to_edit()) {
53
                    $sql = "SELECT a.*, t.image img FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
54
                            WHERE 
55
                              a.c_id = $course_id AND 
56
                              ((a.link=t.link AND t.position='external') OR 
57
                              (a.visibility <= 1 AND 
58
                              (a.image = 'external.gif' OR a.image = 'scormbuilder.gif' OR t.image = 'blog.gif') AND 
59
                              a.image=t.image))
60
                            ORDER BY a.id";
61
                } else {
62
                    $sql = "SELECT a.*, t.image img FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
63
                            WHERE 
64
                              a.c_id = $course_id AND 
65
                              (a.visibility = 1 AND ((a.link=t.link AND t.position='external') OR 
66
                              ((a.image = 'external.gif' OR a.image = 'scormbuilder.gif' OR t.image = 'blog.gif') AND 
67
                              a.image=t.image)))
68
                            ORDER BY a.id";
69
                }
70
                break;
71
            case 'courseAdmin':
72
                $sql = "SELECT a.*, t.image img, t.row, t.column  
73
                        FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
74
                        WHERE a.c_id = $course_id AND admin=1 AND a.link=t.link 
75
                        ORDER BY t.row, t.column";
76
                break;
77
78
            case 'platformAdmin':
79
                $sql = "SELECT *, image img FROM $TBL_ACCUEIL 
80
                        WHERE c_id = $course_id AND visibility = 2 
81
                        ORDER BY id";
82
        }
83
        $result = Database::query($sql);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sql does not seem to be defined for all execution paths leading up to this point.
Loading history...
84
85
        // Grabbing all the tools from $course_tool_table
86
        while ($tool = Database::fetch_array($result)) {
87
            $all_tools[] = $tool;
88
        }
89
90
        $course_id = api_get_course_int_id();
91
92
        // Grabbing all the links that have the property on_homepage set to 1
93
        if ($cat == 'External') {
94
            $tbl_link = Database::get_course_table(TABLE_LINK);
95
            $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
96
            if (api_is_allowed_to_edit(null, true)) {
97
                $sql_links = "SELECT tl.*, tip.visibility
98
                              FROM $tbl_link tl
99
                              LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
100
                              WHERE 	
101
                                tl.c_id = $course_id AND
102
                                tip.c_id = $course_id AND
103
                                tl.on_homepage='1' AND
104
                                tip.visibility != 2";
105
            } else {
106
                $sql_links = "SELECT tl.*, tip.visibility
107
                                FROM $tbl_link tl
108
                                LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
109
                                WHERE 	
110
                                    tl.c_id = $course_id AND
111
                                    tip.c_id = $course_id AND
112
                                    tl.on_homepage='1' AND
113
                                    tip.visibility = 1";
114
            }
115
            $result_links = Database::query($sql_links);
116
            while ($links_row = Database::fetch_array($result_links)) {
117
                $properties = [];
118
                $properties['name'] = $links_row['title'];
119
                $properties['link'] = $links_row['url'];
120
                $properties['visibility'] = $links_row['visibility'];
121
                $properties['img'] = 'external.gif';
122
                $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&amp;id='.$links_row['id'];
123
                $all_tools[] = $properties;
124
            }
125
        }
126
127
        $cell_number = 0;
128
        // Draw line between basic and external, only if there are entries in External
129
        if ($cat == 'External' && count($all_tools)) {
130
            $table->setCellContents(0, 0, '<hr noshade="noshade" size="1"/>');
131
            $table->updateCellAttributes(0, 0, 'colspan="3"');
132
            $cell_number += $numcols;
133
        }
134
135
        foreach ($all_tools as &$tool) {
136
            if (isset($tool['image']) && $tool['image'] == 'scormbuilder.gif') {
137
                // check if the published learnpath is visible for student
138
                $lpId = self::getPublishedLpIdFromLink($tool['link']);
139
140
                if (!api_is_allowed_to_edit(null, true) &&
141
                    !learnpath::is_lp_visible_for_student(
142
                        $lpId,
143
                        api_get_user_id(),
144
                        api_get_course_id(),
145
                        api_get_session_id()
146
                    )
147
                ) {
148
                    continue;
149
                }
150
            }
151
152
            if (api_get_session_id() != 0 &&
153
                in_array($tool['name'], ['course_maintenance', 'course_setting'])
154
            ) {
155
                continue;
156
            }
157
158
            $cell_content = '';
159
            // The name of the tool
160
            $tool_name = self::translate_tool_name($tool);
161
162
            $link_annex = '';
163
            // The url of the tool
164
            if ($tool['img'] != 'external.gif') {
165
                $tool['link'] = api_get_path(WEB_CODE_PATH).$tool['link'];
166
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&amp;';
167
                $link_annex = $qm_or_amp.api_get_cidreq();
168
            } else {
169
                // If an external link ends with 'login=', add the actual login...
170
                $pos = strpos($tool['link'], '?login=');
171
                $pos2 = strpos($tool['link'], '&amp;login=');
172
                if ($pos !== false or $pos2 !== false) {
173
                    $link_annex = $_user['username'];
174
                }
175
            }
176
177
            // Setting the actual image url
178
            $tool['img'] = Display::returnIconPath($tool['img']);
179
            $target = isset($tool['target']) ? $tool['target'] : '';
180
181
            // VISIBLE
182
            if (($tool['visibility'] ||
183
                ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) && $tool['name'] == TOOL_TRACKING)) ||
184
                $cat == 'courseAdmin' || $cat == 'platformAdmin'
185
            ) {
186
                if (strpos($tool['name'], 'visio_') !== false) {
187
                    $cell_content .= '<a  href="javascript: void(0);" onclick="javascript: window.open(\''.$tool['link'].$link_annex.'\',\'window_visio'.api_get_course_id().'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'"><img src="'.$tool['img'].'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
188
                } elseif (strpos($tool['name'], 'chat') !== false &&
189
                    api_get_course_setting('allow_open_chat_window')
190
                ) {
191
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
192
                    $cell_content .= '<a href="javascript: void(0);" onclick="javascript: window.open(\''.$tool['link'].$link_annex.'\',\'window_chat'.api_get_course_id().'\',config=\'height=\'+600+\', width=\'+825+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'"><img src="'.$tool['img'].'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
193
                } else {
194
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
195
                    $cell_content .= '<a href="'.$tool['link'].$link_annex.'" target="'.$target.'"><img src="'.$tool['img'].'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
196
                }
197
            } else {
198
                // INVISIBLE
199
                if (api_is_allowed_to_edit(null, true)) {
200
                    if (strpos($tool['name'], 'visio_') !== false) {
201
                        $cell_content .= '<a  href="javascript: void(0);" onclick="window.open(\''.$tool['link'].$link_annex.'\',\'window_visio'.api_get_course_id().'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'"><img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
202
                    } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
203
                        // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
204
                        $cell_content .= '<a href="javascript: void(0);" onclick="javascript: window.open(\''.$tool['link'].$link_annex.'\',\'window_chat'.api_get_course_id().'\',config=\'height=\'+600+\', width=\'+825+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'" class="text-muted"><img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
205
                    } else {
206
                        // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
207
                        $cell_content .= '<a href="'.$tool['link'].$link_annex.'" target="'.$tool['target'].'" class="text-muted">
208
                            <img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
209
                    }
210
                } else {
211
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
212
                    $cell_content .= '<img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">';
213
                    $cell_content .= '<span class="text-muted">'.$tool_name.'</span>';
214
                }
215
            }
216
217
            $lnk = [];
218
            if (api_is_allowed_to_edit(null, true) &&
219
                $cat != "courseAdmin" &&
220
                !strpos($tool['link'], 'learnpath_handler.php?learnpath_id') &&
221
                !api_is_coach()
222
            ) {
223
                if ($tool['visibility']) {
224
                    $link['name'] = Display::return_icon(
225
                        'remove.gif',
226
                        get_lang('Deactivate'),
227
                        ['style' => 'vertical-align: middle;']
228
                    );
229
                    $link['cmd'] = "hide=yes";
230
                    $lnk[] = $link;
231
                } else {
232
                    $link['name'] = Display::return_icon(
233
                        'add.gif',
234
                        get_lang('Activate'),
235
                        ['style' => 'vertical-align: middle;']
236
                    );
237
                    $link['cmd'] = "restore=yes";
238
                    $lnk[] = $link;
239
                }
240
                if (is_array($lnk)) {
241
                    foreach ($lnk as &$this_lnk) {
242
                        if (isset($tool['adminlink']) && $tool['adminlink']) {
243
                            $cell_content .= '<a href="'.$properties['adminlink'].'">'.
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $properties does not seem to be defined for all execution paths leading up to this point.
Loading history...
244
                                Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
245
                        } else {
246
                            $cell_content .= '<a href="'.api_get_self().'?id='.$tool['id'].'&amp;'.$this_lnk['cmd'].'">'.$this_lnk['name'].'</a>';
247
                        }
248
                    }
249
                }
250
            }
251
            $table->setCellContents($cell_number / $numcols, ($cell_number) % $numcols, $cell_content);
252
            $table->updateCellAttributes($cell_number / $numcols, ($cell_number) % $numcols, 'width="32%" height="42"');
253
            $cell_number++;
254
        }
255
256
        return $table->toHtml();
257
    }
258
259
    /**
260
     * Displays the tools of a certain category.
261
     *
262
     * @param string $course_tool_category contains the category of tools to display:
263
     *                                     "Public", "PublicButHide", "courseAdmin", "claroAdmin"
264
     *
265
     * @return string
266
     */
267
    public static function show_tool_2column($course_tool_category)
268
    {
269
        $html = '';
270
        $web_code_path = api_get_path(WEB_CODE_PATH);
271
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
272
        $course_id = api_get_course_int_id();
273
        $studentView = api_is_student_view_active();
274
        switch ($course_tool_category) {
275
            case TOOL_PUBLIC:
276
                $condition_display_tools = ' WHERE c_id = '.$course_id.' AND visibility = 1 ';
277
                if ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) &&
278
                    !$studentView
279
                ) {
280
                    $condition_display_tools = ' WHERE 
281
                        c_id = '.$course_id.' AND 
282
                        (visibility = 1 OR (visibility = 0 AND name = "'.TOOL_TRACKING.'")) ';
283
                }
284
                $result = Database::query("SELECT * FROM $course_tool_table $condition_display_tools ORDER BY id");
285
                $col_link = "##003399";
286
                break;
287
            case TOOL_PUBLIC_BUT_HIDDEN:
288
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND visibility=0 AND admin=0 ORDER BY id");
289
                $col_link = "##808080";
290
                break;
291
            case TOOL_COURSE_ADMIN:
292
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND admin=1 AND visibility != 2 ORDER BY id");
293
                $col_link = "##003399";
294
                break;
295
            case TOOL_PLATFORM_ADMIN:
296
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND visibility = 2  ORDER BY id");
297
                $col_link = "##003399";
298
        }
299
        $i = 0;
300
301
        // Grabbing all the tools from $course_tool_table
302
        while ($temp_row = Database::fetch_array($result)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
303
            if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN && $temp_row['image'] != 'scormbuilder.gif') {
304
                $temp_row['image'] = str_replace('.gif', '_na.gif', $temp_row['image']);
305
            }
306
            $all_tools_list[] = $temp_row;
307
        }
308
309
        // Grabbing all the links that have the property on_homepage set to 1
310
        $course_link_table = Database::get_course_table(TABLE_LINK);
311
        $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
312
313
        switch ($course_tool_category) {
314
            case TOOL_PUBLIC:
315
                $sql_links = "SELECT tl.*, tip.visibility
316
                        FROM $course_link_table tl
317
                        LEFT JOIN $course_item_property_table tip 
318
                        ON tip.tool='link' AND tl.c_id = tip.c_id AND tl.c_id = $course_id AND tip.ref=tl.id
319
                        WHERE tl.on_homepage='1' AND tip.visibility = 1";
320
                break;
321
            case TOOL_PUBLIC_BUT_HIDDEN:
322
                $sql_links = "SELECT tl.*, tip.visibility
323
                    FROM $course_link_table tl
324
                    LEFT JOIN $course_item_property_table tip 
325
                    ON tip.tool='link' AND tl.c_id = tip.c_id AND tl.c_id = $course_id AND tip.ref=tl.id
326
                    WHERE tl.on_homepage='1' AND tip.visibility = 0";
327
328
                break;
329
            default:
330
                $sql_links = null;
331
                break;
332
        }
333
        if ($sql_links != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $sql_links of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
334
            $properties = [];
335
            $result_links = Database::query($sql_links);
336
            while ($links_row = Database::fetch_array($result_links)) {
337
                unset($properties);
338
                $properties['name'] = $links_row['title'];
339
                $properties['link'] = $links_row['url'];
340
                $properties['visibility'] = $links_row['visibility'];
341
                $properties['image'] = $course_tool_category == TOOL_PUBLIC_BUT_HIDDEN ? 'external_na.gif' : 'external.gif';
342
                $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&id='.$links_row['id'];
343
                $all_tools_list[] = $properties;
344
            }
345
        }
346
        $lnk = [];
347
        if (isset($all_tools_list)) {
348
            foreach ($all_tools_list as &$tool) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $all_tools_list does not seem to be defined for all execution paths leading up to this point.
Loading history...
349
                if ($tool['image'] == 'scormbuilder.gif') {
350
                    // check if the published learnpath is visible for student
351
                    $lpId = self::getPublishedLpIdFromLink($tool['link']);
352
353
                    if (!api_is_allowed_to_edit(null, true) &&
354
                        !learnpath::is_lp_visible_for_student(
355
                            $lpId,
356
                            api_get_user_id(),
357
                            api_get_course_id(),
358
                            api_get_session_id()
359
                        )
360
                    ) {
361
                        continue;
362
                    }
363
                }
364
365
                if (api_get_session_id() != 0 &&
366
                    in_array($tool['name'], ['course_maintenance', 'course_setting'])
367
                ) {
368
                    continue;
369
                }
370
371
                if (!($i % 2)) {
372
                    $html .= "<tr valign=\"top\">";
373
                }
374
375
                // NOTE : Table contains only the image file name, not full path
376
                if (stripos($tool['link'], 'http://') === false &&
377
                    stripos($tool['link'], 'https://') === false &&
378
                    stripos($tool['link'], 'ftp://') === false
379
                ) {
380
                    $tool['link'] = $web_code_path.$tool['link'];
381
                }
382
                $class = '';
383
                if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN) {
384
                    $class = 'class="text-muted"';
385
                }
386
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&amp;';
387
388
                $tool['link'] = $tool['link'];
389
                $html .= '<td width="50%" height="30">';
390
391
                if (strpos($tool['name'], 'visio_') !== false) {
392
                    $html .= '<a  '.$class.' href="javascript: void(0);" onclick="javascript: window.open(\''.htmlspecialchars($tool['link']).(($tool['image'] == 'external.gif' || $tool['image'] == 'external_na.gif') ? '' : $qm_or_amp.api_get_cidreq()).'\',\'window_visio'.api_get_course_id().'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'">';
393
                } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
394
                    $html .= '<a href="javascript: void(0);" onclick="javascript: window.open(\''.htmlspecialchars($tool['link']).$qm_or_amp.api_get_cidreq().'\',\'window_chat'.api_get_course_id().'\',config=\'height=\'+600+\', width=\'+825+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'" '.$class.'>';
395
                } else {
396
                    $target = isset($tool['target']) ? $tool['target'] : '';
397
                    $html .= '<a href="'.
398
                        htmlspecialchars($tool['link']).(($tool['image'] == 'external.gif' || $tool['image'] == 'external_na.gif') ? '' : $qm_or_amp.api_get_cidreq()).'" target="'.$target.'" '.$class.'>';
399
                }
400
401
                $tool_name = self::translate_tool_name($tool);
402
                $html .= Display::return_icon(
403
                    $tool['image'],
404
                    $tool_name,
405
                    [],
406
                    null,
407
                    ICON_SIZE_MEDIUM
408
                ).'&nbsp;'.$tool_name.
409
                '</a>';
410
411
                // This part displays the links to hide or remove a tool.
412
                // These links are only visible by the course manager.
413
                $lnk = [];
414
                if (api_is_allowed_to_edit(null, true) && !api_is_coach()) {
415
                    if ($tool['visibility'] == '1' || $tool['name'] == TOOL_TRACKING) {
416
                        $link['name'] = Display::returnFontAwesomeIcon('minus');
417
                        $link['title'] = get_lang('Deactivate');
418
                        $link['cmd'] = 'hide=yes';
419
                        $lnk[] = $link;
420
                    }
421
422
                    if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN) {
423
                        //$link['name'] = Display::return_icon('add.gif', get_lang('Activate'));
424
                        $link['name'] = Display::returnFontAwesomeIcon('plus');
425
                        $link['title'] = get_lang('Activate');
426
                        $link['cmd'] = 'restore=yes';
427
                        $lnk[] = $link;
428
429
                        if ($tool['added_tool'] == 1) {
430
                            //$link['name'] = Display::return_icon('delete.gif', get_lang('Remove'));
431
                            $link['name'] = Display::returnFontAwesomeIcon('trash');
432
                            $link['title'] = get_lang('Remove');
433
                            $link['cmd'] = 'remove=yes';
434
                            $lnk[] = $link;
435
                        }
436
                    }
437
                    if (isset($tool['adminlink'])) {
438
                        $html .= '<a href="'.$tool['adminlink'].'">'.
439
                            Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
440
                    }
441
                }
442
                if (api_is_platform_admin() && !api_is_coach()) {
443
                    if ($tool['visibility'] == 2) {
444
                        $link['name'] = Display::returnFontAwesomeIcon('undo');
445
                        $link['title'] = get_lang('Activate');
446
                        $link['cmd'] = 'hide=yes';
447
                        $lnk[] = $link;
448
449
                        if ($tool['added_tool'] == 1) {
450
                            $link['name'] = get_lang('Delete');
451
                            $link['cmd'] = 'askDelete=yes';
452
                            $lnk[] = $link;
453
                        }
454
                    }
455
                    if ($tool['visibility'] == 0 && $tool['added_tool'] == 0) {
456
                        $link['name'] = Display::returnFontAwesomeIcon('trash');
457
                        $link['title'] = get_lang('Remove');
458
                        $link['cmd'] = 'remove=yes';
459
                        $lnk[] = $link;
460
                    }
461
                }
462
                if (is_array($lnk)) {
463
                    $html .= '<div class="pull-right">';
464
                    $html .= '<div class="btn-options">';
465
                    $html .= '<div class="btn-group btn-group-sm" role="group">';
466
                    foreach ($lnk as &$this_link) {
467
                        if (!isset($tool['adminlink'])) {
468
                            $html .= '<a class="btn btn-default" title='.$this_link['title'].' href="'.api_get_self().'?'.api_get_cidreq().'&amp;id='.$tool['id'].'&amp;'.$this_link['cmd'].'">'.$this_link['name'].'</a>';
469
                        }
470
                    }
471
                    $html .= '</div>';
472
                    $html .= '</div>';
473
                    $html .= '</div>';
474
                }
475
                $html .= "</td>";
476
477
                if ($i % 2) {
478
                    $html .= "</tr>";
479
                }
480
                $i++;
481
            }
482
        }
483
484
        if ($i % 2) {
485
            $html .= "<td width=\"50%\">&nbsp;</td></tr>";
486
        }
487
488
        return $html;
489
    }
490
491
    /**
492
     * Gets the tools of a certain category. Returns an array expected
493
     * by show_tools_category().
494
     *
495
     * @param string $course_tool_category contains the category of tools to
496
     *                                     display: "toolauthoring", "toolinteraction", "tooladmin", "tooladminplatform", "toolplugin"
497
     * @param int    $courseId             Optional
498
     * @param int    $sessionId            Optional
499
     *
500
     * @return array
501
     */
502
    public static function get_tools_category(
503
        $course_tool_category,
504
        $courseId = 0,
505
        $sessionId = 0
506
    ) {
507
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
508
        $is_platform_admin = api_is_platform_admin();
509
        $all_tools_list = [];
510
511
        // Condition for the session
512
        $sessionId = $sessionId ?: api_get_session_id();
513
        $course_id = $courseId ?: api_get_course_int_id();
514
        $userId = api_get_user_id();
515
        $user = api_get_user_entity($userId);
516
        $condition_session = api_get_session_condition(
517
            $sessionId,
518
            true,
519
            true,
520
            't.session_id'
521
        );
522
523
        $lpTable = Database::get_course_table(TABLE_LP_MAIN);
524
        $studentView = api_is_student_view_active();
525
526
        $orderBy = ' ORDER BY id ';
527
        switch ($course_tool_category) {
528
            case TOOL_STUDENT_VIEW:
529
                $conditions = ' WHERE visibility = 1 AND 
530
                                (category = "authoring" OR category = "interaction" OR category = "plugin") AND 
531
                                t.name <> "notebookteacher" ';
532
                if ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) && !$studentView) {
533
                    $conditions = ' WHERE (
534
                        visibility = 1 AND (
535
                            category = "authoring" OR 
536
                            category = "interaction" OR 
537
                            category = "plugin"
538
                        ) OR (t.name = "'.TOOL_TRACKING.'") 
539
                    )';
540
                }
541
542
                // Add order if there are LPs
543
                $sql = "SELECT t.* FROM $course_tool_table t
544
                        LEFT JOIN $lpTable l 
545
                        ON (t.c_id = l.c_id AND link LIKE concat('%/lp_controller.php?action=view&lp_id=', l.id, '&%'))
546
                        $conditions AND
547
                        t.c_id = $course_id $condition_session 
548
                        ORDER BY CASE WHEN l.display_order IS NULL THEN 0 ELSE 1 END, l.display_order, t.id";
549
                $orderBy = '';
550
                break;
551
            case TOOL_AUTHORING:
552
                $sql = "SELECT t.* FROM $course_tool_table t
553
                        LEFT JOIN $lpTable l 
554
                        ON (t.c_id = l.c_id AND link LIKE concat('%/lp_controller.php?action=view&lp_id=', l.id, '&%'))
555
                        WHERE 
556
                            category = 'authoring' AND t.c_id = $course_id $condition_session
557
                        ORDER BY CASE WHEN l.display_order IS NULL THEN 0 ELSE 1 END, l.display_order, t.id";
558
                $orderBy = '';
559
                break;
560
            case TOOL_INTERACTION:
561
                $sql = "SELECT * FROM $course_tool_table t
562
                        WHERE category = 'interaction' AND c_id = $course_id $condition_session
563
                        ";
564
                break;
565
            case TOOL_ADMIN_VISIBLE:
566
                $sql = "SELECT * FROM $course_tool_table t
567
                        WHERE category = 'admin' AND visibility ='1' AND c_id = $course_id $condition_session
568
                        ";
569
                break;
570
            case TOOL_ADMIN_PLATFORM:
571
                $sql = "SELECT * FROM $course_tool_table t
572
                        WHERE category = 'admin' AND c_id = $course_id $condition_session
573
                        ";
574
                break;
575
            case TOOL_DRH:
576
                $sql = "SELECT * FROM $course_tool_table t
577
                        WHERE t.name IN ('tracking') AND c_id = $course_id $condition_session
578
                        ";
579
                break;
580
            case TOOL_COURSE_PLUGIN:
581
                //Other queries recover id, name, link, image, visibility, admin, address, added_tool, target, category and session_id
582
                // but plugins are not present in the tool table, only globally and inside the course_settings table once configured
583
                $sql = "SELECT * FROM $course_tool_table t
584
                        WHERE category = 'plugin' AND name <> 'courseblock' AND c_id = $course_id $condition_session
585
                        ";
586
                break;
587
        }
588
        $sql .= $orderBy;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sql does not seem to be defined for all execution paths leading up to this point.
Loading history...
589
        $result = Database::query($sql);
590
        $tools = [];
591
        while ($row = Database::fetch_assoc($result)) {
592
            $tools[] = $row;
593
        }
594
595
        // Get the list of hidden tools - this might imply performance slowdowns
596
        // if the course homepage is loaded many times, so the list of hidden
597
        // tools might benefit from a shared memory storage later on
598
        $list = api_get_settings('Tools', 'list', api_get_current_access_url_id());
599
        $hide_list = [];
600
        $check = false;
601
        foreach ($list as $line) {
602
            // Admin can see all tools even if the course_hide_tools configuration is set
603
            if ($is_platform_admin) {
604
                continue;
605
            }
606
            if ($line['variable'] == 'course_hide_tools' && $line['selected_value'] == 'true') {
607
                $hide_list[] = $line['subkey'];
608
                $check = true;
609
            }
610
        }
611
612
        $allowEditionInSession = api_get_configuration_value('allow_edit_tool_visibility_in_session');
613
        // If exists same tool (by name) from session in base course then avoid it. Allow them pass in other cases
614
        $tools = array_filter($tools, function (array $toolToFilter) use ($sessionId, $tools) {
0 ignored issues
show
Unused Code introduced by
The import $sessionId is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
615
            if (!empty($toolToFilter['session_id'])) {
616
                foreach ($tools as $originalTool) {
617
                    if ($toolToFilter['name'] == $originalTool['name'] && empty($originalTool['session_id'])) {
618
                        return false;
619
                    }
620
                }
621
            }
622
623
            return true;
624
        });
625
626
        foreach ($tools as $temp_row) {
627
            $add = false;
628
            if ($check) {
629
                if (!in_array($temp_row['name'], $hide_list)) {
630
                    $add = true;
631
                }
632
            } else {
633
                $add = true;
634
            }
635
636
            if ($allowEditionInSession && !empty($sessionId)) {
637
                // Checking if exist row in session
638
                $criteria = [
639
                    'course' => $course_id,
640
                    'name' => $temp_row['name'],
641
                    'sessionId' => $sessionId,
642
                ];
643
                /** @var CTool $toolObj */
644
                $toolObj = Database::getManager()->getRepository('ChamiloCourseBundle:CTool')->findOneBy($criteria);
645
                if ($toolObj) {
646
                    if (api_is_allowed_to_edit() == false && $toolObj->getVisibility() == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
647
                        continue;
648
                    }
649
                }
650
            }
651
652
            switch ($temp_row['image']) {
653
                case 'scormbuilder.gif':
654
                    $lpId = self::getPublishedLpIdFromLink($temp_row['link']);
655
                    $lp = new learnpath(
656
                        api_get_course_id(),
657
                        $lpId,
658
                        $userId
659
                    );
660
                    $path = $lp->get_preview_image_path(ICON_SIZE_BIG);
661
662
                    if (api_is_allowed_to_edit(null, true)) {
663
                        $add = true;
664
                    } else {
665
                        $add = learnpath::is_lp_visible_for_student(
666
                            $lpId,
667
                            $userId,
668
                            api_get_course_id(),
669
                            api_get_session_id()
670
                        );
671
                    }
672
                    if ($path) {
673
                        $temp_row['custom_image'] = $path;
674
                    }
675
                    break;
676
                case 'lp_category.gif':
677
                    $lpCategory = self::getPublishedLpCategoryFromLink(
678
                        $temp_row['link']
679
                    );
680
                    $add = learnpath::categoryIsVisibleForStudent(
681
                        $lpCategory,
682
                        $user
683
                    );
684
                    break;
685
            }
686
687
            if ($add) {
688
                $all_tools_list[] = $temp_row;
689
            }
690
        }
691
692
        // Grabbing all the links that have the property on_homepage set to 1
693
        $course_link_table = Database::get_course_table(TABLE_LINK);
694
        $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
695
        $condition_session = api_get_session_condition(
696
            $sessionId,
697
            true,
698
            true,
699
            'tip.session_id'
700
        );
701
702
        switch ($course_tool_category) {
703
            case TOOL_AUTHORING:
704
                $sql_links = "SELECT tl.*, tip.visibility
705
                    FROM $course_link_table tl
706
                    LEFT JOIN $course_item_property_table tip
707
                    ON tip.tool='link' AND tip.ref=tl.id
708
                    WHERE
709
                        tl.c_id = $course_id AND
710
                        tip.c_id = $course_id AND
711
                        tl.on_homepage='1' $condition_session";
712
                break;
713
            case TOOL_INTERACTION:
714
                $sql_links = null;
715
                /*
716
                  $sql_links = "SELECT tl.*, tip.visibility
717
                  FROM $course_link_table tl
718
                  LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
719
                  WHERE tl.on_homepage='1' ";
720
                 */
721
                break;
722
            case TOOL_STUDENT_VIEW:
723
                $sql_links = "SELECT tl.*, tip.visibility
724
                    FROM $course_link_table tl
725
                    LEFT JOIN $course_item_property_table tip
726
                    ON tip.tool='link' AND tip.ref=tl.id
727
                    WHERE
728
                        tl.c_id 		= $course_id AND
729
                        tip.c_id 		= $course_id AND
730
                        tl.on_homepage	='1' $condition_session";
731
                break;
732
            case TOOL_ADMIN:
733
                $sql_links = "SELECT tl.*, tip.visibility
734
                    FROM $course_link_table tl
735
                    LEFT JOIN $course_item_property_table tip
736
                    ON tip.tool='link' AND tip.ref=tl.id
737
                    WHERE
738
                        tl.c_id = $course_id AND
739
                        tip.c_id = $course_id AND
740
                        tl.on_homepage='1' $condition_session";
741
                break;
742
            default:
743
                $sql_links = null;
744
                break;
745
        }
746
747
        // Edited by Kevin Van Den Haute ([email protected]) for integrating Smartblogs
748
        if ($sql_links != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $sql_links of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
749
            $result_links = Database::query($sql_links);
750
            if (Database::num_rows($result_links) > 0) {
751
                while ($links_row = Database::fetch_array($result_links, 'ASSOC')) {
752
                    $properties = [];
753
                    $properties['name'] = $links_row['title'];
754
                    $properties['session_id'] = $links_row['session_id'];
755
                    $properties['link'] = $links_row['url'];
756
                    $properties['visibility'] = $links_row['visibility'];
757
                    $properties['image'] = $links_row['visibility'] == '0' ? 'file_html.png' : 'file_html.png';
758
                    $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&id='.$links_row['id'];
759
                    $properties['target'] = $links_row['target'];
760
                    $tmp_all_tools_list[] = $properties;
761
                }
762
            }
763
        }
764
765
        if (isset($tmp_all_tools_list)) {
766
            $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
767
            foreach ($tmp_all_tools_list as $tool) {
768
                if ($tool['image'] == 'blog.gif') {
769
                    // Init
770
                    $blog_id = substr($tool['link'], strrpos($tool['link'], '=') + 1, strlen($tool['link']));
771
772
                    // Get blog members
773
                    if ($is_platform_admin) {
774
                        $sql = "SELECT * FROM $tbl_blogs_rel_user blogs_rel_user
775
                                WHERE blog_id = ".$blog_id;
776
                    } else {
777
                        $sql = "SELECT * FROM $tbl_blogs_rel_user blogs_rel_user
778
                                WHERE blog_id = ".$blog_id." AND user_id = ".$userId;
779
                    }
780
                    $result = Database::query($sql);
781
                    if (Database::num_rows($result) > 0) {
782
                        $all_tools_list[] = $tool;
783
                    }
784
                } else {
785
                    $all_tools_list[] = $tool;
786
                }
787
            }
788
        }
789
790
        $list = self::filterPluginTools($all_tools_list, $course_tool_category);
791
792
        return $list;
793
    }
794
795
    /**
796
     * Displays the tools of a certain category.
797
     *
798
     * @param array $all_tools_list List of tools as returned by get_tools_category()
799
     * @param bool  $rows
800
     *
801
     * @return array
802
     */
803
    public static function show_tools_category($all_tools_list, $rows = false)
0 ignored issues
show
Unused Code introduced by
The parameter $rows is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

803
    public static function show_tools_category($all_tools_list, /** @scrutinizer ignore-unused */ $rows = false)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
804
    {
805
        $_user = api_get_user_info();
806
        $theme = api_get_setting('homepage_view');
807
808
        if ($theme === 'vertical_activity') {
809
            //ordering by get_lang name
810
            $order_tool_list = [];
811
            if (is_array($all_tools_list) && count($all_tools_list) > 0) {
812
                foreach ($all_tools_list as $key => $new_tool) {
813
                    $tool_name = self::translate_tool_name($new_tool);
814
                    $order_tool_list[$key] = $tool_name;
815
                }
816
                natsort($order_tool_list);
817
                $my_temp_tool_array = [];
818
                foreach ($order_tool_list as $key => $new_tool) {
819
                    $my_temp_tool_array[] = $all_tools_list[$key];
820
                }
821
                $all_tools_list = $my_temp_tool_array;
822
            } else {
823
                $all_tools_list = [];
824
            }
825
        }
826
        $web_code_path = api_get_path(WEB_CODE_PATH);
827
        $session_id = api_get_session_id();
828
        $is_platform_admin = api_is_platform_admin();
829
        $allowEditionInSession = api_get_configuration_value('allow_edit_tool_visibility_in_session');
830
        if ($session_id == 0) {
831
            $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && api_is_course_admin();
832
        } else {
833
            $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && !api_is_coach();
834
            if ($allowEditionInSession) {
835
                $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && api_is_coach($session_id, api_get_course_int_id());
836
            }
837
        }
838
839
        $items = [];
840
        $app_plugin = new AppPlugin();
841
842
        if (isset($all_tools_list)) {
843
            $lnk = '';
844
            foreach ($all_tools_list as &$tool) {
845
                $item = [];
846
                $studentview = false;
847
                $tool['original_link'] = $tool['link'];
848
                if ($tool['image'] == 'scormbuilder.gif') {
849
                    // check if the published learnpath is visible for student
850
                    $lpId = self::getPublishedLpIdFromLink($tool['link']);
851
                    if (api_is_allowed_to_edit(null, true)) {
852
                        $studentview = true;
853
                    }
854
                    if (!api_is_allowed_to_edit(null, true) &&
855
                        !learnpath::is_lp_visible_for_student(
856
                            $lpId,
857
                            api_get_user_id(),
858
                            api_get_course_id(),
859
                            api_get_session_id()
860
                        )
861
                    ) {
862
                        continue;
863
                    }
864
                }
865
866
                if ($session_id != 0 && in_array($tool['name'], ['course_setting'])) {
867
                    continue;
868
                }
869
870
                // This part displays the links to hide or remove a tool.
871
                // These links are only visible by the course manager.
872
                unset($lnk);
873
874
                $item['extra'] = null;
875
                $toolAdmin = isset($tool['admin']) ? $tool['admin'] : '';
876
877
                if ($is_allowed_to_edit) {
878
                    if (empty($session_id)) {
879
                        if (isset($tool['id'])) {
880
                            if ($tool['visibility'] == '1' && $toolAdmin != '1') {
881
                                $link['name'] = Display::return_icon(
882
                                    'visible.png',
883
                                    get_lang('Deactivate'),
884
                                    ['id' => 'linktool_'.$tool['iid']],
885
                                    ICON_SIZE_SMALL,
886
                                    false
887
                                );
888
                                $link['cmd'] = 'hide=yes';
889
                                $lnk[] = $link;
890
                            }
891
                            if ($tool['visibility'] == '0' && $toolAdmin != '1') {
892
                                $link['name'] = Display::return_icon(
893
                                    'invisible.png',
894
                                    get_lang('Activate'),
895
                                    ['id' => 'linktool_'.$tool['iid']],
896
                                    ICON_SIZE_SMALL,
897
                                    false
898
                                );
899
                                $link['cmd'] = 'restore=yes';
900
                                $lnk[] = $link;
901
                            }
902
                        }
903
                    } elseif ($allowEditionInSession) {
904
                        $criteria = [
905
                            'course' => api_get_course_int_id(),
906
                            'name' => $tool['name'],
907
                            'sessionId' => $session_id,
908
                        ];
909
                        /** @var CTool $tool */
910
                        $toolObj = Database::getManager()->getRepository('ChamiloCourseBundle:CTool')->findOneBy($criteria);
911
                        if ($toolObj) {
912
                            $visibility = (int) $toolObj->getVisibility();
913
                            switch ($visibility) {
914
                                case '0':
915
                                    $info = pathinfo($tool['image']);
916
                                    $basename = basename($tool['image'], '.'.$info['extension']); // $file is set to "index"
917
                                    $tool['image'] = $basename.'_na.'.$info['extension'];
918
919
                                    $link['name'] = Display::return_icon(
920
                                        'invisible.png',
921
                                        get_lang('Activate'),
922
                                        ['id' => 'linktool_'.$tool['iid']],
923
                                        ICON_SIZE_SMALL,
924
                                        false
925
                                    );
926
                                    $link['cmd'] = 'restore=yes';
927
                                    $lnk[] = $link;
928
                                    break;
929
                                case '1':
930
                                    $link['name'] = Display::return_icon(
931
                                        'visible.png',
932
                                        get_lang('Deactivate'),
933
                                        ['id' => 'linktool_'.$tool['iid']],
934
                                        ICON_SIZE_SMALL,
935
                                        false
936
                                    );
937
                                    $link['cmd'] = 'hide=yes';
938
                                    $lnk[] = $link;
939
                                    break;
940
                            }
941
                        } else {
942
                            $link['name'] = Display::return_icon(
943
                                'visible.png',
944
                                get_lang('Deactivate'),
945
                                ['id' => 'linktool_'.$tool['iid']],
946
                                ICON_SIZE_SMALL,
947
                                false
948
                            );
949
                            $link['cmd'] = 'hide=yes';
950
                            $lnk[] = $link;
951
                        }
952
                    }
953
                    if (!empty($tool['adminlink'])) {
954
                        $item['extra'] = '<a href="'.$tool['adminlink'].'">'.
955
                            Display::return_icon('edit.gif', get_lang('Edit')).
956
                        '</a>';
957
                    }
958
                }
959
960
                // Both checks are necessary as is_platform_admin doesn't take student view into account
961
                if ($is_platform_admin && $is_allowed_to_edit) {
962
                    if ($toolAdmin != '1') {
963
                        $link['cmd'] = 'hide=yes';
964
                    }
965
                }
966
967
                $item['visibility'] = null;
968
                if (isset($lnk) && is_array($lnk)) {
969
                    foreach ($lnk as $this_link) {
970
                        if (empty($tool['adminlink'])) {
971
                            $item['visibility'] .=
972
                                '<a class="make_visible_and_invisible" href="'.api_get_self().'?'.api_get_cidreq().'&id='.$tool['iid'].'&'.$this_link['cmd'].'">'.
973
                                $this_link['name'].'</a>';
974
                        }
975
                    }
976
                } else {
977
                    $item['visibility'] .= '';
978
                }
979
980
                // NOTE : Table contains only the image file name, not full path
981
                if (stripos($tool['link'], 'http://') === false &&
982
                    stripos($tool['link'], 'https://') === false &&
983
                    stripos($tool['link'], 'ftp://') === false
984
                ) {
985
                    $tool['link'] = $web_code_path.$tool['link'];
986
                }
987
988
                $class = '';
989
                if ($tool['visibility'] == '0' && $toolAdmin != '1') {
990
                    $class = 'text-muted';
991
                    $info = pathinfo($tool['image']);
992
                    $basename = basename($tool['image'], '.'.$info['extension']); // $file is set to "index"
993
                    $tool['image'] = $basename.'_na.'.$info['extension'];
994
                }
995
996
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&';
997
                // If it's a link, we don't add the cidReq
998
999
                if ($tool['image'] == 'file_html.png' || $tool['image'] == 'file_html_na.png') {
1000
                    $tool['link'] = $tool['link'];
1001
                } else {
1002
                    $tool['link'] = $tool['link'].$qm_or_amp.api_get_cidreq();
1003
                }
1004
1005
                $tool_link_params = [];
1006
                $toolIid = isset($tool["iid"]) ? $tool["iid"] : null;
1007
1008
                //@todo this visio stuff should be removed
1009
                if (strpos($tool['name'], 'visio_') !== false) {
1010
                    $tool_link_params = [
1011
                        'id' => 'tooldesc_'.$toolIid,
1012
                        'href' => '"javascript: void(0);"',
1013
                        'class' => $class,
1014
                        'onclick' => 'javascript: window.open(\''.$tool['link'].'\',\'window_visio'.api_get_course_id().'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')',
1015
                        'target' => $tool['target'],
1016
                    ];
1017
                } elseif (strpos($tool['name'], 'chat') !== false &&
1018
                    api_get_course_setting('allow_open_chat_window')
1019
                ) {
1020
                    $tool_link_params = [
1021
                        'id' => 'tooldesc_'.$toolIid,
1022
                        'class' => $class,
1023
                        'href' => 'javascript: void(0);',
1024
                        'onclick' => 'javascript: window.open(\''.$tool['link'].'\',\'window_chat'.api_get_course_id().'\',config=\'height=\'+600+\', width=\'+825+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')', //Chat Open Windows
1025
                        'target' => $tool['target'],
1026
                    ];
1027
                } else {
1028
                    $tool_link_params = [
1029
                        'id' => 'tooldesc_'.$toolIid,
1030
                        'href' => $tool['link'],
1031
                        'class' => $class,
1032
                        'target' => $tool['target'],
1033
                    ];
1034
                }
1035
1036
                $tool_name = self::translate_tool_name($tool);
1037
1038
                // Including Courses Plugins
1039
                // Creating title and the link
1040
                if (isset($tool['category']) && $tool['category'] == 'plugin') {
1041
                    $plugin_info = $app_plugin->getPluginInfo($tool['name']);
1042
                    if (isset($plugin_info) && isset($plugin_info['title'])) {
1043
                        $tool_name = $plugin_info['title'];
1044
                    }
1045
1046
                    if (!file_exists(api_get_path(SYS_CODE_PATH).'img/'.$tool['image']) &&
1047
                        !file_exists(api_get_path(SYS_CODE_PATH).'img/icons/64/'.$tool['image'])) {
1048
                        $tool['image'] = 'plugins.png';
1049
                    }
1050
                    $tool_link_params['href'] = api_get_path(WEB_PLUGIN_PATH)
1051
                        .$tool['original_link'].$qm_or_amp.api_get_cidreq();
1052
                }
1053
1054
                // Use in the course home
1055
                $icon = Display::return_icon(
1056
                    $tool['image'],
1057
                    $tool_name,
1058
                    ['class' => 'tool-icon', 'id' => 'toolimage_'.$toolIid],
1059
                    ICON_SIZE_BIG,
1060
                    false
1061
                );
1062
1063
                // Used in the top bar
1064
                $iconMedium = Display::return_icon(
1065
                    $tool['image'],
1066
                    $tool_name,
1067
                    ['class' => 'tool-icon', 'id' => 'toolimage_'.$toolIid],
1068
                    ICON_SIZE_MEDIUM,
1069
                    false
1070
                );
1071
1072
                // Used for vertical navigation
1073
                $iconSmall = Display::return_icon(
1074
                    $tool['image'],
1075
                    $tool_name,
1076
                    ['class' => 'tool-img', 'id' => 'toolimage_'.$toolIid],
1077
                    ICON_SIZE_SMALL,
1078
                    false
1079
                );
1080
1081
                /*if (!empty($tool['custom_icon'])) {
1082
                    $image = self::getCustomWebIconPath().$tool['custom_icon'];
1083
                    $icon = Display::img(
1084
                        $image,
1085
                        $tool['description'],
1086
                        array(
1087
                            'class' => 'tool-icon',
1088
                            'id' => 'toolimage_'.$tool['id']
1089
                        )
1090
                    );
1091
                }*/
1092
1093
                // Validation when belongs to a session
1094
                $session_img = api_get_session_image(
1095
                    $tool['session_id'],
1096
                    !empty($_user['status']) ? $_user['status'] : ''
0 ignored issues
show
Bug introduced by
It seems like ! empty($_user['status']) ? $_user['status'] : '' can also be of type string; however, parameter $status_id of api_get_session_image() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1096
                    /** @scrutinizer ignore-type */ !empty($_user['status']) ? $_user['status'] : ''
Loading history...
1097
                );
1098
                if ($studentview) {
1099
                    $tool_link_params['href'] .= '&isStudentView=true';
1100
                }
1101
                $item['url_params'] = $tool_link_params;
1102
                $item['icon'] = Display::url($icon, $tool_link_params['href'], $tool_link_params);
1103
                $item['only_icon'] = $icon;
1104
                $item['only_icon_medium'] = $iconMedium;
1105
                $item['only_icon_small'] = $iconSmall;
1106
                $item['only_href'] = $tool_link_params['href'];
1107
                $item['tool'] = $tool;
1108
                $item['name'] = $tool_name;
1109
                $tool_link_params['id'] = 'is'.$tool_link_params['id'];
1110
                $item['link'] = Display::url(
1111
                    $tool_name.$session_img,
1112
                    $tool_link_params['href'],
1113
                    $tool_link_params
1114
                );
1115
                $items[] = $item;
1116
            } // end of foreach
1117
        }
1118
1119
        foreach ($items as &$item) {
1120
            $originalImage = self::getToolIcon($item, ICON_SIZE_BIG);
1121
            $item['tool']['only_icon_medium'] = self::getToolIcon($item, ICON_SIZE_MEDIUM, false);
1122
            $item['tool']['only_icon_small'] = self::getToolIcon($item, ICON_SIZE_SMALL, false);
1123
1124
            if ($theme === 'activity_big') {
1125
                $item['tool']['image'] = Display::url(
1126
                    $originalImage,
1127
                    $item['url_params']['href'],
1128
                    $item['url_params']
1129
                );
1130
            }
1131
        }
1132
1133
        return $items;
1134
    }
1135
1136
    /**
1137
     * Shows the general data for a particular meeting.
1138
     *
1139
     * @param int $id_session
1140
     *
1141
     * @return string session data
1142
     */
1143
    public static function show_session_data($id_session)
1144
    {
1145
        $sessionInfo = api_get_session_info($id_session);
1146
1147
        if (empty($sessionInfo)) {
1148
            return '';
1149
        }
1150
1151
        $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
1152
        $sql = 'SELECT name FROM '.$table.'
1153
                WHERE id = "'.intval($sessionInfo['session_category_id']).'"';
1154
        $rs_category = Database::query($sql);
1155
        $session_category = '';
1156
        if (Database::num_rows($rs_category) > 0) {
1157
            $rows_session_category = Database::store_result($rs_category);
1158
            $rows_session_category = $rows_session_category[0];
1159
            $session_category = $rows_session_category['name'];
1160
        }
1161
1162
        $coachInfo = api_get_user_info($sessionInfo['id_coach']);
1163
1164
        $output = '';
1165
        if (!empty($session_category)) {
1166
            $output .= '<tr><td>'.get_lang('SessionCategory').': '.'<b>'.$session_category.'</b></td></tr>';
1167
        }
1168
        $dateInfo = SessionManager::parseSessionDates($sessionInfo);
1169
1170
        $msgDate = $dateInfo['access'];
1171
        $output .= '<tr>
1172
                    <td style="width:50%">'.get_lang('SessionName').': '.'<b>'.$sessionInfo['name'].'</b></td>
1173
                    <td>'.get_lang('GeneralCoach').': '.'<b>'.$coachInfo['complete_name'].'</b></td></tr>';
1174
        $output .= '<tr>
1175
                        <td>'.get_lang('SessionIdentifier').': '.
1176
                            Display::return_icon('star.png', ' ', ['align' => 'absmiddle']).'
1177
                        </td>
1178
                        <td>'.get_lang('Date').': '.'<b>'.$msgDate.'</b>
1179
                        </td>
1180
                    </tr>';
1181
1182
        return $output;
1183
    }
1184
1185
    /**
1186
     * Retrieves the name-field within a tool-record and translates it on necessity.
1187
     *
1188
     * @param array $tool the input record
1189
     *
1190
     * @return string returns the name of the corresponding tool
1191
     */
1192
    public static function translate_tool_name(&$tool)
1193
    {
1194
        static $already_translated_icons = [
1195
            'file_html.gif',
1196
            'file_html_na.gif',
1197
            'file_html.png',
1198
            'file_html_na.png',
1199
            'scormbuilder.gif',
1200
            'scormbuilder_na.gif',
1201
            'blog.gif',
1202
            'blog_na.gif',
1203
            'external.gif',
1204
            'external_na.gif',
1205
        ];
1206
1207
        $toolName = Security::remove_XSS(stripslashes($tool['name']));
1208
1209
        if (isset($tool['image']) && in_array($tool['image'], $already_translated_icons)) {
1210
            return $toolName;
1211
        }
1212
1213
        $toolName = api_underscore_to_camel_case($toolName);
1214
1215
        if (isset($tool['category']) && 'plugin' !== $tool['category'] &&
1216
            isset($GLOBALS['Tool'.$toolName])
1217
        ) {
1218
            return get_lang('Tool'.$toolName);
1219
        }
1220
1221
        return $toolName;
1222
    }
1223
1224
    /**
1225
     * Get published learning path id from link inside course home.
1226
     *
1227
     * @param 	string	Link to published lp
1228
     *
1229
     * @return int Learning path id
1230
     */
1231
    public static function getPublishedLpIdFromLink($link)
1232
    {
1233
        $lpId = 0;
1234
        $param = strstr($link, 'lp_id=');
1235
        if (!empty($param)) {
1236
            $paramList = explode('=', $param);
1237
            if (isset($paramList[1])) {
1238
                $lpId = (int) $paramList[1];
1239
            }
1240
        }
1241
1242
        return $lpId;
1243
    }
1244
1245
    /**
1246
     * Get published learning path category from link inside course home.
1247
     *
1248
     * @param string $link
1249
     *
1250
     * @return CLpCategory
1251
     */
1252
    public static function getPublishedLpCategoryFromLink($link)
1253
    {
1254
        $query = parse_url($link, PHP_URL_QUERY);
1255
        parse_str($query, $params);
1256
        $id = isset($params['id']) ? (int) $params['id'] : 0;
1257
        $em = Database::getManager();
1258
        /** @var CLpCategory $category */
1259
        $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
1260
1261
        return $category;
1262
    }
1263
1264
    /**
1265
     * Show a navigation menu.
1266
     */
1267
    public static function show_navigation_menu()
1268
    {
1269
        $blocks = self::getUserBlocks();
1270
        $class = null;
1271
        $idLearn = null;
1272
        $item = null;
1273
        $marginLeft = 160;
1274
1275
        $html = '<div id="toolnav">';
1276
        $html .= '<ul id="toolnavbox">';
1277
            //students can't see the course settings option
1278
        $showOnlyText = api_get_setting('show_navigation_menu') === 'text';
1279
        $showOnlyIcons = api_get_setting('show_navigation_menu') === 'icons';
1280
1281
        foreach ($blocks as $block) {
1282
            $blockItems = $block['content'];
1283
            foreach ($blockItems as $item) {
1284
            $html .= '<li>';
1285
                if ($showOnlyText) {
1286
                $class = 'text';
1287
                $marginLeft = 170;
1288
                    $show = $item['name'];
1289
                } elseif ($showOnlyIcons) {
1290
                    $class = 'icons';
1291
                    $marginLeft = 25;
1292
                    $show = $item['tool']['only_icon_small'];
1293
                } else {
1294
                    $class = 'icons-text';
1295
                        $show = $item['name'].$item['tool']['only_icon_small'];
1296
                }
1297
1298
                $item['url_params']['class'] = 'btn btn-default text-left '.$class;
1299
                $html .= Display::url(
1300
                    $show,
1301
                    $item['only_href'],
1302
                    $item['url_params']
1303
                );
1304
            $html .= '</li>';
1305
            }
1306
        }
1307
1308
        $html .= '</ul>';
1309
        $html .= '<script>$(function() {
1310
                $("#toolnavbox a").stop().animate({"margin-left":"-'.$marginLeft.'px"},1000);
1311
                $("#toolnavbox > li").hover(
1312
                    function () {
1313
                        $("a",$(this)).stop().animate({"margin-left":"-2px"},200);
1314
                        $("span",$(this)).css("display","block");
1315
                    },
1316
                    function () {
1317
                        $("a",$(this)).stop().animate({"margin-left":"-'.$marginLeft.'px"},200);
1318
                        $("span",$(this)).css("display","initial");
1319
                    }
1320
                );
1321
            });</script>';
1322
        $html .= '</div>';
1323
1324
        return $html;
1325
    }
1326
1327
    /**
1328
     * Show a toolbar with shortcuts to the course tool.
1329
     *
1330
     * @param int $orientation
1331
     *
1332
     * @return string
1333
     */
1334
    public static function getCourseToolBar($orientation = SHORTCUTS_HORIZONTAL): string
1335
    {
1336
        $origin = api_get_origin();
1337
        $courseInfo = api_get_course_info();
1338
        if ($origin === 'learnpath') {
1339
            return '';
1340
        }
1341
1342
        $blocks = self::getUserBlocks();
1343
1344
        $html = '';
1345
        if (!empty($blocks)) {
1346
            $style_id = 'toolshortcuts_vertical';
1347
            if ($orientation == SHORTCUTS_HORIZONTAL) {
1348
                $style_id = 'toolshortcuts_horizontal';
1349
            }
1350
            $html .= '<div id="'.$style_id.'">';
1351
1352
            $html .= Display::url(
1353
                Display::return_icon('home.png', get_lang('CourseHomepageLink'), '', ICON_SIZE_MEDIUM),
1354
                $courseInfo['course_public_url'],
1355
                ['class' => 'items-icon']
1356
            );
1357
1358
            foreach ($blocks as $block) {
1359
                $blockItems = $block['content'];
1360
                foreach ($blockItems as $item) {
1361
                    $item['url_params']['id'] = '';
1362
                    $item['url_params']['class'] = 'items-icon';
1363
                    $html .= Display::url(
1364
                        $item['tool']['only_icon_medium'],
1365
                        $item['only_href'],
1366
                        $item['url_params']
1367
                    );
1368
                    if ($orientation == SHORTCUTS_VERTICAL) {
1369
                        $html .= '<br />';
1370
                    }
1371
                }
1372
            }
1373
            $html .= '</div>';
1374
        }
1375
1376
        return $html;
1377
    }
1378
1379
    /**
1380
     * List course homepage tools from authoring and interaction sections.
1381
     *
1382
     * @param int $courseId  The course ID (guessed from context if not provided)
1383
     * @param int $sessionId The session ID (guessed from context if not provided)
1384
     *
1385
     * @return array List of all tools data from the c_tools table
1386
     */
1387
    public static function toolsIconsAction($courseId = null, $sessionId = null)
1388
    {
1389
        if (empty($courseId)) {
1390
            $courseId = api_get_course_int_id();
1391
        } else {
1392
            $courseId = intval($courseId);
1393
        }
1394
        if (empty($sessionId)) {
1395
            $sessionId = api_get_session_id();
1396
        } else {
1397
            $sessionId = intval($sessionId);
1398
        }
1399
1400
        if (empty($courseId)) {
1401
            // We shouldn't get here, but for some reason api_get_course_int_id()
1402
            // doesn't seem to get the course from the context, sometimes
1403
            return [];
1404
        }
1405
1406
        $table = Database::get_course_table(TABLE_TOOL_LIST);
1407
        $sql = "SELECT * FROM $table
1408
                WHERE category in ('authoring','interaction')
1409
                AND c_id = $courseId
1410
                AND session_id = $sessionId
1411
                ORDER BY id";
1412
1413
        $result = Database::query($sql);
1414
        $data = Database::store_result($result, 'ASSOC');
1415
1416
        return $data;
1417
    }
1418
1419
    /**
1420
     * @param int $editIcon
1421
     *
1422
     * @return array
1423
     */
1424
    public static function getTool($editIcon)
1425
    {
1426
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
1427
        $editIcon = intval($editIcon);
1428
1429
        $sql = "SELECT * FROM $course_tool_table
1430
                WHERE iid = $editIcon";
1431
        $result = Database::query($sql);
1432
        $tool = Database::fetch_assoc($result, 'ASSOC');
1433
1434
        return $tool;
1435
    }
1436
1437
    /**
1438
     * @return string
1439
     */
1440
    public static function getCustomSysIconPath()
1441
    {
1442
        // Check if directory exists or create it if it doesn't
1443
        $dir = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
1444
        if (!is_dir($dir)) {
1445
            mkdir($dir, api_get_permissions_for_new_directories(), true);
1446
        }
1447
1448
        return $dir;
1449
    }
1450
1451
    /**
1452
     * @return string
1453
     */
1454
    public static function getCustomWebIconPath()
1455
    {
1456
        // Check if directory exists or create it if it doesn't
1457
        $dir = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
1458
1459
        return $dir;
1460
    }
1461
1462
    /**
1463
     * @param string $icon
1464
     *
1465
     * @return string
1466
     */
1467
    public static function getDisableIcon($icon)
1468
    {
1469
        $fileInfo = pathinfo($icon);
1470
1471
        return $fileInfo['filename'].'_na.'.$fileInfo['extension'];
1472
    }
1473
1474
    /**
1475
     * @param int   $id
1476
     * @param array $values
1477
     */
1478
    public static function updateTool($id, $values)
1479
    {
1480
        $table = Database::get_course_table(TABLE_TOOL_LIST);
1481
        $params = [
1482
            'name' => $values['name'],
1483
            'link' => $values['link'],
1484
            'target' => $values['target'],
1485
            'visibility' => $values['visibility'],
1486
            'description' => $values['description'],
1487
        ];
1488
1489
        if (isset($_FILES['icon']['size']) && $_FILES['icon']['size'] !== 0) {
1490
            $dir = self::getCustomSysIconPath();
1491
1492
            // Resize image if it is larger than 64px
1493
            $temp = new Image($_FILES['icon']['tmp_name']);
1494
            $picture_infos = $temp->get_image_info();
1495
            if ($picture_infos['width'] > 64) {
1496
                $thumbwidth = 64;
1497
            } else {
1498
                $thumbwidth = $picture_infos['width'];
1499
            }
1500
            if ($picture_infos['height'] > 64) {
1501
                $new_height = 64;
1502
            } else {
1503
                $new_height = $picture_infos['height'];
1504
            }
1505
            $temp->resize($thumbwidth, $new_height, 0);
1506
1507
            //copy the image to the course upload folder
1508
            $path = $dir.$_FILES['icon']['name'];
1509
            $result = $temp->send_image($path);
1510
1511
            $temp = new Image($path);
1512
            $r = $temp->convert2bw();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $r is correct as $temp->convert2bw() targeting Image::convert2bw() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1513
            $ext = pathinfo($path, PATHINFO_EXTENSION);
1514
            $bwPath = substr($path, 0, -(strlen($ext) + 1)).'_na.'.$ext;
1515
1516
            if ($r === false) {
1517
                error_log('Conversion to B&W of '.$path.' failed in '.__FILE__.' at line '.__LINE__);
1518
            } else {
1519
                $temp->send_image($bwPath);
1520
                $iconName = $_FILES['icon']['name'];
1521
                $params['custom_icon'] = $iconName;
1522
            }
1523
        }
1524
1525
        Database::update(
1526
            $table,
1527
            $params,
1528
            [' iid = ?' => [$id]]
1529
        );
1530
    }
1531
1532
    /**
1533
     * @param int $id
1534
     */
1535
    public static function deleteIcon($id)
1536
    {
1537
        $table = Database::get_course_table(TABLE_TOOL_LIST);
1538
        $tool = self::getTool($id);
1539
1540
        if ($tool && !empty($tool['custom_icon'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tool of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1541
            $file = self::getCustomSysIconPath().$tool['custom_icon'];
1542
            $fileInfo = pathinfo($file);
1543
            $fileGray = $fileInfo['filename'].'_na.'.$fileInfo['extension'];
1544
            $fileGray = self::getCustomSysIconPath().$fileGray;
1545
1546
            if (file_exists($file) && is_file($file)) {
1547
                if (Security::check_abs_path($file, self::getCustomSysIconPath())) {
1548
                    unlink($file);
1549
                }
1550
            }
1551
1552
            if (file_exists($fileGray) && is_file($fileGray)) {
1553
                if (Security::check_abs_path($fileGray, self::getCustomSysIconPath())) {
1554
                    unlink($fileGray);
1555
                }
1556
            }
1557
1558
            $params = [
1559
                'custom_icon' => '',
1560
            ];
1561
1562
            Database::update(
1563
                $table,
1564
                $params,
1565
                [' iid = ?' => [$id]]
1566
            );
1567
        }
1568
    }
1569
1570
    /**
1571
     * @return array
1572
     */
1573
    public static function getCourseAdminBlocks()
1574
    {
1575
        $blocks = [];
1576
        $my_list = self::get_tools_category(TOOL_AUTHORING);
1577
1578
        $blocks[] = [
1579
            'title' => get_lang('Authoring'),
1580
            'class' => 'course-tools-author',
1581
            'content' => self::show_tools_category($my_list),
1582
        ];
1583
1584
        $list1 = self::get_tools_category(TOOL_INTERACTION);
1585
        $list2 = self::get_tools_category(TOOL_COURSE_PLUGIN);
1586
        $my_list = array_merge($list1, $list2);
1587
1588
        $blocks[] = [
1589
            'title' => get_lang('Interaction'),
1590
            'class' => 'course-tools-interaction',
1591
            'content' => self::show_tools_category($my_list),
1592
        ];
1593
1594
        $my_list = self::get_tools_category(TOOL_ADMIN_PLATFORM);
1595
1596
        $blocks[] = [
1597
            'title' => get_lang('Administration'),
1598
            'class' => 'course-tools-administration',
1599
            'content' => self::show_tools_category($my_list),
1600
        ];
1601
1602
        return $blocks;
1603
    }
1604
1605
    /**
1606
     * @return array
1607
     */
1608
    public static function getCoachBlocks()
1609
    {
1610
        $blocks = [];
1611
        $my_list = self::get_tools_category(TOOL_STUDENT_VIEW);
1612
1613
        $blocks[] = [
1614
            'content' => self::show_tools_category($my_list),
1615
        ];
1616
1617
        $sessionsCopy = api_get_setting('allow_session_course_copy_for_teachers');
1618
        if ($sessionsCopy === 'true') {
1619
            // Adding only maintenance for coaches.
1620
            $myList = self::get_tools_category(TOOL_ADMIN_PLATFORM);
1621
            $onlyMaintenanceList = [];
1622
1623
            foreach ($myList as $item) {
1624
                if ($item['name'] === 'course_maintenance') {
1625
                    $item['link'] = 'course_info/maintenance_coach.php';
1626
1627
                    $onlyMaintenanceList[] = $item;
1628
                }
1629
            }
1630
1631
            $blocks[] = [
1632
                'title' => get_lang('Administration'),
1633
                'content' => self::show_tools_category($onlyMaintenanceList),
1634
            ];
1635
        }
1636
1637
        return $blocks;
1638
    }
1639
1640
    /**
1641
     * @return array
1642
     */
1643
    public static function getStudentBlocks()
1644
    {
1645
        $blocks = [];
1646
        $tools = self::get_tools_category(TOOL_STUDENT_VIEW);
1647
        $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
1648
            api_get_user_id(),
1649
            api_get_course_info()
1650
        );
1651
1652
        // Force user icon for DRH
1653
        if ($isDrhOfCourse) {
1654
            $addUserTool = true;
1655
            foreach ($tools as $tool) {
1656
                if ($tool['name'] === 'user') {
1657
                    $addUserTool = false;
1658
                    break;
1659
                }
1660
            }
1661
1662
            if ($addUserTool) {
1663
                $tools[] = [
1664
                    'c_id' => api_get_course_int_id(),
1665
                    'name' => 'user',
1666
                    'link' => 'user/user.php',
1667
                    'image' => 'members.gif',
1668
                    'visibility' => '1',
1669
                    'admin' => '0',
1670
                    'address' => 'squaregrey.gif',
1671
                    'added_tool' => '0',
1672
                    'target' => '_self',
1673
                    'category' => 'interaction',
1674
                    'session_id' => api_get_session_id(),
1675
                ];
1676
            }
1677
        }
1678
1679
        if (count($tools) > 0) {
1680
            $blocks[] = ['content' => self::show_tools_category($tools)];
1681
        }
1682
1683
        if ($isDrhOfCourse) {
1684
            $drhTool = self::get_tools_category(TOOL_DRH);
1685
            $blocks[] = ['content' => self::show_tools_category($drhTool)];
1686
        }
1687
1688
        return $blocks;
1689
    }
1690
1691
    /**
1692
     * @return array
1693
     */
1694
    public static function getUserBlocks()
1695
    {
1696
        $sessionId = api_get_session_id();
1697
        // Start of tools for CourseAdmins (teachers/tutors)
1698
        if ($sessionId === 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
1699
            $blocks = self::getCourseAdminBlocks();
1700
        } elseif (api_is_coach()) {
1701
            $blocks = self::getCoachBlocks();
1702
        } else {
1703
            $blocks = self::getStudentBlocks();
1704
        }
1705
1706
        return $blocks;
1707
    }
1708
1709
    /**
1710
     * Filter tool icons. Only show if $patronKey is = :teacher
1711
     * Example dataIcons[i]['name']: parameter titleIcons1:teacher || titleIcons2 || titleIcons3:teacher.
1712
     *
1713
     * @param array  $dataIcons          array Reference to icons
1714
     * @param string $courseToolCategory Current tools category
1715
     *
1716
     * @return array
1717
     */
1718
    private static function filterPluginTools($dataIcons, $courseToolCategory)
1719
    {
1720
        $patronKey = ':teacher';
1721
1722
        if ($courseToolCategory == TOOL_STUDENT_VIEW) {
1723
            //Fix only coach can see external pages - see #8236 - icpna
1724
            if (api_is_coach()) {
1725
                foreach ($dataIcons as $index => $array) {
1726
                    if (isset($array['name'])) {
1727
                        $dataIcons[$index]['name'] = str_replace($patronKey, '', $array['name']);
1728
                    }
1729
                }
1730
1731
                return $dataIcons;
1732
            }
1733
1734
            $flagOrder = false;
1735
1736
            foreach ($dataIcons as $index => $array) {
1737
                if (!isset($array['name'])) {
1738
                    continue;
1739
                }
1740
1741
                $pos = strpos($array['name'], $patronKey);
1742
1743
                if ($pos !== false) {
1744
                    unset($dataIcons[$index]);
1745
                    $flagOrder = true;
1746
                }
1747
            }
1748
1749
            if ($flagOrder) {
1750
                return array_values($dataIcons);
1751
            }
1752
1753
            return $dataIcons;
1754
        }
1755
1756
        // clean patronKey of name icons
1757
        foreach ($dataIcons as $index => $array) {
1758
            if (isset($array['name'])) {
1759
                $dataIcons[$index]['name'] = str_replace($patronKey, '', $array['name']);
1760
            }
1761
        }
1762
1763
        return $dataIcons;
1764
    }
1765
1766
    /**
1767
     * Find the tool icon when homepage_view is activity_big.
1768
     *
1769
     * @param array $item
1770
     * @param int   $iconSize
1771
     * @param bool  $generateId
1772
     *
1773
     * @return string
1774
     */
1775
    private static function getToolIcon(array $item, $iconSize, $generateId = true)
1776
    {
1777
        $image = str_replace('.gif', '.png', $item['tool']['image']);
1778
        $toolIid = isset($item['tool']['iid']) ? $item['tool']['iid'] : null;
1779
1780
        if (isset($item['tool']['custom_image'])) {
1781
            return Display::img(
1782
                $item['tool']['custom_image'],
1783
                $item['name'],
1784
                ['id' => 'toolimage_'.$toolIid]
1785
            );
1786
        }
1787
1788
        if (isset($item['tool']['custom_icon']) && !empty($item['tool']['custom_icon'])) {
1789
            $customIcon = $item['tool']['custom_icon'];
1790
1791
            if ($item['tool']['visibility'] == '0') {
1792
                $customIcon = self::getDisableIcon($item['tool']['custom_icon']);
1793
            }
1794
1795
            return Display::img(
1796
                self::getCustomWebIconPath().$customIcon,
1797
                $item['name'],
1798
                ['id' => 'toolimage_'.$toolIid]
1799
            );
1800
        }
1801
1802
        $id = '';
1803
        if ($generateId) {
1804
            $id = 'toolimage_'.$toolIid;
1805
        }
1806
1807
        return Display::return_icon(
1808
            $image,
1809
            $item['name'],
1810
            ['id' => $id],
1811
            $iconSize,
1812
            false
1813
        );
1814
    }
1815
}
1816