Completed
Push — master ( a34f18...c6c5e0 )
by Julito
15:01
created

CourseHome::getToolIcon()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 24
c 0
b 0
f 0
nc 10
nop 3
dl 0
loc 38
rs 8.6026
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\ToolChain;
5
use Chamilo\CourseBundle\Entity\CLpCategory;
6
use Chamilo\CourseBundle\Entity\CTool;
7
use Doctrine\Common\Collections\Criteria;
8
9
/**
10
 * Class CourseHome.
11
 */
12
class CourseHome
13
{
14
    /**
15
     * Gets the tools of a certain category. Returns an array expected
16
     * by show_tools_category().
17
     *
18
     * @param string $course_tool_category contains the category of tools to
19
     *                                     display: "toolauthoring", "toolinteraction", "tooladmin",
20
     *                                     "tooladminplatform", "toolplugin"
21
     * @param int    $courseId             Optional
22
     * @param int    $sessionId            Optional
23
     *
24
     * @return array
25
     */
26
    public static function get_tools_category(
27
        $course_tool_category,
28
        $courseId = 0,
29
        $sessionId = 0
30
    ) {
31
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
32
        $is_platform_admin = api_is_platform_admin();
33
        $all_tools_list = [];
34
35
        // Condition for the session
36
        $sessionId = $sessionId ?: api_get_session_id();
37
        $course_id = $courseId ?: api_get_course_int_id();
38
        $courseInfo = api_get_course_info_by_id($course_id);
39
        $userId = api_get_user_id();
40
        $user = api_get_user_entity($userId);
41
        $condition_session = api_get_session_condition(
42
            $sessionId,
43
            true,
44
            true,
45
            't.session_id'
46
        );
47
48
        $studentView = api_is_student_view_active();
49
        $orderBy = ' ORDER BY id ';
50
51
        $em = Database::getManager();
52
        $repo = $em->getRepository('ChamiloCourseBundle:CTool');
53
        $qb = $repo->createQueryBuilder('tool');
54
55
        $criteria = \Doctrine\Common\Collections\Criteria::create();
56
57
        switch ($course_tool_category) {
58
            case TOOL_STUDENT_VIEW:
59
                $criteria
60
                    ->where(Criteria::expr()->eq('visibility', 1))
61
                    ->andWhere(Criteria::expr()->in('category', ['authoring', 'interaction']))
62
                ;
63
64
                /*if ((api_is_coach() || api_is_course_tutor() || api_is_platform_admin()) && !$studentView) {
65
                    $conditions = ' WHERE (
66
                        visibility = 1 AND (
67
                            category = "authoring" OR
68
                            category = "interaction" OR
69
                            category = "plugin"
70
                        ) OR (t.name = "'.TOOL_TRACKING.'")
71
                    )';
72
                }*/
73
                break;
74
            case TOOL_AUTHORING:
75
                $criteria
76
                    ->where(Criteria::expr()->in('category', ['authoring']))
77
                ;
78
                break;
79
            case TOOL_INTERACTION:
80
                $criteria
81
                    ->where(Criteria::expr()->in('category', ['interaction']))
82
                ;
83
                break;
84
            case TOOL_ADMIN_VISIBLE:
85
                $criteria
86
                    ->where(Criteria::expr()->eq('visibility', 1))
87
                    ->andWhere(Criteria::expr()->in('category', ['admin']))
88
                ;
89
                break;
90
            case TOOL_ADMIN_PLATFORM:
91
                $criteria
92
                    ->andWhere(Criteria::expr()->in('category', ['admin']))
93
                ;
94
                break;
95
            case TOOL_DRH:
96
                $criteria
97
                    ->andWhere(Criteria::expr()->in('tool.tool.name', ['tracking']))
98
                ;
99
                break;
100
            /*case TOOL_COURSE_PLUGIN:
101
                //Other queries recover id, name, link, image, visibility, admin, address, added_tool, target, category and session_id
102
                // but plugins are not present in the tool table, only globally and inside the course_settings table once configured
103
                $sql = "SELECT * FROM $course_tool_table t
104
                        WHERE category = 'plugin' AND name <> 'courseblock' AND c_id = $course_id $condition_session
105
                        ";*/
106
                break;
107
        }
108
109
        $criteria
110
            ->andWhere(Criteria::expr()->eq('course', api_get_course_entity($courseId)))
111
        ;
112
113
        //$condition_session = $condition_add." ( $session_field = $session_id OR $session_field = 0 OR $session_field IS NULL) ";
114
        /*$criteria
115
            ->andWhere(Criteria::expr()->eq('session', $courseId))
116
        ;*/
117
118
        $qb->addCriteria($criteria);
119
120
        return $qb->getQuery()->getResult();
121
    }
122
123
    /**
124
     * Displays the tools of a certain category.
125
     *
126
     * @param array $all_tools_list List of tools as returned by get_tools_category()
127
     *
128
     * @return array
129
     */
130
    public static function show_tools_category($all_tools_list, ToolChain $toolChain)
131
    {
132
        if (empty($all_tools_list)) {
133
            return [];
134
        }
135
136
        $_user = api_get_user_info();
137
        $session_id = api_get_session_id();
138
        $is_platform_admin = api_is_platform_admin();
139
        $allowEditionInSession = api_get_configuration_value('allow_edit_tool_visibility_in_session');
140
        if ($session_id == 0) {
141
            $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && api_is_course_admin();
142
        } else {
143
            $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && !api_is_coach();
144
            if ($allowEditionInSession) {
145
                $is_allowed_to_edit = api_is_allowed_to_edit(null, true) && api_is_coach($session_id, api_get_course_int_id());
146
            }
147
        }
148
149
150
        $items = [];
151
        /** @var CTool $tool */
152
        foreach ($all_tools_list as $tool) {
153
            $item = [];
154
            $studentview = false;
155
            $toolAdmin = false;
156
            $toolModel = $toolChain->getToolFromName($tool->getTool()->getName());
157
            if ($is_allowed_to_edit) {
158
                if (empty($session_id)) {
159
                    if ($tool->getVisibility() == '1' && $toolAdmin != '1') {
160
                        $link['name'] = Display::return_icon(
161
                            'visible.png',
162
                            get_lang('Deactivate'),
163
                            ['id' => 'linktool_'.$tool->getIid()],
164
                            ICON_SIZE_SMALL,
165
                            false
166
                        );
167
                    }
168
                    if ($tool->getVisibility() == '0' && $toolAdmin != '1') {
169
                        $link['name'] = Display::return_icon(
170
                            'invisible.png',
171
                            get_lang('Activate'),
172
                            ['id' => 'linktool_'.$tool->getIid()],
173
                            ICON_SIZE_SMALL,
174
                            false
175
                        );
176
                    }
177
                } elseif ($allowEditionInSession) {
178
                    $visibility = (int) $tool->getVisibility();
179
                    switch ($visibility) {
180
                        case '0':
181
                            $info = pathinfo($tool['image']);
182
                            $basename = basename($tool['image'], '.'.$info['extension']);
183
                            $tool['image'] = $basename.'_na.'.$info['extension'];
184
                            $link['name'] = Display::return_icon(
185
                                'invisible.png',
186
                                get_lang('Activate'),
187
                                ['id' => 'linktool_'.$tool['iid']],
188
                                ICON_SIZE_SMALL,
189
                                false
190
                            );
191
                            $link['cmd'] = 'restore=yes';
192
                            $lnk[] = $link;
193
                            break;
194
                        case '1':
195
                            $link['name'] = Display::return_icon(
196
                                'visible.png',
197
                                get_lang('Deactivate'),
198
                                ['id' => 'linktool_'.$tool['iid']],
199
                                ICON_SIZE_SMALL,
200
                                false
201
                            );
202
                            $link['cmd'] = 'hide=yes';
203
                            $lnk[] = $link;
204
                            break;
205
                    }
206
                }
207
            }
208
209
            // Both checks are necessary as is_platform_admin doesn't take student view into account
210
            if ($is_platform_admin && $is_allowed_to_edit) {
211
                if ($toolAdmin != '1') {
212
                    $link['cmd'] = 'hide=yes';
213
                }
214
            }
215
216
            $item['visibility'] = '';
217
218
            $class = '';
219
            if ($tool->getVisibility() == '0' && $toolAdmin != '1') {
220
                $class = 'text-muted';
221
                $info = pathinfo($tool['image']);
222
                $basename = basename($tool['image'], '.'.$info['extension']);
223
                $tool['image'] = $basename.'_na.'.$info['extension'];
224
            }
225
226
            $toolIid = $tool->getIid();
227
228
            $tool_link_params = [
229
                'id' => 'tooldesc_'.$toolIid,
230
                'href' => $toolModel->getLink().'?'.api_get_cidreq(),
231
                'class' => $class,
232
            ];
233
234
            $tool_name = $tool->getTool()->getName();
235
236
            $image = 'admin.png';
237
            // Use in the course home
238
            $icon = Display::return_icon(
239
                $image,
240
                $tool_name,
241
                ['class' => 'tool-icon', 'id' => 'toolimage_'.$toolIid],
242
                ICON_SIZE_BIG,
243
                false
244
            );
245
246
            // Validation when belongs to a session
247
            $session_img = '';
248
            if (!empty($tool->getSession())) {
249
                $session_img = api_get_session_image(
250
                    $tool->getSession()->getId(),
251
                    !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

251
                    /** @scrutinizer ignore-type */ !empty($_user['status']) ? $_user['status'] : ''
Loading history...
252
                );
253
            }
254
255
            if ($studentview) {
256
                $tool_link_params['href'] .= '&isStudentView=true';
257
            }
258
            $item['url_params'] = $tool_link_params;
259
            $item['icon'] = Display::url($icon, $tool_link_params['href'], $tool_link_params);
260
            $item['tool'] = $tool;
261
            $item['name'] = $tool_name;
262
263
            $item['href'] = $tool_link_params['href'];
264
            $tool_link_params['id'] = 'is'.$tool_link_params['id'];
265
            $item['link'] = Display::url(
266
                $tool_name.$session_img,
267
                $tool_link_params['href'],
268
                $tool_link_params
269
            );
270
            $items[] = $item;
271
        }
272
273
274
        return $items;
275
    }
276
277
    /**
278
     * Shows the general data for a particular meeting.
279
     *
280
     * @param int $id_session
281
     *
282
     * @return string session data
283
     */
284
    public static function show_session_data($id_session)
285
    {
286
        $sessionInfo = api_get_session_info($id_session);
287
288
        if (empty($sessionInfo)) {
289
            return '';
290
        }
291
292
        $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
293
        $sql = 'SELECT name FROM '.$table.'
294
                WHERE id = "'.intval($sessionInfo['session_category_id']).'"';
295
        $rs_category = Database::query($sql);
296
        $session_category = '';
297
        if (Database::num_rows($rs_category) > 0) {
298
            $rows_session_category = Database::store_result($rs_category);
299
            $rows_session_category = $rows_session_category[0];
300
            $session_category = $rows_session_category['name'];
301
        }
302
303
        $coachInfo = api_get_user_info($sessionInfo['id_coach']);
304
305
        $output = '';
306
        if (!empty($session_category)) {
307
            $output .= '<tr><td>'.get_lang('Sessions categories').': '.'<b>'.$session_category.'</b></td></tr>';
308
        }
309
        $dateInfo = SessionManager::parseSessionDates($sessionInfo);
310
311
        $msgDate = $dateInfo['access'];
312
        $output .= '<tr>
313
                    <td style="width:50%">'.get_lang('Session name').': '.'<b>'.$sessionInfo['name'].'</b></td>
314
                    <td>'.get_lang('General coach').': '.'<b>'.$coachInfo['complete_name'].'</b></td></tr>';
315
        $output .= '<tr>
316
                        <td>'.get_lang('Identifier of session').': '.
317
                            Display::return_icon('star.png', ' ', ['align' => 'absmiddle']).'
318
                        </td>
319
                        <td>'.get_lang('Date').': '.'<b>'.$msgDate.'</b>
320
                        </td>
321
                    </tr>';
322
323
        return $output;
324
    }
325
326
    /**
327
     * Retrieves the name-field within a tool-record and translates it on necessity.
328
     *
329
     * @param array $tool the input record
330
     *
331
     * @return string returns the name of the corresponding tool
332
     */
333
    public static function translate_tool_name(CTool $tool)
334
    {
335
        static $already_translated_icons = [
336
            'file_html.gif',
337
            'file_html_na.gif',
338
            'file_html.png',
339
            'file_html_na.png',
340
            'scormbuilder.gif',
341
            'scormbuilder_na.gif',
342
            'blog.gif',
343
            'blog_na.gif',
344
            'external.gif',
345
            'external_na.gif',
346
        ];
347
348
        $toolName = Security::remove_XSS(stripslashes(strip_tags($tool->getTool()->getName())));
349
350
        return $toolName;
351
352
        if (isset($tool['image']) && in_array($tool['image'], $already_translated_icons)) {
0 ignored issues
show
Unused Code introduced by
IfNode is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
353
            return $toolName;
354
        }
355
356
        $toolName = api_underscore_to_camel_case($toolName);
357
358
        if (isset($tool['category']) && 'plugin' !== $tool['category'] &&
359
            isset($GLOBALS['Tool'.$toolName])
360
        ) {
361
            return get_lang('Tool'.$toolName);
362
        }
363
364
        return $toolName;
365
    }
366
367
    /**
368
     * Get published learning path id from link inside course home.
369
     *
370
     * @param 	string	Link to published lp
371
     *
372
     * @return int Learning path id
373
     */
374
    public static function getPublishedLpIdFromLink($link)
375
    {
376
        $lpId = 0;
377
        $param = strstr($link, 'lp_id=');
378
        if (!empty($param)) {
379
            $paramList = explode('=', $param);
380
            if (isset($paramList[1])) {
381
                $lpId = (int) $paramList[1];
382
            }
383
        }
384
385
        return $lpId;
386
    }
387
388
    /**
389
     * Get published learning path category from link inside course home.
390
     *
391
     * @param string $link
392
     *
393
     * @return CLpCategory
394
     */
395
    public static function getPublishedLpCategoryFromLink($link)
396
    {
397
        $query = parse_url($link, PHP_URL_QUERY);
398
        parse_str($query, $params);
399
        $id = isset($params['id']) ? (int) $params['id'] : 0;
400
        $em = Database::getManager();
401
        /** @var CLpCategory $category */
402
        $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
403
404
        return $category;
405
    }
406
407
    /**
408
     * Show a navigation menu.
409
     */
410
    public static function show_navigation_menu()
411
    {
412
        $blocks = self::getUserBlocks();
0 ignored issues
show
Bug introduced by
The call to CourseHome::getUserBlocks() has too few arguments starting with toolChain. ( Ignorable by Annotation )

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

412
        /** @scrutinizer ignore-call */ 
413
        $blocks = self::getUserBlocks();

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
413
        $class = null;
414
        $idLearn = null;
415
        $item = null;
416
        $marginLeft = 160;
417
418
        $html = '<div id="toolnav">';
419
        $html .= '<ul id="toolnavbox">';
420
421
        $showOnlyText = api_get_setting('show_navigation_menu') === 'text';
422
        $showOnlyIcons = api_get_setting('show_navigation_menu') === 'icons';
423
424
        foreach ($blocks as $block) {
425
            $blockItems = $block['content'];
426
            foreach ($blockItems as $item) {
427
                $html .= '<li>';
428
                if ($showOnlyText) {
429
                    $class = 'text';
430
                    $marginLeft = 170;
431
                    $show = $item['name'];
432
                } elseif ($showOnlyIcons) {
433
                    $class = 'icons';
434
                    $marginLeft = 25;
435
                    $show = $item['tool']['only_icon_small'];
436
                } else {
437
                    $class = 'icons-text';
438
                    $show = $item['name'].$item['tool']['only_icon_small'];
439
                }
440
441
                $item['url_params']['class'] = 'btn btn-default text-left '.$class;
442
                $html .= Display::url(
443
                    $show,
444
                    $item['only_href'],
445
                    $item['url_params']
446
                );
447
                $html .= '</li>';
448
            }
449
        }
450
451
        $html .= '</ul>';
452
        $html .= '<script>$(function() {
453
                $("#toolnavbox a").stop().animate({"margin-left":"-'.$marginLeft.'px"},1000);
454
                $("#toolnavbox > li").hover(
455
                    function () {
456
                        $("a",$(this)).stop().animate({"margin-left":"-2px"},200);
457
                        $("span",$(this)).css("display","block");
458
                    },
459
                    function () {
460
                        $("a",$(this)).stop().animate({"margin-left":"-'.$marginLeft.'px"},200);
461
                        $("span",$(this)).css("display","initial");
462
                    }
463
                );
464
            });</script>';
465
        $html .= '</div>';
466
467
        return $html;
468
    }
469
470
    /**
471
     * Show a toolbar with shortcuts to the course tool.
472
     *
473
     * @param int $orientation
474
     *
475
     * @return string
476
     */
477
    public static function show_navigation_tool_shortcuts($orientation = SHORTCUTS_HORIZONTAL)
478
    {
479
        $origin = api_get_origin();
480
        $courseInfo = api_get_course_info();
481
        if ($origin === 'learnpath') {
482
            return '';
483
        }
484
485
        $blocks = self::getUserBlocks();
0 ignored issues
show
Bug introduced by
The call to CourseHome::getUserBlocks() has too few arguments starting with toolChain. ( Ignorable by Annotation )

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

485
        /** @scrutinizer ignore-call */ 
486
        $blocks = self::getUserBlocks();

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
486
        $html = '';
487
        if (!empty($blocks)) {
488
            $styleId = 'toolshortcuts_vertical';
489
            if ($orientation == SHORTCUTS_HORIZONTAL) {
490
                $styleId = 'toolshortcuts_horizontal';
491
            }
492
            $html .= '<div id="'.$styleId.'">';
493
494
            $html .= Display::url(
495
                Display::return_icon('home.png', get_lang('Course home'), '', ICON_SIZE_MEDIUM),
496
                $courseInfo['course_public_url'],
497
                ['class' => 'items-icon']
498
            );
499
500
            foreach ($blocks as $block) {
501
                $blockItems = $block['content'];
502
                foreach ($blockItems as $item) {
503
                    $item['url_params']['id'] = '';
504
                    $item['url_params']['class'] = 'items-icon';
505
                    $html .= Display::url(
506
                        $item['tool']['only_icon_medium'],
507
                        $item['only_href'],
508
                        $item['url_params']
509
                    );
510
                    if ($orientation == SHORTCUTS_VERTICAL) {
511
                        $html .= '<br />';
512
                    }
513
                }
514
            }
515
            $html .= '</div>';
516
        }
517
518
        return $html;
519
    }
520
521
    /**
522
     * List course homepage tools from authoring and interaction sections.
523
     *
524
     * @param int $courseId  The course ID (guessed from context if not provided)
525
     * @param int $sessionId The session ID (guessed from context if not provided)
526
     *
527
     * @return array List of all tools data from the c_tools table
528
     */
529
    public static function toolsIconsAction($courseId = null, $sessionId = null)
530
    {
531
        if (empty($courseId)) {
532
            $courseId = api_get_course_int_id();
533
        } else {
534
            $courseId = intval($courseId);
535
        }
536
        if (empty($sessionId)) {
537
            $sessionId = api_get_session_id();
538
        } else {
539
            $sessionId = intval($sessionId);
540
        }
541
542
        if (empty($courseId)) {
543
            // We shouldn't get here, but for some reason api_get_course_int_id()
544
            // doesn't seem to get the course from the context, sometimes
545
            return [];
546
        }
547
548
        $table = Database::get_course_table(TABLE_TOOL_LIST);
549
        $sql = "SELECT * FROM $table
550
                WHERE category in ('authoring','interaction')
551
                AND c_id = $courseId
552
                AND session_id = $sessionId
553
                ORDER BY id";
554
555
        $result = Database::query($sql);
556
        $data = Database::store_result($result, 'ASSOC');
557
558
        return $data;
559
    }
560
561
    /**
562
     * @param int $editIcon
563
     *
564
     * @return array
565
     */
566
    public static function getTool($editIcon)
567
    {
568
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
569
        $editIcon = intval($editIcon);
570
571
        $sql = "SELECT * FROM $course_tool_table
572
                WHERE iid = $editIcon";
573
        $result = Database::query($sql);
574
        $tool = Database::fetch_assoc($result, 'ASSOC');
575
576
        return $tool;
577
    }
578
579
    /**
580
     * @return string
581
     */
582
    public static function getCustomSysIconPath()
583
    {
584
        // Check if directory exists or create it if it doesn't
585
        $dir = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
0 ignored issues
show
Bug introduced by
The constant SYS_COURSE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
586
        if (!is_dir($dir)) {
587
            mkdir($dir, api_get_permissions_for_new_directories(), true);
588
        }
589
590
        return $dir;
591
    }
592
593
    /**
594
     * @return string
595
     */
596
    public static function getCustomWebIconPath()
597
    {
598
        // Check if directory exists or create it if it doesn't
599
        $dir = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
600
601
        return $dir;
602
    }
603
604
    /**
605
     * @param string $icon
606
     *
607
     * @return string
608
     */
609
    public static function getDisableIcon($icon)
610
    {
611
        $fileInfo = pathinfo($icon);
612
613
        return $fileInfo['filename'].'_na.'.$fileInfo['extension'];
614
    }
615
616
    /**
617
     * @param int   $id
618
     * @param array $values
619
     */
620
    public static function updateTool($id, $values)
621
    {
622
        $table = Database::get_course_table(TABLE_TOOL_LIST);
623
        $params = [
624
            'name' => $values['name'],
625
            'link' => $values['link'],
626
            'target' => $values['target'],
627
            'visibility' => $values['visibility'],
628
            'description' => $values['description'],
629
        ];
630
631
        if (isset($_FILES['icon']['size']) && $_FILES['icon']['size'] !== 0) {
632
            $dir = self::getCustomSysIconPath();
633
634
            // Resize image if it is larger than 64px
635
            $temp = new Image($_FILES['icon']['tmp_name']);
636
            $picture_infos = $temp->get_image_info();
637
            if ($picture_infos['width'] > 64) {
638
                $thumbwidth = 64;
639
            } else {
640
                $thumbwidth = $picture_infos['width'];
641
            }
642
            if ($picture_infos['height'] > 64) {
643
                $new_height = 64;
644
            } else {
645
                $new_height = $picture_infos['height'];
646
            }
647
            $temp->resize($thumbwidth, $new_height, 0);
648
649
            //copy the image to the course upload folder
650
            $path = $dir.$_FILES['icon']['name'];
651
            $result = $temp->send_image($path);
652
653
            $temp = new Image($path);
654
            $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...
655
            $ext = pathinfo($path, PATHINFO_EXTENSION);
656
            $bwPath = substr($path, 0, -(strlen($ext) + 1)).'_na.'.$ext;
657
658
            if ($r === false) {
659
                error_log('Conversion to B&W of '.$path.' failed in '.__FILE__.' at line '.__LINE__);
660
            } else {
661
                $temp->send_image($bwPath);
662
                $iconName = $_FILES['icon']['name'];
663
                $params['custom_icon'] = $iconName;
664
            }
665
        }
666
667
        Database::update(
668
            $table,
669
            $params,
670
            [' iid = ?' => [$id]]
671
        );
672
    }
673
674
    /**
675
     * @param int $id
676
     */
677
    public static function deleteIcon($id)
678
    {
679
        $table = Database::get_course_table(TABLE_TOOL_LIST);
680
        $tool = self::getTool($id);
681
682
        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...
683
            $file = self::getCustomSysIconPath().$tool['custom_icon'];
684
            $fileInfo = pathinfo($file);
685
            $fileGray = $fileInfo['filename'].'_na.'.$fileInfo['extension'];
686
            $fileGray = self::getCustomSysIconPath().$fileGray;
687
688
            if (file_exists($file) && is_file($file)) {
689
                if (Security::check_abs_path($file, self::getCustomSysIconPath())) {
690
                    unlink($file);
691
                }
692
            }
693
694
            if (file_exists($fileGray) && is_file($fileGray)) {
695
                if (Security::check_abs_path($fileGray, self::getCustomSysIconPath())) {
696
                    unlink($fileGray);
697
                }
698
            }
699
700
            $params = [
701
                'custom_icon' => '',
702
            ];
703
704
            Database::update(
705
                $table,
706
                $params,
707
                [' iid = ?' => [$id]]
708
            );
709
        }
710
    }
711
712
    /**
713
     * @return array
714
     */
715
    public static function getCourseAdminBlocks($toolChain)
716
    {
717
        $blocks = [];
718
        $blocks[] = [
719
            'title' => get_lang('Authoring'),
720
            'class' => 'course-tools-author',
721
            'content' => self::show_tools_category(self::get_tools_category(TOOL_AUTHORING), $toolChain),
722
        ];
723
724
        $blocks[] = [
725
            'title' => get_lang('Interaction'),
726
            'class' => 'course-tools-interaction',
727
            'content' => self::show_tools_category(self::get_tools_category(TOOL_INTERACTION), $toolChain),
728
        ];
729
730
        $blocks[] = [
731
            'title' => get_lang('Administration'),
732
            'class' => 'course-tools-administration',
733
            'content' => self::show_tools_category(self::get_tools_category(TOOL_ADMIN_PLATFORM), $toolChain),
734
        ];
735
736
        return $blocks;
737
    }
738
739
    /**
740
     * @return array
741
     */
742
    public static function getCoachBlocks(ToolChain $toolChain)
743
    {
744
        $blocks = [];
745
        $my_list = self::get_tools_category(TOOL_STUDENT_VIEW);
746
747
        $blocks[] = [
748
            'content' => self::show_tools_category($my_list, $toolChain),
749
        ];
750
751
        $sessionsCopy = api_get_setting('allow_session_course_copy_for_teachers');
752
        if ($sessionsCopy === 'true') {
753
            // Adding only maintenance for coaches.
754
            $myList = self::get_tools_category(TOOL_ADMIN_PLATFORM);
755
            $onlyMaintenanceList = [];
756
757
            foreach ($myList as $item) {
758
                if ($item['name'] === 'course_maintenance') {
759
                    $item['link'] = 'course_info/maintenance_coach.php';
760
761
                    $onlyMaintenanceList[] = $item;
762
                }
763
            }
764
765
            $blocks[] = [
766
                'title' => get_lang('Administration'),
767
                'content' => self::show_tools_category($onlyMaintenanceList, $toolChain),
768
            ];
769
        }
770
771
        return $blocks;
772
    }
773
774
    /**
775
     * @return array
776
     */
777
    public static function getStudentBlocks(ToolChain $toolChain)
778
    {
779
        $blocks = [];
780
        $tools = self::get_tools_category(TOOL_STUDENT_VIEW);
781
        $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
782
            api_get_user_id(),
783
            api_get_course_info()
784
        );
785
786
        // Force user icon for DRH
787
        if ($isDrhOfCourse) {
788
            $addUserTool = true;
789
            foreach ($tools as $tool) {
790
                if ($tool['name'] === 'user') {
791
                    $addUserTool = false;
792
                    break;
793
                }
794
            }
795
796
            if ($addUserTool) {
797
                $tools[] = [
798
                    'c_id' => api_get_course_int_id(),
799
                    'name' => 'user',
800
                    'link' => 'user/user.php',
801
                    'image' => 'members.gif',
802
                    'visibility' => '1',
803
                    'admin' => '0',
804
                    'address' => 'squaregrey.gif',
805
                    'added_tool' => '0',
806
                    'target' => '_self',
807
                    'category' => 'interaction',
808
                    'session_id' => api_get_session_id(),
809
                ];
810
            }
811
        }
812
813
        if (count($tools) > 0) {
814
            $blocks[] = ['content' => self::show_tools_category($tools, $toolChain)];
815
        }
816
817
        if ($isDrhOfCourse) {
818
            $drhTool = self::get_tools_category(TOOL_DRH);
819
            $blocks[] = ['content' => self::show_tools_category($drhTool, $toolChain)];
820
        }
821
822
        return $blocks;
823
    }
824
825
    /**
826
     * @return array
827
     */
828
    public static function getUserBlocks($toolChain)
829
    {
830
        $sessionId = api_get_session_id();
831
        // Start of tools for CourseAdmins (teachers/tutors)
832
        if ($sessionId === 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
833
            $blocks = self::getCourseAdminBlocks($toolChain);
834
        } elseif (api_is_coach()) {
835
            $blocks = self::getCoachBlocks($toolChain);
836
        } else {
837
            $blocks = self::getStudentBlocks($toolChain);
838
        }
839
840
        return $blocks;
841
    }
842
843
    /**
844
     * Filter tool icons. Only show if $patronKey is = :teacher
845
     * Example dataIcons[i]['name']: parameter titleIcons1:teacher || titleIcons2 || titleIcons3:teacher.
846
     *
847
     * @param array  $dataIcons          array Reference to icons
848
     * @param string $courseToolCategory Current tools category
849
     *
850
     * @return array
851
     */
852
    private static function filterPluginTools($dataIcons, $courseToolCategory)
0 ignored issues
show
Unused Code introduced by
The method filterPluginTools() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
853
    {
854
        $patronKey = ':teacher';
855
856
        if ($courseToolCategory == TOOL_STUDENT_VIEW) {
857
            //Fix only coach can see external pages - see #8236 - icpna
858
            if (api_is_coach()) {
859
                foreach ($dataIcons as $index => $array) {
860
                    if (isset($array['name'])) {
861
                        $dataIcons[$index]['name'] = str_replace($patronKey, '', $array['name']);
862
                    }
863
                }
864
865
                return $dataIcons;
866
            }
867
868
            $flagOrder = false;
869
870
            foreach ($dataIcons as $index => $array) {
871
                if (!isset($array['name'])) {
872
                    continue;
873
                }
874
875
                $pos = strpos($array['name'], $patronKey);
876
877
                if ($pos !== false) {
878
                    unset($dataIcons[$index]);
879
                    $flagOrder = true;
880
                }
881
            }
882
883
            if ($flagOrder) {
884
                return array_values($dataIcons);
885
            }
886
887
            return $dataIcons;
888
        }
889
890
        // clean patronKey of name icons
891
        foreach ($dataIcons as $index => $array) {
892
            if (isset($array['name'])) {
893
                $dataIcons[$index]['name'] = str_replace($patronKey, '', $array['name']);
894
            }
895
        }
896
897
        return $dataIcons;
898
    }
899
}
900