Completed
Push — master ( bdb7fb...d3d147 )
by Julito
25:16
created

CourseHome   F

Complexity

Total Complexity 300

Size/Duplication

Total Lines 1701
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1701
rs 0.6314
c 0
b 0
f 0
wmc 300

20 Methods

Rating   Name   Duplication   Size   Complexity  
F show_tool_3column() 0 219 47
F show_tool_2column() 0 215 54
B toolsIconsAction() 0 30 4
B show_session_data() 0 41 4
A getTool() 0 11 1
F get_tools_category() 0 275 47
C show_navigation_menu() 0 85 11
A getPublishedLpCategoryFromLink() 0 10 2
A getDisableIcon() 0 5 1
A getCustomWebIconPath() 0 6 1
D deleteIcon() 0 31 9
D show_tools_category() 0 310 61
B translate_tool_name() 0 28 3
B getToolIcon() 0 33 6
B updateTool() 0 51 6
A getCustomSysIconPath() 0 9 2
A get_published_lp_id_from_link() 0 12 3
C show_navigation_tool_shortcuts() 0 56 13
C filterPluginTools() 0 46 11
D get_navigation_items() 0 84 14

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

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

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