Passed
Push — master ( 6f8cb0...cccadf )
by Julito
09:47
created

CourseHome::getPublishedLpCategoryFromLink()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CLpCategory;
5
use Chamilo\CourseBundle\Entity\CTool;
6
7
/**
8
 * Class CourseHome.
9
 */
10
class CourseHome
11
{
12
    /**
13
     * Gets the html content to show in the 3 column view.
14
     *
15
     * @param string $cat
16
     * @param int    $userId
17
     *
18
     * @return string
19
     */
20
    public static function show_tool_3column($cat, $userId = null)
21
    {
22
        $_user = api_get_user_info($userId);
23
24
        $TBL_ACCUEIL = Database::get_course_table(TABLE_TOOL_LIST);
25
        $TABLE_TOOLS = Database::get_main_table(TABLE_MAIN_COURSE_MODULE);
26
27
        $numcols = 3;
28
        $table = new HTML_Table('width="100%"');
29
        $all_tools = [];
30
31
        $course_id = api_get_course_int_id();
32
        $studentView = api_is_student_view_active();
33
34
        switch ($cat) {
35
            case 'Basic':
36
                $condition_display_tools = ' WHERE a.c_id = '.$course_id.' AND  a.link=t.link AND t.position="basic" ';
37
                if ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) &&
38
                    !$studentView
39
                ) {
40
                    $condition_display_tools = ' WHERE 
41
                        a.c_id = '.$course_id.' AND 
42
                        a.link=t.link AND
43
                         (t.position="basic" OR a.name = "'.TOOL_TRACKING.'") 
44
                    ';
45
                }
46
47
                $sql = "SELECT a.*, t.image img, t.row, t.column  
48
                        FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
49
                        $condition_display_tools ORDER BY t.row, t.column";
50
                break;
51
            case 'External':
52
                if (api_is_allowed_to_edit()) {
53
                    $sql = "SELECT a.*, t.image img FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
54
                            WHERE 
55
                              a.c_id = $course_id AND 
56
                              ((a.link=t.link AND t.position='external') OR 
57
                              (a.visibility <= 1 AND 
58
                              (a.image = 'external.gif' OR a.image = 'scormbuilder.gif' OR t.image = 'blog.gif') AND 
59
                              a.image=t.image))
60
                            ORDER BY a.id";
61
                } else {
62
                    $sql = "SELECT a.*, t.image img FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
63
                            WHERE 
64
                              a.c_id = $course_id AND 
65
                              (a.visibility = 1 AND ((a.link=t.link AND t.position='external') OR 
66
                              ((a.image = 'external.gif' OR a.image = 'scormbuilder.gif' OR t.image = 'blog.gif') AND 
67
                              a.image=t.image)))
68
                            ORDER BY a.id";
69
                }
70
                break;
71
            case 'courseAdmin':
72
                $sql = "SELECT a.*, t.image img, t.row, t.column  
73
                        FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
74
                        WHERE a.c_id = $course_id AND admin=1 AND a.link=t.link 
75
                        ORDER BY t.row, t.column";
76
                break;
77
78
            case 'platformAdmin':
79
                $sql = "SELECT *, image img FROM $TBL_ACCUEIL 
80
                        WHERE c_id = $course_id AND visibility = 2 
81
                        ORDER BY id";
82
        }
83
        $result = Database::query($sql);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sql does not seem to be defined for all execution paths leading up to this point.
Loading history...
84
85
        // Grabbing all the tools from $course_tool_table
86
        while ($tool = Database::fetch_array($result)) {
87
            $all_tools[] = $tool;
88
        }
89
90
        $course_id = api_get_course_int_id();
91
92
        // Grabbing all the links that have the property on_homepage set to 1
93
        if ($cat == 'External') {
94
            $tbl_link = Database::get_course_table(TABLE_LINK);
95
            $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
96
            if (api_is_allowed_to_edit(null, true)) {
97
                $sql_links = "SELECT tl.*, tip.visibility
98
                              FROM $tbl_link tl
99
                              LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
100
                              WHERE 	
101
                                tl.c_id = $course_id AND
102
                                tip.c_id = $course_id AND
103
                                tl.on_homepage='1' AND
104
                                tip.visibility != 2";
105
            } else {
106
                $sql_links = "SELECT tl.*, tip.visibility
107
                                FROM $tbl_link tl
108
                                LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
109
                                WHERE 	
110
                                    tl.c_id = $course_id AND
111
                                    tip.c_id = $course_id AND
112
                                    tl.on_homepage='1' AND
113
                                    tip.visibility = 1";
114
            }
115
            $result_links = Database::query($sql_links);
116
            while ($links_row = Database::fetch_array($result_links)) {
117
                $properties = [];
118
                $properties['name'] = $links_row['title'];
119
                $properties['link'] = $links_row['url'];
120
                $properties['visibility'] = $links_row['visibility'];
121
                $properties['img'] = 'external.gif';
122
                $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&amp;id='.$links_row['id'];
123
                $all_tools[] = $properties;
124
            }
125
        }
126
127
        $cell_number = 0;
128
        // Draw line between basic and external, only if there are entries in External
129
        if ($cat == 'External' && count($all_tools)) {
130
            $table->setCellContents(0, 0, '<hr noshade="noshade" size="1"/>');
131
            $table->updateCellAttributes(0, 0, 'colspan="3"');
132
            $cell_number += $numcols;
133
        }
134
135
        foreach ($all_tools as &$tool) {
136
            if (isset($tool['image']) && $tool['image'] == 'scormbuilder.gif') {
137
                // check if the published learnpath is visible for student
138
                $lpId = self::getPublishedLpIdFromLink($tool['link']);
139
140
                if (!api_is_allowed_to_edit(null, true) &&
141
                    !learnpath::is_lp_visible_for_student(
142
                        $lpId,
143
                        api_get_user_id(),
144
                        api_get_course_info(),
145
                        api_get_session_id()
146
                    )
147
                ) {
148
                    continue;
149
                }
150
            }
151
152
            if (api_get_session_id() != 0 &&
153
                in_array($tool['name'], ['course_maintenance', 'course_setting'])
154
            ) {
155
                continue;
156
            }
157
158
            $cell_content = '';
159
            // The name of the tool
160
            $tool_name = self::translate_tool_name($tool);
161
162
            $link_annex = '';
163
            // The url of the tool
164
            if ($tool['img'] != 'external.gif') {
165
                $tool['link'] = api_get_path(WEB_CODE_PATH).$tool['link'];
166
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&amp;';
167
                $link_annex = $qm_or_amp.api_get_cidreq();
168
            } else {
169
                // If an external link ends with 'login=', add the actual login...
170
                $pos = strpos($tool['link'], '?login=');
171
                $pos2 = strpos($tool['link'], '&amp;login=');
172
                if ($pos !== false or $pos2 !== false) {
173
                    $link_annex = $_user['username'];
174
                }
175
            }
176
177
            // Setting the actual image url
178
            $tool['img'] = Display::returnIconPath($tool['img']);
179
            $target = isset($tool['target']) ? $tool['target'] : '';
180
181
            // VISIBLE
182
            if (($tool['visibility'] ||
183
                ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) && $tool['name'] == TOOL_TRACKING)) ||
184
                $cat == 'courseAdmin' || $cat == 'platformAdmin'
185
            ) {
186
                if (strpos($tool['name'], 'visio_') !== false) {
187
                    $cell_content .= '<a  href="javascript: void(0);" onclick="javascript: window.open(\''.$tool['link'].$link_annex.'\',\'window_visio'.api_get_course_id().'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'"><img src="'.$tool['img'].'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
188
                } elseif (strpos($tool['name'], 'chat') !== false &&
189
                    api_get_course_setting('allow_open_chat_window')
190
                ) {
191
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
192
                    $cell_content .= '<a href="javascript: void(0);" onclick="javascript: window.open(\''.$tool['link'].$link_annex.'\',\'window_chat'.api_get_course_id().'\',config=\'height=\'+600+\', width=\'+825+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'"><img src="'.$tool['img'].'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
193
                } else {
194
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
195
                    $cell_content .= '<a href="'.$tool['link'].$link_annex.'" target="'.$target.'"><img src="'.$tool['img'].'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
196
                }
197
            } else {
198
                // INVISIBLE
199
                if (api_is_allowed_to_edit(null, true)) {
200
                    if (strpos($tool['name'], 'visio_') !== false) {
201
                        $cell_content .= '<a  href="javascript: void(0);" onclick="window.open(\''.$tool['link'].$link_annex.'\',\'window_visio'.api_get_course_id().'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'"><img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
202
                    } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
203
                        // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
204
                        $cell_content .= '<a href="javascript: void(0);" onclick="javascript: window.open(\''.$tool['link'].$link_annex.'\',\'window_chat'.api_get_course_id().'\',config=\'height=\'+600+\', width=\'+825+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'" class="text-muted"><img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
205
                    } else {
206
                        // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
207
                        $cell_content .= '<a href="'.$tool['link'].$link_annex.'" target="'.$tool['target'].'" class="text-muted">
208
                            <img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
209
                    }
210
                } else {
211
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
212
                    $cell_content .= '<img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">';
213
                    $cell_content .= '<span class="text-muted">'.$tool_name.'</span>';
214
                }
215
            }
216
217
            $lnk = [];
218
            if (api_is_allowed_to_edit(null, true) &&
219
                $cat != "courseAdmin" &&
220
                !strpos($tool['link'], 'learnpath_handler.php?learnpath_id') &&
221
                !api_is_coach()
222
            ) {
223
                if ($tool['visibility']) {
224
                    $link['name'] = Display::return_icon(
225
                        'remove.gif',
226
                        get_lang('Deactivate'),
227
                        ['style' => 'vertical-align: middle;']
228
                    );
229
                    $link['cmd'] = "hide=yes";
230
                    $lnk[] = $link;
231
                } else {
232
                    $link['name'] = Display::return_icon(
233
                        'add.gif',
234
                        get_lang('Activate'),
235
                        ['style' => 'vertical-align: middle;']
236
                    );
237
                    $link['cmd'] = "restore=yes";
238
                    $lnk[] = $link;
239
                }
240
                if (is_array($lnk)) {
241
                    foreach ($lnk as &$this_lnk) {
242
                        if (isset($tool['adminlink']) && $tool['adminlink']) {
243
                            $cell_content .= '<a href="'.$properties['adminlink'].'">'.
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $properties does not seem to be defined for all execution paths leading up to this point.
Loading history...
244
                                Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
245
                        } else {
246
                            $cell_content .= '<a href="'.api_get_self().'?id='.$tool['id'].'&amp;'.$this_lnk['cmd'].'">'.$this_lnk['name'].'</a>';
247
                        }
248
                    }
249
                }
250
            }
251
            $table->setCellContents($cell_number / $numcols, ($cell_number) % $numcols, $cell_content);
252
            $table->updateCellAttributes($cell_number / $numcols, ($cell_number) % $numcols, 'width="32%" height="42"');
253
            $cell_number++;
254
        }
255
256
        return $table->toHtml();
257
    }
258
259
    /**
260
     * Displays the tools of a certain category.
261
     *
262
     * @param string $course_tool_category contains the category of tools to display:
263
     *                                     "Public", "PublicButHide", "courseAdmin", "claroAdmin"
264
     *
265
     * @return string
266
     */
267
    public static function show_tool_2column($course_tool_category)
268
    {
269
        $html = '';
270
        $web_code_path = api_get_path(WEB_CODE_PATH);
271
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
272
        $course_id = api_get_course_int_id();
273
        $studentView = api_is_student_view_active();
274
        switch ($course_tool_category) {
275
            case TOOL_PUBLIC:
276
                $condition_display_tools = ' WHERE c_id = '.$course_id.' AND visibility = 1 ';
277
                if ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) &&
278
                    !$studentView
279
                ) {
280
                    $condition_display_tools = ' WHERE 
281
                        c_id = '.$course_id.' AND 
282
                        (visibility = 1 OR (visibility = 0 AND name = "'.TOOL_TRACKING.'")) ';
283
                }
284
                $result = Database::query("SELECT * FROM $course_tool_table $condition_display_tools ORDER BY id");
285
                $col_link = "##003399";
286
                break;
287
            case TOOL_PUBLIC_BUT_HIDDEN:
288
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND visibility=0 AND admin=0 ORDER BY id");
289
                $col_link = "##808080";
290
                break;
291
            case TOOL_COURSE_ADMIN:
292
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND admin=1 AND visibility != 2 ORDER BY id");
293
                $col_link = "##003399";
294
                break;
295
            case TOOL_PLATFORM_ADMIN:
296
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND visibility = 2  ORDER BY id");
297
                $col_link = "##003399";
298
        }
299
        $i = 0;
300
301
        // Grabbing all the tools from $course_tool_table
302
        while ($temp_row = Database::fetch_array($result)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
303
            if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN && $temp_row['image'] != 'scormbuilder.gif') {
304
                $temp_row['image'] = str_replace('.gif', '_na.gif', $temp_row['image']);
305
            }
306
            $all_tools_list[] = $temp_row;
307
        }
308
309
        // Grabbing all the links that have the property on_homepage set to 1
310
        $course_link_table = Database::get_course_table(TABLE_LINK);
311
        $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
312
313
        switch ($course_tool_category) {
314
            case TOOL_PUBLIC:
315
                $sql_links = "SELECT tl.*, tip.visibility
316
                        FROM $course_link_table tl
317
                        LEFT JOIN $course_item_property_table tip 
318
                        ON tip.tool='link' AND tl.c_id = tip.c_id AND tl.c_id = $course_id AND tip.ref=tl.id
319
                        WHERE tl.on_homepage='1' AND tip.visibility = 1";
320
                break;
321
            case TOOL_PUBLIC_BUT_HIDDEN:
322
                $sql_links = "SELECT tl.*, tip.visibility
323
                    FROM $course_link_table tl
324
                    LEFT JOIN $course_item_property_table tip 
325
                    ON tip.tool='link' AND tl.c_id = tip.c_id AND tl.c_id = $course_id AND tip.ref=tl.id
326
                    WHERE tl.on_homepage='1' AND tip.visibility = 0";
327
328
                break;
329
            default:
330
                $sql_links = null;
331
                break;
332
        }
333
        if ($sql_links != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $sql_links of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
334
            $properties = [];
335
            $result_links = Database::query($sql_links);
336
            while ($links_row = Database::fetch_array($result_links)) {
337
                unset($properties);
338
                $properties['name'] = $links_row['title'];
339
                $properties['link'] = $links_row['url'];
340
                $properties['visibility'] = $links_row['visibility'];
341
                $properties['image'] = $course_tool_category == TOOL_PUBLIC_BUT_HIDDEN ? 'external_na.gif' : 'external.gif';
342
                $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&id='.$links_row['id'];
343
                $all_tools_list[] = $properties;
344
            }
345
        }
346
        $lnk = [];
347
        if (isset($all_tools_list)) {
348
            foreach ($all_tools_list as &$tool) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $all_tools_list does not seem to be defined for all execution paths leading up to this point.
Loading history...
349
                if ($tool['image'] == 'scormbuilder.gif') {
350
                    // check if the published learnpath is visible for student
351
                    $lpId = self::getPublishedLpIdFromLink($tool['link']);
352
353
                    if (!api_is_allowed_to_edit(null, true) &&
354
                        !learnpath::is_lp_visible_for_student(
355
                            $lpId,
356
                            api_get_user_id(),
357
                            api_get_course_info(),
358
                            api_get_session_id()
359
                        )
360
                    ) {
361
                        continue;
362
                    }
363
                }
364
365
                if (api_get_session_id() != 0 &&
366
                    in_array($tool['name'], ['course_maintenance', 'course_setting'])
367
                ) {
368
                    continue;
369
                }
370
371
                if (!($i % 2)) {
372
                    $html .= "<tr valign=\"top\">";
373
                }
374
375
                // NOTE : Table contains only the image file name, not full path
376
                if (stripos($tool['link'], 'http://') === false &&
377
                    stripos($tool['link'], 'https://') === false &&
378
                    stripos($tool['link'], 'ftp://') === false
379
                ) {
380
                    $tool['link'] = $web_code_path.$tool['link'];
381
                }
382
                $class = '';
383
                if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN) {
384
                    $class = 'class="text-muted"';
385
                }
386
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&amp;';
387
388
                $tool['link'] = $tool['link'];
389
                $html .= '<td width="50%" height="30">';
390
391
                if (strpos($tool['name'], 'visio_') !== false) {
392
                    $html .= '<a  '.$class.' href="javascript: void(0);" onclick="javascript: window.open(\''.htmlspecialchars($tool['link']).(($tool['image'] == 'external.gif' || $tool['image'] == 'external_na.gif') ? '' : $qm_or_amp.api_get_cidreq()).'\',\'window_visio'.api_get_course_id().'\',config=\'height=\'+730+\', width=\'+1020+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'">';
393
                } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
394
                    $html .= '<a href="javascript: void(0);" onclick="javascript: window.open(\''.htmlspecialchars($tool['link']).$qm_or_amp.api_get_cidreq().'\',\'window_chat'.api_get_course_id().'\',config=\'height=\'+600+\', width=\'+825+\', left=2, top=2, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no\')" target="'.$tool['target'].'" '.$class.'>';
395
                } else {
396
                    $target = isset($tool['target']) ? $tool['target'] : '';
397
                    $html .= '<a href="'.
398
                        htmlspecialchars($tool['link']).(($tool['image'] == 'external.gif' || $tool['image'] == 'external_na.gif') ? '' : $qm_or_amp.api_get_cidreq()).'" target="'.$target.'" '.$class.'>';
399
                }
400
401
                $tool_name = self::translate_tool_name($tool);
402
                $html .= Display::return_icon(
403
                    $tool['image'],
404
                    $tool_name,
405
                    [],
406
                    null,
407
                    ICON_SIZE_MEDIUM
408
                ).'&nbsp;'.$tool_name.
409
                '</a>';
410
411
                // This part displays the links to hide or remove a tool.
412
                // These links are only visible by the course manager.
413
                $lnk = [];
414
                if (api_is_allowed_to_edit(null, true) && !api_is_coach()) {
415
                    if ($tool['visibility'] == '1' || $tool['name'] == TOOL_TRACKING) {
416
                        $link['name'] = Display::returnFontAwesomeIcon('minus');
417
                        $link['title'] = get_lang('Deactivate');
418
                        $link['cmd'] = 'hide=yes';
419
                        $lnk[] = $link;
420
                    }
421
422
                    if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN) {
423
                        //$link['name'] = Display::return_icon('add.gif', get_lang('Activate'));
424
                        $link['name'] = Display::returnFontAwesomeIcon('plus');
425
                        $link['title'] = get_lang('Activate');
426
                        $link['cmd'] = 'restore=yes';
427
                        $lnk[] = $link;
428
429
                        if ($tool['added_tool'] == 1) {
430
                            //$link['name'] = Display::return_icon('delete.gif', get_lang('Remove'));
431
                            $link['name'] = Display::returnFontAwesomeIcon('trash');
432
                            $link['title'] = get_lang('Remove');
433
                            $link['cmd'] = 'remove=yes';
434
                            $lnk[] = $link;
435
                        }
436
                    }
437
                    if (isset($tool['adminlink'])) {
438
                        $html .= '<a href="'.$tool['adminlink'].'">'.
439
                            Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
440
                    }
441
                }
442
                if (api_is_platform_admin() && !api_is_coach()) {
443
                    if ($tool['visibility'] == 2) {
444
                        $link['name'] = Display::returnFontAwesomeIcon('undo');
445
                        $link['title'] = get_lang('Activate');
446
                        $link['cmd'] = 'hide=yes';
447
                        $lnk[] = $link;
448
449
                        if ($tool['added_tool'] == 1) {
450
                            $link['name'] = get_lang('Delete');
451
                            $link['cmd'] = 'askDelete=yes';
452
                            $lnk[] = $link;
453
                        }
454
                    }
455
                    if ($tool['visibility'] == 0 && $tool['added_tool'] == 0) {
456
                        $link['name'] = Display::returnFontAwesomeIcon('trash');
457
                        $link['title'] = get_lang('Remove');
458
                        $link['cmd'] = 'remove=yes';
459
                        $lnk[] = $link;
460
                    }
461
                }
462
                if (is_array($lnk)) {
463
                    $html .= '<div class="pull-right">';
464
                    $html .= '<div class="btn-options">';
465
                    $html .= '<div class="btn-group btn-group-sm" role="group">';
466
                    foreach ($lnk as &$this_link) {
467
                        if (!isset($tool['adminlink'])) {
468
                            $html .= '<a class="btn btn-default" title='.$this_link['title'].' href="'.api_get_self().'?'.api_get_cidreq().'&amp;id='.$tool['id'].'&amp;'.$this_link['cmd'].'">'.$this_link['name'].'</a>';
469
                        }
470
                    }
471
                    $html .= '</div>';
472
                    $html .= '</div>';
473
                    $html .= '</div>';
474
                }
475
                $html .= "</td>";
476
477
                if ($i % 2) {
478
                    $html .= "</tr>";
479
                }
480
                $i++;
481
            }
482
        }
483
484
        if ($i % 2) {
485
            $html .= "<td width=\"50%\">&nbsp;</td></tr>";
486
        }
487
488
        return $html;
489
    }
490
491
    /**
492
     * Gets the tools of a certain category. Returns an array expected
493
     * by show_tools_category().
494
     *
495
     * @param string $course_tool_category contains the category of tools to
496
     *                                     display: "toolauthoring", "toolinteraction", "tooladmin", "tooladminplatform", "toolplugin"
497
     * @param int    $courseId             Optional
498
     * @param int    $sessionId            Optional
499
     *
500
     * @return array
501
     */
502
    public static function get_tools_category(
503
        $course_tool_category,
504
        $courseId = 0,
505
        $sessionId = 0
506
    ) {
507
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
508
        $is_platform_admin = api_is_platform_admin();
509
        $all_tools_list = [];
510
511
        // Condition for the session
512
        $sessionId = $sessionId ?: api_get_session_id();
513
        $course_id = $courseId ?: api_get_course_int_id();
514
        $courseInfo = api_get_course_info_by_id($course_id);
515
        $userId = api_get_user_id();
516
        $user = api_get_user_entity($userId);
517
        $condition_session = api_get_session_condition(
518
            $sessionId,
519
            true,
520
            true,
521
            't.session_id'
522
        );
523
524
        $lpTable = Database::get_course_table(TABLE_LP_MAIN);
525
        $tblLpCategory = Database::get_course_table(TABLE_LP_CATEGORY);
526
        $studentView = api_is_student_view_active();
527
528
        $orderBy = ' ORDER BY id ';
529
        switch ($course_tool_category) {
530
            case TOOL_STUDENT_VIEW:
531
                $conditions = ' WHERE visibility = 1 AND 
532
                                (category = "authoring" OR category = "interaction" OR category = "plugin") AND 
533
                                t.name <> "notebookteacher" ';
534
                if ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) && !$studentView) {
535
                    $conditions = ' WHERE (
536
                        visibility = 1 AND (
537
                            category = "authoring" OR 
538
                            category = "interaction" OR 
539
                            category = "plugin"
540
                        ) OR (t.name = "'.TOOL_TRACKING.'") 
541
                    )';
542
                }
543
544
                // Add order if there are LPs
545
                $sql = "SELECT t.* FROM $course_tool_table t
546
                        LEFT JOIN $lpTable l 
547
                        ON (t.c_id = l.c_id AND link LIKE concat('%/lp_controller.php?action=view&lp_id=', l.id, '&%'))
548
                        LEFT JOIN $tblLpCategory lc
549
                        ON (t.c_id = lc.c_id AND l.category_id = lc.iid)
550
                        $conditions AND
551
                        t.c_id = $course_id $condition_session 
552
                        ORDER BY
553
                            CASE WHEN l.category_id IS NULL THEN 0 ELSE 1 END,
554
                            CASE WHEN l.display_order IS NULL THEN 0 ELSE 1 END,
555
                            lc.position,
556
                            l.display_order,
557
                            t.id";
558
                $orderBy = '';
559
                break;
560
            case TOOL_AUTHORING:
561
                $sql = "SELECT t.* FROM $course_tool_table t
562
                        LEFT JOIN $lpTable l
563
                        ON (t.c_id = l.c_id AND link LIKE concat('%/lp_controller.php?action=view&lp_id=', l.id, '&%'))
564
                        LEFT JOIN $tblLpCategory lc
565
                        ON (t.c_id = lc.c_id AND l.category_id = lc.iid)
566
                        WHERE
567
                            category = 'authoring' AND t.c_id = $course_id $condition_session
568
                        ORDER BY
569
                            CASE WHEN l.category_id IS NULL THEN 0 ELSE 1 END,
570
                            CASE WHEN l.display_order IS NULL THEN 0 ELSE 1 END,
571
                            lc.position,
572
                            l.display_order,
573
                            t.id";
574
                $orderBy = '';
575
                break;
576
            case TOOL_INTERACTION:
577
                $sql = "SELECT * FROM $course_tool_table t
578
                        WHERE category = 'interaction' AND c_id = $course_id $condition_session
579
                        ";
580
                break;
581
            case TOOL_ADMIN_VISIBLE:
582
                $sql = "SELECT * FROM $course_tool_table t
583
                        WHERE category = 'admin' AND visibility ='1' AND c_id = $course_id $condition_session
584
                        ";
585
                break;
586
            case TOOL_ADMIN_PLATFORM:
587
                $sql = "SELECT * FROM $course_tool_table t
588
                        WHERE category = 'admin' AND c_id = $course_id $condition_session
589
                        ";
590
                break;
591
            case TOOL_DRH:
592
                $sql = "SELECT * FROM $course_tool_table t
593
                        WHERE t.name IN ('tracking') AND c_id = $course_id $condition_session
594
                        ";
595
                break;
596
            case TOOL_COURSE_PLUGIN:
597
                //Other queries recover id, name, link, image, visibility, admin, address, added_tool, target, category and session_id
598
                // but plugins are not present in the tool table, only globally and inside the course_settings table once configured
599
                $sql = "SELECT * FROM $course_tool_table t
600
                        WHERE category = 'plugin' AND name <> 'courseblock' AND c_id = $course_id $condition_session
601
                        ";
602
                break;
603
        }
604
        $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...
605
        $result = Database::query($sql);
606
        $tools = [];
607
        while ($row = Database::fetch_assoc($result)) {
608
            $tools[] = $row;
609
        }
610
611
        // Get the list of hidden tools - this might imply performance slowdowns
612
        // if the course homepage is loaded many times, so the list of hidden
613
        // tools might benefit from a shared memory storage later on
614
        $list = api_get_settings('Tools', 'list', api_get_current_access_url_id());
615
        $hide_list = [];
616
        $check = false;
617
        foreach ($list as $line) {
618
            // Admin can see all tools even if the course_hide_tools configuration is set
619
            if ($is_platform_admin) {
620
                continue;
621
            }
622
            if ($line['variable'] == 'course_hide_tools' && $line['selected_value'] == 'true') {
623
                $hide_list[] = $line['subkey'];
624
                $check = true;
625
            }
626
        }
627
628
        $allowEditionInSession = api_get_configuration_value('allow_edit_tool_visibility_in_session');
629
        // If exists same tool (by name) from session in base course then avoid it. Allow them pass in other cases
630
        $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...
631
            if (!empty($toolToFilter['session_id'])) {
632
                foreach ($tools as $originalTool) {
633
                    if ($toolToFilter['name'] == $originalTool['name'] && empty($originalTool['session_id'])) {
634
                        return false;
635
                    }
636
                }
637
            }
638
639
            return true;
640
        });
641
642
        foreach ($tools as $temp_row) {
643
            $add = false;
644
            if ($check) {
645
                if (!in_array($temp_row['name'], $hide_list)) {
646
                    $add = true;
647
                }
648
            } else {
649
                $add = true;
650
            }
651
652
            if ($allowEditionInSession && !empty($sessionId)) {
653
                // Checking if exist row in session
654
                $criteria = [
655
                    'course' => $course_id,
656
                    'name' => $temp_row['name'],
657
                    'sessionId' => $sessionId,
658
                ];
659
                /** @var CTool $toolObj */
660
                $toolObj = Database::getManager()->getRepository('ChamiloCourseBundle:CTool')->findOneBy($criteria);
661
                if ($toolObj) {
662
                    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...
663
                        continue;
664
                    }
665
                }
666
            }
667
668
            switch ($temp_row['image']) {
669
                case 'scormbuilder.gif':
670
                    $lpId = self::getPublishedLpIdFromLink($temp_row['link']);
671
                    $lp = new learnpath(
672
                        api_get_course_id(),
673
                        $lpId,
674
                        $userId
675
                    );
676
                    $path = $lp->get_preview_image_path(ICON_SIZE_BIG);
677
678
                    if (api_is_allowed_to_edit(null, true)) {
679
                        $add = true;
680
                    } else {
681
                        $add = learnpath::is_lp_visible_for_student(
682
                            $lpId,
683
                            $userId,
684
                            $courseInfo,
685
                            $sessionId
686
                        );
687
                    }
688
                    if ($path) {
689
                        $temp_row['custom_image'] = $path;
690
                    }
691
                    break;
692
                case 'lp_category.gif':
693
                    $lpCategory = self::getPublishedLpCategoryFromLink(
694
                        $temp_row['link']
695
                    );
696
                    $add = learnpath::categoryIsVisibleForStudent(
697
                        $lpCategory,
698
                        $user
699
                    );
700
                    break;
701
            }
702
703
            if ($add) {
704
                $all_tools_list[] = $temp_row;
705
            }
706
        }
707
708
        // Grabbing all the links that have the property on_homepage set to 1
709
        $course_link_table = Database::get_course_table(TABLE_LINK);
710
        $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
711
        $condition_session = api_get_session_condition(
712
            $sessionId,
713
            true,
714
            true,
715
            'tip.session_id'
716
        );
717
718
        switch ($course_tool_category) {
719
            case TOOL_AUTHORING:
720
                $sql_links = "SELECT tl.*, tip.visibility
721
                    FROM $course_link_table tl
722
                    LEFT JOIN $course_item_property_table tip
723
                    ON tip.tool='link' AND tip.ref=tl.id
724
                    WHERE
725
                        tl.c_id = $course_id AND
726
                        tip.c_id = $course_id AND
727
                        tl.on_homepage='1' $condition_session";
728
                break;
729
            case TOOL_INTERACTION:
730
                $sql_links = null;
731
                /*
732
                  $sql_links = "SELECT tl.*, tip.visibility
733
                  FROM $course_link_table tl
734
                  LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
735
                  WHERE tl.on_homepage='1' ";
736
                 */
737
                break;
738
            case TOOL_STUDENT_VIEW:
739
                $sql_links = "SELECT tl.*, tip.visibility
740
                    FROM $course_link_table tl
741
                    LEFT JOIN $course_item_property_table tip
742
                    ON tip.tool='link' AND tip.ref=tl.id
743
                    WHERE
744
                        tl.c_id 		= $course_id AND
745
                        tip.c_id 		= $course_id AND
746
                        tl.on_homepage	='1' $condition_session";
747
                break;
748
            case TOOL_ADMIN:
749
                $sql_links = "SELECT tl.*, tip.visibility
750
                    FROM $course_link_table tl
751
                    LEFT JOIN $course_item_property_table tip
752
                    ON tip.tool='link' AND tip.ref=tl.id
753
                    WHERE
754
                        tl.c_id = $course_id AND
755
                        tip.c_id = $course_id AND
756
                        tl.on_homepage='1' $condition_session";
757
                break;
758
            default:
759
                $sql_links = null;
760
                break;
761
        }
762
763
        // Edited by Kevin Van Den Haute ([email protected]) for integrating Smartblogs
764
        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...
765
            $result_links = Database::query($sql_links);
766
            if (Database::num_rows($result_links) > 0) {
767
                while ($links_row = Database::fetch_array($result_links, 'ASSOC')) {
768
                    $properties = [];
769
                    $properties['name'] = $links_row['title'];
770
                    $properties['session_id'] = $links_row['session_id'];
771
                    $properties['link'] = $links_row['url'];
772
                    $properties['visibility'] = $links_row['visibility'];
773
                    $properties['image'] = $links_row['visibility'] == '0' ? 'file_html.png' : 'file_html.png';
774
                    $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&id='.$links_row['id'];
775
                    $properties['target'] = $links_row['target'];
776
                    $tmp_all_tools_list[] = $properties;
777
                }
778
            }
779
        }
780
781
        if (isset($tmp_all_tools_list)) {
782
            $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
783
            foreach ($tmp_all_tools_list as $tool) {
784
                if ($tool['image'] == 'blog.gif') {
785
                    // Get blog id
786
                    $blog_id = substr($tool['link'], strrpos($tool['link'], '=') + 1, strlen($tool['link']));
787
788
                    // Get blog members
789
                    if ($is_platform_admin) {
790
                        $sql = "SELECT * FROM $tbl_blogs_rel_user blogs_rel_user
791
                                WHERE blog_id = ".$blog_id;
792
                    } else {
793
                        $sql = "SELECT * FROM $tbl_blogs_rel_user blogs_rel_user
794
                                WHERE blog_id = ".$blog_id." AND user_id = ".$userId;
795
                    }
796
                    $result = Database::query($sql);
797
                    if (Database::num_rows($result) > 0) {
798
                        $all_tools_list[] = $tool;
799
                    }
800
                } else {
801
                    $all_tools_list[] = $tool;
802
                }
803
            }
804
        }
805
806
        $list = self::filterPluginTools($all_tools_list, $course_tool_category);
807
808
        return $list;
809
    }
810
811
    /**
812
     * Displays the tools of a certain category.
813
     *
814
     * @param array $all_tools_list List of tools as returned by get_tools_category()
815
     *
816
     * @return array
817
     */
818
    public static function show_tools_category($all_tools_list)
819
    {
820
        $_user = api_get_user_info();
821
        $theme = api_get_setting('homepage_view');
822
823
        if ($theme === 'vertical_activity') {
824
            //ordering by get_lang name
825
            $order_tool_list = [];
826
            if (is_array($all_tools_list) && count($all_tools_list) > 0) {
827
                foreach ($all_tools_list as $key => $new_tool) {
828
                    $tool_name = self::translate_tool_name($new_tool);
829
                    $order_tool_list[$key] = $tool_name;
830
                }
831
                natsort($order_tool_list);
832
                $my_temp_tool_array = [];
833
                foreach ($order_tool_list as $key => $new_tool) {
834
                    $my_temp_tool_array[] = $all_tools_list[$key];
835
                }
836
                $all_tools_list = $my_temp_tool_array;
837
            } else {
838
                $all_tools_list = [];
839
            }
840
        }
841
        $web_code_path = api_get_path(WEB_CODE_PATH);
842
        $session_id = api_get_session_id();
843
        $is_platform_admin = api_is_platform_admin();
844
        $allowEditionInSession = api_get_configuration_value('allow_edit_tool_visibility_in_session');
845
        if ($session_id == 0) {
846
            $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && api_is_course_admin();
847
        } else {
848
            $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && !api_is_coach();
849
            if ($allowEditionInSession) {
850
                $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && api_is_coach($session_id, api_get_course_int_id());
851
            }
852
        }
853
854
        $items = [];
855
        $app_plugin = new AppPlugin();
856
857
        if (isset($all_tools_list)) {
858
            $lnk = '';
859
            foreach ($all_tools_list as &$tool) {
860
                $item = [];
861
                $studentview = false;
862
                $tool['original_link'] = $tool['link'];
863
                if ($tool['image'] === 'scormbuilder.gif') {
864
                    // Check if the published learnpath is visible for student
865
                    $lpId = self::getPublishedLpIdFromLink($tool['link']);
866
                    if (api_is_allowed_to_edit(null, true)) {
867
                        $studentview = true;
868
                    }
869
                    if (!api_is_allowed_to_edit(null, true) &&
870
                        !learnpath::is_lp_visible_for_student(
871
                            $lpId,
872
                            api_get_user_id(),
873
                            api_get_course_info(),
874
                            api_get_session_id()
875
                        )
876
                    ) {
877
                        continue;
878
                    }
879
                }
880
881
                if ($session_id != 0 && in_array($tool['name'], ['course_setting'])) {
882
                    continue;
883
                }
884
885
                // This part displays the links to hide or remove a tool.
886
                // These links are only visible by the course manager.
887
                unset($lnk);
888
889
                $item['extra'] = null;
890
                $toolAdmin = isset($tool['admin']) ? $tool['admin'] : '';
891
892
                if ($is_allowed_to_edit) {
893
                    if (empty($session_id)) {
894
                        if (isset($tool['id'])) {
895
                            if ($tool['visibility'] == '1' && $toolAdmin != '1') {
896
                                $link['name'] = Display::return_icon(
897
                                    'visible.png',
898
                                    get_lang('Deactivate'),
899
                                    ['id' => 'linktool_'.$tool['iid']],
900
                                    ICON_SIZE_SMALL,
901
                                    false
902
                                );
903
                                $link['cmd'] = 'hide=yes';
904
                                $lnk[] = $link;
905
                            }
906
                            if ($tool['visibility'] == '0' && $toolAdmin != '1') {
907
                                $link['name'] = Display::return_icon(
908
                                    'invisible.png',
909
                                    get_lang('Activate'),
910
                                    ['id' => 'linktool_'.$tool['iid']],
911
                                    ICON_SIZE_SMALL,
912
                                    false
913
                                );
914
                                $link['cmd'] = 'restore=yes';
915
                                $lnk[] = $link;
916
                            }
917
                        }
918
                    } elseif ($allowEditionInSession) {
919
                        $criteria = [
920
                            'course' => api_get_course_int_id(),
921
                            'name' => $tool['name'],
922
                            'sessionId' => $session_id,
923
                        ];
924
                        /** @var CTool $tool */
925
                        $toolObj = Database::getManager()->getRepository('ChamiloCourseBundle:CTool')->findOneBy($criteria);
926
                        if ($toolObj) {
927
                            $visibility = (int) $toolObj->getVisibility();
928
                            switch ($visibility) {
929
                                case '0':
930
                                    $info = pathinfo($tool['image']);
931
                                    $basename = basename($tool['image'], '.'.$info['extension']);
932
                                    $tool['image'] = $basename.'_na.'.$info['extension'];
933
                                    $link['name'] = Display::return_icon(
934
                                        'invisible.png',
935
                                        get_lang('Activate'),
936
                                        ['id' => 'linktool_'.$tool['iid']],
937
                                        ICON_SIZE_SMALL,
938
                                        false
939
                                    );
940
                                    $link['cmd'] = 'restore=yes';
941
                                    $lnk[] = $link;
942
                                    break;
943
                                case '1':
944
                                    $link['name'] = Display::return_icon(
945
                                        'visible.png',
946
                                        get_lang('Deactivate'),
947
                                        ['id' => 'linktool_'.$tool['iid']],
948
                                        ICON_SIZE_SMALL,
949
                                        false
950
                                    );
951
                                    $link['cmd'] = 'hide=yes';
952
                                    $lnk[] = $link;
953
                                    break;
954
                            }
955
                        } else {
956
                            $link['name'] = Display::return_icon(
957
                                'visible.png',
958
                                get_lang('Deactivate'),
959
                                ['id' => 'linktool_'.$tool['iid']],
960
                                ICON_SIZE_SMALL,
961
                                false
962
                            );
963
                            $link['cmd'] = 'hide=yes';
964
                            $lnk[] = $link;
965
                        }
966
                    }
967
                    if (!empty($tool['adminlink'])) {
968
                        $item['extra'] = '<a href="'.$tool['adminlink'].'">'.
969
                            Display::return_icon('edit.gif', get_lang('Edit')).
970
                        '</a>';
971
                    }
972
                }
973
974
                // Both checks are necessary as is_platform_admin doesn't take student view into account
975
                if ($is_platform_admin && $is_allowed_to_edit) {
976
                    if ($toolAdmin != '1') {
977
                        $link['cmd'] = 'hide=yes';
978
                    }
979
                }
980
981
                $item['visibility'] = '';
982
                if (isset($lnk) && is_array($lnk)) {
983
                    foreach ($lnk as $this_link) {
984
                        if (empty($tool['adminlink'])) {
985
                            $item['visibility'] .=
986
                                '<a class="make_visible_and_invisible" href="'.api_get_self().'?'.api_get_cidreq().'&id='.$tool['iid'].'&'.$this_link['cmd'].'">'.
987
                                $this_link['name'].'</a>';
988
                        }
989
                    }
990
                }
991
992
                // NOTE : Table contains only the image file name, not full path
993
                if (stripos($tool['link'], 'http://') === false &&
994
                    stripos($tool['link'], 'https://') === false &&
995
                    stripos($tool['link'], 'ftp://') === false
996
                ) {
997
                    $tool['link'] = $web_code_path.$tool['link'];
998
                }
999
1000
                $class = '';
1001
                if ($tool['visibility'] == '0' && $toolAdmin != '1') {
1002
                    $class = 'text-muted';
1003
                    $info = pathinfo($tool['image']);
1004
                    $basename = basename($tool['image'], '.'.$info['extension']);
1005
                    $tool['image'] = $basename.'_na.'.$info['extension'];
1006
                }
1007
1008
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&';
1009
1010
                // If it's a link, we don't add the cidReq
1011
                if ($tool['image'] === 'file_html.png' || $tool['image'] === 'file_html_na.png') {
1012
                    $tool['link'] = $tool['link'];
1013
                } else {
1014
                    $tool['link'] = $tool['link'].$qm_or_amp.api_get_cidreq();
1015
                }
1016
1017
                $toolIid = isset($tool['iid']) ? $tool['iid'] : null;
1018
1019
                //@todo this visio stuff should be removed
1020
                if (strpos($tool['name'], 'visio_') !== false) {
1021
                    $tool_link_params = [
1022
                        'id' => 'tooldesc_'.$toolIid,
1023
                        'href' => '"javascript: void(0);"',
1024
                        'class' => $class,
1025
                        '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\')',
1026
                        'target' => $tool['target'],
1027
                    ];
1028
                } elseif (strpos($tool['name'], 'chat') !== false &&
1029
                    api_get_course_setting('allow_open_chat_window')
1030
                ) {
1031
                    $tool_link_params = [
1032
                        'id' => 'tooldesc_'.$toolIid,
1033
                        'class' => $class,
1034
                        'href' => 'javascript: void(0);',
1035
                        '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
1036
                        'target' => $tool['target'],
1037
                    ];
1038
                } else {
1039
                    $tool_link_params = [
1040
                        'id' => 'tooldesc_'.$toolIid,
1041
                        'href' => $tool['link'],
1042
                        'class' => $class,
1043
                        'target' => $tool['target'],
1044
                    ];
1045
                }
1046
1047
                $tool_name = self::translate_tool_name($tool);
1048
1049
                // Including Courses Plugins
1050
                // Creating title and the link
1051
                if (isset($tool['category']) && $tool['category'] == 'plugin') {
1052
                    $plugin_info = $app_plugin->getPluginInfo($tool['name']);
1053
                    if (isset($plugin_info) && isset($plugin_info['title'])) {
1054
                        $tool_name = $plugin_info['title'];
1055
                    }
1056
1057
                    if (!file_exists(api_get_path(SYS_CODE_PATH).'img/'.$tool['image']) &&
1058
                        !file_exists(api_get_path(SYS_CODE_PATH).'img/icons/64/'.$tool['image'])) {
1059
                        $tool['image'] = 'plugins.png';
1060
                    }
1061
                    $tool_link_params['href'] = api_get_path(WEB_PLUGIN_PATH)
1062
                        .$tool['original_link'].$qm_or_amp.api_get_cidreq();
1063
                }
1064
1065
                // Use in the course home
1066
                $icon = Display::return_icon(
1067
                    $tool['image'],
1068
                    $tool_name,
1069
                    ['class' => 'tool-icon', 'id' => 'toolimage_'.$toolIid],
1070
                    ICON_SIZE_BIG,
1071
                    false
1072
                );
1073
1074
                // Used in the top bar
1075
                $iconMedium = Display::return_icon(
1076
                    $tool['image'],
1077
                    $tool_name,
1078
                    ['class' => 'tool-icon', 'id' => 'toolimage_'.$toolIid],
1079
                    ICON_SIZE_MEDIUM,
1080
                    false
1081
                );
1082
1083
                // Used for vertical navigation
1084
                $iconSmall = Display::return_icon(
1085
                    $tool['image'],
1086
                    $tool_name,
1087
                    ['class' => 'tool-img', 'id' => 'toolimage_'.$toolIid],
1088
                    ICON_SIZE_SMALL,
1089
                    false
1090
                );
1091
1092
                /*if (!empty($tool['custom_icon'])) {
1093
                    $image = self::getCustomWebIconPath().$tool['custom_icon'];
1094
                    $icon = Display::img(
1095
                        $image,
1096
                        $tool['description'],
1097
                        array(
1098
                            'class' => 'tool-icon',
1099
                            'id' => 'toolimage_'.$tool['id']
1100
                        )
1101
                    );
1102
                }*/
1103
1104
                // Validation when belongs to a session
1105
                $session_img = api_get_session_image(
1106
                    $tool['session_id'],
1107
                    !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 $statusId 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

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