Passed
Push — master ( 06a804...32f36d )
by Julito
13:31
created

CourseHome::show_navigation_tool_shortcuts()   C

Complexity

Conditions 13
Paths 4

Size

Total Lines 56
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 33
nc 4
nop 1
dl 0
loc 56
rs 6.6166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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()) && !$studentView) {
38
                    $condition_display_tools = ' WHERE 
39
                        a.c_id = '.$course_id.' AND 
40
                        a.link=t.link AND
41
                         (t.position="basic" OR a.name = "'.TOOL_TRACKING.'") 
42
                    ';
43
                }
44
45
                $sql = "SELECT a.*, t.image img, t.row, t.column  
46
                        FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
47
                        $condition_display_tools ORDER BY t.row, t.column";
48
                break;
49
            case 'External':
50
                if (api_is_allowed_to_edit()) {
51
                    $sql = "SELECT a.*, t.image img FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
52
                            WHERE 
53
                              a.c_id = $course_id AND 
54
                              ((a.link=t.link AND t.position='external') OR 
55
                              (a.visibility <= 1 AND 
56
                              (a.image = 'external.gif' OR a.image = 'scormbuilder.gif' OR t.image = 'blog.gif') AND 
57
                              a.image=t.image))
58
                            ORDER BY a.id";
59
                } else {
60
                    $sql = "SELECT a.*, t.image img FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
61
                            WHERE 
62
                              a.c_id = $course_id AND 
63
                              (a.visibility = 1 AND ((a.link=t.link AND t.position='external') OR 
64
                              ((a.image = 'external.gif' OR a.image = 'scormbuilder.gif' OR t.image = 'blog.gif') AND 
65
                              a.image=t.image)))
66
                            ORDER BY a.id";
67
                }
68
                break;
69
            case 'courseAdmin':
70
                $sql = "SELECT a.*, t.image img, t.row, t.column  
71
                        FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
72
                        WHERE a.c_id = $course_id AND admin=1 AND a.link=t.link 
73
                        ORDER BY t.row, t.column";
74
                break;
75
76
            case 'platformAdmin':
77
                $sql = "SELECT *, image img FROM $TBL_ACCUEIL 
78
                        WHERE c_id = $course_id AND visibility = 2 
79
                        ORDER BY id";
80
        }
81
        $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...
82
83
        // Grabbing all the tools from $course_tool_table
84
        while ($tool = Database::fetch_array($result)) {
85
            $all_tools[] = $tool;
86
        }
87
88
        $course_id = api_get_course_int_id();
89
90
        // Grabbing all the links that have the property on_homepage set to 1
91
        if ($cat == 'External') {
92
            $tbl_link = Database::get_course_table(TABLE_LINK);
93
            $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
94
            if (api_is_allowed_to_edit(null, true)) {
95
                $sql_links = "SELECT tl.*, tip.visibility
96
                              FROM $tbl_link tl
97
                              LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
98
                              WHERE 	
99
                                tl.c_id = $course_id AND
100
                                tip.c_id = $course_id AND
101
                                tl.on_homepage='1' AND
102
                                tip.visibility != 2";
103
            } else {
104
                $sql_links = "SELECT tl.*, tip.visibility
105
                                FROM $tbl_link tl
106
                                LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
107
                                WHERE 	
108
                                    tl.c_id = $course_id AND
109
                                    tip.c_id = $course_id AND
110
                                    tl.on_homepage='1' AND
111
                                    tip.visibility = 1";
112
            }
113
            $result_links = Database::query($sql_links);
114
            while ($links_row = Database::fetch_array($result_links)) {
115
                $properties = [];
116
                $properties['name'] = $links_row['title'];
117
                $properties['link'] = $links_row['url'];
118
                $properties['visibility'] = $links_row['visibility'];
119
                $properties['img'] = 'external.gif';
120
                $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&amp;id='.$links_row['id'];
121
                $all_tools[] = $properties;
122
            }
123
        }
124
125
        $cell_number = 0;
126
        // Draw line between basic and external, only if there are entries in External
127
        if ($cat == 'External' && count($all_tools)) {
128
            $table->setCellContents(0, 0, '<hr noshade="noshade" size="1"/>');
129
            $table->updateCellAttributes(0, 0, 'colspan="3"');
130
            $cell_number += $numcols;
131
        }
132
133
        foreach ($all_tools as &$tool) {
134
            if ($tool['image'] == 'scormbuilder.gif') {
135
                // check if the published learnpath is visible for student
136
                $lpId = self::getPublishedLpIdFromLink($tool['link']);
137
                if (!api_is_allowed_to_edit(null, true) &&
138
                    !learnpath::is_lp_visible_for_student(
139
                        $lpId,
140
                        api_get_user_id(),
141
                        api_get_course_id(),
142
                        api_get_session_id()
143
                    )
144
                ) {
145
                    continue;
146
                }
147
            }
148
149
            if (api_get_session_id() != 0 &&
150
                in_array($tool['name'], ['course_maintenance', 'course_setting'])
151
            ) {
152
                continue;
153
            }
154
155
            $cell_content = '';
156
            // The name of the tool
157
            $tool_name = self::translate_tool_name($tool);
158
159
            $link_annex = '';
160
            // The url of the tool
161
            if ($tool['img'] != 'external.gif') {
162
                $tool['link'] = api_get_path(WEB_CODE_PATH).$tool['link'];
163
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&amp;';
164
                $link_annex = $qm_or_amp.api_get_cidreq();
165
            } else {
166
                // If an external link ends with 'login=', add the actual login...
167
                $pos = strpos($tool['link'], '?login=');
168
                $pos2 = strpos($tool['link'], '&amp;login=');
169
                if ($pos !== false or $pos2 !== false) {
170
                    $link_annex = $_user['username'];
171
                }
172
            }
173
174
            // Setting the actual image url
175
            $tool['img'] = Display::returnIconPath($tool['img']);
176
177
            // VISIBLE
178
            if (($tool['visibility'] ||
179
                ((api_is_coach() || api_is_course_tutor()) && $tool['name'] == TOOL_TRACKING)) ||
180
                $cat == 'courseAdmin' || $cat == 'platformAdmin'
181
            ) {
182
                if (strpos($tool['name'], 'visio_') !== false) {
183
                    $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>';
184
                } elseif (strpos($tool['name'], 'chat') !== false &&
185
                    api_get_course_setting('allow_open_chat_window')
186
                ) {
187
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
188
                    $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>';
189
                } else {
190
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
191
                    $cell_content .= '<a href="'.$tool['link'].$link_annex.'" target="'.$tool['target'].'"><img src="'.$tool['img'].'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
192
                }
193
            } else {
194
                // INVISIBLE
195
                if (api_is_allowed_to_edit(null, true)) {
196
                    if (strpos($tool['name'], 'visio_') !== false) {
197
                        $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>';
198
                    } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
199
                        // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
200
                        $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>';
201
                    } else {
202
                        // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
203
                        $cell_content .= '<a href="'.$tool['link'].$link_annex.'" target="'.$tool['target'].'" class="text-muted">
204
                            <img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
205
                    }
206
                } else {
207
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
208
                    $cell_content .= '<img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">';
209
                    $cell_content .= '<span class="text-muted">'.$tool_name.'</span>';
210
                }
211
            }
212
213
            $lnk = [];
214
            if (api_is_allowed_to_edit(null, true) &&
215
                $cat != "courseAdmin" &&
216
                !strpos($tool['link'], 'learnpath_handler.php?learnpath_id') &&
217
                !api_is_coach()
218
            ) {
219
                if ($tool['visibility']) {
220
                    $link['name'] = Display::return_icon(
221
                        'remove.gif',
222
                        get_lang('Deactivate'),
223
                        ['style' => 'vertical-align: middle;']
224
                    );
225
                    $link['cmd'] = "hide=yes";
226
                    $lnk[] = $link;
227
                } else {
228
                    $link['name'] = Display::return_icon(
229
                        'add.gif',
230
                        get_lang('Activate'),
231
                        ['style' => 'vertical-align: middle;']
232
                    );
233
                    $link['cmd'] = "restore=yes";
234
                    $lnk[] = $link;
235
                }
236
                if (is_array($lnk)) {
237
                    foreach ($lnk as &$this_lnk) {
238
                        if (isset($tool['adminlink']) && $tool['adminlink']) {
239
                            $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...
240
                                Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
241
                        } else {
242
                            $cell_content .= '<a href="'.api_get_self().'?id='.$tool['id'].'&amp;'.$this_lnk['cmd'].'">'.$this_lnk['name'].'</a>';
243
                        }
244
                    }
245
                }
246
            }
247
            $table->setCellContents($cell_number / $numcols, ($cell_number) % $numcols, $cell_content);
248
            $table->updateCellAttributes($cell_number / $numcols, ($cell_number) % $numcols, 'width="32%" height="42"');
249
            $cell_number++;
250
        }
251
252
        return $table->toHtml();
253
    }
254
255
    /**
256
     * Displays the tools of a certain category.
257
     *
258
     * @param string $course_tool_category contains the category of tools to display:
259
     *                                     "Public", "PublicButHide", "courseAdmin", "claroAdmin"
260
     *
261
     * @return string
262
     */
263
    public static function show_tool_2column($course_tool_category)
264
    {
265
        $html = '';
266
        $web_code_path = api_get_path(WEB_CODE_PATH);
267
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
268
        $course_id = api_get_course_int_id();
269
        $studentView = api_is_student_view_active();
270
        switch ($course_tool_category) {
271
            case TOOL_PUBLIC:
272
                $condition_display_tools = ' WHERE c_id = '.$course_id.' AND visibility = 1 ';
273
                if ((api_is_coach() || api_is_course_tutor()) && !$studentView) {
274
                    $condition_display_tools = ' WHERE 
275
                        c_id = '.$course_id.' AND 
276
                        (visibility = 1 OR (visibility = 0 AND name = "'.TOOL_TRACKING.'")) ';
277
                }
278
                $result = Database::query("SELECT * FROM $course_tool_table $condition_display_tools ORDER BY id");
279
                $col_link = "##003399";
280
                break;
281
            case TOOL_PUBLIC_BUT_HIDDEN:
282
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND visibility=0 AND admin=0 ORDER BY id");
283
                $col_link = "##808080";
284
                break;
285
            case TOOL_COURSE_ADMIN:
286
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND admin=1 AND visibility != 2 ORDER BY id");
287
                $col_link = "##003399";
288
                break;
289
            case TOOL_PLATFORM_ADMIN:
290
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND visibility = 2  ORDER BY id");
291
                $col_link = "##003399";
292
        }
293
        $i = 0;
294
295
        // Grabbing all the tools from $course_tool_table
296
        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...
297
            if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN && $temp_row['image'] != 'scormbuilder.gif') {
298
                $temp_row['image'] = str_replace('.gif', '_na.gif', $temp_row['image']);
299
            }
300
            $all_tools_list[] = $temp_row;
301
        }
302
303
        // Grabbing all the links that have the property on_homepage set to 1
304
        $course_link_table = Database::get_course_table(TABLE_LINK);
305
        $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
306
307
        switch ($course_tool_category) {
308
            case TOOL_PUBLIC:
309
                $sql_links = "SELECT tl.*, tip.visibility
310
                        FROM $course_link_table tl
311
                        LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tl.c_id = tip.c_id AND tl.c_id = $course_id AND tip.ref=tl.id
312
                        WHERE tl.on_homepage='1' AND tip.visibility = 1";
313
                break;
314
            case TOOL_PUBLIC_BUT_HIDDEN:
315
                $sql_links = "SELECT tl.*, tip.visibility
316
                    FROM $course_link_table tl
317
                    LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tl.c_id = tip.c_id AND tl.c_id = $course_id AND tip.ref=tl.id
318
                    WHERE tl.on_homepage='1' AND tip.visibility = 0";
319
320
                break;
321
            default:
322
                $sql_links = null;
323
                break;
324
        }
325
        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...
326
            $properties = [];
327
            $result_links = Database::query($sql_links);
328
            while ($links_row = Database::fetch_array($result_links)) {
329
                unset($properties);
330
                $properties['name'] = $links_row['title'];
331
                $properties['link'] = $links_row['url'];
332
                $properties['visibility'] = $links_row['visibility'];
333
                $properties['image'] = $course_tool_category == TOOL_PUBLIC_BUT_HIDDEN ? 'external_na.gif' : 'external.gif';
334
                $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&id='.$links_row['id'];
335
                $all_tools_list[] = $properties;
336
            }
337
        }
338
        if (isset($all_tools_list)) {
339
            $lnk = [];
340
            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...
341
                if ($tool['image'] == 'scormbuilder.gif') {
342
                    // check if the published learnpath is visible for student
343
                    $lpId = self::getPublishedLpIdFromLink($tool['link']);
344
345
                    if (!api_is_allowed_to_edit(null, true) &&
346
                        !learnpath::is_lp_visible_for_student(
347
                            $lpId,
348
                            api_get_user_id(),
349
                            api_get_course_id(),
350
                            api_get_session_id()
351
                        )
352
                    ) {
353
                        continue;
354
                    }
355
                }
356
357
                if (api_get_session_id() != 0 &&
358
                    in_array($tool['name'], ['course_maintenance', 'course_setting'])
359
                ) {
360
                    continue;
361
                }
362
363
                if (!($i % 2)) {
364
                    $html .= "<tr valign=\"top\">";
365
                }
366
367
                // NOTE : Table contains only the image file name, not full path
368
                if (stripos($tool['link'], 'http://') === false &&
369
                    stripos($tool['link'], 'https://') === false &&
370
                    stripos($tool['link'], 'ftp://') === false
371
                ) {
372
                    $tool['link'] = $web_code_path.$tool['link'];
373
                }
374
                $class = '';
375
                if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN) {
376
                    $class = 'class="text-muted"';
377
                }
378
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&amp;';
379
380
                $tool['link'] = $tool['link'];
381
                $html .= '<td width="50%" height="30">';
382
383
                if (strpos($tool['name'], 'visio_') !== false) {
384
                    $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'].'">';
385
                } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
386
                    $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.'>';
387
                } else {
388
                    $html .= '<a href="'.htmlspecialchars($tool['link']).(($tool['image'] == 'external.gif' || $tool['image'] == 'external_na.gif') ? '' : $qm_or_amp.api_get_cidreq()).'" target="'.$tool['target'].'" '.$class.'>';
389
                }
390
391
                $tool_name = self::translate_tool_name($tool);
392
                $html .= Display::return_icon(
393
                    $tool['image'],
394
                    $tool_name,
395
                    [],
396
                    null,
397
                    ICON_SIZE_MEDIUM
398
                ).'&nbsp;'.$tool_name.
399
                '</a>';
400
401
                // This part displays the links to hide or remove a tool.
402
                // These links are only visible by the course manager.
403
                unset($lnk);
404
                if (api_is_allowed_to_edit(null, true) && !api_is_coach()) {
405
                    if ($tool['visibility'] == '1' || $tool['name'] == TOOL_TRACKING) {
406
                        $link['name'] = Display::returnFontAwesomeIcon('minus');
407
                        $link['title'] = get_lang('Deactivate');
408
                        $link['cmd'] = 'hide=yes';
409
                        $lnk[] = $link;
410
                    }
411
412
                    if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN) {
413
                        //$link['name'] = Display::return_icon('add.gif', get_lang('Activate'));
414
                        $link['name'] = Display::returnFontAwesomeIcon('plus');
415
                        $link['title'] = get_lang('Activate');
416
                        $link['cmd'] = 'restore=yes';
417
                        $lnk[] = $link;
418
419
                        if ($tool['added_tool'] == 1) {
420
                            //$link['name'] = Display::return_icon('delete.gif', get_lang('Remove'));
421
                            $link['name'] = Display::returnFontAwesomeIcon('trash');
422
                            $link['title'] = get_lang('Remove');
423
                            $link['cmd'] = 'remove=yes';
424
                            $lnk[] = $link;
425
                        }
426
                    }
427
                    if (isset($tool['adminlink'])) {
428
                        $html .= '<a href="'.$tool['adminlink'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
429
                    }
430
                }
431
                if (api_is_platform_admin() && !api_is_coach()) {
432
                    if ($tool['visibility'] == 2) {
433
                        $link['name'] = Display::returnFontAwesomeIcon('undo');
434
                        $link['title'] = get_lang('Activate');
435
                        $link['cmd'] = 'hide=yes';
436
                        $lnk[] = $link;
437
438
                        if ($tool['added_tool'] == 1) {
439
                            $link['name'] = get_lang('Delete');
440
                            $link['cmd'] = 'askDelete=yes';
441
                            $lnk[] = $link;
442
                        }
443
                    }
444
                    if ($tool['visibility'] == 0 && $tool['added_tool'] == 0) {
445
                        $link['name'] = Display::returnFontAwesomeIcon('trash');
446
                        $link['title'] = get_lang('Remove');
447
                        $link['cmd'] = 'remove=yes';
448
                        $lnk[] = $link;
449
                    }
450
                }
451
                if (is_array($lnk)) {
452
                    $html .= '<div class="pull-right">';
453
                    $html .= '<div class="btn-options">';
454
                    $html .= '<div class="btn-group btn-group-sm" role="group">';
455
                    foreach ($lnk as &$this_link) {
456
                        if (!isset($tool['adminlink'])) {
457
                            $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>';
458
                        }
459
                    }
460
                    $html .= '</div>';
461
                    $html .= '</div>';
462
                    $html .= '</div>';
463
                }
464
                $html .= "</td>";
465
466
                if ($i % 2) {
467
                    $html .= "</tr>";
468
                }
469
470
                $i++;
471
            }
472
        }
473
474
        if ($i % 2) {
475
            $html .= "<td width=\"50%\">&nbsp;</td></tr>";
476
        }
477
478
        return $html;
479
    }
480
481
    /**
482
     * Gets the tools of a certain category. Returns an array expected
483
     * by show_tools_category().
484
     *
485
     * @param string $course_tool_category contains the category of tools to
486
     *                                     display: "toolauthoring", "toolinteraction", "tooladmin", "tooladminplatform", "toolplugin"
487
     * @param int    $courseId             Optional
488
     * @param int    $sessionId            Optional
489
     *
490
     * @return array
491
     */
492
    public static function get_tools_category(
493
        $course_tool_category,
494
        $courseId = 0,
495
        $sessionId = 0
496
    ) {
497
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
498
        $is_platform_admin = api_is_platform_admin();
499
        $all_tools_list = [];
500
501
        // Condition for the session
502
        $sessionId = $sessionId ?: api_get_session_id();
503
        $course_id = $courseId ?: api_get_course_int_id();
504
        $userId = api_get_user_id();
505
        $user = api_get_user_entity($userId);
506
        $condition_session = api_get_session_condition(
507
            $sessionId,
508
            true,
509
            true,
510
            't.session_id'
511
        );
512
513
        $lpTable = Database::get_course_table(TABLE_LP_MAIN);
514
        $studentView = api_is_student_view_active();
515
516
        $orderBy = ' ORDER BY id ';
517
        switch ($course_tool_category) {
518
            case TOOL_STUDENT_VIEW:
519
                $conditions = ' WHERE visibility = 1 AND 
520
                                (category = "authoring" OR category = "interaction" OR category = "plugin") AND 
521
                                t.name <> "notebookteacher" ';
522
                if ((api_is_coach() || api_is_course_tutor()) && !$studentView) {
523
                    $conditions = ' WHERE (
524
                        visibility = 1 AND (
525
                            category = "authoring" OR 
526
                            category = "interaction" OR 
527
                            category = "plugin"
528
                        ) OR (t.name = "'.TOOL_TRACKING.'") 
529
                    )';
530
                }
531
532
                /*$sql = "SELECT *
533
                        FROM $course_tool_table t
534
                        $conditions AND
535
                        c_id = $course_id $condition_session
536
                        ";*/
537
                // Add order if there are LPs
538
                $sql = "SELECT t.* FROM $course_tool_table t
539
                        LEFT JOIN $lpTable l 
540
                        ON (t.c_id = l.c_id AND link LIKE concat('%/lp_controller.php?action=view&lp_id=', l.id, '&%'))
541
                        $conditions AND
542
                        t.c_id = $course_id $condition_session 
543
                        ORDER BY CASE WHEN l.display_order IS NULL THEN 0 ELSE 1 END, l.display_order, t.id";
544
                $orderBy = '';
545
                break;
546
            case TOOL_AUTHORING:
547
                /*$sql = "SELECT * FROM $course_tool_table t
548
                        WHERE category = 'authoring' AND c_id = $course_id $condition_session
549
                        ";*/
550
                $sql = "SELECT t.* FROM $course_tool_table t
551
                        LEFT JOIN $lpTable l 
552
                        ON (t.c_id = l.c_id AND link LIKE concat('%/lp_controller.php?action=view&lp_id=', l.id, '&%'))
553
                        WHERE 
554
                            category = 'authoring' AND t.c_id = $course_id $condition_session
555
                        ORDER BY CASE WHEN l.display_order IS NULL THEN 0 ELSE 1 END, l.display_order, t.id";
556
                $orderBy = '';
557
                break;
558
            case TOOL_INTERACTION:
559
                $sql = "SELECT * FROM $course_tool_table t
560
                        WHERE category = 'interaction' AND c_id = $course_id $condition_session
561
                        ";
562
                break;
563
            case TOOL_ADMIN_VISIBLE:
564
                $sql = "SELECT * FROM $course_tool_table t
565
                        WHERE category = 'admin' AND visibility ='1' AND c_id = $course_id $condition_session
566
                        ";
567
                break;
568
            case TOOL_ADMIN_PLATFORM:
569
                $sql = "SELECT * FROM $course_tool_table t
570
                        WHERE category = 'admin' AND c_id = $course_id $condition_session
571
                        ";
572
                break;
573
            case TOOL_DRH:
574
                $sql = "SELECT * FROM $course_tool_table t
575
                        WHERE t.name IN ('tracking') AND c_id = $course_id $condition_session
576
                        ";
577
                break;
578
            case TOOL_COURSE_PLUGIN:
579
                //Other queries recover id, name, link, image, visibility, admin, address, added_tool, target, category and session_id
580
                // but plugins are not present in the tool table, only globally and inside the course_settings table once configured
581
                $sql = "SELECT * FROM $course_tool_table t
582
                        WHERE category = 'plugin' AND name <> 'courseblock' AND c_id = $course_id $condition_session
583
                        ";
584
                break;
585
        }
586
        $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...
587
        $result = Database::query($sql);
588
        $tools = [];
589
        while ($row = Database::fetch_assoc($result)) {
590
            $tools[] = $row;
591
        }
592
593
        // Get the list of hidden tools - this might imply performance slowdowns
594
        // if the course homepage is loaded many times, so the list of hidden
595
        // tools might benefit from a shared memory storage later on
596
        $list = api_get_settings('Tools', 'list', api_get_current_access_url_id());
597
        $hide_list = [];
598
        $check = false;
599
        foreach ($list as $line) {
600
            // Admin can see all tools even if the course_hide_tools configuration is set
601
            if ($is_platform_admin) {
602
                continue;
603
            }
604
            if ($line['variable'] == 'course_hide_tools' && $line['selected_value'] == 'true') {
605
                $hide_list[] = $line['subkey'];
606
                $check = true;
607
            }
608
        }
609
610
        $allowEditionInSession = api_get_configuration_value('allow_edit_tool_visibility_in_session');
611
        // If exists same tool (by name) from session in base course then avoid it. Allow them pass in other cases
612
        $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...
613
            if (!empty($toolToFilter['session_id'])) {
614
                foreach ($tools as $originalTool) {
615
                    if ($toolToFilter['name'] == $originalTool['name'] && empty($originalTool['session_id'])) {
616
                        return false;
617
                    }
618
                }
619
            }
620
621
            return true;
622
        });
623
624
        foreach ($tools as $temp_row) {
625
            $add = false;
626
            if ($check) {
627
                if (!in_array($temp_row['name'], $hide_list)) {
628
                    $add = true;
629
                }
630
            } else {
631
                $add = true;
632
            }
633
634
            if ($allowEditionInSession && !empty($sessionId)) {
635
                // Checking if exist row in session
636
                $criteria = [
637
                    'course' => $course_id,
638
                    'name' => $temp_row['name'],
639
                    'sessionId' => $sessionId,
640
                ];
641
                /** @var CTool $toolObj */
642
                $toolObj = Database::getManager()->getRepository('ChamiloCourseBundle:CTool')->findOneBy($criteria);
643
                if ($toolObj) {
644
                    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...
645
                        continue;
646
                    }
647
                }
648
            }
649
650
            switch ($temp_row['image']) {
651
                case 'scormbuilder.gif':
652
                    $lpId = self::getPublishedLpIdFromLink($temp_row['link']);
653
                    $lp = new learnpath(
654
                        api_get_course_id(),
655
                        $lpId,
656
                        $userId
657
                    );
658
                    $path = $lp->get_preview_image_path(ICON_SIZE_BIG);
659
660
                    $add = learnpath::is_lp_visible_for_student(
661
                        $lpId,
662
                        $userId,
663
                        api_get_course_id(),
664
                        api_get_session_id()
665
                    );
666
                    if ($path) {
667
                        $temp_row['custom_image'] = $path;
668
                    }
669
                    break;
670
                case 'lp_category.gif':
671
                    $lpCategory = self::getPublishedLpCategoryFromLink(
672
                        $temp_row['link']
673
                    );
674
                    $add = learnpath::categoryIsVisibleForStudent(
675
                        $lpCategory,
676
                        $user
677
                    );
678
                    break;
679
            }
680
681
            if ($add) {
682
                $all_tools_list[] = $temp_row;
683
            }
684
        }
685
686
        // Grabbing all the links that have the property on_homepage set to 1
687
        $course_link_table = Database::get_course_table(TABLE_LINK);
688
        $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
689
        $condition_session = api_get_session_condition(
690
            $sessionId,
691
            true,
692
            true,
693
            'tip.session_id'
694
        );
695
696
        switch ($course_tool_category) {
697
            case TOOL_AUTHORING:
698
                $sql_links = "SELECT tl.*, tip.visibility
699
                    FROM $course_link_table tl
700
                    LEFT JOIN $course_item_property_table tip
701
                    ON tip.tool='link' AND tip.ref=tl.id
702
                    WHERE
703
                        tl.c_id = $course_id AND
704
                        tip.c_id = $course_id AND
705
                        tl.on_homepage='1' $condition_session";
706
                break;
707
            case TOOL_INTERACTION:
708
                $sql_links = null;
709
                /*
710
                  $sql_links = "SELECT tl.*, tip.visibility
711
                  FROM $course_link_table tl
712
                  LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
713
                  WHERE tl.on_homepage='1' ";
714
                 */
715
                break;
716
            case TOOL_STUDENT_VIEW:
717
                $sql_links = "SELECT tl.*, tip.visibility
718
                    FROM $course_link_table tl
719
                    LEFT JOIN $course_item_property_table tip
720
                    ON tip.tool='link' AND tip.ref=tl.id
721
                    WHERE
722
                        tl.c_id 		= $course_id AND
723
                        tip.c_id 		= $course_id AND
724
                        tl.on_homepage	='1' $condition_session";
725
                break;
726
            case TOOL_ADMIN:
727
                $sql_links = "SELECT tl.*, tip.visibility
728
                    FROM $course_link_table tl
729
                    LEFT JOIN $course_item_property_table tip
730
                    ON tip.tool='link' AND tip.ref=tl.id
731
                    WHERE
732
                        tl.c_id = $course_id AND
733
                        tip.c_id = $course_id AND
734
                        tl.on_homepage='1' $condition_session";
735
                break;
736
            default:
737
                $sql_links = null;
738
                break;
739
        }
740
741
        // Edited by Kevin Van Den Haute ([email protected]) for integrating Smartblogs
742
        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...
743
            $result_links = Database::query($sql_links);
744
            if (Database::num_rows($result_links) > 0) {
745
                while ($links_row = Database::fetch_array($result_links, 'ASSOC')) {
746
                    $properties = [];
747
                    $properties['name'] = $links_row['title'];
748
                    $properties['session_id'] = $links_row['session_id'];
749
                    $properties['link'] = $links_row['url'];
750
                    $properties['visibility'] = $links_row['visibility'];
751
                    $properties['image'] = $links_row['visibility'] == '0' ? 'file_html.png' : 'file_html.png';
752
                    $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&id='.$links_row['id'];
753
                    $properties['target'] = $links_row['target'];
754
                    $tmp_all_tools_list[] = $properties;
755
                }
756
            }
757
        }
758
759
        if (isset($tmp_all_tools_list)) {
760
            foreach ($tmp_all_tools_list as $tool) {
761
                if ($tool['image'] == 'blog.gif') {
762
                    // Init
763
                    $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
764
765
                    // Get blog id
766
                    $blog_id = substr($tool['link'], strrpos($tool['link'], '=') + 1, strlen($tool['link']));
767
768
                    // Get blog members
769
                    if ($is_platform_admin) {
770
                        $sql = "SELECT * FROM $tbl_blogs_rel_user blogs_rel_user
771
                                WHERE blog_id = ".$blog_id;
772
                    } else {
773
                        $sql = "SELECT * FROM $tbl_blogs_rel_user blogs_rel_user
774
                                WHERE blog_id = ".$blog_id." AND user_id = ".$userId;
775
                    }
776
                    $result = Database::query($sql);
777
                    if (Database::num_rows($result) > 0) {
778
                        $all_tools_list[] = $tool;
779
                    }
780
                } else {
781
                    $all_tools_list[] = $tool;
782
                }
783
            }
784
        }
785
        $all_tools_list = CourseHome::filterPluginTools($all_tools_list, $course_tool_category);
786
787
        return $all_tools_list;
788
    }
789
790
    /**
791
     * Displays the tools of a certain category.
792
     *
793
     * @param array $all_tools_list List of tools as returned by get_tools_category()
794
     * @param bool  $rows
795
     *
796
     * @return array
797
     */
798
    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

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

1074
                    /** @scrutinizer ignore-type */ !empty($_user['status']) ? $_user['status'] : ''
Loading history...
1075
                );
1076
                if ($studentview) {
1077
                    $tool_link_params['href'] .= '&isStudentView=true';
1078
                }
1079
                $item['url_params'] = $tool_link_params;
1080
                $item['icon'] = Display::url($icon, $tool_link_params['href'], $tool_link_params);
1081
                $item['tool'] = $tool;
1082
                $item['name'] = $tool_name;
1083
                $tool_link_params['id'] = 'is'.$tool_link_params['id'];
1084
                $item['link'] = Display::url(
1085
                    $tool_name.$session_img,
1086
                    $tool_link_params['href'],
1087
                    $tool_link_params
1088
                );
1089
                $items[] = $item;
1090
                $i++;
1091
            } // end of foreach
1092
        }
1093
1094
        if (api_get_setting('homepage_view') != 'activity_big') {
1095
            return $items;
1096
        }
1097
1098
        foreach ($items as &$item) {
1099
            $originalImage = self::getToolIcon($item);
1100
            $item['tool']['image'] = Display::url(
1101
                $originalImage,
1102
                $item['url_params']['href'],
1103
                $item['url_params']
1104
            );
1105
        }
1106
1107
        return $items;
1108
    }
1109
1110
    /**
1111
     * Shows the general data for a particular meeting.
1112
     *
1113
     * @param int $id_session
1114
     *
1115
     * @return string session data
1116
     */
1117
    public static function show_session_data($id_session)
1118
    {
1119
        $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
1120
1121
        $sessionInfo = api_get_session_info($id_session);
1122
1123
        if (empty($sessionInfo)) {
1124
            return '';
1125
        }
1126
1127
        $sql = 'SELECT name FROM '.$session_category_table.'
1128
                WHERE id = "'.intval($sessionInfo['session_category_id']).'"';
1129
        $rs_category = Database::query($sql);
1130
        $session_category = '';
1131
        if (Database::num_rows($rs_category) > 0) {
1132
            $rows_session_category = Database::store_result($rs_category);
1133
            $rows_session_category = $rows_session_category[0];
1134
            $session_category = $rows_session_category['name'];
1135
        }
1136
1137
        $coachInfo = api_get_user_info($sessionInfo['id_coach']);
1138
1139
        $output = '';
1140
        if (!empty($session_category)) {
1141
            $output .= '<tr><td>'.get_lang('SessionCategory').': '.'<b>'.$session_category.'</b></td></tr>';
1142
        }
1143
        $dateInfo = SessionManager::parseSessionDates($sessionInfo);
1144
1145
        $msgDate = $dateInfo['access'];
1146
        $output .= '<tr>
1147
                    <td style="width:50%">'.get_lang('SessionName').': '.'<b>'.$sessionInfo['name'].'</b></td>
1148
                    <td>'.get_lang('GeneralCoach').': '.'<b>'.$coachInfo['complete_name'].'</b></td></tr>';
1149
        $output .= '<tr>
1150
                        <td>'.get_lang('SessionIdentifier').': '.
1151
                            Display::return_icon('star.png', ' ', ['align' => 'absmiddle']).'
1152
                        </td>
1153
                        <td>'.get_lang('Date').': '.'<b>'.$msgDate.'</b>
1154
                        </td>
1155
                    </tr>';
1156
1157
        return $output;
1158
    }
1159
1160
    /**
1161
     * Retrieves the name-field within a tool-record and translates it on necessity.
1162
     *
1163
     * @param array $tool the input record
1164
     *
1165
     * @return string returns the name of the corresponding tool
1166
     */
1167
    public static function translate_tool_name(&$tool)
1168
    {
1169
        static $already_translated_icons = [
1170
            'file_html.gif',
1171
            'file_html_na.gif',
1172
            'file_html.png',
1173
            'file_html_na.png',
1174
            'scormbuilder.gif',
1175
            'scormbuilder_na.gif',
1176
            'blog.gif',
1177
            'blog_na.gif',
1178
            'external.gif',
1179
            'external_na.gif',
1180
        ];
1181
1182
        $toolName = Security::remove_XSS(stripslashes($tool['name']));
1183
1184
        if (in_array($tool['image'], $already_translated_icons)) {
1185
            return $toolName;
1186
        }
1187
1188
        $toolName = api_underscore_to_camel_case($toolName);
1189
1190
        if (isset($GLOBALS['Tool'.$toolName])) {
1191
            return get_lang('Tool'.$toolName);
1192
        }
1193
1194
        return $toolName;
1195
    }
1196
1197
    /**
1198
     * Get published learning path id from link inside course home.
1199
     *
1200
     * @param 	string	Link to published lp
1201
     *
1202
     * @return int Learning path id
1203
     */
1204
    public static function getPublishedLpIdFromLink($link)
1205
    {
1206
        $lpId = 0;
1207
        $param = strstr($link, 'lp_id=');
1208
        if (!empty($param)) {
1209
            $paramList = explode('=', $param);
1210
            if (isset($paramList[1])) {
1211
                $lpId = (int) $paramList[1];
1212
            }
1213
        }
1214
1215
        return $lpId;
1216
    }
1217
1218
    /**
1219
     * Get published learning path category from link inside course home.
1220
     *
1221
     * @param string $link
1222
     *
1223
     * @return CLpCategory
1224
     */
1225
    public static function getPublishedLpCategoryFromLink($link)
1226
    {
1227
        $query = parse_url($link, PHP_URL_QUERY);
1228
        parse_str($query, $params);
1229
        $id = isset($params['id']) ? (int) $params['id'] : 0;
1230
        $em = Database::getManager();
1231
        /** @var CLpCategory $category */
1232
        $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
1233
1234
        return $category;
1235
    }
1236
1237
    /**
1238
     * @param bool $include_admin_tools
1239
     *
1240
     * @return array
1241
     */
1242
    public static function get_navigation_items($include_admin_tools = false)
1243
    {
1244
        $navigation_items = [];
1245
        $course_id = api_get_course_int_id();
1246
        $courseInfo = api_get_course_info();
1247
        $sessionId = api_get_session_id();
1248
1249
        if (!empty($course_id)) {
1250
            $course_tools_table = Database::get_course_table(TABLE_TOOL_LIST);
1251
            /* 	Link to the Course homepage */
1252
            $navigation_items['home']['image'] = 'home.gif';
1253
            $navigation_items['home']['link'] = $courseInfo['course_public_url'];
1254
            $navigation_items['home']['name'] = get_lang('CourseHomepageLink');
1255
1256
            $sql = "SELECT * FROM $course_tools_table
1257
                    WHERE c_id = $course_id AND visibility='1' and admin='0'
1258
                    ORDER BY id ASC";
1259
            $result = Database::query($sql);
1260
1261
            $hideTools = [];
1262
            $hideToolsKeys = [];
1263
            if (!api_is_platform_admin()) {
1264
                $hideTools = api_get_setting('course_hide_tools');
1265
                $hideToolsKeys = array_keys($hideTools);
1266
            }
1267
1268
            while ($row = Database::fetch_array($result)) {
1269
                if (!empty($hideTools)) {
1270
                    if (in_array($row['name'], $hideToolsKeys)) {
1271
                        // Tool is hidden
1272
                        if ($hideTools[$row['name']] == 'true') {
1273
                            continue;
1274
                        }
1275
                    }
1276
                }
1277
1278
                $navigation_items[$row['id']] = $row;
1279
                if (stripos($row['link'], 'http://') === false &&
1280
                    stripos($row['link'], 'https://') === false
1281
                ) {
1282
                    $navigation_items[$row['id']]['link'] = api_get_path(WEB_CODE_PATH);
1283
1284
                    if ($row['category'] == 'plugin') {
1285
                        $plugin = new AppPlugin();
1286
                        $pluginInfo = $plugin->getPluginInfo($row['name']);
1287
                        if (isset($pluginInfo['title'])) {
1288
                            $navigation_items[$row['id']]['link'] = api_get_path(WEB_PLUGIN_PATH);
1289
                            $navigation_items[$row['id']]['name'] = $pluginInfo['title'];
1290
                        }
1291
                    } else {
1292
                        $navigation_items[$row['id']]['name'] = self::translate_tool_name($row);
1293
                    }
1294
1295
                    $navigation_items[$row['id']]['link'] .= $row['link'];
1296
                }
1297
            }
1298
1299
            /* Admin (edit rights) only links
1300
            - Course settings (course admin only)
1301
            - Course rights (roles & rights overview) */
1302
            if ($include_admin_tools) {
1303
                $sql = "SELECT name, image FROM $course_tools_table
1304
                        WHERE c_id = $course_id  AND link='course_info/infocours.php'";
1305
                $sql_result = Database::query($sql);
1306
                $course_setting_info = Database::fetch_array($sql_result);
1307
                $course_setting_visual_name = self::translate_tool_name($course_setting_info);
1308
                if ($sessionId == 0) {
1309
                    // course settings item
1310
                    $navigation_items['course_settings']['image'] = $course_setting_info['image'];
1311
                    $navigation_items['course_settings']['link'] = api_get_path(WEB_CODE_PATH).'course_info/infocours.php';
1312
                    $navigation_items['course_settings']['name'] = $course_setting_visual_name;
1313
                }
1314
            }
1315
        }
1316
1317
        foreach ($navigation_items as $key => $navigation_item) {
1318
            if (strstr($navigation_item['link'], '?')) {
1319
                //link already contains a parameter, add course id parameter with &
1320
                $parameter_separator = '&amp;';
1321
            } else {
1322
                //link doesn't contain a parameter yet, add course id parameter with ?
1323
                $parameter_separator = '?';
1324
            }
1325
            //$navigation_items[$key]['link'] .= $parameter_separator.api_get_cidreq();
1326
            $navigation_items[$key]['link'] .= $parameter_separator.'cidReq='.api_get_course_id().'&gidReq=0&id_session='.$sessionId;
1327
        }
1328
1329
        return $navigation_items;
1330
    }
1331
1332
    /**
1333
     * Show a navigation menu.
1334
     */
1335
    public static function show_navigation_menu()
1336
    {
1337
        $navigation_items = self::get_navigation_items(true);
1338
        $course_id = api_get_course_id();
1339
1340
        $class = null;
1341
        $idLearn = null;
1342
        $item = null;
1343
        $marginLeft = 160;
1344
1345
        $html = '<div id="toolnav">';
1346
        $html .= '<ul id="toolnavbox">';
1347
        $count = 0;
1348
        foreach ($navigation_items as $key => $navigation_item) {
1349
            //students can't see the course settings option
1350
            $count++;
1351
            if (!api_is_allowed_to_edit() && $key == 'course_settings') {
1352
                continue;
1353
            }
1354
            $html .= '<li>';
1355
            $url_item = parse_url($navigation_item['link']);
1356
            $url_current = parse_url($_SERVER['REQUEST_URI']);
1357
1358
            if (api_get_setting('show_navigation_menu') == 'text') {
1359
                $class = 'text';
1360
                $marginLeft = 170;
1361
                $item = $navigation_item['name'];
1362
            } elseif (api_get_setting('show_navigation_menu') == 'icons') {
1363
                $class = 'icons';
1364
                $marginLeft = 25;
1365
                $item = Display::return_icon(
1366
                    substr($navigation_item['image'], 0, -3)."png",
1367
                    $navigation_item['name'],
1368
                    ['class' => 'tool-img'],
1369
                    ICON_SIZE_SMALL
1370
                );
1371
            } else {
1372
                $class = 'icons-text';
1373
                $item = $navigation_item['name'].
1374
                    Display::return_icon(
1375
                        substr($navigation_item['image'], 0, -3)."png",
1376
                        $navigation_item['name'],
1377
                        ['class' => 'tool-img'],
1378
                        ICON_SIZE_SMALL
1379
                    );
1380
            }
1381
1382
            if (stristr($url_item['path'], $url_current['path'])) {
1383
                if (!isset($_GET['learnpath_id']) || strpos($url_item['query'], 'learnpath_id='.intval($_GET['learnpath_id'])) === 0) {
1384
                    $idLearn = ' id="here"';
1385
                }
1386
            }
1387
1388
            if (strpos($navigation_item['link'], 'chat') !== false &&
1389
                api_get_course_setting('allow_open_chat_window', $course_id)
1390
            ) {
1391
                $html .= '<a '.$idLearn.' class="btn btn-default text-left '.$class.' " href="javascript: void(0);" onclick="javascript: window.open(\''.$navigation_item['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\')" target="'.$navigation_item['target'].'"';
1392
                $html .= ' title="'.$navigation_item['name'].'">';
1393
                $html .= $item;
1394
                $html .= '</a>';
1395
            } else {
1396
                $html .= '<a '.$idLearn.' class="btn btn-default text-left '.$class.'" href="'.$navigation_item['link'].'" target="_top" title="'.$navigation_item['name'].'">';
1397
                $html .= $item;
1398
                $html .= '</a>';
1399
            }
1400
1401
            $html .= '</li>';
1402
        }
1403
        $html .= '</ul>';
1404
        $html .= '<script>$(function() {
1405
                $("#toolnavbox a").stop().animate({"margin-left":"-'.$marginLeft.'px"},1000);
1406
                $("#toolnavbox > li").hover(
1407
                    function () {
1408
                        $("a",$(this)).stop().animate({"margin-left":"-2px"},200);
1409
                        $("span",$(this)).css("display","block");
1410
                    },
1411
                    function () {
1412
                        $("a",$(this)).stop().animate({"margin-left":"-'.$marginLeft.'px"},200);
1413
                        $("span",$(this)).css("display","initial");
1414
                    }
1415
                );
1416
            });</script>';
1417
        $html .= '</div>';
1418
1419
        return $html;
1420
    }
1421
1422
    /**
1423
     * Show a toolbar with shortcuts to the course tool.
1424
     *
1425
     * @param int $orientation
1426
     *
1427
     * @return string
1428
     */
1429
    public static function getCourseToolBar($orientation = SHORTCUTS_HORIZONTAL): string
1430
    {
1431
        $origin = api_get_origin();
1432
        if ($origin === 'learnpath') {
1433
            return '';
1434
        }
1435
1436
        $navigation_items = self::get_navigation_items(false);
1437
        $html = '';
1438
        if (!empty($navigation_items)) {
1439
            $style_id = 'toolshortcuts_vertical';
1440
            if ($orientation === SHORTCUTS_HORIZONTAL) {
1441
                $style_id = 'toolshortcuts_horizontal';
1442
            }
1443
            $html .= '<div id="'.$style_id.'">';
1444
            foreach ($navigation_items as $key => $navigation_item) {
1445
                if (strpos($navigation_item['link'], 'chat') !== false &&
1446
                    api_get_course_setting('allow_open_chat_window')
1447
                ) {
1448
                    $html .= '<a class="items-icon" href="javascript: void(0);" onclick="javascript: window.open(\''.$navigation_item['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\')" target="'.$navigation_item['target'].'"';
1449
                } else {
1450
                    $html .= '<a class="items-icon" href="'.$navigation_item['link'].'"';
1451
                }
1452
                if (strpos(api_get_self(), $navigation_item['link']) !== false) {
1453
                    $html .= ' id="here"';
1454
                }
1455
                $html .= ' target="_top" title="'.$navigation_item['name'].'">';
1456
1457
                if (isset($navigation_item['category']) && $navigation_item['category'] == 'plugin') {
1458
                    /*$plugin_info = $app_plugin->getPluginInfo($navigation_item['name']);
1459
                    if (isset($plugin_info) && isset($plugin_info['title'])) {
1460
                        $tool_name = $plugin_info['title'];
1461
                    }*/
1462
                    if (!file_exists(api_get_path(SYS_CODE_PATH).'img/'.$navigation_item['image']) &&
1463
                        !file_exists(api_get_path(SYS_CODE_PATH).'img/icons/'.ICON_SIZE_MEDIUM.'/'.$navigation_item['image'])
1464
                    ) {
1465
                        $navigation_item['image'] = 'plugins.png';
1466
                    }
1467
                }
1468
1469
                $html .= Display::return_icon(
1470
                    substr($navigation_item['image'], 0, -3).'png',
1471
                    $navigation_item['name'],
1472
                    [],
1473
                    ICON_SIZE_MEDIUM
1474
                );
1475
                $html .= '</a> ';
1476
                if ($orientation == SHORTCUTS_VERTICAL) {
1477
                    $html .= '<br />';
1478
                }
1479
            }
1480
            $html .= '</div>';
1481
        }
1482
1483
        return $html;
1484
    }
1485
1486
    /**
1487
     * List course homepage tools from authoring and interaction sections.
1488
     *
1489
     * @param int $courseId  The course ID (guessed from context if not provided)
1490
     * @param int $sessionId The session ID (guessed from context if not provided)
1491
     *
1492
     * @return array List of all tools data from the c_tools table
1493
     */
1494
    public static function toolsIconsAction($courseId = null, $sessionId = null)
1495
    {
1496
        if (empty($courseId)) {
1497
            $courseId = api_get_course_int_id();
1498
        } else {
1499
            $courseId = intval($courseId);
1500
        }
1501
        if (empty($sessionId)) {
1502
            $sessionId = api_get_session_id();
1503
        } else {
1504
            $sessionId = intval($sessionId);
1505
        }
1506
1507
        if (empty($courseId)) {
1508
            // We shouldn't get here, but for some reason api_get_course_int_id()
1509
            // doesn't seem to get the course from the context, sometimes
1510
            return [];
1511
        }
1512
1513
        $table = Database::get_course_table(TABLE_TOOL_LIST);
1514
        $sql = "SELECT * FROM $table
1515
                WHERE category in ('authoring','interaction')
1516
                AND c_id = $courseId
1517
                AND session_id = $sessionId
1518
                ORDER BY id";
1519
1520
        $result = Database::query($sql);
1521
        $data = Database::store_result($result, 'ASSOC');
1522
1523
        return $data;
1524
    }
1525
1526
    /**
1527
     * @param int $editIcon
1528
     *
1529
     * @return array
1530
     */
1531
    public static function getTool($editIcon)
1532
    {
1533
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
1534
        $editIcon = intval($editIcon);
1535
1536
        $sql = "SELECT * FROM $course_tool_table
1537
                WHERE iid = $editIcon";
1538
        $result = Database::query($sql);
1539
        $tool = Database::fetch_assoc($result, 'ASSOC');
1540
1541
        return $tool;
1542
    }
1543
1544
    /**
1545
     * @return string
1546
     */
1547
    public static function getCustomSysIconPath()
1548
    {
1549
        // Check if directory exists or create it if it doesn't
1550
        $dir = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
1551
        if (!is_dir($dir)) {
1552
            mkdir($dir, api_get_permissions_for_new_directories(), true);
1553
        }
1554
1555
        return $dir;
1556
    }
1557
1558
    /**
1559
     * @return string
1560
     */
1561
    public static function getCustomWebIconPath()
1562
    {
1563
        // Check if directory exists or create it if it doesn't
1564
        $dir = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
1565
1566
        return $dir;
1567
    }
1568
1569
    /**
1570
     * @param string $icon
1571
     *
1572
     * @return string
1573
     */
1574
    public static function getDisableIcon($icon)
1575
    {
1576
        $fileInfo = pathinfo($icon);
1577
1578
        return $fileInfo['filename'].'_na.'.$fileInfo['extension'];
1579
    }
1580
1581
    /**
1582
     * @param int   $id
1583
     * @param array $values
1584
     */
1585
    public static function updateTool($id, $values)
1586
    {
1587
        $table = Database::get_course_table(TABLE_TOOL_LIST);
1588
        $params = [
1589
            'name' => $values['name'],
1590
            'link' => $values['link'],
1591
            'target' => $values['target'],
1592
            'visibility' => $values['visibility'],
1593
            'description' => $values['description'],
1594
        ];
1595
1596
        if (isset($_FILES['icon']['size']) && $_FILES['icon']['size'] !== 0) {
1597
            $dir = self::getCustomSysIconPath();
1598
1599
            // Resize image if it is larger than 64px
1600
            $temp = new Image($_FILES['icon']['tmp_name']);
1601
            $picture_infos = $temp->get_image_info();
1602
            if ($picture_infos['width'] > 64) {
1603
                $thumbwidth = 64;
1604
            } else {
1605
                $thumbwidth = $picture_infos['width'];
1606
            }
1607
            if ($picture_infos['height'] > 64) {
1608
                $new_height = 64;
1609
            } else {
1610
                $new_height = $picture_infos['height'];
1611
            }
1612
            $temp->resize($thumbwidth, $new_height, 0);
1613
1614
            //copy the image to the course upload folder
1615
            $path = $dir.$_FILES['icon']['name'];
1616
            $result = $temp->send_image($path);
1617
1618
            $temp = new Image($path);
1619
            $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...
1620
            $ext = pathinfo($path, PATHINFO_EXTENSION);
1621
            $bwPath = substr($path, 0, -(strlen($ext) + 1)).'_na.'.$ext;
1622
1623
            if ($r === false) {
1624
                error_log('Conversion to B&W of '.$path.' failed in '.__FILE__.' at line '.__LINE__);
1625
            } else {
1626
                $temp->send_image($bwPath);
1627
                $iconName = $_FILES['icon']['name'];
1628
                $params['custom_icon'] = $iconName;
1629
            }
1630
        }
1631
1632
        Database::update(
1633
            $table,
1634
            $params,
1635
            [' iid = ?' => [$id]]
1636
        );
1637
    }
1638
1639
    /**
1640
     * @param int $id
1641
     */
1642
    public static function deleteIcon($id)
1643
    {
1644
        $table = Database::get_course_table(TABLE_TOOL_LIST);
1645
        $tool = self::getTool($id);
1646
1647
        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...
1648
            $file = self::getCustomSysIconPath().$tool['custom_icon'];
1649
            $fileInfo = pathinfo($file);
1650
            $fileGray = $fileInfo['filename'].'_na.'.$fileInfo['extension'];
1651
            $fileGray = self::getCustomSysIconPath().$fileGray;
1652
1653
            if (file_exists($file) && is_file($file)) {
1654
                if (Security::check_abs_path($file, self::getCustomSysIconPath())) {
1655
                    unlink($file);
1656
                }
1657
            }
1658
1659
            if (file_exists($fileGray) && is_file($fileGray)) {
1660
                if (Security::check_abs_path($fileGray, self::getCustomSysIconPath())) {
1661
                    unlink($fileGray);
1662
                }
1663
            }
1664
1665
            $params = [
1666
                'custom_icon' => '',
1667
            ];
1668
1669
            Database::update(
1670
                $table,
1671
                $params,
1672
                [' iid = ?' => [$id]]
1673
            );
1674
        }
1675
    }
1676
1677
    /**
1678
     * Filter tool icons. Only show if $patronKey is = :teacher
1679
     * Example dataIcons[i]['name']: parameter titleIcons1:teacher || titleIcons2 || titleIcons3:teacher.
1680
     *
1681
     * @param array  $dataIcons          array Reference to icons
1682
     * @param string $courseToolCategory Current tools category
1683
     *
1684
     * @return array
1685
     */
1686
    private static function filterPluginTools($dataIcons, $courseToolCategory)
1687
    {
1688
        $patronKey = ':teacher';
1689
1690
        if ($courseToolCategory == TOOL_STUDENT_VIEW) {
1691
            //Fix only coach can see external pages - see #8236 - icpna
1692
            if (api_is_coach()) {
1693
                foreach ($dataIcons as $index => $array) {
1694
                    if (isset($array['name'])) {
1695
                        $dataIcons[$index]['name'] = str_replace($patronKey, '', $array['name']);
1696
                    }
1697
                }
1698
1699
                return $dataIcons;
1700
            }
1701
1702
            $flagOrder = false;
1703
1704
            foreach ($dataIcons as $index => $array) {
1705
                if (!isset($array['name'])) {
1706
                    continue;
1707
                }
1708
1709
                $pos = strpos($array['name'], $patronKey);
1710
1711
                if ($pos !== false) {
1712
                    unset($dataIcons[$index]);
1713
                    $flagOrder = true;
1714
                }
1715
            }
1716
1717
            if ($flagOrder) {
1718
                return array_values($dataIcons);
1719
            }
1720
1721
            return $dataIcons;
1722
        }
1723
1724
        // clean patronKey of name icons
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
    /**
1735
     * Find the tool icon when homepage_view is activity_big.
1736
     *
1737
     * @param array $item
1738
     *
1739
     * @return string
1740
     */
1741
    private static function getToolIcon(array $item)
1742
    {
1743
        $image = str_replace('.gif', '.png', $item['tool']['image']);
1744
        $toolIid = isset($item['tool']['iid']) ? $item['tool']['iid'] : null;
1745
1746
        if (isset($item['tool']['custom_image'])) {
1747
            return Display::img(
1748
                $item['tool']['custom_image'],
1749
                $item['name'],
1750
                ['id' => 'toolimage_'.$toolIid]
1751
            );
1752
        }
1753
1754
        if (isset($item['tool']['custom_icon']) && !empty($item['tool']['custom_icon'])) {
1755
            $customIcon = $item['tool']['custom_icon'];
1756
1757
            if ($item['tool']['visibility'] == '0') {
1758
                $customIcon = self::getDisableIcon($item['tool']['custom_icon']);
1759
            }
1760
1761
            return Display::img(
1762
                self::getCustomWebIconPath().$customIcon,
1763
                $item['name'],
1764
                ['id' => 'toolimage_'.$toolIid]
1765
            );
1766
        }
1767
1768
        return Display::return_icon(
1769
            $image,
1770
            $item['name'],
1771
            ['id' => 'toolimage_'.$toolIid],
1772
            ICON_SIZE_BIG,
1773
            false
1774
        );
1775
    }
1776
}
1777