Passed
Push — master ( 59256e...15bb7c )
by Julito
10:12
created

CourseHome::deleteIcon()   B

Complexity

Conditions 9
Paths 10

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 19
nc 10
nop 1
dl 0
loc 31
rs 8.0555
c 0
b 0
f 0
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 (0 == $session_id) {
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
        $items = [];
150
        /** @var CTool $tool */
151
        foreach ($all_tools_list as $tool) {
152
            $item = [];
153
            $studentview = false;
154
            $toolAdmin = false;
155
            $toolModel = $toolChain->getToolFromName($tool->getTool()->getName());
156
            if ($is_allowed_to_edit) {
157
                if (empty($session_id)) {
158
                    if ('1' == $tool->getVisibility() && '1' != $toolAdmin) {
159
                        $link['name'] = Display::return_icon(
160
                            'visible.png',
161
                            get_lang('Deactivate'),
162
                            ['id' => 'linktool_'.$tool->getIid()],
163
                            ICON_SIZE_SMALL,
164
                            false
165
                        );
166
                    }
167
                    if ('0' == $tool->getVisibility() && '1' != $toolAdmin) {
168
                        $link['name'] = Display::return_icon(
169
                            'invisible.png',
170
                            get_lang('Activate'),
171
                            ['id' => 'linktool_'.$tool->getIid()],
172
                            ICON_SIZE_SMALL,
173
                            false
174
                        );
175
                    }
176
                } elseif ($allowEditionInSession) {
177
                    $visibility = (int) $tool->getVisibility();
178
                    switch ($visibility) {
179
                        case '0':
180
                            $info = pathinfo($tool['image']);
181
                            $basename = basename($tool['image'], '.'.$info['extension']);
182
                            $tool['image'] = $basename.'_na.'.$info['extension'];
183
                            $link['name'] = Display::return_icon(
184
                                'invisible.png',
185
                                get_lang('Activate'),
186
                                ['id' => 'linktool_'.$tool['iid']],
187
                                ICON_SIZE_SMALL,
188
                                false
189
                            );
190
                            $link['cmd'] = 'restore=yes';
191
                            $lnk[] = $link;
192
                            break;
193
                        case '1':
194
                            $link['name'] = Display::return_icon(
195
                                'visible.png',
196
                                get_lang('Deactivate'),
197
                                ['id' => 'linktool_'.$tool['iid']],
198
                                ICON_SIZE_SMALL,
199
                                false
200
                            );
201
                            $link['cmd'] = 'hide=yes';
202
                            $lnk[] = $link;
203
                            break;
204
                    }
205
                }
206
            }
207
208
            // Both checks are necessary as is_platform_admin doesn't take student view into account
209
            if ($is_platform_admin && $is_allowed_to_edit) {
210
                if ('1' != $toolAdmin) {
211
                    $link['cmd'] = 'hide=yes';
212
                }
213
            }
214
215
            $item['visibility'] = '';
216
217
            $class = '';
218
            if ('0' == $tool->getVisibility() && '1' != $toolAdmin) {
219
                $class = 'text-muted';
220
                $info = pathinfo($tool['image']);
221
                $basename = basename($tool['image'], '.'.$info['extension']);
222
                $tool['image'] = $basename.'_na.'.$info['extension'];
223
            }
224
225
            $toolIid = $tool->getIid();
226
227
            $tool_link_params = [
228
                'id' => 'tooldesc_'.$toolIid,
229
                'href' => $toolModel->getLink().'?'.api_get_cidreq(),
230
                'class' => $class,
231
            ];
232
233
            $tool_name = $tool->getTool()->getName();
234
235
            $image = 'admin.png';
236
            // Use in the course home
237
            $icon = Display::return_icon(
238
                $image,
239
                $tool_name,
240
                ['class' => 'tool-icon', 'id' => 'toolimage_'.$toolIid],
241
                ICON_SIZE_BIG,
242
                false
243
            );
244
245
            // Validation when belongs to a session
246
            $session_img = '';
247
            if (!empty($tool->getSession())) {
248
                $session_img = api_get_session_image(
249
                    $tool->getSession()->getId(),
250
                    !empty($_user['status']) ? $_user['status'] : ''
251
                );
252
            }
253
254
            if ($studentview) {
255
                $tool_link_params['href'] .= '&isStudentView=true';
256
            }
257
            $item['url_params'] = $tool_link_params;
258
            $item['icon'] = Display::url($icon, $tool_link_params['href'], $tool_link_params);
259
            $item['tool'] = $tool;
260
            $item['name'] = $tool_name;
261
262
            $item['href'] = $tool_link_params['href'];
263
            $tool_link_params['id'] = 'is'.$tool_link_params['id'];
264
            $item['link'] = Display::url(
265
                $tool_name.$session_img,
266
                $tool_link_params['href'],
267
                $tool_link_params
268
            );
269
            $items[] = $item;
270
        }
271
272
        return $items;
273
    }
274
275
    /**
276
     * Shows the general data for a particular meeting.
277
     *
278
     * @param int $id_session
279
     *
280
     * @return string session data
281
     */
282
    public static function show_session_data($id_session)
283
    {
284
        $sessionInfo = api_get_session_info($id_session);
285
286
        if (empty($sessionInfo)) {
287
            return '';
288
        }
289
290
        $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
291
        $sql = 'SELECT name FROM '.$table.'
292
                WHERE id = "'.intval($sessionInfo['session_category_id']).'"';
293
        $rs_category = Database::query($sql);
294
        $session_category = '';
295
        if (Database::num_rows($rs_category) > 0) {
296
            $rows_session_category = Database::store_result($rs_category);
297
            $rows_session_category = $rows_session_category[0];
298
            $session_category = $rows_session_category['name'];
299
        }
300
301
        $coachInfo = api_get_user_info($sessionInfo['id_coach']);
302
303
        $output = '';
304
        if (!empty($session_category)) {
305
            $output .= '<tr><td>'.get_lang('Sessions categories').': '.'<b>'.$session_category.'</b></td></tr>';
306
        }
307
        $dateInfo = SessionManager::parseSessionDates($sessionInfo);
308
309
        $msgDate = $dateInfo['access'];
310
        $output .= '<tr>
311
                    <td style="width:50%">'.get_lang('Session name').': '.'<b>'.$sessionInfo['name'].'</b></td>
312
                    <td>'.get_lang('General coach').': '.'<b>'.$coachInfo['complete_name'].'</b></td></tr>';
313
        $output .= '<tr>
314
                        <td>'.get_lang('Identifier of session').': '.
315
                            Display::return_icon('star.png', ' ', ['align' => 'absmiddle']).'
316
                        </td>
317
                        <td>'.get_lang('Date').': '.'<b>'.$msgDate.'</b>
318
                        </td>
319
                    </tr>';
320
321
        return $output;
322
    }
323
324
    /**
325
     * Retrieves the name-field within a tool-record and translates it on necessity.
326
     *
327
     * @param array $tool the input record
328
     *
329
     * @return string returns the name of the corresponding tool
330
     */
331
    public static function translate_tool_name(CTool $tool)
332
    {
333
        static $already_translated_icons = [
334
            'file_html.gif',
335
            'file_html_na.gif',
336
            'file_html.png',
337
            'file_html_na.png',
338
            'scormbuilder.gif',
339
            'scormbuilder_na.gif',
340
            'blog.gif',
341
            'blog_na.gif',
342
            'external.gif',
343
            'external_na.gif',
344
        ];
345
346
        $toolName = Security::remove_XSS(stripslashes(strip_tags($tool->getTool()->getName())));
347
348
        return $toolName;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $toolName also could return the type array which is incompatible with the documented return type string.
Loading history...
349
350
        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...
351
            return $toolName;
352
        }
353
354
        $toolName = api_underscore_to_camel_case($toolName);
355
356
        if (isset($tool['category']) && 'plugin' !== $tool['category'] &&
357
            isset($GLOBALS['Tool'.$toolName])
358
        ) {
359
            return get_lang('Tool'.$toolName);
360
        }
361
362
        return $toolName;
363
    }
364
365
    /**
366
     * Get published learning path id from link inside course home.
367
     *
368
     * @param 	string	Link to published lp
369
     *
370
     * @return int Learning path id
371
     */
372
    public static function getPublishedLpIdFromLink($link)
373
    {
374
        $lpId = 0;
375
        $param = strstr($link, 'lp_id=');
376
        if (!empty($param)) {
377
            $paramList = explode('=', $param);
378
            if (isset($paramList[1])) {
379
                $lpId = (int) $paramList[1];
380
            }
381
        }
382
383
        return $lpId;
384
    }
385
386
    /**
387
     * Get published learning path category from link inside course home.
388
     *
389
     * @param string $link
390
     *
391
     * @return CLpCategory
392
     */
393
    public static function getPublishedLpCategoryFromLink($link)
394
    {
395
        $query = parse_url($link, PHP_URL_QUERY);
396
        parse_str($query, $params);
397
        $id = isset($params['id']) ? (int) $params['id'] : 0;
398
        $em = Database::getManager();
399
        /** @var CLpCategory $category */
400
        $category = $em->find('ChamiloCourseBundle:CLpCategory', $id);
401
402
        return $category;
403
    }
404
405
    /**
406
     * Show a navigation menu.
407
     */
408
    public static function show_navigation_menu()
409
    {
410
        $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

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

483
        /** @scrutinizer ignore-call */ 
484
        $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...
484
        $html = '';
485
        if (!empty($blocks)) {
486
            $styleId = 'toolshortcuts_vertical';
487
            if (SHORTCUTS_HORIZONTAL == $orientation) {
488
                $styleId = 'toolshortcuts_horizontal';
489
            }
490
            $html .= '<div id="'.$styleId.'">';
491
492
            $html .= Display::url(
493
                Display::return_icon('home.png', get_lang('Course home'), '', ICON_SIZE_MEDIUM),
494
                $courseInfo['course_public_url'],
495
                ['class' => 'items-icon']
496
            );
497
498
            foreach ($blocks as $block) {
499
                $blockItems = $block['content'];
500
                foreach ($blockItems as $item) {
501
                    $item['url_params']['id'] = '';
502
                    $item['url_params']['class'] = 'items-icon';
503
                    $html .= Display::url(
504
                        $item['tool']['only_icon_medium'],
505
                        $item['only_href'],
506
                        $item['url_params']
507
                    );
508
                    if (SHORTCUTS_VERTICAL == $orientation) {
509
                        $html .= '<br />';
510
                    }
511
                }
512
            }
513
            $html .= '</div>';
514
        }
515
516
        return $html;
517
    }
518
519
    /**
520
     * List course homepage tools from authoring and interaction sections.
521
     *
522
     * @param int $courseId  The course ID (guessed from context if not provided)
523
     * @param int $sessionId The session ID (guessed from context if not provided)
524
     *
525
     * @return array List of all tools data from the c_tools table
526
     */
527
    public static function toolsIconsAction($courseId = null, $sessionId = null)
528
    {
529
        if (empty($courseId)) {
530
            $courseId = api_get_course_int_id();
531
        } else {
532
            $courseId = intval($courseId);
533
        }
534
        if (empty($sessionId)) {
535
            $sessionId = api_get_session_id();
536
        } else {
537
            $sessionId = intval($sessionId);
538
        }
539
540
        if (empty($courseId)) {
541
            // We shouldn't get here, but for some reason api_get_course_int_id()
542
            // doesn't seem to get the course from the context, sometimes
543
            return [];
544
        }
545
546
        $table = Database::get_course_table(TABLE_TOOL_LIST);
547
        $sql = "SELECT * FROM $table
548
                WHERE category in ('authoring','interaction')
549
                AND c_id = $courseId
550
                AND session_id = $sessionId
551
                ORDER BY id";
552
553
        $result = Database::query($sql);
554
        $data = Database::store_result($result, 'ASSOC');
555
556
        return $data;
557
    }
558
559
    /**
560
     * @param int $editIcon
561
     *
562
     * @return array
563
     */
564
    public static function getTool($editIcon)
565
    {
566
        $course_tool_table = Database::get_course_table(TABLE_TOOL_LIST);
567
        $editIcon = intval($editIcon);
568
569
        $sql = "SELECT * FROM $course_tool_table
570
                WHERE iid = $editIcon";
571
        $result = Database::query($sql);
572
        $tool = Database::fetch_assoc($result, 'ASSOC');
573
574
        return $tool;
575
    }
576
577
    /**
578
     * @return string
579
     */
580
    public static function getCustomSysIconPath()
581
    {
582
        // Check if directory exists or create it if it doesn't
583
        $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...
Bug introduced by
The function api_get_course_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

583
        $dir = api_get_path(SYS_COURSE_PATH)./** @scrutinizer ignore-call */ api_get_course_path().'/upload/course_home_icons/';
Loading history...
584
        if (!is_dir($dir)) {
585
            mkdir($dir, api_get_permissions_for_new_directories(), true);
586
        }
587
588
        return $dir;
589
    }
590
591
    /**
592
     * @return string
593
     */
594
    public static function getCustomWebIconPath()
595
    {
596
        // Check if directory exists or create it if it doesn't
597
        $dir = api_get_path(WEB_COURSE_PATH).api_get_course_path().'/upload/course_home_icons/';
0 ignored issues
show
Bug introduced by
The function api_get_course_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

597
        $dir = api_get_path(WEB_COURSE_PATH)./** @scrutinizer ignore-call */ api_get_course_path().'/upload/course_home_icons/';
Loading history...
598
599
        return $dir;
600
    }
601
602
    /**
603
     * @param string $icon
604
     *
605
     * @return string
606
     */
607
    public static function getDisableIcon($icon)
608
    {
609
        $fileInfo = pathinfo($icon);
610
611
        return $fileInfo['filename'].'_na.'.$fileInfo['extension'];
612
    }
613
614
    /**
615
     * @param int   $id
616
     * @param array $values
617
     */
618
    public static function updateTool($id, $values)
619
    {
620
        $table = Database::get_course_table(TABLE_TOOL_LIST);
621
        $params = [
622
            'name' => $values['name'],
623
            'link' => $values['link'],
624
            'target' => $values['target'],
625
            'visibility' => $values['visibility'],
626
            'description' => $values['description'],
627
        ];
628
629
        if (isset($_FILES['icon']['size']) && 0 !== $_FILES['icon']['size']) {
630
            /*$dir = self::getCustomSysIconPath();
631
632
            // Resize image if it is larger than 64px
633
            $temp = new Image($_FILES['icon']['tmp_name']);
634
            $picture_infos = $temp->get_image_info();
635
            if ($picture_infos['width'] > 64) {
636
                $thumbwidth = 64;
637
            } else {
638
                $thumbwidth = $picture_infos['width'];
639
            }
640
            if ($picture_infos['height'] > 64) {
641
                $new_height = 64;
642
            } else {
643
                $new_height = $picture_infos['height'];
644
            }
645
            $temp->resize($thumbwidth, $new_height, 0);
646
647
            //copy the image to the course upload folder
648
            $path = $dir.$_FILES['icon']['name'];
649
            $result = $temp->send_image($path);
650
651
            $temp = new Image($path);
652
            $r = $temp->convert2bw();
653
            $ext = pathinfo($path, PATHINFO_EXTENSION);
654
            $bwPath = substr($path, 0, -(strlen($ext) + 1)).'_na.'.$ext;
655
656
            if (false === $r) {
657
                error_log('Conversion to B&W of '.$path.' failed in '.__FILE__.' at line '.__LINE__);
658
            } else {
659
                $temp->send_image($bwPath);
660
                $iconName = $_FILES['icon']['name'];
661
                $params['custom_icon'] = $iconName;
662
            }*/
663
        }
664
665
        Database::update(
666
            $table,
667
            $params,
668
            [' iid = ?' => [$id]]
669
        );
670
    }
671
672
    /**
673
     * @param int $id
674
     */
675
    public static function deleteIcon($id)
676
    {
677
        $table = Database::get_course_table(TABLE_TOOL_LIST);
678
        $tool = self::getTool($id);
679
680
        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...
681
            $file = self::getCustomSysIconPath().$tool['custom_icon'];
682
            $fileInfo = pathinfo($file);
683
            $fileGray = $fileInfo['filename'].'_na.'.$fileInfo['extension'];
684
            $fileGray = self::getCustomSysIconPath().$fileGray;
685
686
            if (file_exists($file) && is_file($file)) {
687
                if (Security::check_abs_path($file, self::getCustomSysIconPath())) {
688
                    unlink($file);
689
                }
690
            }
691
692
            if (file_exists($fileGray) && is_file($fileGray)) {
693
                if (Security::check_abs_path($fileGray, self::getCustomSysIconPath())) {
694
                    unlink($fileGray);
695
                }
696
            }
697
698
            $params = [
699
                'custom_icon' => '',
700
            ];
701
702
            Database::update(
703
                $table,
704
                $params,
705
                [' iid = ?' => [$id]]
706
            );
707
        }
708
    }
709
710
    /**
711
     * @return array
712
     */
713
    public static function getCourseAdminBlocks($toolChain)
714
    {
715
        $blocks = [];
716
        $blocks[] = [
717
            'title' => get_lang('Authoring'),
718
            'class' => 'course-tools-author',
719
            'content' => self::show_tools_category(self::get_tools_category(TOOL_AUTHORING), $toolChain),
720
        ];
721
722
        $blocks[] = [
723
            'title' => get_lang('Interaction'),
724
            'class' => 'course-tools-interaction',
725
            'content' => self::show_tools_category(self::get_tools_category(TOOL_INTERACTION), $toolChain),
726
        ];
727
728
        $blocks[] = [
729
            'title' => get_lang('Administration'),
730
            'class' => 'course-tools-administration',
731
            'content' => self::show_tools_category(self::get_tools_category(TOOL_ADMIN_PLATFORM), $toolChain),
732
        ];
733
734
        return $blocks;
735
    }
736
737
    /**
738
     * @return array
739
     */
740
    public static function getCoachBlocks(ToolChain $toolChain)
741
    {
742
        $blocks = [];
743
        $blocks[] = [
744
            'content' => self::show_tools_category(self::get_tools_category(TOOL_STUDENT_VIEW), $toolChain),
745
        ];
746
747
        $sessionsCopy = api_get_setting('allow_session_course_copy_for_teachers');
748
        if ('true' === $sessionsCopy) {
749
            // Adding only maintenance for coaches.
750
            $myList = self::get_tools_category(TOOL_ADMIN_PLATFORM);
751
            $onlyMaintenanceList = [];
752
753
            foreach ($myList as $item) {
754
                if ('course_maintenance' === $item['name']) {
755
                    $item['link'] = 'course_info/maintenance_coach.php';
756
757
                    $onlyMaintenanceList[] = $item;
758
                }
759
            }
760
761
            $blocks[] = [
762
                'title' => get_lang('Administration'),
763
                'content' => self::show_tools_category($onlyMaintenanceList, $toolChain),
764
            ];
765
        }
766
767
        return $blocks;
768
    }
769
770
    /**
771
     * @return array
772
     */
773
    public static function getStudentBlocks(ToolChain $toolChain)
774
    {
775
        $blocks = [];
776
        $tools = self::get_tools_category(TOOL_STUDENT_VIEW);
777
        $isDrhOfCourse = CourseManager::isUserSubscribedInCourseAsDrh(
778
            api_get_user_id(),
779
            api_get_course_info()
780
        );
781
782
        // Force user icon for DRH
783
        if ($isDrhOfCourse) {
784
            $addUserTool = true;
785
            foreach ($tools as $tool) {
786
                if ('user' === $tool['name']) {
787
                    $addUserTool = false;
788
                    break;
789
                }
790
            }
791
792
            if ($addUserTool) {
793
                $tools[] = [
794
                    'c_id' => api_get_course_int_id(),
795
                    'name' => 'user',
796
                    'link' => 'user/user.php',
797
                    'image' => 'members.gif',
798
                    'visibility' => '1',
799
                    'admin' => '0',
800
                    'address' => 'squaregrey.gif',
801
                    'added_tool' => '0',
802
                    'target' => '_self',
803
                    'category' => 'interaction',
804
                    'session_id' => api_get_session_id(),
805
                ];
806
            }
807
        }
808
809
        if (count($tools) > 0) {
810
            $blocks[] = ['content' => self::show_tools_category($tools, $toolChain)];
811
        }
812
813
        if ($isDrhOfCourse) {
814
            $drhTool = self::get_tools_category(TOOL_DRH);
815
            $blocks[] = ['content' => self::show_tools_category($drhTool, $toolChain)];
816
        }
817
818
        return $blocks;
819
    }
820
821
    /**
822
     * @return array
823
     */
824
    public static function getUserBlocks($toolChain)
825
    {
826
        $sessionId = api_get_session_id();
827
        // Start of tools for CourseAdmins (teachers/tutors)
828
        if (0 === $sessionId && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
829
            $blocks = self::getCourseAdminBlocks($toolChain);
830
        } elseif (api_is_coach()) {
831
            $blocks = self::getCoachBlocks($toolChain);
832
        } else {
833
            $blocks = self::getStudentBlocks($toolChain);
834
        }
835
836
        return $blocks;
837
    }
838
839
    /**
840
     * @param string $toolName
841
     * @param int    $courseId
842
     * @param int    $sessionId Optional.
843
     *
844
     * @return bool
845
     */
846
    public static function getToolVisibility($toolName, $courseId, $sessionId = 0)
847
    {
848
        $allowEditionInSession = api_get_configuration_value('allow_edit_tool_visibility_in_session');
849
850
        $em = Database::getManager();
851
        $toolRepo = $em->getRepository('ChamiloCourseBundle:CTool');
852
853
        /** @var CTool $tool */
854
        $tool = $toolRepo->findOneBy(['cId' => $courseId, 'sessionId' => 0, 'name' => $toolName]);
855
        $visibility = $tool->getVisibility();
856
857
        if ($allowEditionInSession && $sessionId) {
858
            $tool = $toolRepo->findOneBy(
859
                ['cId' => $courseId, 'sessionId' => $sessionId, 'name' => $toolName]
860
            );
861
862
            if ($tool) {
863
                $visibility = $tool->getVisibility();
864
            }
865
        }
866
867
        return $visibility;
868
    }
869
870
    /**
871
     * Filter tool icons. Only show if $patronKey is = :teacher
872
     * Example dataIcons[i]['name']: parameter titleIcons1:teacher || titleIcons2 || titleIcons3:teacher.
873
     *
874
     * @param array  $dataIcons          array Reference to icons
875
     * @param string $courseToolCategory Current tools category
876
     *
877
     * @return array
878
     */
879
    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...
880
    {
881
        $patronKey = ':teacher';
882
883
        if (TOOL_STUDENT_VIEW == $courseToolCategory) {
884
            //Fix only coach can see external pages - see #8236 - icpna
885
            if (api_is_coach()) {
886
                foreach ($dataIcons as $index => $array) {
887
                    if (isset($array['name'])) {
888
                        $dataIcons[$index]['name'] = str_replace($patronKey, '', $array['name']);
889
                    }
890
                }
891
892
                return $dataIcons;
893
            }
894
895
            $flagOrder = false;
896
897
            foreach ($dataIcons as $index => $array) {
898
                if (!isset($array['name'])) {
899
                    continue;
900
                }
901
902
                $pos = strpos($array['name'], $patronKey);
903
904
                if (false !== $pos) {
905
                    unset($dataIcons[$index]);
906
                    $flagOrder = true;
907
                }
908
            }
909
910
            if ($flagOrder) {
911
                return array_values($dataIcons);
912
            }
913
914
            return $dataIcons;
915
        }
916
917
        // clean patronKey of name icons
918
        foreach ($dataIcons as $index => $array) {
919
            if (isset($array['name'])) {
920
                $dataIcons[$index]['name'] = str_replace($patronKey, '', $array['name']);
921
            }
922
        }
923
924
        return $dataIcons;
925
    }
926
927
    /**
928
     * Find the tool icon when homepage_view is activity_big.
929
     *
930
     * @param int  $iconSize
931
     * @param bool $generateId
932
     *
933
     * @return string
934
     */
935
    private static function getToolIcon(array $item, $iconSize, $generateId = true)
0 ignored issues
show
Unused Code introduced by
The method getToolIcon() 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...
936
    {
937
        $image = str_replace('.gif', '.png', $item['tool']['image']);
938
        $toolIid = isset($item['tool']['iid']) ? $item['tool']['iid'] : null;
939
940
        if (isset($item['tool']['custom_image'])) {
941
            return Display::img(
942
                $item['tool']['custom_image'],
943
                $item['name'],
944
                ['id' => 'toolimage_'.$toolIid]
945
            );
946
        }
947
948
        if (isset($item['tool']['custom_icon']) && !empty($item['tool']['custom_icon'])) {
949
            $customIcon = $item['tool']['custom_icon'];
950
951
            if ('0' == $item['tool']['visibility']) {
952
                $customIcon = self::getDisableIcon($item['tool']['custom_icon']);
953
            }
954
955
            return Display::img(
956
                self::getCustomWebIconPath().$customIcon,
957
                $item['name'],
958
                ['id' => 'toolimage_'.$toolIid]
959
            );
960
        }
961
962
        $id = '';
963
        if ($generateId) {
964
            $id = 'toolimage_'.$toolIid;
965
        }
966
967
        return Display::return_icon(
968
            $image,
969
            $item['name'],
970
            ['id' => $id],
971
            $iconSize,
972
            false
973
        );
974
    }
975
}
976