Completed
Push — master ( cc3037...815120 )
by Julito
29:55
created

CourseHome::availableTools()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 23
nc 1
nop 0
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class CourseHome
6
 */
7
class CourseHome
8
{
9
    /**
10
     * Gets the html content to show in the 3 column view
11
     */
12
    public static function show_tool_3column($cat, $userId = null)
13
    {
14
        $_user = api_get_user_info($userId);
15
16
        $TBL_ACCUEIL = Database :: get_course_table(TABLE_TOOL_LIST);
17
        $TABLE_TOOLS = Database :: get_main_table(TABLE_MAIN_COURSE_MODULE);
18
19
        $numcols = 3;
20
        $table = new HTML_Table('width="100%"');
21
        $all_tools = array();
22
23
        $course_id = api_get_course_int_id();
24
25
        switch ($cat) {
26 View Code Duplication
            case 'Basic':
27
                $condition_display_tools = ' WHERE a.c_id = '.$course_id.' AND  a.link=t.link AND t.position="basic" ';
28
                if ((api_is_coach() || api_is_course_tutor()) && $_SESSION['studentview'] != 'studentview') {
29
                    $condition_display_tools = ' WHERE a.c_id = '.$course_id.' AND a.link=t.link AND (t.position="basic" OR a.name = "'.TOOL_TRACKING.'") ';
30
                }
31
32
                $sql = "SELECT a.*, t.image img, t.row, t.column  FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
33
                        $condition_display_tools ORDER BY t.row, t.column";
34
                break;
35
            case 'External':
36
                if (api_is_allowed_to_edit()) {
37
                    $sql = "SELECT a.*, t.image img FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
38
                            WHERE a.c_id = $course_id AND ((a.link=t.link AND t.position='external')
39
                            OR (a.visibility <= 1 AND (a.image = 'external.gif' OR a.image = 'scormbuilder.gif' OR t.image = 'blog.gif') AND a.image=t.image))
40
                            ORDER BY a.id";
41
                } else {
42
                    $sql = "SELECT a.*, t.image img FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
43
                            WHERE a.c_id = $course_id AND (a.visibility = 1 AND ((a.link=t.link AND t.position='external')
44
                            OR ((a.image = 'external.gif' OR a.image = 'scormbuilder.gif' OR t.image = 'blog.gif') AND a.image=t.image)))
45
                            ORDER BY a.id";
46
                }
47
                break;
48
            case 'courseAdmin':
49
                $sql = "SELECT a.*, t.image img, t.row, t.column  FROM $TBL_ACCUEIL a, $TABLE_TOOLS t
50
                        WHERE a.c_id = $course_id AND admin=1 AND a.link=t.link ORDER BY t.row, t.column";
51
                break;
52
53
            case 'platformAdmin':
54
                $sql = "SELECT *, image img FROM $TBL_ACCUEIL WHERE c_id = $course_id AND visibility = 2 ORDER BY id";
55
        }
56
        $result = Database::query($sql);
57
58
        // Grabbing all the tools from $course_tool_table
59
        while ($tool = Database::fetch_array($result)) {
60
            $all_tools[] = $tool;
61
        }
62
63
        $course_id = api_get_course_int_id();
64
65
        // Grabbing all the links that have the property on_homepage set to 1
66
        if ($cat == 'External') {
67
            $tbl_link = Database :: get_course_table(TABLE_LINK);
68
            $tbl_item_property = Database :: get_course_table(TABLE_ITEM_PROPERTY);
69
            if (api_is_allowed_to_edit(null, true)) {
70
                $sql_links = "SELECT tl.*, tip.visibility
71
								FROM $tbl_link tl
72
                                LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
73
                                WHERE 	tl.c_id = $course_id AND
74
                                		tip.c_id = $course_id AND
75
                						tl.on_homepage='1' AND
76
                						tip.visibility != 2";
77
            } else {
78
                $sql_links = "SELECT tl.*, tip.visibility
79
                                    FROM $tbl_link tl
80
                                    LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
81
                                    WHERE 	tl.c_id = $course_id AND
82
                                			tip.c_id = $course_id AND
83
                							tl.on_homepage='1' AND
84
                							tip.visibility = 1";
85
            }
86
            $result_links = Database::query($sql_links);
87 View Code Duplication
            while ($links_row = Database::fetch_array($result_links)) {
88
                $properties = array();
89
                $properties['name'] = $links_row['title'];
90
                $properties['link'] = $links_row['url'];
91
                $properties['visibility'] = $links_row['visibility'];
92
                $properties['img'] = 'external.gif';
93
                $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&amp;id='.$links_row['id'];
94
                $all_tools[] = $properties;
95
            }
96
        }
97
98
        $cell_number = 0;
99
        // Draw line between basic and external, only if there are entries in External
100
        if ($cat == 'External' && count($all_tools)) {
101
            $table->setCellContents(0, 0, '<hr noshade="noshade" size="1"/>');
102
            $table->updateCellAttributes(0, 0, 'colspan="3"');
103
            $cell_number += $numcols;
104
        }
105
106
        foreach ($all_tools as & $tool) {
107 View Code Duplication
            if ($tool['image'] == 'scormbuilder.gif') {
108
                // check if the published learnpath is visible for student
109
                $published_lp_id = self::get_published_lp_id_from_link($tool['link']);
110
                if (!api_is_allowed_to_edit(null, true) &&
111
                    !learnpath::is_lp_visible_for_student(
112
                        $published_lp_id,
113
                        api_get_user_id(),
114
                        api_get_course_id(),
115
                        api_get_session_id()
116
                    )
117
                ) {
118
                    continue;
119
                }
120
            }
121
122 View Code Duplication
            if (api_get_session_id() != 0 &&
123
                in_array($tool['name'], array('course_maintenance', 'course_setting'))
124
            ) {
125
                continue;
126
            }
127
128
            $cell_content = '';
129
            // The name of the tool
130
            $tool_name = self::translate_tool_name($tool);
131
132
            $link_annex = '';
133
            // The url of the tool
134
            if ($tool['img'] != 'external.gif') {
135
                $tool['link'] = api_get_path(WEB_CODE_PATH).$tool['link'];
136
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&amp;';
137
                $link_annex = $qm_or_amp.api_get_cidreq();
138
            } else {
139
                // If an external link ends with 'login=', add the actual login...
140
                $pos = strpos($tool['link'], '?login=');
141
                $pos2 = strpos($tool['link'], '&amp;login=');
142
                if ($pos !== false or $pos2 !== false) {
143
                    $link_annex = $_user['username'];
144
                }
145
            }
146
147
            // Setting the actual image url
148
            $tool['img'] = Display::returnIconPath($tool['img']);
149
150
            // VISIBLE
151
            if (($tool['visibility'] ||
152
                ((api_is_coach() || api_is_course_tutor()) && $tool['name'] == TOOL_TRACKING)) ||
153
                $cat == 'courseAdmin' || $cat == 'platformAdmin'
154
            ) {
155
                if (strpos($tool['name'], 'visio_') !== false) {
156
                    $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>';
157 View Code Duplication
                } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
158
                    $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>';
159
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
160
                } else {
161
                    $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>';
162
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
163
                }
164
            } else {
165
                // INVISIBLE
166
                if (api_is_allowed_to_edit(null, true)) {
167
                    if (strpos($tool['name'], 'visio_') !== false) {
168
                        $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>';
169 View Code Duplication
                    } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
170
                        $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>';
171
                        // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
172
                    } else {
173
                        $cell_content .= '<a href="'.$tool['link'].$link_annex.'" target="'.$tool['target'].'" class="text-muted">
174
                                            <img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">'.$tool_name.'</a>';
175
                        // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
176
                    }
177
                } else {
178
                    $cell_content .= '<img src="'.str_replace(".gif", "_na.gif", $tool['img']).'" title="'.$tool_name.'" alt="'.$tool_name.'" align="absmiddle" border="0">';
179
                    // don't replace img with display::return_icon because $tool['img'] = api_get_path(WEB_IMG_PATH).$tool['img']
180
                    $cell_content .= '<span class="text-muted">'.$tool_name.'</span>';
181
                }
182
            }
183
184
            $lnk = array();
185
            if (api_is_allowed_to_edit(null, true) &&
186
                $cat != "courseAdmin" &&
187
                !strpos($tool['link'], 'learnpath_handler.php?learnpath_id') &&
188
                !api_is_coach()
189
            ) {
190
                if ($tool['visibility']) {
191
                    $link['name'] = Display::return_icon('remove.gif', get_lang('Deactivate'), array('style' => 'vertical-align: middle;'));
192
                    $link['cmd'] = "hide=yes";
193
                    $lnk[] = $link;
194
                } else {
195
                    $link['name'] = Display::return_icon('add.gif', get_lang('Activate'), array('style' => 'vertical-align: middle;'));
196
                    $link['cmd'] = "restore=yes";
197
                    $lnk[] = $link;
198
                }
199
                if (is_array($lnk)) {
200
                    foreach ($lnk as & $this_lnk) {
201
                        if ($tool['adminlink']) {
202
                            $cell_content .= '<a href="'.$properties['adminlink'].'">'.
203
                                Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
204
                        } else {
205
                            $cell_content .= '<a href="'.api_get_self().'?id='.$tool['id'].'&amp;'.$this_lnk['cmd'].'">'.$this_lnk['name'].'</a>';
206
                        }
207
                    }
208
                }
209
            }
210
            $table->setCellContents($cell_number / $numcols, ($cell_number) % $numcols, $cell_content);
211
            $table->updateCellAttributes($cell_number / $numcols, ($cell_number) % $numcols, 'width="32%" height="42"');
212
            $cell_number++;
213
        }
214
215
        return $table->toHtml();
216
    }
217
218
    /**
219
     * Displays the tools of a certain category.
220
     *
221
     * @return void
222
     * @param string $course_tool_category	contains the category of tools to display:
223
     * "Public", "PublicButHide", "courseAdmin", "claroAdmin"
224
     */
225
    public static function show_tool_2column($course_tool_category)
226
    {
227
        $html = '';
228
        $web_code_path = api_get_path(WEB_CODE_PATH);
229
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
230
231
        $course_id = api_get_course_int_id();
232
233
        switch ($course_tool_category) {
234 View Code Duplication
            case TOOL_PUBLIC:
235
                $condition_display_tools = ' WHERE c_id = '.$course_id.' AND visibility = 1 ';
236
                if ((api_is_coach() || api_is_course_tutor()) && $_SESSION['studentview'] != 'studentview') {
237
                    $condition_display_tools = ' WHERE c_id = '.$course_id.' AND (visibility = 1 OR (visibility = 0 AND name = "'.TOOL_TRACKING.'")) ';
238
                }
239
                $result = Database::query("SELECT * FROM $course_tool_table $condition_display_tools ORDER BY id");
240
                $col_link = "##003399";
241
                break;
242
            case TOOL_PUBLIC_BUT_HIDDEN:
243
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND visibility=0 AND admin=0 ORDER BY id");
244
                $col_link = "##808080";
245
                break;
246
            case TOOL_COURSE_ADMIN:
247
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND admin=1 AND visibility != 2 ORDER BY id");
248
                $col_link = "##003399";
249
                break;
250
            case TOOL_PLATFORM_ADMIN:
251
                $result = Database::query("SELECT * FROM $course_tool_table WHERE c_id = $course_id AND visibility = 2  ORDER BY id");
252
                $col_link = "##003399";
253
        }
254
        $i = 0;
255
256
        // Grabbing all the tools from $course_tool_table
257
        while ($temp_row = Database::fetch_array($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
258
            if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN && $temp_row['image'] != 'scormbuilder.gif') {
259
                $temp_row['image'] = str_replace('.gif', '_na.gif', $temp_row['image']);
260
            }
261
            $all_tools_list[] = $temp_row;
262
        }
263
264
        // Grabbing all the links that have the property on_homepage set to 1
265
        $course_link_table = Database::get_course_table(TABLE_LINK);
266
        $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
267
268
        switch ($course_tool_category) {
269
            case TOOL_PUBLIC:
270
                $sql_links = "SELECT tl.*, tip.visibility
271
                        FROM $course_link_table tl
272
                        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
273
                        WHERE tl.on_homepage='1' AND tip.visibility = 1";
274
                break;
275
            case TOOL_PUBLIC_BUT_HIDDEN:
276
                $sql_links = "SELECT tl.*, tip.visibility
277
                    FROM $course_link_table tl
278
                    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
279
                    WHERE tl.on_homepage='1' AND tip.visibility = 0";
280
281
                break;
282
            default:
283
                $sql_links = null;
284
                break;
285
        }
286
        if ($sql_links != null) {
287
            $properties = array();
288
            $result_links = Database::query($sql_links);
289 View Code Duplication
            while ($links_row = Database::fetch_array($result_links)) {
290
                unset($properties);
291
                $properties['name'] = $links_row['title'];
292
                $properties['link'] = $links_row['url'];
293
                $properties['visibility'] = $links_row['visibility'];
294
                $properties['image'] = $course_tool_category == TOOL_PUBLIC_BUT_HIDDEN ? 'external_na.gif' : 'external.gif';
295
                $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&id='.$links_row['id'];
296
                $all_tools_list[] = $properties;
297
            }
298
        }
299
        if (isset($all_tools_list)) {
300
            $lnk = array();
301
            foreach ($all_tools_list as & $tool) {
302 View Code Duplication
                if ($tool['image'] == 'scormbuilder.gif') {
303
                    // check if the published learnpath is visible for student
304
                    $published_lp_id = self::get_published_lp_id_from_link($tool['link']);
305
306
                    if (!api_is_allowed_to_edit(null, true) &&
307
                        !learnpath::is_lp_visible_for_student(
308
                            $published_lp_id,
309
                            api_get_user_id(),
310
                            api_get_course_id(),
311
                            api_get_session_id()
312
                        )
313
                    ) {
314
                        continue;
315
                    }
316
                }
317
318 View Code Duplication
                if (api_get_session_id() != 0 &&
319
                    in_array($tool['name'], array('course_maintenance', 'course_setting'))
320
                ) {
321
                    continue;
322
                }
323
324
                if (!($i % 2)) {
325
                    $html .= "<tr valign=\"top\">";
326
                }
327
328
                // NOTE : Table contains only the image file name, not full path
329 View Code Duplication
                if (stripos($tool['link'], 'http://') === false &&
330
                    stripos($tool['link'], 'https://') === false &&
331
                    stripos($tool['link'], 'ftp://') === false
332
                ) {
333
                    $tool['link'] = $web_code_path.$tool['link'];
334
                }
335
                $class = '';
336
                if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN) {
337
                    $class = 'class="text-muted"';
338
                }
339
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&amp;';
340
341
                $tool['link'] = $tool['link'];
342
                $html .= '<td width="50%" height="30">';
343
344
                if (strpos($tool['name'], 'visio_') !== false) {
345
                    $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'].'">';
346
                } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
347
                    $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.'>';
348
                } else {
349
                    $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.'>';
350
                }
351
352
                $tool_name = self::translate_tool_name($tool);
353
                $html .= Display::return_icon(
354
                        $tool['image'],
355
                        $tool_name,
356
                        array(),
357
                        null,
358
                        ICON_SIZE_MEDIUM
359
                    ) . '&nbsp;' . $tool_name . '</a>';
360
361
                // This part displays the links to hide or remove a tool.
362
                // These links are only visible by the course manager.
363
                unset($lnk);
364
                if (api_is_allowed_to_edit(null, true) && !api_is_coach()) {
365 View Code Duplication
                    if ($tool['visibility'] == '1' || $tool['name'] == TOOL_TRACKING) {
366
                        $link['name'] = Display::returnFontAwesomeIcon('minus');
367
                        $link['title'] = get_lang('Deactivate');
368
                        $link['cmd'] = 'hide=yes';
369
                        $lnk[] = $link;
370
                    }
371
372 View Code Duplication
                    if ($course_tool_category == TOOL_PUBLIC_BUT_HIDDEN) {
373
                        //$link['name'] = Display::return_icon('add.gif', get_lang('Activate'));
374
                        $link['name'] = Display::returnFontAwesomeIcon('plus');
375
                        $link['title'] = get_lang('Activate');
376
                        $link['cmd'] = 'restore=yes';
377
                        $lnk[] = $link;
378
379
                        if ($tool['added_tool'] == 1) {
380
                            //$link['name'] = Display::return_icon('delete.gif', get_lang('Remove'));
381
                            $link['name'] = Display::returnFontAwesomeIcon('trash');
382
                            $link['title'] = get_lang('Remove');
383
                            $link['cmd'] = 'remove=yes';
384
                            $lnk[] = $link;
385
                        }
386
                    }
387
                    if (isset($tool['adminlink'])) {
388
                        $html .= '<a href="'.$tool['adminlink'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
389
                    }
390
                }
391
                if (api_is_platform_admin() && !api_is_coach()) {
392 View Code Duplication
                    if ($tool['visibility'] == 2) {
393
                        $link['name'] = Display::returnFontAwesomeIcon('undo');
394
                        $link['title'] = get_lang('Activate');
395
                        $link['cmd'] = 'hide=yes';
396
                        $lnk[] = $link;
397
398
                        if ($tool['added_tool'] == 1) {
399
                            $link['name'] = get_lang('Delete');
400
                            $link['cmd'] = 'askDelete=yes';
401
                            $lnk[] = $link;
402
                        }
403
                    }
404 View Code Duplication
                    if ($tool['visibility'] == 0 && $tool['added_tool'] == 0) {
405
                        $link['name'] = Display::returnFontAwesomeIcon('trash');
406
                        $link['title'] = get_lang('Remove');
407
                        $link['cmd'] = 'remove=yes';
408
                        $lnk[] = $link;
409
                    }
410
                }
411
                if (is_array($lnk)) {
412
                    $html .= '<div class="pull-right">';
413
                    $html .= '<div class="btn-options">';
414
                    $html .= '<div class="btn-group btn-group-sm" role="group">';
415 View Code Duplication
                    foreach ($lnk as & $this_link) {
416
                        if (!isset($tool['adminlink'])) {
417
                            $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>';
418
                        }
419
                    }
420
                    $html .= '</div>';
421
                    $html .= '</div>';
422
                    $html .= '</div>';
423
                }
424
                $html .= "</td>";
425
426
                if ($i % 2) {
427
                    $html .= "</tr>";
428
                }
429
430
                $i++;
431
            }
432
        }
433
434
        if ($i % 2) {
435
            $html .= "<td width=\"50%\">&nbsp;</td></tr>";
436
        }
437
438
        return $html;
439
    }
440
441
    /**
442
     * Gets the tools of a certain category. Returns an array expected
443
     * by show_tools_category()
444
     * @param string $course_tool_category contains the category of tools to
445
     * display: "toolauthoring", "toolinteraction", "tooladmin", "tooladminplatform", "toolplugin"
446
     * @param int $courseId Optional
447
     * @param int $sessionId Optional
448
     * @return array
449
     */
450
    public static function get_tools_category($course_tool_category, $courseId = 0, $sessionId = 0)
451
    {
452
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
453
        $is_platform_admin = api_is_platform_admin();
454
        $all_tools_list = array();
455
456
        // Condition for the session
457
        $session_id = $sessionId ?: api_get_session_id();
458
        $course_id = $courseId ?: api_get_course_int_id();
459
        $condition_session = api_get_session_condition($session_id, true, true, 't.session_id');
460
461
        switch ($course_tool_category) {
462
            case TOOL_STUDENT_VIEW:
463
                $conditions = ' WHERE visibility = 1 AND (category = "authoring" OR category = "interaction" OR category = "plugin") ';
464
                if ((api_is_coach() || api_is_course_tutor()) && $_SESSION['studentview'] != 'studentview') {
465
                    $conditions = ' WHERE (visibility = 1 AND (category = "authoring" OR category = "interaction" OR category = "plugin") OR (name = "'.TOOL_TRACKING.'") )   ';
466
                }
467
                $sql = "SELECT *
468
                        FROM $course_tool_table t
469
                        $conditions AND
470
                        c_id = $course_id $condition_session
471
                        ORDER BY id";
472
                $result = Database::query($sql);
473
                break;
474
            case TOOL_AUTHORING:
475
                $sql = "SELECT * FROM $course_tool_table t
476
                        WHERE category = 'authoring' AND c_id = $course_id $condition_session
477
                        ORDER BY id";
478
                $result = Database::query($sql);
479
                break;
480
            case TOOL_INTERACTION:
481
                $sql = "SELECT * FROM $course_tool_table t
482
                        WHERE category = 'interaction' AND c_id = $course_id $condition_session
483
                        ORDER BY id";
484
                $result = Database::query($sql);
485
                break;
486
            case TOOL_ADMIN_VISIBLE:
487
                $sql = "SELECT * FROM $course_tool_table t
488
                        WHERE category = 'admin' AND visibility ='1' AND c_id = $course_id $condition_session
489
                        ORDER BY id";
490
                $result = Database::query($sql);
491
                break;
492
            case TOOL_ADMIN_PLATFORM:
493
                $sql = "SELECT * FROM $course_tool_table t
494
                        WHERE category = 'admin' AND c_id = $course_id $condition_session
495
                        ORDER BY id";
496
                $result = Database::query($sql);
497
                break;
498
            case TOOL_DRH:
499
                $sql = "SELECT * FROM $course_tool_table t
500
                        WHERE name IN ('tracking') AND c_id = $course_id $condition_session
501
                        ORDER BY id";
502
                $result = Database::query($sql);
503
                break;
504
            case TOOL_COURSE_PLUGIN:
505
                //Other queries recover id, name, link, image, visibility, admin, address, added_tool, target, category and session_id
506
                // but plugins are not present in the tool table, only globally and inside the course_settings table once configured
507
                $sql = "SELECT * FROM $course_tool_table t
508
                        WHERE category = 'plugin' AND name <> 'courseblock' AND c_id = $course_id $condition_session
509
                        ORDER BY id";
510
                $result = Database::query($sql);
511
                break;
512
        }
513
514
        //Get the list of hidden tools - this might imply performance slowdowns
515
        // if the course homepage is loaded many times, so the list of hidden
516
        // tools might benefit from a shared memory storage later on
517
        $list = api_get_settings('Tools', 'list', api_get_current_access_url_id());
518
        $hide_list = array();
519
        $check = false;
520
521
        foreach ($list as $line) {
522
            // Admin can see all tools even if the course_hide_tools configuration is set
523
            if ($is_platform_admin) {
524
                continue;
525
            }
526
            if ($line['variable'] == 'course_hide_tools' and $line['selected_value'] == 'true') {
527
                $hide_list[] = $line['subkey'];
528
                $check = true;
529
            }
530
        }
531
532
        while ($temp_row = Database::fetch_assoc($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_assoc() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
533
            $add = false;
534
            if ($check) {
535
                if (!in_array($temp_row['name'], $hide_list)) {
536
                    $add = true;
537
                }
538
            } else {
539
                $add = true;
540
            }
541
542
            if ($temp_row['image'] == 'scormbuilder.gif') {
543
                $lp_id = self::get_published_lp_id_from_link($temp_row['link']);
544
                $lp = new learnpath(
545
                    api_get_course_id(),
546
                    $lp_id,
547
                    api_get_user_id()
548
                );
549
                $path = $lp->get_preview_image_path(ICON_SIZE_BIG);
550
                $add = $lp->is_lp_visible_for_student(
551
                    $lp_id,
552
                    api_get_user_id(),
553
                    api_get_course_id(),
554
                    api_get_session_id()
555
                );
556
                if ($path) {
557
                    $temp_row['custom_image'] = $path;
558
                }
559
            }
560
561
            if ($add) {
562
                $all_tools_list[] = $temp_row;
563
            }
564
        }
565
566
        // Grabbing all the links that have the property on_homepage set to 1
567
        $course_link_table = Database::get_course_table(TABLE_LINK);
568
        $course_item_property_table = Database::get_course_table(TABLE_ITEM_PROPERTY);
569
        $condition_session = api_get_session_condition($session_id, true, true, 'tip.session_id');
570
571
        switch ($course_tool_category) {
572
            case TOOL_AUTHORING:
573
                $sql_links = "SELECT tl.*, tip.visibility
574
                    FROM $course_link_table tl
575
                    LEFT JOIN $course_item_property_table tip
576
                    ON tip.tool='link' AND tip.ref=tl.id
577
                    WHERE
578
                        tl.c_id = $course_id AND
579
                        tip.c_id = $course_id AND
580
                        tl.on_homepage='1' $condition_session";
581
                break;
582
            case TOOL_INTERACTION:
583
                $sql_links = null;
584
                /*
585
                  $sql_links = "SELECT tl.*, tip.visibility
586
                  FROM $course_link_table tl
587
                  LEFT JOIN $course_item_property_table tip ON tip.tool='link' AND tip.ref=tl.id
588
                  WHERE tl.on_homepage='1' ";
589
                 */
590
                break;
591
            case TOOL_STUDENT_VIEW:
592
                $sql_links = "SELECT tl.*, tip.visibility
593
                    FROM $course_link_table tl
594
                    LEFT JOIN $course_item_property_table tip
595
                    ON tip.tool='link' AND tip.ref=tl.id
596
                    WHERE
597
                        tl.c_id 		= $course_id AND
598
                        tip.c_id 		= $course_id AND
599
                        tl.on_homepage	='1' $condition_session";
600
                break;
601
            case TOOL_ADMIN:
602
                $sql_links = "SELECT tl.*, tip.visibility
603
                    FROM $course_link_table tl
604
                    LEFT JOIN $course_item_property_table tip
605
                    ON tip.tool='link' AND tip.ref=tl.id
606
                    WHERE
607
                        tl.c_id = $course_id AND
608
                        tip.c_id = $course_id AND
609
                        tl.on_homepage='1' $condition_session";
610
                break;
611
            default:
612
                $sql_links = null;
613
                break;
614
        }
615
616
        // Edited by Kevin Van Den Haute ([email protected]) for integrating Smartblogs
617
        if ($sql_links != null) {
618
            $result_links = Database::query($sql_links);
619
620
            if (Database::num_rows($result_links) > 0) {
621
                while ($links_row = Database::fetch_array($result_links, 'ASSOC')) {
622
                    $properties = array();
623
                    $properties['name'] = $links_row['title'];
624
                    $properties['session_id'] = $links_row['session_id'];
625
                    $properties['link'] = $links_row['url'];
626
                    $properties['visibility'] = $links_row['visibility'];
627
                    $properties['image'] = $links_row['visibility'] == '0' ? 'file_html.png' : 'file_html.png';
628
                    $properties['adminlink'] = api_get_path(WEB_CODE_PATH).'link/link.php?action=editlink&id='.$links_row['id'];
629
                    $properties['target'] = $links_row['target'];
630
                    $tmp_all_tools_list[] = $properties;
631
                }
632
            }
633
        }
634
635
        if (isset($tmp_all_tools_list)) {
636
            foreach ($tmp_all_tools_list as $tool) {
637
                if ($tool['image'] == 'blog.gif') {
638
                    // Init
639
                    $tbl_blogs_rel_user = Database::get_course_table(TABLE_BLOGS_REL_USER);
640
641
                    // Get blog id
642
                    $blog_id = substr($tool['link'], strrpos($tool['link'], '=') + 1, strlen($tool['link']));
643
644
                    // Get blog members
645
                    if ($is_platform_admin) {
646
                        $sql_blogs = "SELECT * FROM $tbl_blogs_rel_user blogs_rel_user
647
                                      WHERE blog_id =".$blog_id;
648
                    } else {
649
                        $sql_blogs = "SELECT * FROM $tbl_blogs_rel_user blogs_rel_user
650
                                      WHERE blog_id =".$blog_id." AND user_id = ".api_get_user_id();
651
                    }
652
                    $result_blogs = Database::query($sql_blogs);
653
654
                    if (Database::num_rows($result_blogs) > 0) {
655
                        $all_tools_list[] = $tool;
656
                    }
657
                } else {
658
                    $all_tools_list[] = $tool;
659
                }
660
            }
661
        }
662
663
        return $all_tools_list;
664
    }
665
666
    /**
667
     * Displays the tools of a certain category.
668
     * @param $urlGenerator
669
     * @param array $all_tools_list List of tools as returned by get_tools_category()
670
     * @param bool  $rows
671
     *
672
     * @return string
673
     */
674
    public static function show_tools_category($urlGenerator, $all_tools_list, $rows = false)
675
    {
676
        $_user = api_get_user_info();
677
        $web_code_path = api_get_path(WEB_CODE_PATH);
678
        $session_id = api_get_session_id();
679
        $is_platform_admin = api_is_platform_admin();
680
        $theme = api_get_setting('homepage_view');
681
682
        if ($theme === 'vertical_activity') {
683
            //ordering by get_lang name
684
            $order_tool_list = array();
685
            if (is_array($all_tools_list) && count($all_tools_list) > 0) {
686
                foreach ($all_tools_list as $key => $new_tool) {
687
                    $tool_name = self::translate_tool_name($new_tool);
688
                    $order_tool_list [$key] = $tool_name;
689
                }
690
                natsort($order_tool_list);
691
                $my_temp_tool_array = array();
692
                foreach ($order_tool_list as $key => $new_tool) {
693
                    $my_temp_tool_array[] = $all_tools_list[$key];
694
                }
695
                $all_tools_list = $my_temp_tool_array;
696
            } else {
697
                $all_tools_list = array();
698
            }
699
        }
700
701
        if ($session_id == 0 ) {
702
            $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && api_is_course_admin();
703
        } else {
704
            $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && !api_is_coach();
705
        }
706
707
        $i = 0;
708
        $items = array();
709
        $app_plugin = new AppPlugin();
710
711
        $toolChain = \Chamilo\CoreBundle\Framework\Container::getToolChain();
712
713
        if (isset($all_tools_list)) {
714
            $lnk = '';
715
716
            foreach ($all_tools_list as & $tool) {
717
                $item = array();
718
                $studentview = false;
719
720
                // Using tool chain to load links instead of loading link from the database.
721
                $toolObject = $toolChain->getToolFromName($tool['name']);
722
                if ($toolObject) {
723
                    $tool['link'] = $toolObject->getLink();
724
                }
725
726
                $tool['original_link'] = $tool['link'];
727
728
                if ($tool['image'] == 'scormbuilder.gif') {
729
                    // check if the published learnpath is visible for student
730
                    $published_lp_id = self::get_published_lp_id_from_link($tool['link']);
731
                    if (api_is_allowed_to_edit(null, true)) {
732
                        $studentview = true;
733
                    }
734
                    if (!api_is_allowed_to_edit(null, true) &&
735
                        !learnpath::is_lp_visible_for_student(
736
                            $published_lp_id,
737
                            api_get_user_id(),
738
                            api_get_course_id(),
739
                            api_get_session_id()
740
                        )
741
                    ) {
742
                        continue;
743
                    }
744
                }
745
746
                if ($session_id != 0 && in_array($tool['name'], array('course_setting'))) {
747
                    continue;
748
                }
749
750
                // This part displays the links to hide or remove a tool.
751
                // These links are only visible by the course manager.
752
                unset($lnk);
753
754
                $item['extra'] = null;
755
                $toolAdmin = isset($tool['admin']) ? $tool['admin'] : '';
756
757
                if ($is_allowed_to_edit) {
758
                    if (empty($session_id)) {
759
                        if (isset($tool['id'])) {
760 View Code Duplication
                            if ($tool['visibility'] == '1' && $toolAdmin != '1') {
761
                                $link['name'] = Display::return_icon(
762
                                    'visible.png',
763
                                    get_lang('Deactivate'),
764
                                    array('id' => 'linktool_'.$tool['id']),
765
                                    ICON_SIZE_SMALL,
766
                                    false
767
                                );
768
                                $link['cmd'] = 'hide=yes';
769
                                $lnk[] = $link;
770
                            }
771 View Code Duplication
                            if ($tool['visibility'] == '0' && $toolAdmin != '1') {
772
                                $link['name'] = Display::return_icon(
773
                                    'invisible.png',
774
                                    get_lang('Activate'),
775
                                    array('id' => 'linktool_'.$tool['id']),
776
                                    ICON_SIZE_SMALL,
777
                                    false
778
                                );
779
                                $link['cmd'] = 'restore=yes';
780
                                $lnk[] = $link;
781
                            }
782
                        }
783
                    }
784
                    if (!empty($tool['adminlink'])) {
785
                        $item['extra'] = '<a href="'.$tool['adminlink'].'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
786
                    }
787
                }
788
789
                // Both checks are necessary as is_platform_admin doesn't take student view into account
790
                if ($is_platform_admin && $is_allowed_to_edit) {
791
                    if ($toolAdmin != '1') {
792
                        $link['cmd'] = 'hide=yes';
793
                    }
794
                }
795
796
                $item['visibility'] = null;
797
798
                if (isset($lnk) && is_array($lnk)) {
799 View Code Duplication
                    foreach ($lnk as $this_link) {
800
                        if (empty($tool['adminlink'])) {
801
                            $item['visibility'] .= '<a class="make_visible_and_invisible" href="'.api_get_self().'?'.api_get_cidreq().'&amp;id='.$tool['id'].'&amp;'.$this_link['cmd'].'">'.
802
                                $this_link['name'].'</a>';
803
                        }
804
                    }
805
                } else {
806
                    $item['visibility'] .= '';
807
                }
808
809
                // NOTE : Table contains only the image file name, not full path
810 View Code Duplication
                if (stripos($tool['link'], 'http://') === false &&
811
                    stripos($tool['link'], 'https://') === false &&
812
                    stripos($tool['link'], 'ftp://') === false
813
                ) {
814
                    $tool['link'] = $web_code_path.$tool['link'];
815
                }
816
817
                if ($tool['visibility'] == '0' && $toolAdmin != '1') {
818
                    $class = 'text-muted';
819
                    $info = pathinfo($tool['image']);
820
                    $basename = basename($tool['image'], '.'.$info['extension']); // $file is set to "index"
821
                    $tool['image'] = $basename.'_na.'.$info['extension'];
822
                } else {
823
                    $class = '';
824
                }
825
826
                $qm_or_amp = strpos($tool['link'], '?') === false ? '?' : '&';
827
                // If it's a link, we don't add the cidReq
828
829
                if ($tool['image'] == 'file_html.png' || $tool['image'] == 'file_html_na.png') {
830
                    $tool['link'] = $tool['link'].$qm_or_amp;
831
                } else {
832
                    $tool['link'] = $tool['link'].$qm_or_amp.api_get_cidreq();
833
                }
834
835
                $tool_link_params = array();
836
                $toolId = isset($tool["id"]) ? $tool["id"] : null;
837
838
                //@todo this visio stuff should be removed
839
                if (strpos($tool['name'], 'visio_') !== false) {
840
                    $tool_link_params = array(
841
                        'id' => 'tooldesc_'.$toolId,
842
                        'href' => '"javascript: void(0);"',
843
                        'class' => $class,
844
                        '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\')',
845
                        'target' => $tool['target']
846
                    );
847
                } elseif (strpos($tool['name'], 'chat') !== false && api_get_course_setting('allow_open_chat_window')) {
848
                    $tool_link_params = array(
849
                        'id' => 'tooldesc_'.$toolId,
850
                        'class' => $class,
851
                        'href' => 'javascript: void(0);',
852
                        '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
853
                        'target' => $tool['target']
854
                    );
855
                } else {
856
                    $tool_link_params = array(
857
                        'id' => 'tooldesc_'.$toolId,
858
                        'href' => $tool['link'],
859
                        'class' => $class,
860
                        'target' => $tool['target']
861
                    );
862
                }
863
864
                $tool_name = self::translate_tool_name($tool);
865
866
                // Including Courses Plugins
867
                // Creating title and the link
868
                if (isset($tool['category']) && $tool['category'] == 'plugin') {
869
                    $plugin_info = $app_plugin->getPluginInfo($tool['name']);
870
                    if (isset($plugin_info) && isset($plugin_info['title'])) {
871
                        $tool_name = $plugin_info['title'];
872
                    }
873
874
                    if (!file_exists(api_get_path(SYS_CODE_PATH).'img/'.$tool['image']) &&
875
                        !file_exists(api_get_path(SYS_CODE_PATH).'img/icons/64/'.$tool['image'])) {
876
                        $tool['image'] = 'plugins.png';
877
                    }
878
                    $tool_link_params['href'] = api_get_path(WEB_PLUGIN_PATH).$tool['original_link'].'?'.api_get_cidreq();
879
                }
880
881
                $icon = Display::return_icon(
882
                    $tool['image'],
883
                    $tool_name,
884
                    array('class' => 'tool-icon', 'id' => 'toolimage_'.$toolId),
885
                    ICON_SIZE_BIG,
886
                    false
887
                );
888
889
                /*if (!empty($tool['custom_icon'])) {
890
                    $image = self::getCustomWebIconPath().$tool['custom_icon'];
891
                    $icon = Display::img(
892
                        $image,
893
                        $tool['description'],
894
                        array(
895
                            'class' => 'tool-icon',
896
                            'id' => 'toolimage_'.$tool['id']
897
                        )
898
                    );
899
                }*/
900
901
                // Validation when belongs to a session
902
                $session_img = api_get_session_image($tool['session_id'], (!empty($_user['status']) ? $_user['status'] : ''));
903
                if ($studentview) {
904
                    $tool_link_params['href'] .= '&isStudentView=true';
905
                }
906
                $item['url_params'] = $tool_link_params;
907
                $item['icon'] = Display::url($icon, $tool_link_params['href'], $tool_link_params);
908
                $item['tool'] = $tool;
909
                $item['name'] = $tool_name;
910
                $tool_link_params['id'] = 'is'.$tool_link_params['id'];
911
                $item['link'] = Display::url(
912
                    $tool_name.$session_img,
913
                    $tool_link_params['href'],
914
                    $tool_link_params
915
                );
916
917
                $items[] = $item;
918
919
                $i++;
920
            } // end of foreach
921
        }
922
923
        $i = 0;
924
        $html = '';
925
926
        if (!empty($items)) {
927
            foreach ($items as $item) {
928
                switch ($theme) {
929
                    case 'activity_big':
930
                        $data = '';
931
                        $html .= '<div class="col-xs-6 col-md-3 course-tool">';
932
                        $image = (substr($item['tool']['image'], 0, strpos($item['tool']['image'], '.'))).'.png';
933
                        $toolId = isset($item['tool']['id']) ? $item['tool']['id'] : null;
934
935
                        if (isset($item['tool']['custom_image'])) {
936
                            $original_image = Display::img(
937
                                $item['tool']['custom_image'],
938
                                $item['name'],
939
                                array('id' => 'toolimage_'.$toolId)
940
                            );
941
                        } elseif (isset($item['tool']['custom_icon']) &&
942
                            !empty($item['tool']['custom_icon'])
943
                        ) {
944
                            $customIcon = $item['tool']['custom_icon'];
945
                            if ($item['tool']['visibility'] == '0') {
946
                                $fileInfo = pathinfo($item['tool']['custom_icon']);
947
                                $customIcon = self::getDisableIcon($item['tool']['custom_icon']);
948
                            }
949
                            $original_image = Display::img(
950
                                self::getCustomWebIconPath().$customIcon,
951
                                $item['name'],
952
                                array('id' => 'toolimage_'.$toolId)
953
                            );
954
                        } else {
955
                            $original_image = Display::return_icon(
956
                                $image,
957
                                $item['name'],
958
                                array('id' => 'toolimage_'.$toolId),
959
                                ICON_SIZE_BIG,
960
                                false
961
                            );
962
                        }
963
964
                        $data .= Display::url($original_image, $item['url_params']['href'], $item['url_params']);
965
                        $html .= Display::div($data, array('class' => 'big_icon')); //box-image reflection
966
                        $html .= Display::div('<h4>'.$item['visibility'].$item['extra'].$item['link'].'</h4>', array('class' => 'content'));
967
                        $html .= '</div>';
968
969
                        break;
970
                    case 'activity':
971
                        $html .= '<div class="offset2 col-md-4 course-tool">';
972
                        $html .= $item['extra'];
973
                        $html .= $item['visibility'];
974
                        $html .= $item['icon'];
975
                        $html .= $item['link'];
976
                        $html .= '</div>';
977
                        break;
978
                    case 'vertical_activity':
979
                        if ($i == 0) {
980
                            $html .= '<ul>';
981
                        }
982
                        $image = (substr($item['tool']['image'], 0, strpos($item['tool']['image'], '.'))).'.png';
983
                        $original_image = Display::return_icon(
984
                                $image,
985
                                $item['name'],
986
                                array('id' => 'toolimage_'.$item['tool']['id']),
987
                                ICON_SIZE_SMALL,
988
                                false
989
                            );
990
                        $html .= '<li class="course-tool">';
991
                        $html .= $item['extra'];
992
                        $html .= $item['visibility'];
993
                        $url = Display::url($original_image, $item['url_params']['href'], $item['url_params']);
994
                        $html .= $url;
995
                        $html .= $item['link'];
996
                        $html .= '</li>';
997
998
                        if ($i == count($items) - 1) {
999
                            $html .= '</ul>';
1000
                        }
1001
                        break;
1002
                }
1003
                $i++;
1004
            }
1005
        }
1006
1007
         return array(
1008
            'content' => $html,
1009
            'tool_list' => $items
1010
        );
1011
    }
1012
1013
    /**
1014
     * Shows the general data for a particular meeting
1015
     *
1016
     * @param id	session id
1017
     * @return string	session data
1018
     */
1019
    public static function show_session_data($id_session)
1020
    {
1021
        $session_category_table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
1022
1023
        $sessionInfo = api_get_session_info($id_session);
1024
1025
        if (empty($sessionInfo)) {
1026
            return '';
1027
        }
1028
1029
        $sql = 'SELECT name FROM '.$session_category_table.'
1030
                WHERE id = "'.intval($sessionInfo['session_category_id']).'"';
1031
        $rs_category = Database::query($sql);
1032
        $session_category = '';
1033 View Code Duplication
        if (Database::num_rows($rs_category) > 0) {
1034
            $rows_session_category = Database::store_result($rs_category);
1035
            $rows_session_category = $rows_session_category[0];
1036
            $session_category = $rows_session_category['name'];
1037
        }
1038
1039
        $coachInfo = api_get_user_info($sessionInfo['id_coach']);
1040
1041
        $output = '';
1042
        if (!empty($session_category)) {
1043
            $output .= '<tr><td>'.get_lang('SessionCategory').': '.'<b>'.$session_category.'</b></td></tr>';
1044
        }
1045
        $dateInfo = SessionManager::parseSessionDates($sessionInfo);
1046
1047
        $msgDate = $dateInfo['access'];
1048
        $output .= '<tr>
1049
                    <td style="width:50%">'.get_lang('SessionName').': '.'<b>'.$sessionInfo['name'].'</b></td>
1050
                    <td>'.get_lang('GeneralCoach').': '.'<b>'.$coachInfo['complete_name'].'</b></td></tr>';
1051
        $output .= '<tr>
1052
                        <td>'.get_lang('SessionIdentifier').': '.
1053
                            Display::return_icon('star.png', ' ', array('align' => 'absmiddle')).'
1054
                        </td>
1055
                        <td>'.get_lang('Date').': '.'<b>'.$msgDate.'</b>
1056
                        </td>
1057
                    </tr>';
1058
1059
        return $output;
1060
    }
1061
1062
    /**
1063
     * Retrieves the name-field within a tool-record and translates it on necessity.
1064
     * @param array $tool		The input record.
1065
     * @return string			Returns the name of the corresponding tool.
1066
     */
1067
    public static function translate_tool_name(& $tool)
1068
    {
1069
        static $already_translated_icons = array(
1070
            'file_html.gif',
1071
            'file_html_na.gif',
1072
            'file_html.png',
1073
            'file_html_na.png',
1074
            'scormbuilder.gif',
1075
            'scormbuilder_na.gif',
1076
            'blog.gif',
1077
            'blog_na.gif',
1078
            'external.gif',
1079
            'external_na.gif'
1080
        );
1081
1082
        $toolName = Security::remove_XSS(stripslashes($tool['name']));
1083
1084
        if (in_array($tool['image'], $already_translated_icons)) {
1085
            return $toolName;
1086
        }
1087
1088
        $toolName = api_underscore_to_camel_case($toolName);
1089
1090
        if (isset($GLOBALS['Tool' . $toolName])) {
1091
            return get_lang('Tool' . $toolName);
1092
        }
1093
1094
        return $toolName;
1095
    }
1096
1097
    /**
1098
     * Get published learning path id from link inside course home
1099
     * @param 	string	Link to published lp
1100
     * @return	int		Learning path id
1101
     */
1102
    public static function get_published_lp_id_from_link($published_lp_link)
1103
    {
1104
        $lp_id = 0;
1105
        $param_lp_id = strstr($published_lp_link, 'lp_id=');
1106
        if (!empty($param_lp_id)) {
1107
            $a_param_lp_id = explode('=', $param_lp_id);
1108
            if (isset($a_param_lp_id[1])) {
1109
                $lp_id = intval($a_param_lp_id[1]);
1110
            }
1111
        }
1112
1113
        return $lp_id;
1114
    }
1115
1116
    /**
1117
     * @param bool $include_admin_tools
1118
     * @return array
1119
     */
1120
    public static function get_navigation_items($include_admin_tools = false)
1121
    {
1122
        $navigation_items = array();
1123
        $course_id = api_get_course_int_id();
1124
        $courseInfo = api_get_course_info();
1125
        $sessionId = api_get_session_id();
1126
1127
        if (!empty($course_id)) {
1128
1129
            $course_tools_table = Database :: get_course_table(TABLE_TOOL_LIST);
1130
1131
            /* 	Link to the Course homepage */
1132
            $navigation_items['home']['image'] = 'home.gif';
1133
            $navigation_items['home']['link'] = $courseInfo['course_public_url'];
1134
            $navigation_items['home']['name'] = get_lang('CourseHomepageLink');
1135
1136
            $sql = "SELECT * FROM $course_tools_table
1137
                    WHERE c_id = $course_id AND visibility='1' and admin='0'
1138
                    ORDER BY id ASC";
1139
            $sql_result = Database::query($sql);
1140
            while ($row = Database::fetch_array($sql_result)) {
1141
                $navigation_items[$row['id']] = $row;
1142
                if (stripos($row['link'], 'http://') === false && stripos($row['link'], 'https://') === false) {
1143
                    $navigation_items[$row['id']]['link'] = api_get_path(WEB_CODE_PATH).$row['link'];
1144
                    $navigation_items[$row['id']]['name'] = CourseHome::translate_tool_name($row);
1145
                }
1146
            }
1147
1148
            /* 	Admin (edit rights) only links
1149
              - Course settings (course admin only)
1150
              - Course rights (roles & rights overview) */
1151
1152
            if ($include_admin_tools) {
1153
                $sql = "SELECT name, image FROM $course_tools_table
1154
                        WHERE c_id = $course_id  AND link='course_info/infocours.php'";
1155
                $sql_result = Database::query($sql);
1156
                $course_setting_info = Database::fetch_array($sql_result);
1157
                $course_setting_visual_name = CourseHome::translate_tool_name($course_setting_info);
1158
                if ($sessionId == 0) {
1159
                    // course settings item
1160
                    $navigation_items['course_settings']['image'] = $course_setting_info['image'];
1161
                    $navigation_items['course_settings']['link'] = api_get_path(WEB_CODE_PATH).'course_info/infocours.php';
1162
                    $navigation_items['course_settings']['name'] = $course_setting_visual_name;
1163
                }
1164
            }
1165
        }
1166
1167
        foreach ($navigation_items as $key => $navigation_item) {
1168
            if (strstr($navigation_item['link'], '?')) {
1169
                //link already contains a parameter, add course id parameter with &
1170
                $parameter_separator = '&amp;';
1171
            } else {
1172
                //link doesn't contain a parameter yet, add course id parameter with ?
1173
                $parameter_separator = '?';
1174
            }
1175
            //$navigation_items[$key]['link'] .= $parameter_separator.api_get_cidreq();
1176
            $navigation_items[$key]['link'] .= $parameter_separator.'cidReq='.api_get_course_id().'&gidReq=0&id_session='.$sessionId;
1177
        }
1178
1179
        return $navigation_items;
1180
    }
1181
1182
    /**
1183
     * Show a navigation menu
1184
     */
1185
    public static function show_navigation_menu()
1186
    {
1187
        $navigation_items = self::get_navigation_items(true);
1188
        $course_id = api_get_course_id();
1189
1190
        $class= null;
1191
        $idLearn = null;
1192
        $item = null;
1193
        $marginLeft = 160;
1194
1195
        $html = '<div id="toolnav">';
1196
        $html .= '<ul id="toolnavbox">';
1197
        $count = 0;
1198
        foreach ($navigation_items as $key => $navigation_item) {
1199
            //students can't see the course settings option
1200
            $count++;
1201
            if (!api_is_allowed_to_edit() && $key == 'course_settings') {
1202
                continue;
1203
            }
1204
            $html .= '<li>';
1205
            $url_item = parse_url($navigation_item['link']);
1206
            $url_current = parse_url($_SERVER['REQUEST_URI']);
1207
1208
            if (api_get_setting('show_navigation_menu') == 'text') {
1209
                $class = 'text';
1210
                $marginLeft = 170;
1211
                $item = $navigation_item['name'];
1212
            } else if (api_get_setting('show_navigation_menu') == 'icons') {
1213
                $class = 'icons';
1214
                $marginLeft = 25;
1215
                $item = Display::return_icon(substr($navigation_item['image'],0,-3)."png", $navigation_item['name'], array('class'=>'tool-img'), ICON_SIZE_SMALL);
1216
            } else {
1217
                $class = 'icons-text';
1218
                $item = $navigation_item['name'] . Display::return_icon(substr($navigation_item['image'],0,-3)."png", $navigation_item['name'], array('class'=>'tool-img'), ICON_SIZE_SMALL);
1219
            }
1220
1221
            if (stristr($url_item['path'], $url_current['path'])) {
1222
                if (!isset($_GET['learnpath_id']) || strpos($url_item['query'], 'learnpath_id='.intval($_GET['learnpath_id'])) === 0) {
1223
                    $idLearn = ' id="here"';
1224
                }
1225
            }
1226
1227
            if (strpos($navigation_item['link'], 'chat') !== false &&
1228
                api_get_course_setting('allow_open_chat_window', $course_id)
1229
            ) {
1230
                $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'].'"';
1231
                $html .= ' title="'.$navigation_item['name'].'">';
1232
                $html .=  $item;
1233
                $html .= '</a>';
1234
            } else {
1235
                $html .= '<a ' . $idLearn . ' class="btn btn-default text-left ' . $class . '" href="'.$navigation_item['link'].'" target="_top" title="'.$navigation_item['name'].'">';
1236
                $html .=  $item;
1237
                $html .= '</a>';
1238
            }
1239
1240
            $html .= '</li>';
1241
        }
1242
        $html .= '</ul>';
1243
        $html .= '<script>$(function() {
1244
                $("#toolnavbox a").stop().animate({"margin-left":"-' . $marginLeft . 'px"},1000);
1245
                $("#toolnavbox > li").hover(
1246
                    function () {
1247
                        $("a",$(this)).stop().animate({"margin-left":"-2px"},200);
1248
                        $("span",$(this)).css("display","block");
1249
                    },
1250
                    function () {
1251
                        $("a",$(this)).stop().animate({"margin-left":"-' . $marginLeft . 'px"},200);
1252
                        $("span",$(this)).css("display","initial");
1253
                    }
1254
                );
1255
            });</script>';
1256
        $html .= '</div>';
1257
1258
        return $html;
1259
    }
1260
1261
    /**
1262
     * Show a toolbar with shortcuts to the course tool
1263
     */
1264
    public static function show_navigation_tool_shortcuts($orientation = SHORTCUTS_HORIZONTAL)
1265
    {
1266
        $navigation_items = self::get_navigation_items(false);
1267
        $html = '';
1268
        if (!empty($navigation_items)) {
1269
            if ($orientation == SHORTCUTS_HORIZONTAL) {
1270
                $style_id = "toolshortcuts_horizontal";
1271
            } else {
1272
                $style_id = "toolshortcuts_vertical";
1273
            }
1274
            $html .= '<div id="'.$style_id.'">';
1275
            foreach ($navigation_items as $key => $navigation_item) {
1276
                if (strpos($navigation_item['link'], 'chat') !== false &&
1277
                    api_get_course_setting('allow_open_chat_window')
1278
                ) {
1279
                    $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'].'"';
1280
                } else {
1281
                    $html .= '<a class="items-icon" href="'.$navigation_item['link'].'"';
1282
                }
1283
                if (strpos(api_get_self(), $navigation_item['link']) !== false) {
1284
                    $html .= ' id="here"';
1285
                }
1286
                $html .= ' target="_top" title="'.$navigation_item['name'].'">';
1287
                $html .= Display::return_icon(substr($navigation_item['image'],0,-3)."png", $navigation_item['name'], null, ICON_SIZE_MEDIUM);
1288
                //$html .= '<img src="'.api_get_path(WEB_IMG_PATH).$navigation_item['image'].'" alt="'.$navigation_item['name'].'"/>';
1289
                $html .= '</a> ';
1290
                if ($orientation == SHORTCUTS_VERTICAL) {
1291
                    $html .= '<br />';
1292
                }
1293
            }
1294
            $html .= '</div>';
1295
1296
        }
1297
1298
        return $html;
1299
    }
1300
1301
    /**
1302
     * List course homepage tools from authoring and interaction sections
1303
     * @param   int $courseId The course ID (guessed from context if not provided)
1304
     * @param   int $sessionId The session ID (guessed from context if not provided)
1305
     * @return  array List of all tools data from the c_tools table
1306
     */
1307
    public static function toolsIconsAction($courseId = null, $sessionId = null)
1308
    {
1309
        if (empty($courseId)) {
1310
            $courseId = api_get_course_int_id();
1311
        } else {
1312
            $courseId = intval($courseId);
1313
        }
1314
        if (empty($sessionId)) {
1315
            $sessionId = api_get_session_id();
1316
        } else {
1317
            $sessionId = intval($sessionId);
1318
        }
1319
1320
        if (empty($courseId)) {
1321
            // We shouldn't get here, but for some reason api_get_course_int_id()
1322
            // doesn't seem to get the course from the context, sometimes
1323
            return array();
1324
        }
1325
1326
        $table  = Database::get_course_table(TABLE_TOOL_LIST);
1327
        $sql = "SELECT * FROM $table
1328
                WHERE category in ('authoring','interaction')
1329
                AND c_id = $courseId
1330
                AND session_id = $sessionId
1331
                ORDER BY id";
1332
1333
        $result = Database::query($sql);
1334
        $data = Database::store_result($result, 'ASSOC');
1335
1336
        return $data;
1337
    }
1338
1339
    /**
1340
     * @param int $editIcon
1341
     * @return array
1342
     */
1343 View Code Duplication
    public static function getTool($editIcon)
1344
    {
1345
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
1346
        $editIcon = intval($editIcon);
1347
1348
        $sql = "SELECT * FROM $course_tool_table
1349
                WHERE iid = $editIcon";
1350
        $result = Database::query($sql);
1351
        $tool = Database::fetch_assoc($result, 'ASSOC');
1352
1353
        return $tool;
1354
    }
1355
1356
    /**
1357
     * @return string
1358
     */
1359
    public static function getCustomSysIconPath()
1360
    {
1361
        // Check if directory exists or create it if it doesn't
1362
        $dir = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
1363
        if (!is_dir($dir)) {
1364
            mkdir($dir, api_get_permissions_for_new_directories(), true);
1365
        }
1366
1367
        return $dir;
1368
    }
1369
1370
    /**
1371
     * @return string
1372
     */
1373
    public static function getCustomWebIconPath()
1374
    {
1375
        // Check if directory exists or create it if it doesn't
1376
        $dir = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
1377
1378
        return $dir;
1379
    }
1380
1381
    /**
1382
     * @param string $icon
1383
     * @return string
1384
     */
1385
    public static function getDisableIcon($icon)
1386
    {
1387
        $fileInfo = pathinfo($icon);
1388
1389
        return $fileInfo['filename'].'_na.'.$fileInfo['extension'];
1390
    }
1391
1392
    /**
1393
     * @param int $id
1394
     * @param array $values
1395
     */
1396
    public static function updateTool($id, $values)
1397
    {
1398
        $table = Database::get_course_table(TABLE_TOOL_LIST);
1399
        $params = [
1400
            'name' => $values['name'],
1401
            'link' => $values['link'],
1402
            'target' => $values['target'],
1403
            'visibility' => $values['visibility'],
1404
            'description' => $values['description'],
1405
        ];
1406
1407
        if (isset($_FILES['icon']['size']) && $_FILES['icon']['size'] !== 0) {
1408
            $dir = self::getCustomSysIconPath();
1409
1410
            // Resize image if it is larger than 64px
1411
            $temp = new Image($_FILES['icon']['tmp_name']);
1412
            $picture_infos = $temp->get_image_info();
1413
            if ($picture_infos['width'] > 64) {
1414
                $thumbwidth = 64;
1415
            } else {
1416
                $thumbwidth = $picture_infos['width'];
1417
            }
1418
            if ($picture_infos['height'] > 64) {
1419
                $new_height = 64;
1420
            } else {
1421
                $new_height = $picture_infos['height'];
1422
            }
1423
            $temp->resize($thumbwidth, $new_height, 0);
1424
1425
            //copy the image to the course upload folder
1426
            $path = $dir.$_FILES['icon']['name'];
1427
            $result = $temp->send_image($path);
1428
1429
            $temp = new Image($path);
1430
            $r = $temp->convert2bw();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $r is correct as $temp->convert2bw() (which targets 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...
1431
            $ext = pathinfo($path, PATHINFO_EXTENSION);
1432
            $bwPath = substr($path,0,-(strlen($ext)+1)) . '_na.' . $ext;
1433
1434
            if ($r === false) {
1435
                error_log('Conversion to B&W of '.$path.' failed in '.__FILE__.' at line '.__LINE__);
1436
            } else {
1437
                $temp->send_image($bwPath);
1438
                $iconName = $_FILES['icon']['name'];
1439
                $params['custom_icon'] = $iconName;
1440
            }
1441
        }
1442
1443
        Database::update(
1444
            $table,
1445
            $params,
1446
            [' iid = ?' => [$id]]
1447
        );
1448
    }
1449
1450
    /**
1451
     * @param int $id
1452
     */
1453
    public static function deleteIcon($id)
1454
    {
1455
        $table = Database::get_course_table(TABLE_TOOL_LIST);
1456
        $tool = self::getTool($id);
1457
1458
        if ($tool && !empty($tool['custom_icon'])) {
1459
            $file = self::getCustomSysIconPath().$tool['custom_icon'];
1460
            $fileInfo = pathinfo($file);
1461
            $fileGray = $fileInfo['filename'].'_na.'.$fileInfo['extension'];
1462
            $fileGray = self::getCustomSysIconPath().$fileGray;
1463
1464 View Code Duplication
            if (file_exists($file) && is_file($file)) {
1465
                if (Security::check_abs_path($file, self::getCustomSysIconPath())) {
1466
                    unlink($file);
1467
                }
1468
            }
1469
1470 View Code Duplication
            if (file_exists($fileGray) && is_file($fileGray)) {
1471
                if (Security::check_abs_path($fileGray, self::getCustomSysIconPath())) {
1472
                    unlink($fileGray);
1473
                }
1474
            }
1475
1476
            $params = [
1477
                'custom_icon' => ''
1478
            ];
1479
1480
            Database::update(
1481
                $table,
1482
                $params,
1483
                [' iid = ?' => [$id]]
1484
            );
1485
        }
1486
    }
1487
1488
    /**
1489
     * @param string $text
1490
     * @param array $toolList
1491
     * @return string
1492
     */
1493
    public static function replaceTextWithToolUrls($text, $toolList)
1494
    {
1495
        if (empty($toolList)) {
1496
            return $text;
1497
        }
1498
1499
        foreach ($toolList as $tool) {
1500
            if (!isset($tool['icon'])) {
1501
                continue;
1502
            }
1503
            $toolName = $tool['tool']['name'];
1504
            $search = array("{{ ".$toolName." }}", "{{".$toolName."}}", "((".$toolName."))", "(( ".$toolName." ))");
1505
            $text = str_replace($search, $tool['icon'], $text);
1506
        }
1507
1508
        // Cleaning tags that are not used.
1509
        $tools = self::availableTools();
1510
        foreach ($tools as $toolName) {
1511
            $search = array("{{ ".$toolName." }}", "{{".$toolName."}}", "((".$toolName."))", "(( ".$toolName." ))");
1512
            $text = str_replace($search, null, $text);
1513
        }
1514
1515
        return $text;
1516
    }
1517
1518
    /**
1519
     * Available tools
1520
     * @return array
1521
     */
1522
    public static function availableTools()
1523
    {
1524
        return array(
1525
            'course_description',
1526
            'quiz',
1527
            'announcement',
1528
            'forum',
1529
            'dropbox',
1530
            'user',
1531
            'group',
1532
            'chat',
1533
            'student_publication',
1534
            'survey',
1535
            'wiki',
1536
            'gradebook',
1537
            'glossary',
1538
            'notebook',
1539
            'attendance',
1540
            'course_progress',
1541
            'curriculum',
1542
            'blog_management',
1543
            'tracking',
1544
            'course_setting',
1545
            'course_maintenance'
1546
        );
1547
    }
1548
}
1549