Passed
Push — master ( 30419d...1022c5 )
by
unknown
19:06 queued 10:45
created

SocialManager::getAutoExtendLink()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 2
dl 0
loc 17
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Message;
6
use Chamilo\CoreBundle\Entity\MessageAttachment;
7
use Chamilo\CoreBundle\Entity\UserRelUser;
8
use Chamilo\CoreBundle\Enums\ActionIcon;
9
use Chamilo\CoreBundle\Enums\ObjectIcon;
10
use Chamilo\CoreBundle\Enums\StateIcon;
11
use Chamilo\CoreBundle\Framework\Container;
12
use Chamilo\CourseBundle\Entity\CForumPost;
13
use Chamilo\CourseBundle\Entity\CForumThread;
14
15
/**
16
 * Class SocialManager.
17
 *
18
 * This class provides methods for the social network management.
19
 * Include/require it in your code to use its features.
20
 */
21
class SocialManager extends UserManager
22
{
23
    const DEFAULT_WALL_POSTS = 10;
24
    const DEFAULT_SCROLL_NEW_POST = 5;
25
26
    /**
27
     * Constructor.
28
     */
29
    public function __construct()
30
    {
31
    }
32
33
    /**
34
     * Allow to see contacts list.
35
     *
36
     * @author isaac flores paz
37
     *
38
     * @return array
39
     */
40
    public static function show_list_type_friends()
41
    {
42
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
43
        $sql = 'SELECT id, title FROM '.$table.'
44
                WHERE id<>6
45
                ORDER BY id ASC';
46
        $result = Database::query($sql);
47
        $friend_relation_list = [];
48
        while ($row = Database::fetch_assoc($result)) {
49
            $friend_relation_list[] = $row;
50
        }
51
        $count_list = count($friend_relation_list);
52
        if (0 == $count_list) {
53
            $friend_relation_list[] = get_lang('Unknown');
54
        } else {
55
            return $friend_relation_list;
56
        }
57
    }
58
59
    /**
60
     * Get the kind of relation between contacts.
61
     *
62
     * @param int  $user_id     user id
63
     * @param int  $user_friend user friend id
64
     * @param bool $includeRH   include the RH relationship
65
     *
66
     * @return int
67
     *
68
     * @author isaac flores paz
69
     */
70
    public static function get_relation_between_contacts($user_id, $user_friend, $includeRH = false)
71
    {
72
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
73
        $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
74
        if (false == $includeRH) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
75
            $sql = 'SELECT rt.id as id
76
                FROM '.$table.' rt
77
                WHERE rt.id = (
78
                    SELECT uf.relation_type
79
                    FROM '.$userRelUserTable.' uf
80
                    WHERE
81
                        user_id='.((int) $user_id).' AND
82
                        friend_user_id='.((int) $user_friend).' AND
83
                        uf.relation_type <> '.UserRelUser::USER_RELATION_TYPE_RRHH.'
84
                    LIMIT 1
85
                )';
86
        } else {
87
            $sql = 'SELECT rt.id as id
88
                FROM '.$table.' rt
89
                WHERE rt.id = (
90
                    SELECT uf.relation_type
91
                    FROM '.$userRelUserTable.' uf
92
                    WHERE
93
                        user_id='.((int) $user_id).' AND
94
                        friend_user_id='.((int) $user_friend).'
95
                    LIMIT 1
96
                )';
97
        }
98
        $res = Database::query($sql);
99
        if (Database::num_rows($res) > 0) {
100
            $row = Database::fetch_assoc($res);
101
102
            return (int) $row['id'];
103
        } else {
104
            if ('true' === api_get_setting('social.social_make_teachers_friend_all')) {
105
                $adminsList = UserManager::get_all_administrators();
106
                foreach ($adminsList as $admin) {
107
                    if (api_get_user_id() == $admin['user_id']) {
108
                        return UserRelUser::USER_RELATION_TYPE_GOODFRIEND;
109
                    }
110
                }
111
                $targetUserCoursesList = CourseManager::get_courses_list_by_user_id(
112
                    $user_id,
113
                    true,
114
                    false
115
                );
116
                $currentUserId = api_get_user_id();
117
                foreach ($targetUserCoursesList as $course) {
118
                    $teachersList = CourseManager::get_teacher_list_from_course_code($course['code']);
119
                    foreach ($teachersList as $teacher) {
120
                        if ($currentUserId == $teacher['user_id']) {
121
                            return UserRelUser::USER_RELATION_TYPE_GOODFRIEND;
122
                        }
123
                    }
124
                }
125
            } else {
126
                return UserRelUser::USER_UNKNOWN;
127
            }
128
        }
129
    }
130
131
    /**
132
     * Gets friends id list.
133
     *
134
     * @param int  user id
135
     * @param int group id
136
     * @param string name to search
137
     * @param bool true will load firstname, lastname, and image name
138
     *
139
     * @return array
140
     *
141
     * @author Julio Montoya <[email protected]> Cleaning code, function renamed, $load_extra_info option added
142
     * @author isaac flores paz
143
     */
144
    public static function get_friends(
145
        $user_id,
146
        $id_group = null,
147
        $search_name = null,
148
        $load_extra_info = true
149
    ) {
150
        $user_id = (int) $user_id;
151
152
        $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
153
        $tbl_my_user = Database::get_main_table(TABLE_MAIN_USER);
154
        $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
155
                WHERE
156
                    relation_type NOT IN ('.UserRelUser::USER_RELATION_TYPE_DELETED.', '.UserRelUser::USER_RELATION_TYPE_RRHH.') AND
157
                    friend_user_id<>'.$user_id.' AND
158
                    user_id='.$user_id;
159
        if (isset($id_group) && $id_group > 0) {
160
            $sql .= ' AND relation_type='.$id_group;
161
        }
162
        if (isset($search_name)) {
163
            $search_name = trim($search_name);
164
            $search_name = str_replace(' ', '', $search_name);
165
            $sql .= ' AND friend_user_id IN (
166
                SELECT user_id FROM '.$tbl_my_user.'
167
                WHERE
168
                    firstName LIKE "%'.Database::escape_string($search_name).'%" OR
169
                    lastName LIKE "%'.Database::escape_string($search_name).'%" OR
170
                    '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
171
                ) ';
172
        }
173
174
        $res = Database::query($sql);
175
        $list = [];
176
        while ($row = Database::fetch_assoc($res)) {
177
            if ($load_extra_info) {
178
                $userInfo = api_get_user_info($row['friend_user_id']);
179
                $list[] = [
180
                    'friend_user_id' => $row['friend_user_id'],
181
                    'firstName' => $userInfo['firstName'],
182
                    'lastName' => $userInfo['lastName'],
183
                    'username' => $userInfo['username'],
184
                    'image' => $userInfo['avatar'],
185
                    'user_info' => $userInfo,
186
                ];
187
            } else {
188
                $list[] = $row;
189
            }
190
        }
191
192
        return $list;
193
    }
194
195
    /**
196
     * Get number of messages sent to other users.
197
     *
198
     * @param int $userId
199
     *
200
     * @return int
201
     */
202
    public static function getCountMessagesSent($userId)
203
    {
204
        $userId = (int) $userId;
205
        $table = Database::get_main_table(TABLE_MESSAGE);
206
        $sql = 'SELECT COUNT(*) FROM '.$table.'
207
                WHERE
208
                    user_sender_id='.$userId.' AND
209
                    msg_status < 5';
210
        $res = Database::query($sql);
211
        $row = Database::fetch_row($res);
212
213
        return $row[0];
214
    }
215
216
    /**
217
     * Get number of messages received from other users.
218
     *
219
     * @param int $receiver_id
220
     *
221
     * @return int
222
     */
223
    public static function getCountMessagesReceived($receiver_id)
224
    {
225
        $table = Database::get_main_table(TABLE_MESSAGE);
226
        $sql = 'SELECT COUNT(*) FROM '.$table.'
227
                WHERE
228
                    user_receiver_id='.intval($receiver_id).' AND
229
                    msg_status < 4';
230
        $res = Database::query($sql);
231
        $row = Database::fetch_row($res);
232
233
        return $row[0];
234
    }
235
236
    /**
237
     * Get number of messages posted on own wall.
238
     *
239
     * @param int $userId
240
     *
241
     * @return int
242
     */
243
    public static function getCountWallPostedMessages($userId)
244
    {
245
        $userId = (int) $userId;
246
247
        if (empty($userId)) {
248
            return 0;
249
        }
250
251
        $table = Database::get_main_table(TABLE_MESSAGE);
252
        $sql = 'SELECT COUNT(*)
253
                FROM '.$table.'
254
                WHERE
255
                    user_sender_id='.$userId.' AND
256
                    (msg_status = '.MESSAGE_STATUS_WALL.' OR
257
                    msg_status = '.MESSAGE_STATUS_WALL_POST.') AND
258
                    parent_id = 0';
259
        $res = Database::query($sql);
260
        $row = Database::fetch_row($res);
261
262
        return $row[0];
263
    }
264
265
    /**
266
     * Get invitation list received by user.
267
     *
268
     * @author isaac flores paz
269
     *
270
     * @param int $userId
271
     * @param int $limit
272
     *
273
     * @return array
274
     */
275
    public static function get_list_invitation_of_friends_by_user_id($userId, $limit = 0)
276
    {
277
        $userId = (int) $userId;
278
        $limit = (int) $limit;
279
280
        if (empty($userId)) {
281
            return [];
282
        }
283
284
        $table = Database::get_main_table(TABLE_MESSAGE);
285
        $sql = 'SELECT user_sender_id, send_date, title, content
286
                FROM '.$table.'
287
                WHERE
288
                    user_receiver_id = '.$userId.' AND
289
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
290
        if (null != $limit && $limit > 0) {
291
            $sql .= ' LIMIT '.$limit;
292
        }
293
        $res = Database::query($sql);
294
        $list = [];
295
        while ($row = Database::fetch_assoc($res)) {
296
            $list[] = $row;
297
        }
298
299
        return $list;
300
    }
301
302
    /**
303
     * Get invitation list sent by user.
304
     *
305
     * @author Julio Montoya <[email protected]>
306
     *
307
     * @param int $userId
308
     *
309
     * @return array
310
     */
311
    public static function get_list_invitation_sent_by_user_id($userId)
312
    {
313
        $userId = (int) $userId;
314
315
        if (empty($userId)) {
316
            return [];
317
        }
318
319
        $table = Database::get_main_table(TABLE_MESSAGE);
320
        $sql = 'SELECT user_receiver_id, send_date,title,content
321
                FROM '.$table.'
322
                WHERE
323
                    user_sender_id = '.$userId.' AND
324
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
325
        $res = Database::query($sql);
326
        $list = [];
327
        while ($row = Database::fetch_assoc($res)) {
328
            $list[$row['user_receiver_id']] = $row;
329
        }
330
331
        return $list;
332
    }
333
334
    /**
335
     * Get count invitation sent by user.
336
     *
337
     * @author Julio Montoya <[email protected]>
338
     *
339
     * @param int $userId
340
     *
341
     * @return int
342
     */
343
    public static function getCountInvitationSent($userId)
344
    {
345
        $userId = (int) $userId;
346
347
        if (empty($userId)) {
348
            return 0;
349
        }
350
351
        $table = Database::get_main_table(TABLE_MESSAGE);
352
        $sql = 'SELECT count(user_receiver_id) count
353
                FROM '.$table.'
354
                WHERE
355
                    user_sender_id = '.$userId.' AND
356
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
357
        $res = Database::query($sql);
358
        if (Database::num_rows($res)) {
359
            $row = Database::fetch_assoc($res);
360
361
            return (int) $row['count'];
362
        }
363
364
        return 0;
365
    }
366
367
    /**
368
     * Accepts invitation.
369
     *
370
     * @param int $user_send_id
371
     * @param int $user_receiver_id
372
     *
373
     * @return bool
374
     *
375
     * @author isaac flores paz
376
     * @author Julio Montoya <[email protected]> Cleaning code
377
     */
378
    public static function invitation_accepted($user_send_id, $user_receiver_id)
379
    {
380
        if (empty($user_send_id) || empty($user_receiver_id)) {
381
            return false;
382
        }
383
384
        $table = Database::get_main_table(TABLE_MESSAGE);
385
        $sql = "UPDATE $table
386
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
387
                WHERE
388
                    user_sender_id = ".((int) $user_send_id)." AND
389
                    user_receiver_id=".((int) $user_receiver_id)." AND
390
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
391
        Database::query($sql);
392
393
        return true;
394
    }
395
396
    /**
397
     * Denies invitation.
398
     *
399
     * @param int user sender id
400
     * @param int user receiver id
401
     *
402
     * @return bool
403
     *
404
     * @author isaac flores paz
405
     * @author Julio Montoya <[email protected]> Cleaning code
406
     */
407
    public static function invitation_denied($user_send_id, $user_receiver_id)
408
    {
409
        if (empty($user_send_id) || empty($user_receiver_id)) {
410
            return false;
411
        }
412
        $table = Database::get_main_table(TABLE_MESSAGE);
413
        $sql = 'DELETE FROM '.$table.'
414
                WHERE
415
                    user_sender_id =  '.((int) $user_send_id).' AND
416
                    user_receiver_id='.((int) $user_receiver_id).' AND
417
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
418
        Database::query($sql);
419
420
        return true;
421
    }
422
423
    /**
424
     * Shows the avatar block in social pages.
425
     *
426
     * @param string $show     highlight link possible values:
427
     *                         group_add,
428
     *                         home,
429
     *                         messages,
430
     *                         messages_inbox,
431
     *                         messages_compose,
432
     *                         messages_outbox,
433
     *                         invitations,
434
     *                         shared_profile,
435
     *                         friends,
436
     *                         groups search
437
     * @param int    $group_id
438
     * @param int    $user_id
439
     */
440
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
441
    {
442
        $user_id = (int) $user_id;
443
        $group_id = (int) $group_id;
444
445
        if (empty($user_id)) {
446
            $user_id = api_get_user_id();
447
        }
448
449
        $show_groups = [
450
            'groups',
451
            'group_messages',
452
            'messages_list',
453
            'group_add',
454
            'mygroups',
455
            'group_edit',
456
            'member_list',
457
            'invite_friends',
458
            'waiting_list',
459
            'browse_groups',
460
        ];
461
462
        $template = new Template(null, false, false, false, false, false);
463
464
        if (in_array($show, $show_groups) && !empty($group_id)) {
465
            // Group image
466
            $userGroup = new UserGroupModel();
467
            $group_info = $userGroup->get($group_id);
468
            $userGroupImage = $userGroup->get_picture_group(
469
                $group_id,
470
                $group_info['picture'],
471
                128,
472
                GROUP_IMAGE_SIZE_BIG
473
            );
474
            $template->assign('show_group', true);
475
            $template->assign('group_id', $group_id);
476
            $template->assign('user_group_image', $userGroupImage);
477
            $template->assign(
478
                'user_is_group_admin',
479
                $userGroup->is_group_admin(
480
                    $group_id,
481
                    api_get_user_id()
482
                )
483
            );
484
        } else {
485
            $template->assign('show_group', false);
486
            $template->assign('show_user', true);
487
            $template->assign(
488
                'user_image',
489
                [
490
                    'big' => UserManager::getUserPicture(
491
                        $user_id,
492
                        USER_IMAGE_SIZE_BIG
493
                    ),
494
                    'normal' => UserManager::getUserPicture(
495
                        $user_id,
496
                        USER_IMAGE_SIZE_MEDIUM
497
                    ),
498
                ]
499
            );
500
        }
501
502
        return $template->fetch($template->get_template('social/avatar_block.tpl'));
503
    }
504
505
    /**
506
     * Displays a sortable table with the list of online users.
507
     *
508
     * @param array $user_list The list of users to be shown
509
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
510
     *
511
     * @return string HTML block or null if and ID was defined
512
     * @assert (null) === false
513
     */
514
    public static function display_user_list($user_list, $wrap = true)
515
    {
516
        $html = '';
517
518
        if (isset($_GET['id']) || count($user_list) < 1) {
519
            return false;
520
        }
521
522
        $course_url = '';
523
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
524
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
525
        }
526
527
        $hide = ('true' === api_get_setting('platform.hide_complete_name_in_whoisonline'));
528
        foreach ($user_list as $uid) {
529
            $user_info = api_get_user_info($uid, true);
530
            $lastname = $user_info['lastname'];
531
            $firstname = $user_info['firstname'];
532
            $completeName = $firstname.', '.$lastname;
533
            $user_rol = 1 == $user_info['status'] ? Display::getMdiIcon(ObjectIcon::TEACHER, 'ch-tool-icon', null, ICON_SIZE_TINY, get_lang('Trainer')) : Display::getMdiIcon(ObjectIcon::USER, 'ch-tool-icon', null, ICON_SIZE_TINY, get_lang('Learner'));
534
            $status_icon_chat = null;
535
            if (isset($user_info['user_is_online_in_chat']) && 1 == $user_info['user_is_online_in_chat']) {
536
                $status_icon_chat = Display::getMdiIcon(StateIcon::ONLINE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Online'));
537
            } else {
538
                $status_icon_chat = Display::getMdiIcon(StateIcon::OFFLINE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Offline'));
539
            }
540
541
            $userPicture = $user_info['avatar'];
542
            $officialCode = '';
543
            if ('true' === api_get_setting('show_official_code_whoisonline')) {
544
                $officialCode .= '<div class="items-user-official-code">
545
                    <p style="min-height: 30px;" title="'.get_lang('Code').'">'.$user_info['official_code'].'</p></div>';
546
            }
547
548
            if (true === $hide) {
549
                $completeName = '';
550
                $firstname = '';
551
                $lastname = '';
552
            }
553
554
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
555
556
            $url = null;
557
            // Anonymous users can't have access to the profile
558
            if (!api_is_anonymous()) {
559
                if ('true' === api_get_setting('allow_social_tool')) {
560
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
561
                } else {
562
                    $url = '?id='.$uid.$course_url;
563
                }
564
            } else {
565
                $url = null;
566
            }
567
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
568
569
            $html .= '<div class="col-xs-6 col-md-2">
570
                        <div class="items-user">
571
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
572
                            <div class="items-user-name">
573
                            '.$name.'
574
                            </div>
575
                            '.$officialCode.'
576
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
577
                        </div>
578
                      </div>';
579
        }
580
581
        return $html;
582
    }
583
584
    /**
585
     * @param string $content
586
     * @param string $span_count
587
     *
588
     * @return string
589
     */
590
    public static function social_wrapper_div($content, $span_count)
591
    {
592
        $span_count = (int) $span_count;
593
        $html = '<div class="span'.$span_count.'">';
594
        $html .= '<div class="well_border">';
595
        $html .= $content;
596
        $html .= '</div></div>';
597
598
        return $html;
599
    }
600
601
    /**
602
     * Dummy function.
603
     */
604
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
605
    {
606
        $content = '';
607
        switch ($place) {
608
            case SOCIAL_CENTER_PLUGIN:
609
                $social_plugins = [1, 2];
610
                if (is_array($social_plugins) && count($social_plugins) > 0) {
611
                    $content .= '<div id="social-plugins">';
612
                    foreach ($social_plugins as $plugin) {
613
                        $content .= '<div class="social-plugin-item">';
614
                        $content .= $plugin;
615
                        $content .= '</div>';
616
                    }
617
                    $content .= '</div>';
618
                }
619
                break;
620
            case SOCIAL_LEFT_PLUGIN:
621
                break;
622
            case SOCIAL_RIGHT_PLUGIN:
623
                break;
624
        }
625
626
        return $content;
627
    }
628
629
    /**
630
     * Gets all messages from someone's wall (within specific limits).
631
     *
632
     * @param int        $userId     id of wall shown
633
     * @param int|string $parentId   id message (Post main)
634
     * @param int|array  $groupId
635
     * @param int|array  $friendId
636
     * @param string     $startDate  Date from which we want to show the messages, in UTC time
637
     * @param int        $start      Limit for the number of parent messages we want to show
638
     * @param int        $length     Wall message query offset
639
     * @param bool       $getCount
640
     * @param array      $threadList
641
     *
642
     * @return array|int
643
     *
644
     * @author Yannick Warnier
645
     */
646
    public static function getWallMessages(
647
        $userId,
648
        $parentId = 0,
649
        $groupId = 0,
650
        $friendId = 0,
651
        $startDate = '',
652
        $start = 0,
653
        $length = 10,
654
        $getCount = false,
655
        $threadList = []
656
    ) {
657
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
658
659
        $parentId = (int) $parentId;
660
        $userId = (int) $userId;
661
        $start = (int) $start;
662
        $length = (int) $length;
663
664
        $select = " SELECT
665
                    id,
666
                    user_sender_id,
667
                    user_receiver_id,
668
                    send_date,
669
                    content,
670
                    parent_id,
671
                    msg_status,
672
                    group_id,
673
                    '' as forum_id,
674
                    '' as thread_id,
675
                    '' as c_id
676
                  ";
677
678
        if ($getCount) {
679
            $select = ' SELECT count(id) as count_items ';
680
        }
681
682
        $sqlBase = "$select FROM $tblMessage m WHERE ";
683
        $sql = [];
684
        $sql[1] = $sqlBase."msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
685
686
        // Get my own posts
687
        $userReceiverCondition = ' (
688
            user_receiver_id = '.$userId.' AND
689
            msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
690
            parent_id = '.$parentId.'
691
        )';
692
693
        $sql[1] .= $userReceiverCondition;
694
695
        $sql[2] = $sqlBase.' msg_status = '.MESSAGE_STATUS_PROMOTED.' ';
696
697
        // Get my group posts
698
        $groupCondition = '';
699
        if (!empty($groupId)) {
700
            if (is_array($groupId)) {
701
                $groupId = array_map('intval', $groupId);
702
                $groupId = implode(",", $groupId);
703
                $groupCondition = " ( group_id IN ($groupId) ";
704
            } else {
705
                $groupId = (int) $groupId;
706
                $groupCondition = " ( group_id = $groupId ";
707
            }
708
            $groupCondition .= ' AND (msg_type = '.Message::MESSAGE_TYPE_GROUP.') ';
709
        }
710
        if (!empty($groupCondition)) {
711
            $sql[3] = $sqlBase.$groupCondition;
712
        }
713
714
        // Get my friend posts
715
        $friendCondition = '';
716
        if (!empty($friendId)) {
717
            if (is_array($friendId)) {
718
                $friendId = array_map('intval', $friendId);
719
                $friendId = implode(",", $friendId);
720
                $friendCondition = " ( user_receiver_id IN ($friendId) ";
721
            } else {
722
                $friendId = (int) $friendId;
723
                $friendCondition = " ( user_receiver_id = $friendId ";
724
            }
725
            $friendCondition .= ' AND msg_status = '.MESSAGE_STATUS_WALL_POST.' AND parent_id = 0) ';
726
        }
727
        if (!empty($friendCondition)) {
728
            $sql[4] = $sqlBase.$friendCondition;
729
        }
730
731
        if (!empty($threadList)) {
732
            if ($getCount) {
733
                $select = ' SELECT count(iid) count_items ';
734
            } else {
735
                $select = " SELECT
736
                                iid as id,
737
                                poster_id as user_sender_id,
738
                                '' as user_receiver_id,
739
                                post_date as send_date,
740
                                post_text as content,
741
                                '' as parent_id,
742
                                ".MESSAGE_STATUS_FORUM." as msg_status,
743
                                '' as group_id,
744
                                forum_id,
745
                                thread_id,
746
                                c_id
747
                            ";
748
            }
749
750
            $threadList = array_map('intval', $threadList);
751
            $threadList = implode("','", $threadList);
752
            $condition = " thread_id IN ('$threadList') ";
753
            $sql[5] = "$select
754
                    FROM c_forum_post
755
                    WHERE $condition
756
                ";
757
        }
758
759
        if ($getCount) {
760
            $count = 0;
761
            foreach ($sql as $oneQuery) {
762
                if (!empty($oneQuery)) {
763
                    $res = Database::query($oneQuery);
764
                    $row = Database::fetch_array($res);
765
                    $count += (int) $row['count_items'];
766
                }
767
            }
768
769
            return $count;
770
        }
771
772
        $sqlOrder = ' ORDER BY send_date DESC ';
773
        $sqlLimit = " LIMIT $start, $length ";
774
        $messages = [];
775
        foreach ($sql as $index => $oneQuery) {
776
            if (5 === $index) {
777
                // Exception only for the forum query above (field name change)
778
                $oneQuery .= ' ORDER BY post_date DESC '.$sqlLimit;
779
            } else {
780
                $oneQuery .= $sqlOrder.$sqlLimit;
781
            }
782
            $res = Database::query($oneQuery);
783
            $em = Database::getManager();
784
            if (Database::num_rows($res) > 0) {
785
                $repo = $em->getRepository(CForumPost::class);
786
                $repoThread = $em->getRepository(CForumThread::class);
787
                $groups = [];
788
                $userGroup = new UserGroupModel();
789
                $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
790
                while ($row = Database::fetch_assoc($res)) {
791
                    $row['group_info'] = [];
792
                    if (!empty($row['group_id'])) {
793
                        if (!in_array($row['group_id'], $groups)) {
794
                            $group = $userGroup->get($row['group_id']);
795
                            $group['url'] = $urlGroup.$group['id'];
796
                            $groups[$row['group_id']] = $group;
797
                            $row['group_info'] = $group;
798
                        } else {
799
                            $row['group_info'] = $groups[$row['group_id']];
800
                        }
801
                    }
802
803
                    // Forums
804
                    $row['post_title'] = '';
805
                    $row['forum_title'] = '';
806
                    $row['thread_url'] = '';
807
                    if (MESSAGE_STATUS_FORUM === (int) $row['msg_status']) {
808
                        // @todo use repositories to get post and threads.
809
                        /** @var CForumPost $post */
810
                        $post = $repo->find($row['id']);
811
                        /** @var CForumThread $thread */
812
                        $thread = $repoThread->find($row['thread_id']);
813
                        if ($post && $thread) {
814
                            //$courseInfo = api_get_course_info_by_id($post->getCId());
815
                            $row['post_title'] = $post->getForum()->getTitle();
816
                            $row['forum_title'] = $thread->getTitle();
817
                            $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
818
                                    //'cid' => $courseInfo['real_id'],
819
                                    'forum' => $post->getForum()->getIid(),
820
                                    'thread' => $post->getThread()->getIid(),
821
                                    'post_id' => $post->getIid(),
822
                                ]).'#post_id_'.$post->getIid();
823
                        }
824
                    }
825
826
                    $messages[$row['id']] = $row;
827
                }
828
            }
829
        }
830
        // Reordering messages by ID (reverse order) is enough to have the
831
        // latest first, as there is currently no option to edit messages
832
        // afterwards
833
        krsort($messages);
834
835
        return $messages;
836
    }
837
838
    /**
839
     * @return array
840
     */
841
    public static function getAttachmentPreviewList(Message $message)
842
    {
843
        $list = [];
844
        //if (empty($message['group_id'])) {
845
        $files = $message->getAttachments();
846
        if ($files) {
0 ignored issues
show
introduced by
$files is of type Doctrine\Common\Collections\Collection, thus it always evaluated to true.
Loading history...
847
            $repo = Container::getMessageAttachmentRepository();
848
            /** @var MessageAttachment $file */
849
            foreach ($files as $file) {
850
                $url = $repo->getResourceFileUrl($file);
851
                $display = Display::fileHtmlGuesser($file->getFilename(), $url);
852
                $list[] = $display;
853
            }
854
        }
855
        /*} else {
856
            $list = MessageManager::getAttachmentLinkList($messageId, 0);
857
        }*/
858
859
        return $list;
860
    }
861
862
    /**
863
     * @param array $message
864
     *
865
     * @return string
866
     */
867
    public static function getPostAttachment($message)
868
    {
869
        $previews = self::getAttachmentPreviewList($message);
870
871
        if (empty($previews)) {
872
            return '';
873
        }
874
875
        return implode('', $previews);
876
    }
877
878
    /**
879
     * @param array $messages
880
     *
881
     * @return array
882
     */
883
    public static function formatWallMessages($messages)
884
    {
885
        $data = [];
886
        $users = [];
887
        foreach ($messages as $key => $message) {
888
            $userIdLoop = $message['user_sender_id'];
889
            $userFriendIdLoop = $message['user_receiver_id'];
890
            if (!isset($users[$userIdLoop])) {
891
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
892
            }
893
894
            if (!isset($users[$userFriendIdLoop])) {
895
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
896
            }
897
898
            $html = self::headerMessagePost(
899
                $users[$userIdLoop],
900
                $users[$userFriendIdLoop],
901
                $message
902
            );
903
904
            $data[$key] = $message;
905
            $data[$key]['html'] = $html;
906
        }
907
908
        return $data;
909
    }
910
911
    /**
912
     * verify if Url Exist - Using Curl.
913
     */
914
    public static function verifyUrl(string $uri): bool
915
    {
916
        $client = new Client();
917
918
        try {
919
            $response = $client->request('GET', $uri, [
920
                'timeout' => 15,
921
                'verify' => false,
922
                'headers' => [
923
                    'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
924
                ],
925
            ]);
926
927
            if (200 !== $response->getStatusCode()) {
928
                return false;
929
            }
930
931
            return true;
932
        } catch (Exception $e) {
933
            return false;
934
        }
935
    }
936
937
    /**
938
     * Generate the social block for a user.
939
     *
940
     * @param int    $userId            The user id
941
     * @param string $groupBlock        Optional. Highlight link possible values:
942
     *                                  group_add, home, messages, messages_inbox, messages_compose,
943
     *                                  messages_outbox, invitations, shared_profile, friends, groups, search
944
     * @param int    $groupId           Optional. Group ID
945
     * @param bool   $show_full_profile
946
     *
947
     * @return string The HTML code with the social block
948
     */
949
    public static function setSocialUserBlock(
950
        Template $template,
951
        $userId,
952
        $groupBlock = '',
953
        $groupId = 0,
954
        $show_full_profile = true
955
    ) {
956
        if ('true' !== api_get_setting('allow_social_tool')) {
957
            return '';
958
        }
959
960
        $currentUserId = api_get_user_id();
961
        $userId = (int) $userId;
962
        $userRelationType = 0;
963
964
        $socialAvatarBlock = self::show_social_avatar_block(
965
            $groupBlock,
966
            $groupId,
967
            $userId
968
        );
969
970
        $profileEditionLink = null;
971
        if ($currentUserId === $userId) {
972
            $profileEditionLink = Display::getProfileEditionLink($userId);
973
        } else {
974
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
975
        }
976
977
        $options = api_get_setting('profile.profile_fields_visibility', true);
978
        if (isset($options['options'])) {
979
            $options = $options['options'];
980
        }
981
982
        $vCardUserLink = Display::getVCardUserLink($userId);
983
        if (isset($options['vcard']) && false === $options['vcard']) {
984
            $vCardUserLink = '';
985
        }
986
987
        $userInfo = api_get_user_info($userId, true, false, true, true);
988
989
        if (isset($options['firstname']) && false === $options['firstname']) {
990
            $userInfo['firstname'] = '';
991
        }
992
        if (isset($options['lastname']) && false === $options['lastname']) {
993
            $userInfo['lastname'] = '';
994
        }
995
996
        if (isset($options['email']) && false === $options['email']) {
997
            $userInfo['email'] = '';
998
        }
999
1000
        // Ofaj
1001
        $hasCertificates = Certificate::getCertificateByUser($userId);
1002
        $userInfo['has_certificates'] = 0;
1003
        if (!empty($hasCertificates)) {
1004
            $userInfo['has_certificates'] = 1;
1005
        }
1006
1007
        $userInfo['is_admin'] = UserManager::is_admin($userId);
1008
        $language = api_get_language_from_iso($userInfo['language']);
1009
1010
        if ($language) {
0 ignored issues
show
introduced by
$language is of type Chamilo\CoreBundle\Entity\Language, thus it always evaluated to true.
Loading history...
1011
            $userInfo['language'] = [
1012
                'label' => $language->getOriginalName(),
1013
                'value' => $language->getEnglishName(),
1014
                'code' => $language->getIsocode(),
1015
            ];
1016
        }
1017
1018
        error_log('$userInfo ->'.print_r($userInfo['language'], true));
0 ignored issues
show
Bug introduced by
Are you sure print_r($userInfo['language'], true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

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

1018
        error_log('$userInfo ->'./** @scrutinizer ignore-type */ print_r($userInfo['language'], true));
Loading history...
1019
1020
        if (isset($options['language']) && false === $options['language']) {
1021
            $userInfo['language'] = '';
1022
        }
1023
1024
        if (isset($options['photo']) && false === $options['photo']) {
1025
            $socialAvatarBlock = '';
1026
        }
1027
1028
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
1029
        $showLanguageFlag = ('true' === api_get_setting('social.social_show_language_flag_in_profile'));
1030
1031
        $template->assign('user', $userInfo);
1032
        $template->assign('show_language_flag', $showLanguageFlag);
1033
        $template->assign('extra_info', $extraFieldBlock);
1034
        $template->assign('social_avatar_block', $socialAvatarBlock);
1035
        $template->assign('profile_edition_link', $profileEditionLink);
1036
        //Added the link to export the vCard to the Template
1037
1038
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
1039
        if ($show_full_profile) {
1040
            $template->assign('vcard_user_link', $vCardUserLink);
1041
        }
1042
1043
        if ('1' === api_get_setting('gamification_mode')) {
1044
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
1045
                $userId,
1046
                $userInfo['status']
1047
            );
1048
1049
            $template->assign('gamification_points', $gamificationPoints);
1050
        }
1051
        $chatEnabled = api_is_global_chat_enabled();
1052
1053
        if (isset($options['chat']) && false === $options['chat']) {
1054
            $chatEnabled = '';
1055
        }
1056
1057
        $template->assign('chat_enabled', $chatEnabled);
1058
        $template->assign('user_relation', $userRelationType);
1059
        $template->assign('user_relation_type_friend', UserRelUser::USER_RELATION_TYPE_FRIEND);
1060
        $template->assign('show_full_profile', $show_full_profile);
1061
1062
        $templateName = $template->get_template('social/user_block.tpl');
1063
1064
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
1065
            $templateName = $template->get_template('social/group_block.tpl');
1066
        }
1067
1068
        $template->assign('social_avatar_block', $template->fetch($templateName));
1069
    }
1070
1071
    /**
1072
     * @param int $user_id
1073
     * @param $link_shared
1074
     * @param bool $showLinkToChat
1075
     *
1076
     * @return string
1077
     */
1078
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
1079
    {
1080
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1081
        $friends = self::get_friends($user_id, UserRelUser::USER_RELATION_TYPE_FRIEND);
1082
        $numberFriends = count($friends);
1083
        $friendHtml = '';
1084
1085
        if (!empty($numberFriends)) {
1086
            $friendHtml .= '<div class="list-group contact-list">';
1087
            $j = 1;
1088
1089
            usort(
1090
                $friends,
1091
                function ($a, $b) {
1092
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
1093
                }
1094
            );
1095
1096
            foreach ($friends as $friend) {
1097
                if ($j > $numberFriends) {
1098
                    break;
1099
                }
1100
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
1101
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
1102
1103
                $statusIcon = Display::getMdiIcon(StateIcon::OFFLINE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Offline'));
1104
                $status = 0;
1105
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
1106
                    $statusIcon = Display::getMdiIcon(StateIcon::ONLINE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Online'));
1107
                    $status = 1;
1108
                }
1109
1110
                $friendAvatarMedium = UserManager::getUserPicture(
1111
                    $friend['friend_user_id'],
1112
                    USER_IMAGE_SIZE_MEDIUM
1113
                );
1114
                $friendAvatarSmall = UserManager::getUserPicture(
1115
                    $friend['friend_user_id'],
1116
                    USER_IMAGE_SIZE_SMALL
1117
                );
1118
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
1119
1120
                $relation = self::get_relation_between_contacts(
1121
                    $friend['friend_user_id'],
1122
                    api_get_user_id()
1123
                );
1124
1125
                if ($showLinkToChat) {
1126
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
1127
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
1128
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
1129
                } else {
1130
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
1131
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
1132
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
1133
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
1134
                }
1135
1136
                $friendHtml .= '</a>';
1137
1138
                $j++;
1139
            }
1140
            $friendHtml .= '</div>';
1141
        } else {
1142
            $friendHtml = Display::return_message(get_lang('No friends in your contact list'), 'warning');
1143
        }
1144
1145
        return $friendHtml;
1146
    }
1147
1148
    /**
1149
     * @param string $urlForm
1150
     *
1151
     * @return string
1152
     */
1153
    public static function getWallForm($urlForm)
1154
    {
1155
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
1156
        $form = new FormValidator(
1157
            'social_wall_main',
1158
            'post',
1159
            $urlForm.$userId,
1160
            null,
1161
            ['enctype' => 'multipart/form-data'],
1162
            FormValidator::LAYOUT_HORIZONTAL
1163
        );
1164
1165
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('Write something on your friend\'s wall') : get_lang(
1166
            'Social wallWhatAreYouThinkingAbout'
1167
        );
1168
1169
        $form->addTextarea(
1170
            'social_wall_new_msg_main',
1171
            null,
1172
            [
1173
                'placeholder' => $socialWallPlaceholder,
1174
                'cols-size' => [1, 12, 1],
1175
                'aria-label' => $socialWallPlaceholder,
1176
            ]
1177
        );
1178
        $form->addHtml('<div class="form-group">');
1179
        $form->addHtml('<div class="col-sm-6">');
1180
        $form->addFile('picture', get_lang('File upload'), ['custom' => true]);
1181
        $form->addHtml('</div>');
1182
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
1183
        $form->addButtonSend(
1184
            get_lang('Post'),
1185
            'wall_post_button',
1186
            false,
1187
            [
1188
                'cols-size' => [1, 10, 1],
1189
                'custom' => true,
1190
            ]
1191
        );
1192
        $form->addHtml('</div></div>');
1193
        $form->addHtml('</div>');
1194
        $form->addHidden('url_content', '');
1195
        $form->protect();
1196
        $html = Display::panel($form->returnForm(), get_lang('Social wall'));
1197
1198
        return $html;
1199
    }
1200
1201
    /**
1202
     * @param string $message
1203
     * @param string $content
1204
     *
1205
     * @return string
1206
     */
1207
    public static function wrapPost($message, $content)
1208
    {
1209
        $class = '';
1210
        if (MESSAGE_STATUS_PROMOTED === (int) $message['msg_status']) {
1211
            $class = 'promoted_post';
1212
        }
1213
1214
        return Display::panel($content, '',
1215
            '',
1216
            'default',
1217
            '',
1218
            'post_'.$message['id'],
1219
            null,
1220
            $class
1221
        );
1222
    }
1223
1224
    /**
1225
     * Get HTML code block for user skills.
1226
     *
1227
     * @param int    $userId      The user ID
1228
     * @param string $orientation
1229
     *
1230
     * @return string
1231
     */
1232
    public static function getSkillBlock($userId, $orientation = 'horizontal')
1233
    {
1234
        if (false === SkillModel::isAllowed($userId, false)) {
1235
            return '';
1236
        }
1237
1238
        $skill = new SkillModel();
1239
        $ranking = $skill->getUserSkillRanking($userId);
1240
1241
        $template = new Template(null, false, false, false, false, false);
1242
        $template->assign('ranking', $ranking);
1243
        $template->assign('orientation', $orientation);
1244
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
1245
        $template->assign('user_id', $userId);
1246
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
1247
1248
        $skillBlock = $template->get_template('social/skills_block.tpl');
1249
1250
        return $template->fetch($skillBlock);
1251
    }
1252
1253
    /**
1254
     * @param int  $user_id
1255
     * @param bool $isArray
1256
     *
1257
     * @return string|array
1258
     */
1259
    public static function getExtraFieldBlock($user_id, $isArray = false)
1260
    {
1261
        $fieldVisibility = api_get_setting('profile.profile_fields_visibility', true);
1262
        $fieldVisibilityKeys = [];
1263
        if (isset($fieldVisibility['options'])) {
1264
            $fieldVisibility = $fieldVisibility['options'];
1265
            $fieldVisibilityKeys = array_keys($fieldVisibility);
1266
        }
1267
1268
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
1269
        $extra_user_data = UserManager::get_extra_user_data($user_id);
1270
1271
        $extra_information = '';
1272
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
1273
            $extra_information_value = '';
1274
            $extraField = new ExtraField('user');
1275
            $listType = [];
1276
            $extraFieldItem = [];
1277
            foreach ($extra_user_data as $key => $data) {
1278
                if (empty($data)) {
1279
                    continue;
1280
                }
1281
                if (in_array($key, $fieldVisibilityKeys) && false === $fieldVisibility[$key]) {
1282
                    continue;
1283
                }
1284
1285
                // Avoiding parameters
1286
                if (in_array(
1287
                    $key,
1288
                    [
1289
                        'mail_notify_invitation',
1290
                        'mail_notify_message',
1291
                        'mail_notify_group_message',
1292
                    ]
1293
                )) {
1294
                    continue;
1295
                }
1296
                // get display text, visibility and type from user_field table
1297
                $field_variable = str_replace('extra_', '', $key);
1298
1299
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
1300
                    $field_variable
1301
                );
1302
1303
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
1304
                    continue;
1305
                }
1306
1307
                // if is not visible skip
1308
                if (1 != $extraFieldInfo['visible_to_self']) {
1309
                    continue;
1310
                }
1311
1312
                // if is not visible to others skip also
1313
                if (1 != $extraFieldInfo['visible_to_others']) {
1314
                    continue;
1315
                }
1316
1317
                if (is_array($data)) {
1318
                    switch ($extraFieldInfo['value_type']) {
1319
                        case ExtraField::FIELD_TYPE_RADIO:
1320
                            $objEfOption = new ExtraFieldOption('user');
1321
                            $value = $data['extra_'.$extraFieldInfo['variable']];
1322
                            $optionInfo = $objEfOption->repo->getFieldOptionByFieldAndOption(
1323
                                (int) $extraFieldInfo['id'],
1324
                                $value,
1325
                                $objEfOption->extraField->getItemType()
1326
                            );
1327
1328
                            if (!empty($optionInfo[0])) {
1329
                                $extraFieldItem = [
1330
                                    'variable' => $extraFieldInfo['variable'],
1331
                                    'label' => ucfirst($extraFieldInfo['display_text']),
1332
                                    'value' => $optionInfo[0]->getDisplayText(),
1333
                                ];
1334
                            } else {
1335
                                $extraFieldItem = [
1336
                                    'variable' => $extraFieldInfo['variable'],
1337
                                    'label' => ucfirst($extraFieldInfo['display_text']),
1338
                                    'value' => implode(',', $data),
1339
                                ];
1340
                            }
1341
                            break;
1342
                        default:
1343
                            $extra_information_value .=
1344
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
1345
                                .' '.implode(',', $data).'</li>';
1346
                            $extraFieldItem = [
1347
                                'variable' => $extraFieldInfo['variable'],
1348
                                'label' => ucfirst($extraFieldInfo['display_text']),
1349
                                'value' => implode(',', $data),
1350
                            ];
1351
                            break;
1352
                    }
1353
                } else {
1354
                    switch ($extraFieldInfo['value_type']) {
1355
                        case ExtraField::FIELD_TYPE_RADIO:
1356
                            $objEfOption = new ExtraFieldOption('user');
1357
                            $optionInfo = $objEfOption->repo->getFieldOptionByFieldAndOption(
1358
                                (int) $extraFieldInfo['id'],
1359
                                $extraFieldInfo['value'],
1360
                                $objEfOption->extraField->getItemType()
1361
                            );
1362
                            break;
1363
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
1364
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
1365
                            $data = explode('::', $data);
1366
                            $data = $data[0];
1367
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
1368
                            $extraFieldItem = [
1369
                                'variable' => $extraFieldInfo['variable'],
1370
                                'label' => ucfirst($extraFieldInfo['display_text']),
1371
                                'value' => $data,
1372
                            ];
1373
                            break;
1374
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
1375
                            $id_options = explode('::', $data);
1376
                            $value_options = [];
1377
                            // get option display text from user_field_options table
1378
                            foreach ($id_options as $id_option) {
1379
                                $sql = "SELECT display_text
1380
                                    FROM $t_ufo
1381
                                    WHERE id = '$id_option'";
1382
                                $res_options = Database::query($sql);
1383
                                $row_options = Database::fetch_row($res_options);
1384
                                $value_options[] = $row_options[0];
1385
                            }
1386
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
1387
                                .' '.implode(' ', $value_options).'</li>';
1388
                            $extraFieldItem = [
1389
                                'variable' => $extraFieldInfo['variable'],
1390
                                'label' => ucfirst($extraFieldInfo['display_text']),
1391
                                'value' => $value_options,
1392
                            ];
1393
                            break;
1394
                        case ExtraField::FIELD_TYPE_TAG:
1395
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
1396
1397
                            $tag_tmp = '';
1398
                            foreach ($user_tags as $tags) {
1399
                                $tag_tmp .= '<a class="label label_tag"'
1400
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
1401
                                    .$tags['tag']
1402
                                    .'</a>';
1403
                            }
1404
                            if (is_array($user_tags) && count($user_tags) > 0) {
1405
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
1406
                                    .' '.$tag_tmp.'</li>';
1407
                            }
1408
                            $extraFieldItem = [
1409
                                'variable' => $extraFieldInfo['variable'],
1410
                                'label' => ucfirst($extraFieldInfo['display_text']),
1411
                                'value' => $tag_tmp,
1412
                            ];
1413
                            break;
1414
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
1415
                            $icon_path = UserManager::get_favicon_from_url($data);
1416
                            if (false == self::verifyUrl($icon_path)) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1417
                                break;
1418
                            }
1419
                            $bottom = '0.2';
1420
                            //quick hack for hi5
1421
                            $domain = parse_url($icon_path, PHP_URL_HOST);
1422
                            if ('www.hi5.com' == $domain || 'hi5.com' == $domain) {
1423
                                $bottom = '-0.8';
1424
                            }
1425
                            $data = '<a href="'.$data.'">'
1426
                                .'<img src="'.$icon_path.'" alt="icon"'
1427
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
1428
                                .$extraFieldInfo['display_text']
1429
                                .'</a>';
1430
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
1431
                            $extraFieldItem = [
1432
                                'variable' => $extraFieldInfo['variable'],
1433
                                'label' => ucfirst($extraFieldInfo['display_text']),
1434
                                'value' => $data,
1435
                            ];
1436
                            break;
1437
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
1438
                            $parsedData = explode('::', $data);
1439
1440
                            if (!$parsedData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsedData of type string[] 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...
1441
                                break;
1442
                            }
1443
1444
                            $objEfOption = new ExtraFieldOption('user');
1445
                            $optionInfo = $objEfOption->get($parsedData[0]);
1446
1447
                            $extra_information_value .= '<li class="list-group-item">'
1448
                                .$optionInfo['display_text'].': '
1449
                                .$parsedData[1].'</li>';
1450
                            $extraFieldItem = [
1451
                                'variable' => $extraFieldInfo['variable'],
1452
                                'label' => ucfirst($extraFieldInfo['display_text']),
1453
                                'value' => $parsedData[1],
1454
                            ];
1455
                            break;
1456
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
1457
                            $optionIds = explode(';', $data);
1458
                            $optionValues = [];
1459
1460
                            foreach ($optionIds as $optionId) {
1461
                                $objEfOption = new ExtraFieldOption('user');
1462
                                $optionInfo = $objEfOption->get($optionId);
1463
1464
                                $optionValues[] = $optionInfo['display_text'];
1465
                            }
1466
                            $extra_information_value .= '<li class="list-group-item">'
1467
                                .ucfirst($extraFieldInfo['display_text']).': '
1468
                                .implode(' ', $optionValues).'</li>';
1469
                            $extraFieldItem = [
1470
                                'variable' => $extraFieldInfo['variable'],
1471
                                'label' => ucfirst($extraFieldInfo['display_text']),
1472
                                'value' => implode(' ', $optionValues),
1473
                            ];
1474
                            break;
1475
                        default:
1476
                            // Ofaj
1477
                            // Converts "Date of birth" into "age"
1478
                            if ('terms_datedenaissance' === $key) {
1479
                                $dataArray = date_to_str_ago($data, 'UTC', true);
1480
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
1481
                                if (!empty($dataToString)) {
1482
                                    $data = $dataToString;
1483
                                    $extraFieldInfo['display_text'] = get_lang('Age');
1484
                                }
1485
                            }
1486
1487
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
1488
                            $extraFieldItem = [
1489
                                'variable' => $extraFieldInfo['variable'],
1490
                                'label' => ucfirst($extraFieldInfo['display_text']),
1491
                                'value' => $data,
1492
                            ];
1493
                            break;
1494
                    }
1495
                }
1496
1497
                $listType[] = $extraFieldItem;
1498
            }
1499
1500
            if ($isArray) {
1501
                return $listType;
1502
            } else {
1503
                // if there are information to show
1504
                if (!empty($extra_information_value)) {
1505
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
1506
                    $extra_information .= Display::panelCollapse(
1507
                        get_lang('Extra information'),
1508
                        $extra_information_value,
1509
                        'sn-extra-information',
1510
                        null,
1511
                        'sn-extra-accordion',
1512
                        'sn-extra-collapse'
1513
                    );
1514
                }
1515
            }
1516
        }
1517
1518
        return $extra_information;
1519
    }
1520
1521
    /**
1522
     * @param int   $countPost
1523
     * @param array $htmlHeadXtra
1524
     */
1525
    public static function getScrollJs($countPost, &$htmlHeadXtra)
1526
    {
1527
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
1528
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
1529
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
1530
        $locale = api_get_language_isocode();
1531
1532
        // Add Jquery scroll pagination plugin
1533
        //$htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
1534
        // Add Jquery Time ago plugin
1535
        //$htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
1536
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
1537
        if (file_exists($timeAgoLocaleDir)) {
1538
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
1539
        }
1540
1541
        if ($countPost > self::DEFAULT_WALL_POSTS) {
1542
            $htmlHeadXtra[] = '<script>
1543
            $(function() {
1544
                var container = $("#wallMessages");
1545
                container.jscroll({
1546
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
1547
                    nextSelector: "a.nextPage:last",
1548
                    contentSelector: "",
1549
                    callback: timeAgo
1550
                });
1551
            });
1552
            </script>';
1553
        }
1554
1555
        $htmlHeadXtra[] = '<script>
1556
            function deleteMessage(id)
1557
            {
1558
                $.ajax({
1559
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1560
                    success: function (result) {
1561
                        if (result) {
1562
                            $("#message_" + id).parent().parent().parent().parent().html(result);
1563
                        }
1564
                    }
1565
                });
1566
            }
1567
1568
            function deleteComment(id)
1569
            {
1570
                $.ajax({
1571
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1572
                    success: function (result) {
1573
                        if (result) {
1574
                            $("#message_" + id).parent().parent().parent().html(result);
1575
                        }
1576
                    }
1577
                });
1578
            }
1579
1580
            function submitComment(messageId)
1581
            {
1582
                var data = $("#form_comment_"+messageId).serializeArray();
1583
                $.ajax({
1584
                    type : "POST",
1585
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
1586
                    data: data,
1587
                    success: function (result) {
1588
                        if (result) {
1589
                            $("#post_" + messageId + " textarea").val("");
1590
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
1591
                            $("#post_" + messageId + " .sub-mediapost").append(
1592
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved.')).'</div>\')
1593
                            );
1594
1595
                            $("#result_" + messageId + "").fadeIn("fast", function() {
1596
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
1597
                                    $(this).remove();
1598
                                });
1599
                            });
1600
                        }
1601
                    }
1602
                });
1603
            }
1604
1605
            $(function() {
1606
                timeAgo();
1607
1608
                /*$(".delete_message").on("click", function() {
1609
                    var id = $(this).attr("id");
1610
                    id = id.split("_")[1];
1611
                    $.ajax({
1612
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1613
                        success: function (result) {
1614
                            if (result) {
1615
                                $("#message_" + id).parent().parent().parent().parent().html(result);
1616
                            }
1617
                        }
1618
                    });
1619
                });
1620
1621
1622
                $(".delete_comment").on("click", function() {
1623
                    var id = $(this).attr("id");
1624
                    id = id.split("_")[1];
1625
                    $.ajax({
1626
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1627
                        success: function (result) {
1628
                            if (result) {
1629
                                $("#message_" + id).parent().parent().parent().html(result);
1630
                            }
1631
                        }
1632
                    });
1633
                });
1634
                */
1635
            });
1636
1637
            function timeAgo() {
1638
                $(".timeago").timeago();
1639
            }
1640
            </script>';
1641
    }
1642
1643
    /**
1644
     * @param int $userId
1645
     * @param int $countPost
1646
     *
1647
     * @return string
1648
     */
1649
    public static function getAutoExtendLink($userId, $countPost)
1650
    {
1651
        $userId = (int) $userId;
1652
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
1653
        $socialAutoExtendLink = '';
1654
        if ($countPost > self::DEFAULT_WALL_POSTS) {
1655
            $socialAutoExtendLink = Display::url(
1656
                get_lang('See more'),
1657
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
1658
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
1659
                [
1660
                    'class' => 'nextPage next',
1661
                ]
1662
            );
1663
        }
1664
1665
        return $socialAutoExtendLink;
1666
    }
1667
1668
    /**
1669
     * @param int $userId
1670
     *
1671
     * @return array
1672
     */
1673
    public static function getThreadList($userId)
1674
    {
1675
        return [];
1676
        $forumCourseId = (int) api_get_setting('forum.global_forums_course_id');
0 ignored issues
show
Unused Code introduced by
$forumCourseId = (int)ap...obal_forums_course_id') 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...
1677
1678
        $threads = [];
1679
        if (!empty($forumCourseId)) {
1680
            $courseInfo = api_get_course_info_by_id($forumCourseId);
1681
            /*getNotificationsPerUser($userId, true, $forumCourseId);
1682
            $notification = Session::read('forum_notification');
1683
            Session::erase('forum_notification');*/
1684
1685
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
1686
                'cid' => $courseInfo['real_id'],
1687
            ]).'&';
1688
            if (isset($notification['thread']) && !empty($notification['thread'])) {
1689
                $threadList = array_filter(array_unique($notification['thread']));
1690
                $repo = Container::getForumThreadRepository();
1691
                foreach ($threadList as $threadId) {
1692
                    /** @var CForumThread $thread */
1693
                    $thread = $repo->find($threadId);
1694
                    if ($thread) {
1695
                        $threadUrl = $threadUrlBase.http_build_query([
1696
                            'forum' => $thread->getForum()->getIid(),
1697
                            'thread' => $thread->getIid(),
1698
                        ]);
1699
                        $threads[] = [
1700
                            'id' => $threadId,
1701
                            'url' => Display::url(
1702
                                $thread->getTitle(),
1703
                                $threadUrl
1704
                            ),
1705
                            'name' => Display::url(
1706
                                $thread->getTitle(),
1707
                                $threadUrl
1708
                            ),
1709
                            'description' => '',
1710
                        ];
1711
                    }
1712
                }
1713
            }
1714
        }
1715
1716
        return $threads;
1717
    }
1718
1719
    /**
1720
     * @param int $userId
1721
     *
1722
     * @return string
1723
     */
1724
    public static function getGroupBlock($userId)
1725
    {
1726
        $threadList = self::getThreadList($userId);
1727
        $userGroup = new UserGroupModel();
1728
1729
        $forumCourseId = (int) api_get_setting('forum.global_forums_course_id');
1730
        $courseInfo = null;
1731
        if (!empty($forumCourseId)) {
1732
            $courseInfo = api_get_course_info_by_id($forumCourseId);
1733
        }
1734
1735
        $social_group_block = '';
1736
        if (!empty($courseInfo)) {
1737
            if (!empty($threadList)) {
1738
                $social_group_block .= '<div class="list-group">';
1739
                foreach ($threadList as $group) {
1740
                    $social_group_block .= ' <li class="list-group-item">';
1741
                    $social_group_block .= $group['name'];
1742
                    $social_group_block .= '</li>';
1743
                }
1744
                $social_group_block .= '</div>';
1745
            }
1746
1747
            $social_group_block .= Display::url(
1748
                get_lang('See all communities'),
1749
                api_get_path(WEB_CODE_PATH).'forum/index.php?cid='.$courseInfo['real_id']
1750
            );
1751
1752
            if (!empty($social_group_block)) {
1753
                $social_group_block = Display::panelCollapse(
1754
                    get_lang('My communities'),
1755
                    $social_group_block,
1756
                    'sm-groups',
1757
                    null,
1758
                    'grups-acordion',
1759
                    'groups-collapse'
1760
                );
1761
            }
1762
        } else {
1763
            // Load my groups
1764
            $results = $userGroup->get_groups_by_user(
1765
                $userId,
1766
                [
1767
                    GROUP_USER_PERMISSION_ADMIN,
1768
                    GROUP_USER_PERMISSION_READER,
1769
                    GROUP_USER_PERMISSION_MODERATOR,
1770
                    GROUP_USER_PERMISSION_HRM,
1771
                ]
1772
            );
1773
1774
            $myGroups = [];
1775
            if (!empty($results)) {
1776
                foreach ($results as $result) {
1777
                    $id = $result['id'];
1778
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
1779
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
1780
1781
                    $group_url = "group_view.php?id=$id";
1782
1783
                    $link = Display::url(
1784
                        api_ucwords(cut($result['name'], 40, true)),
1785
                        $group_url
1786
                    );
1787
1788
                    $result['name'] = $link;
1789
1790
                    $picture = $userGroup->get_picture_group(
1791
                        $id,
1792
                        $result['picture'],
1793
                        null,
1794
                        GROUP_IMAGE_SIZE_BIG
1795
                    );
1796
1797
                    $result['picture'] = '<img class="img-responsive" src="'.$picture.'" />';
1798
                    $group_actions = '<div class="group-more"><a class="btn btn--plain" href="groups.php?#tab_browse-2">'.
1799
                        get_lang('See more').'</a></div>';
1800
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
1801
                    $myGroups[] = [
1802
                        'url' => Display::url(
1803
                            $result['picture'],
1804
                            $group_url
1805
                        ),
1806
                        'name' => $result['name'],
1807
                        'description' => $group_info.$group_actions,
1808
                    ];
1809
                }
1810
1811
                $social_group_block .= '<div class="list-group">';
1812
                foreach ($myGroups as $group) {
1813
                    $social_group_block .= ' <li class="list-group-item">';
1814
                    $social_group_block .= $group['name'];
1815
                    $social_group_block .= '</li>';
1816
                }
1817
                $social_group_block .= '</div>';
1818
1819
                $form = new FormValidator(
1820
                    'find_groups_form',
1821
                    'get',
1822
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
1823
                    null,
1824
                    null,
1825
                    FormValidator::LAYOUT_BOX_NO_LABEL
1826
                );
1827
                $form->addHidden('search_type', 2);
1828
1829
                $form->addText(
1830
                    'q',
1831
                    get_lang('Search'),
1832
                    false,
1833
                    [
1834
                        'aria-label' => get_lang('Search'),
1835
                        'custom' => true,
1836
                        'placeholder' => get_lang('Search'),
1837
                    ]
1838
                );
1839
1840
                $social_group_block .= $form->returnForm();
1841
1842
                if (!empty($social_group_block)) {
1843
                    $social_group_block = Display::panelCollapse(
1844
                        get_lang('My groups'),
1845
                        $social_group_block,
1846
                        'sm-groups',
1847
                        null,
1848
                        'grups-acordion',
1849
                        'groups-collapse'
1850
                    );
1851
                }
1852
            }
1853
        }
1854
1855
        return $social_group_block;
1856
    }
1857
1858
    /**
1859
     * @param string $selected
1860
     *
1861
     * @return string
1862
     */
1863
    public static function getHomeProfileTabs($selected = 'home')
1864
    {
1865
        $headers = [
1866
            [
1867
                'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
1868
                'content' => get_lang('Profile'),
1869
            ],
1870
        ];
1871
        $allowJustification = 'true' === api_get_plugin_setting('justification', 'tool_enable');
1872
        if ($allowJustification) {
1873
            $plugin = Justification::create();
1874
            $headers[] = [
1875
                'url' => api_get_path(WEB_CODE_PATH).'auth/justification.php',
1876
                'content' => $plugin->get_lang('Justification'),
1877
            ];
1878
        }
1879
1880
        $allowPauseTraining = 'true' === api_get_plugin_setting('pausetraining', 'tool_enable');
1881
        $allowEdit = 'true' === api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation');
1882
        if ($allowPauseTraining && $allowEdit) {
1883
            $plugin = PauseTraining::create();
1884
            $headers[] = [
1885
                'url' => api_get_path(WEB_CODE_PATH).'auth/PauseTraining.php',
1886
                'content' => $plugin->get_lang('PauseTraining'),
1887
            ];
1888
        }
1889
1890
        $selectedItem = 1;
1891
        foreach ($headers as $header) {
1892
            $info = pathinfo($header['url']);
1893
            if ($selected === $info['filename']) {
1894
                break;
1895
            }
1896
            $selectedItem++;
1897
        }
1898
1899
        $tabs = '';
1900
        if (count($headers) > 1) {
1901
            $tabs = Display::tabsOnlyLink($headers, $selectedItem);
1902
        }
1903
1904
        return $tabs;
1905
    }
1906
1907
    /**
1908
     * Returns the formatted header message post.
1909
     *
1910
     * @param int   $authorInfo
1911
     * @param int   $receiverInfo
1912
     * @param array $message      Message data
1913
     *
1914
     * @return string $html       The formatted header message post
1915
     */
1916
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
1917
    {
1918
        $currentUserId = api_get_user_id();
1919
        $authorId = (int) $authorInfo['user_id'];
1920
        $receiverId = (int) $receiverInfo['user_id'];
1921
        $iconStatus = $authorInfo['icon_status'];
1922
1923
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
1924
        $avatarAuthor = $authorInfo['avatar'];
1925
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
1926
        $nameCompleteAuthor = $authorInfo['complete_name'];
1927
1928
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
1929
        $nameCompleteReceiver = $receiverInfo['complete_name'];
1930
1931
        $htmlReceiver = '';
1932
        if ($authorId !== $receiverId) {
1933
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
1934
        }
1935
1936
        if (!empty($message['group_info'])) {
1937
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
1938
        }
1939
        $canEdit = ($currentUserId == $authorInfo['user_id'] || $currentUserId == $receiverInfo['user_id']) && empty($message['group_info']);
1940
1941
        if (!empty($message['thread_id'])) {
1942
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
1943
            $canEdit = false;
1944
        }
1945
1946
        $postAttachment = self::getPostAttachment($message);
1947
1948
        $html = '<div class="top-mediapost" >';
1949
        $html .= '<div class="pull-right btn-group btn-group-sm">';
1950
1951
        $html .= MessageManager::getLikesButton(
1952
            $message['id'],
1953
            $currentUserId,
1954
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
1955
        );
1956
1957
        if ($canEdit) {
1958
            $htmlDelete = Display::url(
1959
                Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_SMALL),
1960
                'javascript:void(0)',
1961
                [
1962
                    'id' => 'message_'.$message['id'],
1963
                    'title' => get_lang('Delete comment'),
1964
                    'onclick' => 'deleteMessage('.$message['id'].')',
1965
                    'class' => 'btn btn--plain',
1966
                ]
1967
            );
1968
1969
            $html .= $htmlDelete;
1970
        }
1971
        $html .= '</div>';
1972
1973
        $html .= '<div class="user-image" >';
1974
        $html .= '<a href="'.$urlAuthor.'">
1975
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
1976
        $html .= '</div>';
1977
        $html .= '<div class="user-data">';
1978
        $html .= $iconStatus;
1979
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
1980
        $html .= '<div class="post-date">'.$date.'</div>';
1981
        $html .= '</div>';
1982
        $html .= '<div class="msg-content">';
1983
        if (!empty($postAttachment)) {
1984
            $html .= '<div class="post-attachment thumbnail">';
1985
            $html .= $postAttachment;
1986
            $html .= '</div>';
1987
        }
1988
        $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
1989
        $html .= '</div>';
1990
        $html .= '</div>'; // end mediaPost
1991
1992
        // Popularity post functionality
1993
        $html .= '<div class="popularity-mediapost"></div>';
1994
1995
        return $html;
1996
    }
1997
}
1998