Passed
Push — master ( 44b866...954b89 )
by Julito
07:40
created

SocialManager   F

Complexity

Total Complexity 287

Size/Duplication

Total Lines 2578
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 1331
dl 0
loc 2578
rs 0.8
c 0
b 0
f 0
wmc 287

39 Methods

Rating   Name   Duplication   Size   Complexity  
A getCountFriends() 0 22 3
A show_list_type_friends() 0 16 3
B get_relation_between_contacts() 0 57 9
B get_friends() 0 49 7
A __construct() 0 2 1
B getUserRssFeed() 0 49 11
B readContentWithOpenGraph() 0 26 8
A show_social_avatar_block() 0 63 4
A getScriptToGetOpenGraph() 0 19 1
A get_message_number_invitation_by_user_id() 0 15 2
B get_plugins() 0 23 7
F show_social_menu() 0 393 48
F setSocialUserBlock() 0 118 23
A getWallForm() 0 45 3
A get_list_invitation_sent_by_user_id() 0 21 3
F getExtraFieldBlock() 0 256 39
A getCountMessagesReceived() 0 11 1
F getWallMessages() 0 190 22
B listMyFriendsBlock() 0 68 7
A invitation_accepted() 0 16 3
A wrapPost() 0 14 2
A formatWallMessages() 0 26 4
B getHomeProfileTabs() 0 42 7
C getGroupBlock() 0 132 10
A social_wrapper_div() 0 9 1
A getAttachmentPreviewList() 0 19 3
A verifyUrl() 0 17 2
A get_list_invitation_of_friends_by_user_id() 0 25 5
A getSkillBlock() 0 19 4
A getCountInvitationSent() 0 22 3
B headerMessagePost() 0 80 9
B getThreadList() 0 44 6
A getPostAttachment() 0 9 2
A invitation_denied() 0 14 3
A getCountWallPostedMessages() 0 20 2
A getScrollJs() 0 102 3
A getAutoExtendLink() 0 17 2
A getCountMessagesSent() 0 12 1
C display_user_list() 0 68 13

How to fix   Complexity   

Complex Class

Complex classes like SocialManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SocialManager, and based on these observations, apply Extract Interface, too.

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\Framework\Container;
8
use Chamilo\CourseBundle\Entity\CForumPost;
9
use Chamilo\CourseBundle\Entity\CForumThread;
10
use ChamiloSession as Session;
11
use Laminas\Feed\Reader\Entry\Rss;
12
use Laminas\Feed\Reader\Reader;
13
14
/**
15
 * Class SocialManager.
16
 *
17
 * This class provides methods for the social network management.
18
 * Include/require it in your code to use its features.
19
 */
20
class SocialManager extends UserManager
21
{
22
    const DEFAULT_WALL_POSTS = 10;
23
    const DEFAULT_SCROLL_NEW_POST = 5;
24
25
    /**
26
     * Constructor.
27
     */
28
    public function __construct()
29
    {
30
    }
31
32
    /**
33
     * Allow to see contacts list.
34
     *
35
     * @author isaac flores paz
36
     *
37
     * @return array
38
     */
39
    public static function show_list_type_friends()
40
    {
41
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
42
        $sql = 'SELECT id, title FROM '.$table.'
43
                WHERE id<>6
44
                ORDER BY id ASC';
45
        $result = Database::query($sql);
46
        $friend_relation_list = [];
47
        while ($row = Database::fetch_array($result, 'ASSOC')) {
48
            $friend_relation_list[] = $row;
49
        }
50
        $count_list = count($friend_relation_list);
51
        if (0 == $count_list) {
52
            $friend_relation_list[] = get_lang('Unknown');
53
        } else {
54
            return $friend_relation_list;
55
        }
56
    }
57
58
    /**
59
     * Get the kind of relation between contacts.
60
     *
61
     * @param int  $user_id     user id
62
     * @param int  $user_friend user friend id
63
     * @param bool $includeRH   include the RH relationship
64
     *
65
     * @return int
66
     *
67
     * @author isaac flores paz
68
     */
69
    public static function get_relation_between_contacts($user_id, $user_friend, $includeRH = false)
70
    {
71
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
72
        $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
73
        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...
74
            $sql = 'SELECT rt.id as id
75
                FROM '.$table.' rt
76
                WHERE rt.id = (
77
                    SELECT uf.relation_type
78
                    FROM '.$userRelUserTable.' uf
79
                    WHERE
80
                        user_id='.((int) $user_id).' AND
81
                        friend_user_id='.((int) $user_friend).' AND
82
                        uf.relation_type <> '.USER_RELATION_TYPE_RRHH.'
83
                    LIMIT 1
84
                )';
85
        } else {
86
            $sql = 'SELECT rt.id as id
87
                FROM '.$table.' rt
88
                WHERE rt.id = (
89
                    SELECT uf.relation_type
90
                    FROM '.$userRelUserTable.' uf
91
                    WHERE
92
                        user_id='.((int) $user_id).' AND
93
                        friend_user_id='.((int) $user_friend).'
94
                    LIMIT 1
95
                )';
96
        }
97
        $res = Database::query($sql);
98
        if (Database::num_rows($res) > 0) {
99
            $row = Database::fetch_array($res, 'ASSOC');
100
101
            return (int) $row['id'];
102
        } else {
103
            if (api_get_configuration_value('social_make_teachers_friend_all')) {
104
                $adminsList = UserManager::get_all_administrators();
105
                foreach ($adminsList as $admin) {
106
                    if (api_get_user_id() == $admin['user_id']) {
107
                        return USER_RELATION_TYPE_GOODFRIEND;
108
                    }
109
                }
110
                $targetUserCoursesList = CourseManager::get_courses_list_by_user_id(
111
                    $user_id,
112
                    true,
113
                    false
114
                );
115
                $currentUserId = api_get_user_id();
116
                foreach ($targetUserCoursesList as $course) {
117
                    $teachersList = CourseManager::get_teacher_list_from_course_code($course['code']);
118
                    foreach ($teachersList as $teacher) {
119
                        if ($currentUserId == $teacher['user_id']) {
120
                            return USER_RELATION_TYPE_GOODFRIEND;
121
                        }
122
                    }
123
                }
124
            } else {
125
                return USER_UNKNOWN;
126
            }
127
        }
128
    }
129
130
    /**
131
     * Get count of friends from user.
132
     *
133
     * @param int $userId
134
     *
135
     * @return int
136
     */
137
    public static function getCountFriends($userId)
138
    {
139
        $table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
140
        $userId = (int) $userId;
141
        if (empty($userId)) {
142
            return 0;
143
        }
144
145
        $sql = 'SELECT count(friend_user_id) count
146
                FROM '.$table.'
147
                WHERE
148
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
149
                    friend_user_id<>'.$userId.' AND
150
                    user_id='.$userId;
151
        $res = Database::query($sql);
152
        if (Database::num_rows($res)) {
153
            $row = Database::fetch_array($res, 'ASSOC');
154
155
            return (int) $row['count'];
156
        }
157
158
        return 0;
159
    }
160
161
    /**
162
     * Gets friends id list.
163
     *
164
     * @param int  user id
165
     * @param int group id
166
     * @param string name to search
167
     * @param bool true will load firstname, lastname, and image name
168
     *
169
     * @return array
170
     *
171
     * @author Julio Montoya <[email protected]> Cleaning code, function renamed, $load_extra_info option added
172
     * @author isaac flores paz
173
     */
174
    public static function get_friends(
175
        $user_id,
176
        $id_group = null,
177
        $search_name = null,
178
        $load_extra_info = true
179
    ) {
180
        $user_id = (int) $user_id;
181
182
        $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
183
        $tbl_my_user = Database::get_main_table(TABLE_MAIN_USER);
184
        $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
185
                WHERE
186
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
187
                    friend_user_id<>'.$user_id.' AND
188
                    user_id='.$user_id;
189
        if (isset($id_group) && $id_group > 0) {
190
            $sql .= ' AND relation_type='.$id_group;
191
        }
192
        if (isset($search_name)) {
193
            $search_name = trim($search_name);
194
            $search_name = str_replace(' ', '', $search_name);
195
            $sql .= ' AND friend_user_id IN (
196
                SELECT user_id FROM '.$tbl_my_user.'
197
                WHERE
198
                    firstName LIKE "%'.Database::escape_string($search_name).'%" OR
199
                    lastName LIKE "%'.Database::escape_string($search_name).'%" OR
200
                    '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
201
                ) ';
202
        }
203
204
        $res = Database::query($sql);
205
        $list = [];
206
        while ($row = Database::fetch_array($res, 'ASSOC')) {
207
            if ($load_extra_info) {
208
                $userInfo = api_get_user_info($row['friend_user_id']);
209
                $list[] = [
210
                    'friend_user_id' => $row['friend_user_id'],
211
                    'firstName' => $userInfo['firstName'],
212
                    'lastName' => $userInfo['lastName'],
213
                    'username' => $userInfo['username'],
214
                    'image' => $userInfo['avatar'],
215
                    'user_info' => $userInfo,
216
                ];
217
            } else {
218
                $list[] = $row;
219
            }
220
        }
221
222
        return $list;
223
    }
224
225
    /**
226
     * Get number messages of the inbox.
227
     *
228
     * @author isaac flores paz
229
     *
230
     * @param int $userId user receiver id
231
     *
232
     * @return int
233
     */
234
    public static function get_message_number_invitation_by_user_id($userId)
235
    {
236
        $table = Database::get_main_table(TABLE_MESSAGE);
237
        $userId = (int) $userId;
238
        $sql = 'SELECT COUNT(*) as count_message_in_box FROM '.$table.'
239
                WHERE
240
                    user_receiver_id='.$userId.' AND
241
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
242
        $res = Database::query($sql);
243
        $row = Database::fetch_array($res, 'ASSOC');
244
        if ($row) {
245
            return (int) $row['count_message_in_box'];
246
        }
247
248
        return 0;
249
    }
250
251
    /**
252
     * Get number of messages sent to other users.
253
     *
254
     * @param int $userId
255
     *
256
     * @return int
257
     */
258
    public static function getCountMessagesSent($userId)
259
    {
260
        $userId = (int) $userId;
261
        $table = Database::get_main_table(TABLE_MESSAGE);
262
        $sql = 'SELECT COUNT(*) FROM '.$table.'
263
                WHERE
264
                    user_sender_id='.$userId.' AND
265
                    msg_status < 5';
266
        $res = Database::query($sql);
267
        $row = Database::fetch_row($res);
268
269
        return $row[0];
270
    }
271
272
    /**
273
     * Get number of messages received from other users.
274
     *
275
     * @param int $receiver_id
276
     *
277
     * @return int
278
     */
279
    public static function getCountMessagesReceived($receiver_id)
280
    {
281
        $table = Database::get_main_table(TABLE_MESSAGE);
282
        $sql = 'SELECT COUNT(*) FROM '.$table.'
283
                WHERE
284
                    user_receiver_id='.intval($receiver_id).' AND
285
                    msg_status < 4';
286
        $res = Database::query($sql);
287
        $row = Database::fetch_row($res);
288
289
        return $row[0];
290
    }
291
292
    /**
293
     * Get number of messages posted on own wall.
294
     *
295
     * @param int $userId
296
     *
297
     * @return int
298
     */
299
    public static function getCountWallPostedMessages($userId)
300
    {
301
        $userId = (int) $userId;
302
303
        if (empty($userId)) {
304
            return 0;
305
        }
306
307
        $table = Database::get_main_table(TABLE_MESSAGE);
308
        $sql = 'SELECT COUNT(*)
309
                FROM '.$table.'
310
                WHERE
311
                    user_sender_id='.$userId.' AND
312
                    (msg_status = '.MESSAGE_STATUS_WALL.' OR
313
                    msg_status = '.MESSAGE_STATUS_WALL_POST.') AND
314
                    parent_id = 0';
315
        $res = Database::query($sql);
316
        $row = Database::fetch_row($res);
317
318
        return $row[0];
319
    }
320
321
    /**
322
     * Get invitation list received by user.
323
     *
324
     * @author isaac flores paz
325
     *
326
     * @param int $userId
327
     * @param int $limit
328
     *
329
     * @return array
330
     */
331
    public static function get_list_invitation_of_friends_by_user_id($userId, $limit = 0)
332
    {
333
        $userId = (int) $userId;
334
        $limit = (int) $limit;
335
336
        if (empty($userId)) {
337
            return [];
338
        }
339
340
        $table = Database::get_main_table(TABLE_MESSAGE);
341
        $sql = 'SELECT user_sender_id, send_date, title, content
342
                FROM '.$table.'
343
                WHERE
344
                    user_receiver_id = '.$userId.' AND
345
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
346
        if (null != $limit && $limit > 0) {
347
            $sql .= ' LIMIT '.$limit;
348
        }
349
        $res = Database::query($sql);
350
        $list = [];
351
        while ($row = Database::fetch_array($res, 'ASSOC')) {
352
            $list[] = $row;
353
        }
354
355
        return $list;
356
    }
357
358
    /**
359
     * Get invitation list sent by user.
360
     *
361
     * @author Julio Montoya <[email protected]>
362
     *
363
     * @param int $userId
364
     *
365
     * @return array
366
     */
367
    public static function get_list_invitation_sent_by_user_id($userId)
368
    {
369
        $userId = (int) $userId;
370
371
        if (empty($userId)) {
372
            return [];
373
        }
374
375
        $table = Database::get_main_table(TABLE_MESSAGE);
376
        $sql = 'SELECT user_receiver_id, send_date,title,content
377
                FROM '.$table.'
378
                WHERE
379
                    user_sender_id = '.$userId.' AND
380
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
381
        $res = Database::query($sql);
382
        $list = [];
383
        while ($row = Database::fetch_array($res, 'ASSOC')) {
384
            $list[$row['user_receiver_id']] = $row;
385
        }
386
387
        return $list;
388
    }
389
390
    /**
391
     * Get count invitation sent by user.
392
     *
393
     * @author Julio Montoya <[email protected]>
394
     *
395
     * @param int $userId
396
     *
397
     * @return int
398
     */
399
    public static function getCountInvitationSent($userId)
400
    {
401
        $userId = (int) $userId;
402
403
        if (empty($userId)) {
404
            return 0;
405
        }
406
407
        $table = Database::get_main_table(TABLE_MESSAGE);
408
        $sql = 'SELECT count(user_receiver_id) count
409
                FROM '.$table.'
410
                WHERE
411
                    user_sender_id = '.$userId.' AND
412
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
413
        $res = Database::query($sql);
414
        if (Database::num_rows($res)) {
415
            $row = Database::fetch_array($res, 'ASSOC');
416
417
            return (int) $row['count'];
418
        }
419
420
        return 0;
421
    }
422
423
    /**
424
     * Accepts invitation.
425
     *
426
     * @param int $user_send_id
427
     * @param int $user_receiver_id
428
     *
429
     * @return bool
430
     *
431
     * @author isaac flores paz
432
     * @author Julio Montoya <[email protected]> Cleaning code
433
     */
434
    public static function invitation_accepted($user_send_id, $user_receiver_id)
435
    {
436
        if (empty($user_send_id) || empty($user_receiver_id)) {
437
            return false;
438
        }
439
440
        $table = Database::get_main_table(TABLE_MESSAGE);
441
        $sql = "UPDATE $table
442
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
443
                WHERE
444
                    user_sender_id = ".((int) $user_send_id)." AND
445
                    user_receiver_id=".((int) $user_receiver_id)." AND
446
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
447
        Database::query($sql);
448
449
        return true;
450
    }
451
452
    /**
453
     * Denies invitation.
454
     *
455
     * @param int user sender id
456
     * @param int user receiver id
457
     *
458
     * @return bool
459
     *
460
     * @author isaac flores paz
461
     * @author Julio Montoya <[email protected]> Cleaning code
462
     */
463
    public static function invitation_denied($user_send_id, $user_receiver_id)
464
    {
465
        if (empty($user_send_id) || empty($user_receiver_id)) {
466
            return false;
467
        }
468
        $table = Database::get_main_table(TABLE_MESSAGE);
469
        $sql = 'DELETE FROM '.$table.'
470
                WHERE
471
                    user_sender_id =  '.((int) $user_send_id).' AND
472
                    user_receiver_id='.((int) $user_receiver_id).' AND
473
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
474
        Database::query($sql);
475
476
        return true;
477
    }
478
479
    /**
480
     * Get user's feeds.
481
     *
482
     * @param int $user  User ID
483
     * @param int $limit Limit of posts per feed
484
     *
485
     * @return string HTML section with all feeds included
486
     *
487
     * @author  Yannick Warnier
488
     *
489
     * @since   Dokeos 1.8.6.1
490
     */
491
    public static function getUserRssFeed($user, $limit = 5)
492
    {
493
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
494
495
        if (empty($feed)) {
496
            return '';
497
        }
498
        $feeds = explode(';', $feed['rssfeeds']);
499
        if (0 == count($feeds)) {
500
            return '';
501
        }
502
        $res = '';
503
        foreach ($feeds as $url) {
504
            if (empty($url)) {
505
                continue;
506
            }
507
            try {
508
                $channel = Reader::import($url);
509
                $i = 1;
510
                if (!empty($channel)) {
511
                    $iconRss = '';
512
                    if (!empty($feed)) {
513
                        $iconRss = Display::url(
514
                            Display::return_icon('social_rss.png', '', [], 22),
515
                            Security::remove_XSS($feed['rssfeeds']),
516
                            ['target' => '_blank']
517
                        );
518
                    }
519
520
                    $res .= '<h3 class="title-rss">'.$iconRss.' '.$channel->getTitle().'</h3>';
521
                    $res .= '<div class="rss-items">';
522
                    /** @var Rss $item */
523
                    foreach ($channel as $item) {
524
                        if ($limit >= 0 and $i > $limit) {
525
                            break;
526
                        }
527
                        $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
528
                        $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
529
                        $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
530
                        $i++;
531
                    }
532
                    $res .= '</div>';
533
                }
534
            } catch (Exception $e) {
535
                error_log($e->getMessage());
536
            }
537
        }
538
539
        return $res;
540
    }
541
542
    /**
543
     * Shows the avatar block in social pages.
544
     *
545
     * @param string $show     highlight link possible values:
546
     *                         group_add,
547
     *                         home,
548
     *                         messages,
549
     *                         messages_inbox,
550
     *                         messages_compose,
551
     *                         messages_outbox,
552
     *                         invitations,
553
     *                         shared_profile,
554
     *                         friends,
555
     *                         groups search
556
     * @param int    $group_id
557
     * @param int    $user_id
558
     */
559
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
560
    {
561
        $user_id = (int) $user_id;
562
        $group_id = (int) $group_id;
563
564
        if (empty($user_id)) {
565
            $user_id = api_get_user_id();
566
        }
567
568
        $show_groups = [
569
            'groups',
570
            'group_messages',
571
            'messages_list',
572
            'group_add',
573
            'mygroups',
574
            'group_edit',
575
            'member_list',
576
            'invite_friends',
577
            'waiting_list',
578
            'browse_groups',
579
        ];
580
581
        $template = new Template(null, false, false, false, false, false);
582
583
        if (in_array($show, $show_groups) && !empty($group_id)) {
584
            // Group image
585
            $userGroup = new UserGroupModel();
586
            $group_info = $userGroup->get($group_id);
587
            $userGroupImage = $userGroup->get_picture_group(
588
                $group_id,
589
                $group_info['picture'],
590
                128,
591
                GROUP_IMAGE_SIZE_BIG
592
            );
593
            $template->assign('show_group', true);
594
            $template->assign('group_id', $group_id);
595
            $template->assign('user_group_image', $userGroupImage);
596
            $template->assign(
597
                'user_is_group_admin',
598
                $userGroup->is_group_admin(
599
                    $group_id,
600
                    api_get_user_id()
601
                )
602
            );
603
        } else {
604
            $template->assign('show_group', false);
605
            $template->assign('show_user', true);
606
            $template->assign(
607
                'user_image',
608
                [
609
                    'big' => UserManager::getUserPicture(
610
                        $user_id,
611
                        USER_IMAGE_SIZE_BIG
612
                    ),
613
                    'normal' => UserManager::getUserPicture(
614
                        $user_id,
615
                        USER_IMAGE_SIZE_MEDIUM
616
                    ),
617
                ]
618
            );
619
        }
620
621
        return $template->fetch($template->get_template('social/avatar_block.tpl'));
622
    }
623
624
    /**
625
     * Shows the right menu of the Social Network tool.
626
     *
627
     * @param string $show                       highlight link possible values:
628
     *                                           group_add,
629
     *                                           home,
630
     *                                           messages,
631
     *                                           messages_inbox,
632
     *                                           messages_compose ,
633
     *                                           messages_outbox,
634
     *                                           invitations,
635
     *                                           shared_profile,
636
     *                                           friends,
637
     *                                           groups search
638
     * @param int    $group_id                   group id
639
     * @param int    $user_id                    user id
640
     * @param bool   $show_full_profile          show profile or not (show or hide the user image/information)
641
     * @param bool   $show_delete_account_button
642
     */
643
    public static function show_social_menu(
644
        $show = '',
645
        $group_id = 0,
646
        $user_id = 0,
647
        $show_full_profile = false,
648
        $show_delete_account_button = false
649
    ) {
650
        $user_id = (int) $user_id;
651
        $group_id = (int) $group_id;
652
653
        if (empty($user_id)) {
654
            $user_id = api_get_user_id();
655
        }
656
657
        $usergroup = new UserGroupModel();
658
        $show_groups = [
659
            'groups',
660
            'group_messages',
661
            'messages_list',
662
            'group_add',
663
            'mygroups',
664
            'group_edit',
665
            'member_list',
666
            'invite_friends',
667
            'waiting_list',
668
            'browse_groups',
669
        ];
670
671
        // get count unread message and total invitations
672
        /*ount_unread_message = MessageManager::getCountNewMessagesFromDB(api_get_user_id());
673
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;*/
674
        $count_unread_message = null;
675
676
        $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
677
        $group_pending_invitations = $usergroup->get_groups_by_user(
678
            api_get_user_id(),
679
            GROUP_USER_PERMISSION_PENDING_INVITATION,
680
            false
681
        );
682
        $group_pending_invitations = count($group_pending_invitations);
683
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
684
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
685
686
        $filesIcon = Display::return_icon('sn-files.png', get_lang('My files'), null, ICON_SIZE_SMALL);
687
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), null, ICON_SIZE_SMALL);
688
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('Social groups'), null, ICON_SIZE_SMALL);
689
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), null, ICON_SIZE_SMALL);
690
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), null, ICON_SIZE_SMALL);
691
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), null, ICON_SIZE_SMALL);
692
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('My shared profile'));
693
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), null, ICON_SIZE_SMALL);
694
        $portfolioIcon = Display::return_icon('wiki_task.png', get_lang('Portfolio'));
695
        $personalDataIcon = Display::return_icon('database.png', get_lang('Personal data'));
696
        $messageSocialIcon = Display::return_icon('promoted_message.png', get_lang('PromotedMessages'));
697
698
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
699
        $groupUrl = api_get_path(WEB_CODE_PATH).'social/groups.php';
700
        if (!empty($forumCourseId)) {
701
            $courseInfo = api_get_course_info_by_id($forumCourseId);
702
            if (!empty($courseInfo)) {
703
                $groupUrl = api_get_path(WEB_CODE_PATH).'forum/index.php?cid='.$courseInfo['real_id'];
704
            }
705
        }
706
707
        $html = '';
708
        $active = null;
709
        if (!in_array(
710
            $show,
711
            ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
712
        )) {
713
            $links = '<ul class="nav-bar">';
714
            $active = 'home' === $show ? 'active' : null;
715
            $links .= '
716
                <li class="home-icon '.$active.'">
717
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
718
                        '.$homeIcon.' '.get_lang('Home').'
719
                    </a>
720
                </li>';
721
            $active = 'messages' === $show ? 'active' : null;
722
            $links .= '
723
                <li class="messages-icon '.$active.'">
724
                    <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
725
                        '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
726
                    </a>
727
                </li>';
728
729
            // Invitations
730
            $active = 'invitations' === $show ? 'active' : null;
731
            $links .= '
732
                <li class="invitations-icon '.$active.'">
733
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
734
                        '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
735
                    </a>
736
                </li>';
737
738
            // Shared profile and groups
739
            $active = 'shared_profile' === $show ? 'active' : null;
740
            $links .= '
741
                <li class="shared-profile-icon'.$active.'">
742
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
743
                        '.$sharedProfileIcon.' '.get_lang('My shared profile').'
744
                    </a>
745
                </li>';
746
            $active = 'friends' === $show ? 'active' : null;
747
            $links .= '
748
                <li class="friends-icon '.$active.'">
749
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
750
                        '.$friendsIcon.' '.get_lang('Friends').'
751
                    </a>
752
                </li>';
753
            $active = 'browse_groups' === $show ? 'active' : null;
754
            $links .= '
755
                <li class="browse-groups-icon '.$active.'">
756
                    <a href="'.$groupUrl.'">
757
                        '.$groupsIcon.' '.get_lang('Social groups').'
758
                    </a>
759
                </li>';
760
761
            // Search users
762
            $active = 'search' === $show ? 'active' : null;
763
            $links .= '
764
                <li class="search-icon '.$active.'">
765
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
766
                        '.$searchIcon.' '.get_lang('Search').'
767
                    </a>
768
                </li>';
769
770
            // My files
771
            $active = 'myfiles' === $show ? 'active' : null;
772
773
            /*$myFiles = '
774
                <li class="myfiles-icon '.$active.'">
775
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
776
                        '.$filesIcon.' '.get_lang('My files').'
777
                    </a>
778
                </li>';
779
780
            if ('false' === api_get_setting('allow_my_files')) {
781
                $myFiles = '';
782
            }
783
            $links .= $myFiles;*/
784
            if (api_get_configuration_value('allow_portfolio_tool')) {
785
                $links .= '
786
                    <li class="portoflio-icon '.('portfolio' === $show ? 'active' : '').'">
787
                        <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
788
                            '.$portfolioIcon.' '.get_lang('Portfolio').'
789
                        </a>
790
                    </li>
791
                ';
792
            }
793
794
            if (!api_get_configuration_value('disable_gdpr')) {
795
                $active = 'personal-data' === $show ? 'active' : null;
796
                $personalData = '
797
                    <li class="personal-data-icon '.$active.'">
798
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
799
                            '.$personalDataIcon.' '.get_lang('Personal data').'
800
                        </a>
801
                    </li>';
802
                $links .= $personalData;
803
            }
804
805
            if (api_is_platform_admin()) {
806
                $active = 'promoted_messages' === $show ? 'active' : null;
807
                $personalData = '
808
                    <li class="personal-data-icon '.$active.'">
809
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/promoted_messages.php">
810
                            '.$messageSocialIcon.' '.get_lang('PromotedMessages').'
811
                        </a>
812
                    </li>';
813
                $links .= $personalData;
814
            }
815
            $links .= '</ul>';
816
            $html .= Display::panelCollapse(
817
                get_lang('Social network'),
818
                $links,
819
                'social-network-menu',
820
                null,
821
                'sn-sidebar',
822
                'sn-sidebar-collapse'
823
            );
824
        }
825
826
        if (!empty($group_id) && in_array($show, $show_groups)) {
827
            $html .= $usergroup->show_group_column_information(
828
                $group_id,
829
                api_get_user_id(),
830
                $show
831
            );
832
        }
833
834
        if ('shared_profile' === $show) {
835
            $links = '<ul class="nav-bar">';
836
            // My own profile
837
            if ($show_full_profile && $user_id == api_get_user_id()) {
838
                $links .= '
839
                    <li class="home-icon '.$active.'">
840
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
841
                            '.$homeIcon.' '.get_lang('Home').'
842
                        </a>
843
                    </li>
844
                    <li class="messages-icon '.$active.'">
845
                        <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
846
                            '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
847
                        </a>
848
                    </li>';
849
                $active = 'invitations' === $show ? 'active' : null;
850
                $links .= '
851
                    <li class="invitations-icon'.$active.'">
852
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
853
                            '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
854
                        </a>
855
                    </li>';
856
857
                $links .= '
858
                    <li class="shared-profile-icon active">
859
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
860
                            '.$sharedProfileIcon.' '.get_lang('My shared profile').'
861
                        </a>
862
                    </li>
863
                    <li class="friends-icon">
864
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
865
                            '.$friendsIcon.' '.get_lang('Friends').'
866
                        </a>
867
                    </li>';
868
869
                $links .= '<li class="browse-groups-icon">
870
                        <a href="'.$groupUrl.'">
871
                            '.$groupsIcon.' '.get_lang('Social groups').'
872
                        </a>
873
                        </li>';
874
875
                $active = 'search' == $show ? 'active' : null;
876
                $links .= '
877
                    <li class="search-icon '.$active.'">
878
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
879
                            '.$searchIcon.' '.get_lang('Search').'
880
                        </a>
881
                    </li>';
882
                $active = 'myfiles' == $show ? 'active' : null;
883
884
                $myFiles = '
885
                    <li class="myfiles-icon '.$active.'">
886
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
887
                            '.$filesIcon.' '.get_lang('My files').'
888
                        </a>
889
                    </li>';
890
891
                if ('false' === api_get_setting('allow_my_files')) {
892
                    $myFiles = '';
893
                }
894
                $links .= $myFiles;
895
896
                if (api_get_configuration_value('allow_portfolio_tool')) {
897
                    $links .= '
898
                        <li class="portoflio-icon '.('portfolio' == $show ? 'active' : '').'">
899
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
900
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
901
                            </a>
902
                        </li>
903
                    ';
904
                }
905
906
                if (!api_get_configuration_value('disable_gdpr')) {
907
                    $active = 'personal-data' == $show ? 'active' : null;
908
                    $personalData = '
909
                    <li class="personal-data-icon '.$active.'">
910
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
911
                            '.$personalDataIcon.' '.get_lang('Personal data').'
912
                        </a>
913
                    </li>';
914
                    $links .= $personalData;
915
                    $links .= '</ul>';
916
                }
917
            }
918
919
            // My friend profile.
920
            if ($user_id != api_get_user_id()) {
921
                $sendMessageText = get_lang('Send message');
922
                $sendMessageIcon = Display::return_icon(
923
                    'new-message.png',
924
                    $sendMessageText
925
                );
926
                $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
927
                    'a' => 'get_user_popup',
928
                    'user_id' => $user_id,
929
                ]);
930
931
                $links .= '<li>';
932
                $links .= Display::url(
933
                    "$sendMessageIcon $sendMessageText",
934
                    $sendMessageUrl,
935
                    [
936
                        'class' => 'ajax',
937
                        'title' => $sendMessageText,
938
                        'data-title' => $sendMessageText,
939
                    ]
940
                );
941
                $links .= '</li>';
942
943
                if (api_get_configuration_value('allow_portfolio_tool')) {
944
                    $links .= '
945
                        <li class="portoflio-icon '.('portfolio' == $show ? 'active' : '').'">
946
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id.'">
947
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
948
                            </a>
949
                        </li>
950
                    ';
951
                }
952
            }
953
954
            // Check if I already sent an invitation message
955
            $invitationSentList = self::get_list_invitation_sent_by_user_id(api_get_user_id());
956
957
            if (isset($invitationSentList[$user_id]) && is_array($invitationSentList[$user_id]) &&
958
                count($invitationSentList[$user_id]) > 0
959
            ) {
960
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
961
                    Display::return_icon('invitation.png', get_lang('You already sent an invitation'))
962
                    .'&nbsp;&nbsp;'.get_lang('You already sent an invitation').'</a></li>';
963
            } else {
964
                if (!$show_full_profile) {
965
                    $links .= '<li>
966
                        <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('Send invitation').'">'.
967
                        Display::return_icon('invitation.png', get_lang('Invite to join my group of friends')).'&nbsp;'.get_lang('Send invitation').
968
                        '</a></li>';
969
                }
970
            }
971
972
            $links .= '</ul>';
973
            $html .= Display::panelCollapse(
974
                get_lang('Social network'),
975
                $links,
976
                'social-network-menu',
977
                null,
978
                'sn-sidebar',
979
                'sn-sidebar-collapse'
980
            );
981
982
            if ($show_full_profile && $user_id == api_get_user_id()) {
983
                // Announcements
984
                $announcements = [];
985
                $announcementsByCourse = AnnouncementManager::getAnnouncementCourseTotalByUser($user_id);
986
987
                if (!empty($announcementsByCourse)) {
988
                    foreach ($announcementsByCourse as $announcement) {
989
                        $resourceLink = $announcement->getFirstResourceLink();
990
                        $course = $resourceLink->getCourse();
991
                        //$courseInfo = api_get_course_info_by_id($announcement->getCId());
992
                        if ($course) {
993
                            $url = Display::url(
994
                                Display::return_icon(
995
                                    'announcement.png',
996
                                    get_lang('Announcements')
997
                                ).$course->getName(),
998
                                api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cid='.$course->getId()
999
                            );
1000
                            $announcements[] = Display::tag('li', $url);
1001
                        }
1002
                    }
1003
                }
1004
1005
                if (!empty($announcements)) {
1006
                    $html .= '<div class="social_menu_items">';
1007
                    $html .= '<ul>';
1008
                    foreach ($announcements as $announcement) {
1009
                        $html .= $announcement;
1010
                    }
1011
                    $html .= '</ul>';
1012
                    $html .= '</div>';
1013
                }
1014
            }
1015
        }
1016
1017
        if ($show_delete_account_button) {
1018
            $html .= '<div class="panel panel-default"><div class="panel-body">';
1019
            $html .= '<ul class="nav-bar"><li>';
1020
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
1021
            $html .= Display::url(
1022
                Display::return_icon(
1023
                    'delete.png',
1024
                    get_lang('Unsubscribe'),
1025
                    [],
1026
                    ICON_SIZE_TINY
1027
                ).get_lang('Unsubscribe'),
1028
                $url
1029
            );
1030
            $html .= '</li></ul>';
1031
            $html .= '</div></div>';
1032
        }
1033
        $html .= '';
1034
1035
        return $html;
1036
    }
1037
1038
    /**
1039
     * Displays a sortable table with the list of online users.
1040
     *
1041
     * @param array $user_list The list of users to be shown
1042
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
1043
     *
1044
     * @return string HTML block or null if and ID was defined
1045
     * @assert (null) === false
1046
     */
1047
    public static function display_user_list($user_list, $wrap = true)
1048
    {
1049
        $html = '';
1050
1051
        if (isset($_GET['id']) || count($user_list) < 1) {
1052
            return false;
1053
        }
1054
1055
        $course_url = '';
1056
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1057
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($_GET['cidReq']) of type array|string 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

1057
            $course_url = '&amp;cidReq='./** @scrutinizer ignore-type */ Security::remove_XSS($_GET['cidReq']);
Loading history...
1058
        }
1059
1060
        $hide = api_get_configuration_value('hide_complete_name_in_whoisonline');
1061
        foreach ($user_list as $uid) {
1062
            $user_info = api_get_user_info($uid, true);
1063
            $lastname = $user_info['lastname'];
1064
            $firstname = $user_info['firstname'];
1065
            $completeName = $firstname.', '.$lastname;
1066
            $user_rol = 1 == $user_info['status'] ? Display::return_icon('teacher.png', get_lang('Trainer'), null, ICON_SIZE_TINY) : Display::return_icon('user.png', get_lang('Learner'), null, ICON_SIZE_TINY);
1067
            $status_icon_chat = null;
1068
            if (isset($user_info['user_is_online_in_chat']) && 1 == $user_info['user_is_online_in_chat']) {
1069
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1070
            } else {
1071
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1072
            }
1073
1074
            $userPicture = $user_info['avatar'];
1075
            $officialCode = '';
1076
            if ('true' === api_get_setting('show_official_code_whoisonline')) {
1077
                $officialCode .= '<div class="items-user-official-code">
1078
                    <p style="min-height: 30px;" title="'.get_lang('Code').'">'.$user_info['official_code'].'</p></div>';
1079
            }
1080
1081
            if (true === $hide) {
1082
                $completeName = '';
1083
                $firstname = '';
1084
                $lastname = '';
1085
            }
1086
1087
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1088
1089
            $url = null;
1090
            // Anonymous users can't have access to the profile
1091
            if (!api_is_anonymous()) {
1092
                if ('true' === api_get_setting('allow_social_tool')) {
1093
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1094
                } else {
1095
                    $url = '?id='.$uid.$course_url;
1096
                }
1097
            } else {
1098
                $url = null;
1099
            }
1100
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1101
1102
            $html .= '<div class="col-xs-6 col-md-2">
1103
                        <div class="items-user">
1104
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1105
                            <div class="items-user-name">
1106
                            '.$name.'
1107
                            </div>
1108
                            '.$officialCode.'
1109
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1110
                        </div>
1111
                      </div>';
1112
        }
1113
1114
        return $html;
1115
    }
1116
1117
    /**
1118
     * @param string $content
1119
     * @param string $span_count
1120
     *
1121
     * @return string
1122
     */
1123
    public static function social_wrapper_div($content, $span_count)
1124
    {
1125
        $span_count = (int) $span_count;
1126
        $html = '<div class="span'.$span_count.'">';
1127
        $html .= '<div class="well_border">';
1128
        $html .= $content;
1129
        $html .= '</div></div>';
1130
1131
        return $html;
1132
    }
1133
1134
    /**
1135
     * Dummy function.
1136
     */
1137
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1138
    {
1139
        $content = '';
1140
        switch ($place) {
1141
            case SOCIAL_CENTER_PLUGIN:
1142
                $social_plugins = [1, 2];
1143
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1144
                    $content .= '<div id="social-plugins">';
1145
                    foreach ($social_plugins as $plugin) {
1146
                        $content .= '<div class="social-plugin-item">';
1147
                        $content .= $plugin;
1148
                        $content .= '</div>';
1149
                    }
1150
                    $content .= '</div>';
1151
                }
1152
                break;
1153
            case SOCIAL_LEFT_PLUGIN:
1154
                break;
1155
            case SOCIAL_RIGHT_PLUGIN:
1156
                break;
1157
        }
1158
1159
        return $content;
1160
    }
1161
1162
    /**
1163
     * Gets all messages from someone's wall (within specific limits).
1164
     *
1165
     * @param int        $userId     id of wall shown
1166
     * @param int|string $parentId   id message (Post main)
1167
     * @param int|array  $groupId
1168
     * @param int|array  $friendId
1169
     * @param string     $startDate  Date from which we want to show the messages, in UTC time
1170
     * @param int        $start      Limit for the number of parent messages we want to show
1171
     * @param int        $length     Wall message query offset
1172
     * @param bool       $getCount
1173
     * @param array      $threadList
1174
     *
1175
     * @return array|int
1176
     *
1177
     * @author Yannick Warnier
1178
     */
1179
    public static function getWallMessages(
1180
        $userId,
1181
        $parentId = 0,
1182
        $groupId = 0,
1183
        $friendId = 0,
1184
        $startDate = '',
1185
        $start = 0,
1186
        $length = 10,
1187
        $getCount = false,
1188
        $threadList = []
1189
    ) {
1190
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1191
1192
        $parentId = (int) $parentId;
1193
        $userId = (int) $userId;
1194
        $start = (int) $start;
1195
        $length = (int) $length;
1196
1197
        $select = " SELECT
1198
                    id,
1199
                    user_sender_id,
1200
                    user_receiver_id,
1201
                    send_date,
1202
                    content,
1203
                    parent_id,
1204
                    msg_status,
1205
                    group_id,
1206
                    '' as forum_id,
1207
                    '' as thread_id,
1208
                    '' as c_id
1209
                  ";
1210
1211
        if ($getCount) {
1212
            $select = ' SELECT count(id) as count_items ';
1213
        }
1214
1215
        $sqlBase = "$select FROM $tblMessage m WHERE ";
1216
        $sql = [];
1217
        $sql[1] = $sqlBase."msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
1218
1219
        // Get my own posts
1220
        $userReceiverCondition = ' (
1221
            user_receiver_id = '.$userId.' AND
1222
            msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
1223
            parent_id = '.$parentId.'
1224
        )';
1225
1226
        $sql[1] .= $userReceiverCondition;
1227
1228
        $sql[2] = $sqlBase.' msg_status = '.MESSAGE_STATUS_PROMOTED.' ';
1229
1230
        // Get my group posts
1231
        $groupCondition = '';
1232
        if (!empty($groupId)) {
1233
            if (is_array($groupId)) {
1234
                $groupId = array_map('intval', $groupId);
1235
                $groupId = implode(",", $groupId);
1236
                $groupCondition = " ( group_id IN ($groupId) ";
1237
            } else {
1238
                $groupId = (int) $groupId;
1239
                $groupCondition = " ( group_id = $groupId ";
1240
            }
1241
            $groupCondition .= ' AND (msg_status = '.MESSAGE_STATUS_NEW.' OR msg_status = '.MESSAGE_STATUS_UNREAD.')) ';
1242
        }
1243
        if (!empty($groupCondition)) {
1244
            $sql[3] = $sqlBase.$groupCondition;
1245
        }
1246
1247
        // Get my friend posts
1248
        $friendCondition = '';
1249
        if (!empty($friendId)) {
1250
            if (is_array($friendId)) {
1251
                $friendId = array_map('intval', $friendId);
1252
                $friendId = implode(",", $friendId);
1253
                $friendCondition = " ( user_receiver_id IN ($friendId) ";
1254
            } else {
1255
                $friendId = (int) $friendId;
1256
                $friendCondition = " ( user_receiver_id = $friendId ";
1257
            }
1258
            $friendCondition .= ' AND msg_status = '.MESSAGE_STATUS_WALL_POST.' AND parent_id = 0) ';
1259
        }
1260
        if (!empty($friendCondition)) {
1261
            $sql[4] = $sqlBase.$friendCondition;
1262
        }
1263
1264
        if (!empty($threadList)) {
1265
            if ($getCount) {
1266
                $select = ' SELECT count(iid) count_items ';
1267
            } else {
1268
                $select = " SELECT
1269
                                iid as id,
1270
                                poster_id as user_sender_id,
1271
                                '' as user_receiver_id,
1272
                                post_date as send_date,
1273
                                post_text as content,
1274
                                '' as parent_id,
1275
                                ".MESSAGE_STATUS_FORUM." as msg_status,
1276
                                '' as group_id,
1277
                                forum_id,
1278
                                thread_id,
1279
                                c_id
1280
                            ";
1281
            }
1282
1283
            $threadList = array_map('intval', $threadList);
1284
            $threadList = implode("','", $threadList);
1285
            $condition = " thread_id IN ('$threadList') ";
1286
            $sql[5] = "$select
1287
                    FROM c_forum_post
1288
                    WHERE $condition
1289
                ";
1290
        }
1291
1292
        if ($getCount) {
1293
            $count = 0;
1294
            foreach ($sql as $oneQuery) {
1295
                if (!empty($oneQuery)) {
1296
                    $res = Database::query($oneQuery);
1297
                    $row = Database::fetch_array($res);
1298
                    $count += (int) $row['count_items'];
1299
                }
1300
            }
1301
1302
            return $count;
1303
        }
1304
1305
        $sqlOrder = ' ORDER BY send_date DESC ';
1306
        $sqlLimit = " LIMIT $start, $length ";
1307
        $messages = [];
1308
        foreach ($sql as $index => $oneQuery) {
1309
            if (5 === $index) {
1310
                // Exception only for the forum query above (field name change)
1311
                $oneQuery .= ' ORDER BY post_date DESC '.$sqlLimit;
1312
            } else {
1313
                $oneQuery .= $sqlOrder.$sqlLimit;
1314
            }
1315
            $res = Database::query($oneQuery);
1316
            $em = Database::getManager();
1317
            if (Database::num_rows($res) > 0) {
1318
                $repo = $em->getRepository(CForumPost::class);
1319
                $repoThread = $em->getRepository(CForumThread::class);
1320
                $groups = [];
1321
                $userGroup = new UserGroupModel();
1322
                $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
1323
                while ($row = Database::fetch_array($res, 'ASSOC')) {
1324
                    $row['group_info'] = [];
1325
                    if (!empty($row['group_id'])) {
1326
                        if (!in_array($row['group_id'], $groups)) {
1327
                            $group = $userGroup->get($row['group_id']);
1328
                            $group['url'] = $urlGroup.$group['id'];
1329
                            $groups[$row['group_id']] = $group;
1330
                            $row['group_info'] = $group;
1331
                        } else {
1332
                            $row['group_info'] = $groups[$row['group_id']];
1333
                        }
1334
                    }
1335
1336
                    // Forums
1337
                    $row['post_title'] = '';
1338
                    $row['forum_title'] = '';
1339
                    $row['thread_url'] = '';
1340
                    if (MESSAGE_STATUS_FORUM === (int) $row['msg_status']) {
1341
                        // @todo use repositories to get post and threads.
1342
                        /** @var CForumPost $post */
1343
                        $post = $repo->find($row['id']);
1344
                        /** @var CForumThread $thread */
1345
                        $thread = $repoThread->find($row['thread_id']);
1346
                        if ($post && $thread) {
1347
                            //$courseInfo = api_get_course_info_by_id($post->getCId());
1348
                            $row['post_title'] = $post->getForum()->getForumTitle();
1349
                            $row['forum_title'] = $thread->getThreadTitle();
1350
                            $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
1351
                                    //'cid' => $courseInfo['real_id'],
1352
                                    'forum' => $post->getForum()->getIid(),
1353
                                    'thread' => $post->getThread()->getIid(),
1354
                                    'post_id' => $post->getIid(),
1355
                                ]).'#post_id_'.$post->getIid();
1356
                        }
1357
                    }
1358
1359
                    $messages[$row['id']] = $row;
1360
                }
1361
            }
1362
        }
1363
        // Reordering messages by ID (reverse order) is enough to have the
1364
        // latest first, as there is currently no option to edit messages
1365
        // afterwards
1366
        krsort($messages);
1367
1368
        return $messages;
1369
    }
1370
1371
    /**
1372
     * @return array
1373
     */
1374
    public static function getAttachmentPreviewList(Message $message)
1375
    {
1376
        $list = [];
1377
        //if (empty($message['group_id'])) {
1378
        $files = $message->getAttachments();
1379
        if ($files) {
0 ignored issues
show
introduced by
$files is of type Doctrine\Common\Collections\Collection, thus it always evaluated to true.
Loading history...
1380
            $repo = Container::getMessageAttachmentRepository();
1381
            /** @var MessageAttachment $file */
1382
            foreach ($files as $file) {
1383
                $url = $repo->getResourceFileUrl($file);
1384
                $display = Display::fileHtmlGuesser($file->getFilename(), $url);
1385
                $list[] = $display;
1386
            }
1387
        }
1388
        /*} else {
1389
            $list = MessageManager::getAttachmentLinkList($messageId, 0);
1390
        }*/
1391
1392
        return $list;
1393
    }
1394
1395
    /**
1396
     * @param array $message
1397
     *
1398
     * @return string
1399
     */
1400
    public static function getPostAttachment($message)
1401
    {
1402
        $previews = self::getAttachmentPreviewList($message);
1403
1404
        if (empty($previews)) {
1405
            return '';
1406
        }
1407
1408
        return implode('', $previews);
1409
    }
1410
1411
    /**
1412
     * @param array $messages
1413
     *
1414
     * @return array
1415
     */
1416
    public static function formatWallMessages($messages)
1417
    {
1418
        $data = [];
1419
        $users = [];
1420
        foreach ($messages as $key => $message) {
1421
            $userIdLoop = $message['user_sender_id'];
1422
            $userFriendIdLoop = $message['user_receiver_id'];
1423
            if (!isset($users[$userIdLoop])) {
1424
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1425
            }
1426
1427
            if (!isset($users[$userFriendIdLoop])) {
1428
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
1429
            }
1430
1431
            $html = self::headerMessagePost(
1432
                $users[$userIdLoop],
1433
                $users[$userFriendIdLoop],
1434
                $message
1435
            );
1436
1437
            $data[$key] = $message;
1438
            $data[$key]['html'] = $html;
1439
        }
1440
1441
        return $data;
1442
    }
1443
1444
    /**
1445
     * get html data with OpenGrap passing the URL.
1446
     *
1447
     * @param $link url
1448
     *
1449
     * @return string data html
1450
     */
1451
    public static function readContentWithOpenGraph($link)
1452
    {
1453
        if (false === strpos($link, "://") && "/" != substr($link, 0, 1)) {
1454
            $link = "http://".$link;
1455
        }
1456
        $graph = OpenGraph::fetch($link);
1457
        $link = parse_url($link);
1458
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
1459
        if (!$graph) {
1460
            return false;
1461
        }
1462
        $url = $graph->url;
1463
        $image = $graph->image;
1464
        $description = $graph->description;
1465
        $title = $graph->title;
1466
        $html = '<div class="thumbnail social-thumbnail">';
1467
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
1468
                <img class="img-responsive social-image" src="'.$image.'" /></a>';
1469
        $html .= '<div class="social-description">';
1470
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
1471
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
1472
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
1473
        $html .= '</div>';
1474
        $html .= '</div>';
1475
1476
        return $html;
1477
    }
1478
1479
    /**
1480
     * verify if Url Exist - Using Curl.
1481
     *
1482
     * @param $uri url
1483
     *
1484
     * @return bool
1485
     */
1486
    public static function verifyUrl($uri)
1487
    {
1488
        $curl = curl_init($uri);
1489
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
1490
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
1491
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1492
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
1493
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
1494
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
1495
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
1496
        $response = curl_exec($curl);
1497
        curl_close($curl);
1498
        if (!empty($response)) {
1499
            return true;
1500
        }
1501
1502
        return false;
1503
    }
1504
1505
    /**
1506
     * Generate the social block for a user.
1507
     *
1508
     * @param int    $userId            The user id
1509
     * @param string $groupBlock        Optional. Highlight link possible values:
1510
     *                                  group_add, home, messages, messages_inbox, messages_compose,
1511
     *                                  messages_outbox, invitations, shared_profile, friends, groups, search
1512
     * @param int    $groupId           Optional. Group ID
1513
     * @param bool   $show_full_profile
1514
     *
1515
     * @return string The HTML code with the social block
1516
     */
1517
    public static function setSocialUserBlock(
1518
        Template $template,
1519
        $userId,
1520
        $groupBlock = '',
1521
        $groupId = 0,
1522
        $show_full_profile = true
1523
    ) {
1524
        if ('true' !== api_get_setting('allow_social_tool')) {
1525
            return '';
1526
        }
1527
1528
        $currentUserId = api_get_user_id();
1529
        $userId = (int) $userId;
1530
        $userRelationType = 0;
1531
1532
        $socialAvatarBlock = self::show_social_avatar_block(
1533
            $groupBlock,
1534
            $groupId,
1535
            $userId
1536
        );
1537
1538
        $profileEditionLink = null;
1539
        if ($currentUserId === $userId) {
1540
            $profileEditionLink = Display::getProfileEditionLink($userId);
1541
        } else {
1542
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
1543
        }
1544
1545
        $options = api_get_configuration_value('profile_fields_visibility');
1546
        if (isset($options['options'])) {
1547
            $options = $options['options'];
1548
        }
1549
1550
        $vCardUserLink = Display::getVCardUserLink($userId);
1551
        if (isset($options['vcard']) && false === $options['vcard']) {
1552
            $vCardUserLink = '';
1553
        }
1554
1555
        $userInfo = api_get_user_info($userId, true, false, true, true);
1556
1557
        if (isset($options['firstname']) && false === $options['firstname']) {
1558
            $userInfo['firstname'] = '';
1559
        }
1560
        if (isset($options['lastname']) && false === $options['lastname']) {
1561
            $userInfo['lastname'] = '';
1562
        }
1563
1564
        if (isset($options['email']) && false === $options['email']) {
1565
            $userInfo['email'] = '';
1566
        }
1567
1568
        // Ofaj
1569
        $hasCertificates = Certificate::getCertificateByUser($userId);
1570
        $userInfo['has_certificates'] = 0;
1571
        if (!empty($hasCertificates)) {
1572
            $userInfo['has_certificates'] = 1;
1573
        }
1574
1575
        $userInfo['is_admin'] = UserManager::is_admin($userId);
1576
        $languageId = api_get_language_from_iso($userInfo['language']);
1577
        $languageInfo = api_get_language_info($languageId);
1578
        if ($languageInfo) {
1579
            $userInfo['language'] = [
1580
                'label' => $languageInfo['original_name'],
1581
                'value' => $languageInfo['english_name'],
1582
                'code' => $languageInfo['isocode'],
1583
            ];
1584
        }
1585
1586
        if (isset($options['language']) && false === $options['language']) {
1587
            $userInfo['language'] = '';
1588
        }
1589
1590
        if (isset($options['photo']) && false === $options['photo']) {
1591
            $socialAvatarBlock = '';
1592
        }
1593
1594
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
1595
        $showLanguageFlag = api_get_configuration_value('social_show_language_flag_in_profile');
1596
1597
        $template->assign('user', $userInfo);
1598
        $template->assign('show_language_flag', $showLanguageFlag);
1599
        $template->assign('extra_info', $extraFieldBlock);
1600
        $template->assign('social_avatar_block', $socialAvatarBlock);
1601
        $template->assign('profile_edition_link', $profileEditionLink);
1602
        //Added the link to export the vCard to the Template
1603
1604
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
1605
        if ($show_full_profile) {
1606
            $template->assign('vcard_user_link', $vCardUserLink);
1607
        }
1608
1609
        if ('1' === api_get_setting('gamification_mode')) {
1610
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
1611
                $userId,
1612
                $userInfo['status']
1613
            );
1614
1615
            $template->assign('gamification_points', $gamificationPoints);
1616
        }
1617
        $chatEnabled = api_is_global_chat_enabled();
1618
1619
        if (isset($options['chat']) && false === $options['chat']) {
1620
            $chatEnabled = '';
1621
        }
1622
1623
        $template->assign('chat_enabled', $chatEnabled);
1624
        $template->assign('user_relation', $userRelationType);
1625
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
1626
        $template->assign('show_full_profile', $show_full_profile);
1627
1628
        $templateName = $template->get_template('social/user_block.tpl');
1629
1630
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
1631
            $templateName = $template->get_template('social/group_block.tpl');
1632
        }
1633
1634
        $template->assign('social_avatar_block', $template->fetch($templateName));
1635
    }
1636
1637
    /**
1638
     * @param int $user_id
1639
     * @param $link_shared
1640
     * @param bool $showLinkToChat
1641
     *
1642
     * @return string
1643
     */
1644
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
1645
    {
1646
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1647
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
1648
        $numberFriends = count($friends);
1649
        $friendHtml = '';
1650
1651
        if (!empty($numberFriends)) {
1652
            $friendHtml .= '<div class="list-group contact-list">';
1653
            $j = 1;
1654
1655
            usort(
1656
                $friends,
1657
                function ($a, $b) {
1658
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
1659
                }
1660
            );
1661
1662
            foreach ($friends as $friend) {
1663
                if ($j > $numberFriends) {
1664
                    break;
1665
                }
1666
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
1667
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
1668
1669
                $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
1670
                $status = 0;
1671
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
1672
                    $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
1673
                    $status = 1;
1674
                }
1675
1676
                $friendAvatarMedium = UserManager::getUserPicture(
1677
                    $friend['friend_user_id'],
1678
                    USER_IMAGE_SIZE_MEDIUM
1679
                );
1680
                $friendAvatarSmall = UserManager::getUserPicture(
1681
                    $friend['friend_user_id'],
1682
                    USER_IMAGE_SIZE_SMALL
1683
                );
1684
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
1685
1686
                $relation = self::get_relation_between_contacts(
1687
                    $friend['friend_user_id'],
1688
                    api_get_user_id()
1689
                );
1690
1691
                if ($showLinkToChat) {
1692
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
1693
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
1694
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
1695
                } else {
1696
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
1697
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
1698
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
1699
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
1700
                }
1701
1702
                $friendHtml .= '</a>';
1703
1704
                $j++;
1705
            }
1706
            $friendHtml .= '</div>';
1707
        } else {
1708
            $friendHtml = Display::return_message(get_lang('No friends in your contact list'), 'warning');
1709
        }
1710
1711
        return $friendHtml;
1712
    }
1713
1714
    /**
1715
     * @return string Get the JS code necessary for social wall to load open graph from URLs.
1716
     */
1717
    public static function getScriptToGetOpenGraph()
1718
    {
1719
        return '<script>
1720
            $(function() {
1721
                $("[name=\'social_wall_new_msg_main\']").on("paste", function(e) {
1722
                    $.ajax({
1723
                        contentType: "application/x-www-form-urlencoded",
1724
                        beforeSend: function() {
1725
                            $("[name=\'wall_post_button\']").prop( "disabled", true );
1726
                            $(".panel-preview").hide();
1727
                            $(".spinner").html("'
1728
                                .'<div class=\'text-center\'>'
1729
                                .'<em class=\'fa fa-spinner fa-pulse fa-1x\'></em>'
1730
                                .'<p>'.get_lang('Loading').' '.get_lang('Preview').'</p>'
1731
                                .'</div>'
1732
                            .'");
1733
                        },
1734
                        type: "POST",
1735
                        url: "'.api_get_path(WEB_AJAX_PATH).'social.ajax.php?a=read_url_with_open_graph",
1736
                        data: "social_wall_new_msg_main=" + e.originalEvent.clipboardData.getData("text"),
1737
                        success: function(response) {
1738
                            $("[name=\'wall_post_button\']").prop("disabled", false);
1739
                            if (!response == false) {
1740
                                $(".spinner").html("");
1741
                                $(".panel-preview").show();
1742
                                $(".url_preview").html(response);
1743
                                $("[name=\'url_content\']").val(response);
1744
                                $(".url_preview img").addClass("img-responsive");
1745
                            } else {
1746
                                $(".spinner").html("");
1747
                            }
1748
                        }
1749
                    });
1750
                });
1751
            });
1752
        </script>';
1753
    }
1754
1755
    /**
1756
     * @param string $urlForm
1757
     *
1758
     * @return string
1759
     */
1760
    public static function getWallForm($urlForm)
1761
    {
1762
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
1763
        $form = new FormValidator(
1764
            'social_wall_main',
1765
            'post',
1766
            $urlForm.$userId,
1767
            null,
1768
            ['enctype' => 'multipart/form-data'],
1769
            FormValidator::LAYOUT_HORIZONTAL
1770
        );
1771
1772
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('Write something on your friend\'s wall') : get_lang(
1773
            'Social wallWhatAreYouThinkingAbout'
1774
        );
1775
1776
        $form->addTextarea(
1777
            'social_wall_new_msg_main',
1778
            null,
1779
            [
1780
                'placeholder' => $socialWallPlaceholder,
1781
                'cols-size' => [1, 12, 1],
1782
                'aria-label' => $socialWallPlaceholder,
1783
            ]
1784
        );
1785
        $form->addHtml('<div class="form-group">');
1786
        $form->addHtml('<div class="col-sm-6">');
1787
        $form->addFile('picture', get_lang('File upload'), ['custom' => true]);
1788
        $form->addHtml('</div>');
1789
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
1790
        $form->addButtonSend(
1791
            get_lang('Post'),
1792
            'wall_post_button',
1793
            false,
1794
            [
1795
                'cols-size' => [1, 10, 1],
1796
                'custom' => true,
1797
            ]
1798
        );
1799
        $form->addHtml('</div></div>');
1800
        $form->addHtml('</div>');
1801
        $form->addHidden('url_content', '');
1802
        $html = Display::panel($form->returnForm(), get_lang('Social wall'));
1803
1804
        return $html;
1805
    }
1806
1807
    /**
1808
     * @param string $message
1809
     * @param string $content
1810
     *
1811
     * @return string
1812
     */
1813
    public static function wrapPost($message, $content)
1814
    {
1815
        $class = '';
1816
        if (MESSAGE_STATUS_PROMOTED === (int) $message['msg_status']) {
1817
            $class = 'promoted_post';
1818
        }
1819
1820
        return Display::panel($content, '',
1821
            '',
1822
            'default',
1823
            '',
1824
            'post_'.$message['id'],
1825
            null,
1826
            $class
1827
        );
1828
    }
1829
1830
    /**
1831
     * Get HTML code block for user skills.
1832
     *
1833
     * @param int    $userId      The user ID
1834
     * @param string $orientation
1835
     *
1836
     * @return string
1837
     */
1838
    public static function getSkillBlock($userId, $orientation = 'horizontal')
1839
    {
1840
        if (false === SkillModel::isAllowed($userId, false)) {
1841
            return '';
1842
        }
1843
1844
        $skill = new SkillModel();
1845
        $ranking = $skill->getUserSkillRanking($userId);
1846
1847
        $template = new Template(null, false, false, false, false, false);
1848
        $template->assign('ranking', $ranking);
1849
        $template->assign('orientation', $orientation);
1850
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
1851
        $template->assign('user_id', $userId);
1852
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
1853
1854
        $skillBlock = $template->get_template('social/skills_block.tpl');
1855
1856
        return $template->fetch($skillBlock);
1857
    }
1858
1859
    /**
1860
     * @param int  $user_id
1861
     * @param bool $isArray
1862
     *
1863
     * @return string|array
1864
     */
1865
    public static function getExtraFieldBlock($user_id, $isArray = false)
1866
    {
1867
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
1868
        $fieldVisibilityKeys = [];
1869
        if (isset($fieldVisibility['options'])) {
1870
            $fieldVisibility = $fieldVisibility['options'];
1871
            $fieldVisibilityKeys = array_keys($fieldVisibility);
1872
        }
1873
1874
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
1875
        $extra_user_data = UserManager::get_extra_user_data($user_id);
1876
1877
        $extra_information = '';
1878
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
1879
            $extra_information_value = '';
1880
            $extraField = new ExtraField('user');
1881
            $listType = [];
1882
            $extraFieldItem = [];
1883
            foreach ($extra_user_data as $key => $data) {
1884
                if (empty($data)) {
1885
                    continue;
1886
                }
1887
                if (in_array($key, $fieldVisibilityKeys) && false === $fieldVisibility[$key]) {
1888
                    continue;
1889
                }
1890
1891
                // Avoiding parameters
1892
                if (in_array(
1893
                    $key,
1894
                    [
1895
                        'mail_notify_invitation',
1896
                        'mail_notify_message',
1897
                        'mail_notify_group_message',
1898
                    ]
1899
                )) {
1900
                    continue;
1901
                }
1902
                // get display text, visibility and type from user_field table
1903
                $field_variable = str_replace('extra_', '', $key);
1904
1905
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
1906
                    $field_variable
1907
                );
1908
1909
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
1910
                    continue;
1911
                }
1912
1913
                // if is not visible skip
1914
                if (1 != $extraFieldInfo['visible_to_self']) {
1915
                    continue;
1916
                }
1917
1918
                // if is not visible to others skip also
1919
                if (1 != $extraFieldInfo['visible_to_others']) {
1920
                    continue;
1921
                }
1922
1923
                if (is_array($data)) {
1924
                    switch ($extraFieldInfo['field_type']) {
1925
                        case ExtraField::FIELD_TYPE_RADIO:
1926
                            $objEfOption = new ExtraFieldOption('user');
1927
                            $value = $data['extra_'.$extraFieldInfo['variable']];
1928
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
1929
                                $extraFieldInfo['id'],
1930
                                $value
1931
                            );
1932
1933
                            if ($optionInfo && isset($optionInfo[0])) {
1934
                                $optionInfo = $optionInfo[0];
1935
                                $extraFieldItem = [
1936
                                    'variable' => $extraFieldInfo['variable'],
1937
                                    'label' => ucfirst($extraFieldInfo['display_text']),
1938
                                    'value' => $optionInfo['display_text'],
1939
                                ];
1940
                            } else {
1941
                                $extraFieldItem = [
1942
                                    'variable' => $extraFieldInfo['variable'],
1943
                                    'label' => ucfirst($extraFieldInfo['display_text']),
1944
                                    'value' => implode(',', $data),
1945
                                ];
1946
                            }
1947
                            break;
1948
                        default:
1949
                            $extra_information_value .=
1950
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
1951
                                .' '.implode(',', $data).'</li>';
1952
                            $extraFieldItem = [
1953
                                'variable' => $extraFieldInfo['variable'],
1954
                                'label' => ucfirst($extraFieldInfo['display_text']),
1955
                                'value' => implode(',', $data),
1956
                            ];
1957
                            break;
1958
                    }
1959
                } else {
1960
                    switch ($extraFieldInfo['field_type']) {
1961
                        case ExtraField::FIELD_TYPE_RADIO:
1962
                            $objEfOption = new ExtraFieldOption('user');
1963
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
1964
                            break;
1965
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
1966
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
1967
                            $data = explode('::', $data);
1968
                            $data = $data[0];
1969
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
1970
                            $extraFieldItem = [
1971
                                'variable' => $extraFieldInfo['variable'],
1972
                                'label' => ucfirst($extraFieldInfo['display_text']),
1973
                                'value' => $data,
1974
                            ];
1975
                            break;
1976
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
1977
                            $id_options = explode('::', $data);
1978
                            $value_options = [];
1979
                            // get option display text from user_field_options table
1980
                            foreach ($id_options as $id_option) {
1981
                                $sql = "SELECT display_text
1982
                                    FROM $t_ufo
1983
                                    WHERE id = '$id_option'";
1984
                                $res_options = Database::query($sql);
1985
                                $row_options = Database::fetch_row($res_options);
1986
                                $value_options[] = $row_options[0];
1987
                            }
1988
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
1989
                                .' '.implode(' ', $value_options).'</li>';
1990
                            $extraFieldItem = [
1991
                                'variable' => $extraFieldInfo['variable'],
1992
                                'label' => ucfirst($extraFieldInfo['display_text']),
1993
                                'value' => $value_options,
1994
                            ];
1995
                            break;
1996
                        case ExtraField::FIELD_TYPE_TAG:
1997
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
1998
1999
                            $tag_tmp = '';
2000
                            foreach ($user_tags as $tags) {
2001
                                $tag_tmp .= '<a class="label label_tag"'
2002
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
2003
                                    .$tags['tag']
2004
                                    .'</a>';
2005
                            }
2006
                            if (is_array($user_tags) && count($user_tags) > 0) {
2007
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2008
                                    .' '.$tag_tmp.'</li>';
2009
                            }
2010
                            $extraFieldItem = [
2011
                                'variable' => $extraFieldInfo['variable'],
2012
                                'label' => ucfirst($extraFieldInfo['display_text']),
2013
                                'value' => $tag_tmp,
2014
                            ];
2015
                            break;
2016
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
2017
                            $icon_path = UserManager::get_favicon_from_url($data);
2018
                            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...
2019
                                break;
2020
                            }
2021
                            $bottom = '0.2';
2022
                            //quick hack for hi5
2023
                            $domain = parse_url($icon_path, PHP_URL_HOST);
2024
                            if ('www.hi5.com' == $domain || 'hi5.com' == $domain) {
2025
                                $bottom = '-0.8';
2026
                            }
2027
                            $data = '<a href="'.$data.'">'
2028
                                .'<img src="'.$icon_path.'" alt="icon"'
2029
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
2030
                                .$extraFieldInfo['display_text']
2031
                                .'</a>';
2032
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
2033
                            $extraFieldItem = [
2034
                                'variable' => $extraFieldInfo['variable'],
2035
                                'label' => ucfirst($extraFieldInfo['display_text']),
2036
                                'value' => $data,
2037
                            ];
2038
                            break;
2039
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
2040
                            $parsedData = explode('::', $data);
2041
2042
                            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...
2043
                                break;
2044
                            }
2045
2046
                            $objEfOption = new ExtraFieldOption('user');
2047
                            $optionInfo = $objEfOption->get($parsedData[0]);
2048
2049
                            $extra_information_value .= '<li class="list-group-item">'
2050
                                .$optionInfo['display_text'].': '
2051
                                .$parsedData[1].'</li>';
2052
                            $extraFieldItem = [
2053
                                'variable' => $extraFieldInfo['variable'],
2054
                                'label' => ucfirst($extraFieldInfo['display_text']),
2055
                                'value' => $parsedData[1],
2056
                            ];
2057
                            break;
2058
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
2059
                            $optionIds = explode(';', $data);
2060
                            $optionValues = [];
2061
2062
                            foreach ($optionIds as $optionId) {
2063
                                $objEfOption = new ExtraFieldOption('user');
2064
                                $optionInfo = $objEfOption->get($optionId);
2065
2066
                                $optionValues[] = $optionInfo['display_text'];
2067
                            }
2068
                            $extra_information_value .= '<li class="list-group-item">'
2069
                                .ucfirst($extraFieldInfo['display_text']).': '
2070
                                .implode(' ', $optionValues).'</li>';
2071
                            $extraFieldItem = [
2072
                                'variable' => $extraFieldInfo['variable'],
2073
                                'label' => ucfirst($extraFieldInfo['display_text']),
2074
                                'value' => implode(' ', $optionValues),
2075
                            ];
2076
                            break;
2077
                        default:
2078
                            // Ofaj
2079
                            // Converts "Date of birth" into "age"
2080
                            if ('terms_datedenaissance' === $key) {
2081
                                $dataArray = date_to_str_ago($data, 'UTC', true);
2082
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
2083
                                if (!empty($dataToString)) {
2084
                                    $data = $dataToString;
2085
                                    $extraFieldInfo['display_text'] = get_lang('Age');
2086
                                }
2087
                            }
2088
2089
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2090
                            $extraFieldItem = [
2091
                                'variable' => $extraFieldInfo['variable'],
2092
                                'label' => ucfirst($extraFieldInfo['display_text']),
2093
                                'value' => $data,
2094
                            ];
2095
                            break;
2096
                    }
2097
                }
2098
2099
                $listType[] = $extraFieldItem;
2100
            }
2101
2102
            if ($isArray) {
2103
                return $listType;
2104
            } else {
2105
                // if there are information to show
2106
                if (!empty($extra_information_value)) {
2107
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
2108
                    $extra_information .= Display::panelCollapse(
2109
                        get_lang('Extra information'),
2110
                        $extra_information_value,
2111
                        'sn-extra-information',
2112
                        null,
2113
                        'sn-extra-accordion',
2114
                        'sn-extra-collapse'
2115
                    );
2116
                }
2117
            }
2118
        }
2119
2120
        return $extra_information;
2121
    }
2122
2123
    /**
2124
     * @param int   $countPost
2125
     * @param array $htmlHeadXtra
2126
     */
2127
    public static function getScrollJs($countPost, &$htmlHeadXtra)
2128
    {
2129
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
2130
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
2131
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
2132
        $locale = api_get_language_isocode();
2133
2134
        // Add Jquery scroll pagination plugin
2135
        //$htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
2136
        // Add Jquery Time ago plugin
2137
        //$htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
2138
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
2139
        if (file_exists($timeAgoLocaleDir)) {
2140
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
2141
        }
2142
2143
        if ($countPost > self::DEFAULT_WALL_POSTS) {
2144
            $htmlHeadXtra[] = '<script>
2145
            $(function() {
2146
                var container = $("#wallMessages");
2147
                container.jscroll({
2148
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
2149
                    nextSelector: "a.nextPage:last",
2150
                    contentSelector: "",
2151
                    callback: timeAgo
2152
                });
2153
            });
2154
            </script>';
2155
        }
2156
2157
        $htmlHeadXtra[] = '<script>
2158
            function deleteMessage(id)
2159
            {
2160
                $.ajax({
2161
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2162
                    success: function (result) {
2163
                        if (result) {
2164
                            $("#message_" + id).parent().parent().parent().parent().html(result);
2165
                        }
2166
                    }
2167
                });
2168
            }
2169
2170
            function deleteComment(id)
2171
            {
2172
                $.ajax({
2173
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2174
                    success: function (result) {
2175
                        if (result) {
2176
                            $("#message_" + id).parent().parent().parent().html(result);
2177
                        }
2178
                    }
2179
                });
2180
            }
2181
2182
            function submitComment(messageId)
2183
            {
2184
                var data = $("#form_comment_"+messageId).serializeArray();
2185
                $.ajax({
2186
                    type : "POST",
2187
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
2188
                    data: data,
2189
                    success: function (result) {
2190
                        if (result) {
2191
                            $("#post_" + messageId + " textarea").val("");
2192
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
2193
                            $("#post_" + messageId + " .sub-mediapost").append(
2194
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved.')).'</div>\')
2195
                            );
2196
2197
                            $("#result_" + messageId + "").fadeIn("fast", function() {
2198
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
2199
                                    $(this).remove();
2200
                                });
2201
                            });
2202
                        }
2203
                    }
2204
                });
2205
            }
2206
2207
            $(function() {
2208
                timeAgo();
2209
2210
                /*$(".delete_message").on("click", function() {
2211
                    var id = $(this).attr("id");
2212
                    id = id.split("_")[1];
2213
                    $.ajax({
2214
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2215
                        success: function (result) {
2216
                            if (result) {
2217
                                $("#message_" + id).parent().parent().parent().parent().html(result);
2218
                            }
2219
                        }
2220
                    });
2221
                });
2222
2223
2224
                $(".delete_comment").on("click", function() {
2225
                    var id = $(this).attr("id");
2226
                    id = id.split("_")[1];
2227
                    $.ajax({
2228
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2229
                        success: function (result) {
2230
                            if (result) {
2231
                                $("#message_" + id).parent().parent().parent().html(result);
2232
                            }
2233
                        }
2234
                    });
2235
                });
2236
                */
2237
            });
2238
2239
            function timeAgo() {
2240
                $(".timeago").timeago();
2241
            }
2242
            </script>';
2243
    }
2244
2245
    /**
2246
     * @param int $userId
2247
     * @param int $countPost
2248
     *
2249
     * @return string
2250
     */
2251
    public static function getAutoExtendLink($userId, $countPost)
2252
    {
2253
        $userId = (int) $userId;
2254
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
2255
        $socialAutoExtendLink = '';
2256
        if ($countPost > self::DEFAULT_WALL_POSTS) {
2257
            $socialAutoExtendLink = Display::url(
2258
                get_lang('See more'),
2259
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
2260
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
2261
                [
2262
                    'class' => 'nextPage next',
2263
                ]
2264
            );
2265
        }
2266
2267
        return $socialAutoExtendLink;
2268
    }
2269
2270
    /**
2271
     * @param int $userId
2272
     *
2273
     * @return array
2274
     */
2275
    public static function getThreadList($userId)
2276
    {
2277
        return [];
2278
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
0 ignored issues
show
Unused Code introduced by
$forumCourseId = api_get...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...
2279
2280
        $threads = [];
2281
        if (!empty($forumCourseId)) {
2282
            $courseInfo = api_get_course_info_by_id($forumCourseId);
2283
            /*getNotificationsPerUser($userId, true, $forumCourseId);
2284
            $notification = Session::read('forum_notification');
2285
            Session::erase('forum_notification');*/
2286
2287
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
2288
                'cid' => $courseInfo['real_id'],
2289
            ]).'&';
2290
            if (isset($notification['thread']) && !empty($notification['thread'])) {
2291
                $threadList = array_filter(array_unique($notification['thread']));
2292
                $repo = Container::getForumThreadRepository();
2293
                foreach ($threadList as $threadId) {
2294
                    /** @var CForumThread $thread */
2295
                    $thread = $repo->find($threadId);
2296
                    if ($thread) {
2297
                        $threadUrl = $threadUrlBase.http_build_query([
2298
                            'forum' => $thread->getForum()->getIid(),
2299
                            'thread' => $thread->getIid(),
2300
                        ]);
2301
                        $threads[] = [
2302
                            'id' => $threadId,
2303
                            'url' => Display::url(
2304
                                $thread->getThreadTitle(),
2305
                                $threadUrl
2306
                            ),
2307
                            'name' => Display::url(
2308
                                $thread->getThreadTitle(),
2309
                                $threadUrl
2310
                            ),
2311
                            'description' => '',
2312
                        ];
2313
                    }
2314
                }
2315
            }
2316
        }
2317
2318
        return $threads;
2319
    }
2320
2321
    /**
2322
     * @param int $userId
2323
     *
2324
     * @return string
2325
     */
2326
    public static function getGroupBlock($userId)
2327
    {
2328
        $threadList = self::getThreadList($userId);
2329
        $userGroup = new UserGroupModel();
2330
2331
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
2332
        $courseInfo = null;
2333
        if (!empty($forumCourseId)) {
2334
            $courseInfo = api_get_course_info_by_id($forumCourseId);
2335
        }
2336
2337
        $social_group_block = '';
2338
        if (!empty($courseInfo)) {
2339
            if (!empty($threadList)) {
2340
                $social_group_block .= '<div class="list-group">';
2341
                foreach ($threadList as $group) {
2342
                    $social_group_block .= ' <li class="list-group-item">';
2343
                    $social_group_block .= $group['name'];
2344
                    $social_group_block .= '</li>';
2345
                }
2346
                $social_group_block .= '</div>';
2347
            }
2348
2349
            $social_group_block .= Display::url(
2350
                get_lang('See all communities'),
2351
                api_get_path(WEB_CODE_PATH).'forum/index.php?cid='.$courseInfo['real_id']
2352
            );
2353
2354
            if (!empty($social_group_block)) {
2355
                $social_group_block = Display::panelCollapse(
2356
                    get_lang('My communities'),
2357
                    $social_group_block,
2358
                    'sm-groups',
2359
                    null,
2360
                    'grups-acordion',
2361
                    'groups-collapse'
2362
                );
2363
            }
2364
        } else {
2365
            // Load my groups
2366
            $results = $userGroup->get_groups_by_user(
2367
                $userId,
2368
                [
2369
                    GROUP_USER_PERMISSION_ADMIN,
2370
                    GROUP_USER_PERMISSION_READER,
2371
                    GROUP_USER_PERMISSION_MODERATOR,
2372
                    GROUP_USER_PERMISSION_HRM,
2373
                ]
2374
            );
2375
2376
            $myGroups = [];
2377
            if (!empty($results)) {
2378
                foreach ($results as $result) {
2379
                    $id = $result['id'];
2380
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
2381
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
2382
2383
                    $group_url = "group_view.php?id=$id";
2384
2385
                    $link = Display::url(
2386
                        api_ucwords(cut($result['name'], 40, true)),
2387
                        $group_url
2388
                    );
2389
2390
                    $result['name'] = $link;
2391
2392
                    $picture = $userGroup->get_picture_group(
2393
                        $id,
2394
                        $result['picture'],
2395
                        null,
2396
                        GROUP_IMAGE_SIZE_BIG
2397
                    );
2398
2399
                    $result['picture'] = '<img class="img-responsive" src="'.$picture.'" />';
2400
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
2401
                        get_lang('See more').'</a></div>';
2402
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
2403
                    $myGroups[] = [
2404
                        'url' => Display::url(
2405
                            $result['picture'],
2406
                            $group_url
2407
                        ),
2408
                        'name' => $result['name'],
2409
                        'description' => $group_info.$group_actions,
2410
                    ];
2411
                }
2412
2413
                $social_group_block .= '<div class="list-group">';
2414
                foreach ($myGroups as $group) {
2415
                    $social_group_block .= ' <li class="list-group-item">';
2416
                    $social_group_block .= $group['name'];
2417
                    $social_group_block .= '</li>';
2418
                }
2419
                $social_group_block .= '</div>';
2420
2421
                $form = new FormValidator(
2422
                    'find_groups_form',
2423
                    'get',
2424
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
2425
                    null,
2426
                    null,
2427
                    FormValidator::LAYOUT_BOX_NO_LABEL
2428
                );
2429
                $form->addHidden('search_type', 2);
2430
2431
                $form->addText(
2432
                    'q',
2433
                    get_lang('Search'),
2434
                    false,
2435
                    [
2436
                        'aria-label' => get_lang('Search'),
2437
                        'custom' => true,
2438
                        'placeholder' => get_lang('Search'),
2439
                    ]
2440
                );
2441
2442
                $social_group_block .= $form->returnForm();
2443
2444
                if (!empty($social_group_block)) {
2445
                    $social_group_block = Display::panelCollapse(
2446
                        get_lang('My groups'),
2447
                        $social_group_block,
2448
                        'sm-groups',
2449
                        null,
2450
                        'grups-acordion',
2451
                        'groups-collapse'
2452
                    );
2453
                }
2454
            }
2455
        }
2456
2457
        return $social_group_block;
2458
    }
2459
2460
    /**
2461
     * @param string $selected
2462
     *
2463
     * @return string
2464
     */
2465
    public static function getHomeProfileTabs($selected = 'home')
2466
    {
2467
        $headers = [
2468
            [
2469
                'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
2470
                'content' => get_lang('Profile'),
2471
            ],
2472
        ];
2473
        $allowJustification = 'true' === api_get_plugin_setting('justification', 'tool_enable');
2474
        if ($allowJustification) {
2475
            $plugin = Justification::create();
2476
            $headers[] = [
2477
                'url' => api_get_path(WEB_CODE_PATH).'auth/justification.php',
2478
                'content' => $plugin->get_lang('Justification'),
2479
            ];
2480
        }
2481
2482
        $allowPauseTraining = 'true' === api_get_plugin_setting('pausetraining', 'tool_enable');
2483
        $allowEdit = 'true' === api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation');
2484
        if ($allowPauseTraining && $allowEdit) {
2485
            $plugin = PauseTraining::create();
2486
            $headers[] = [
2487
                'url' => api_get_path(WEB_CODE_PATH).'auth/pausetraining.php',
2488
                'content' => $plugin->get_lang('PauseTraining'),
2489
            ];
2490
        }
2491
2492
        $selectedItem = 1;
2493
        foreach ($headers as $header) {
2494
            $info = pathinfo($header['url']);
2495
            if ($selected === $info['filename']) {
2496
                break;
2497
            }
2498
            $selectedItem++;
2499
        }
2500
2501
        $tabs = '';
2502
        if (count($headers) > 1) {
2503
            $tabs = Display::tabsOnlyLink($headers, $selectedItem);
2504
        }
2505
2506
        return $tabs;
2507
    }
2508
2509
    /**
2510
     * Returns the formatted header message post.
2511
     *
2512
     * @param int   $authorInfo
2513
     * @param int   $receiverInfo
2514
     * @param array $message      Message data
2515
     *
2516
     * @return string $html       The formatted header message post
2517
     */
2518
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
2519
    {
2520
        $currentUserId = api_get_user_id();
2521
        $authorId = (int) $authorInfo['user_id'];
2522
        $receiverId = (int) $receiverInfo['user_id'];
2523
        $iconStatus = $authorInfo['icon_status'];
2524
2525
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
2526
        $avatarAuthor = $authorInfo['avatar'];
2527
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
2528
        $nameCompleteAuthor = $authorInfo['complete_name'];
2529
2530
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
2531
        $nameCompleteReceiver = $receiverInfo['complete_name'];
2532
2533
        $htmlReceiver = '';
2534
        if ($authorId !== $receiverId) {
2535
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
2536
        }
2537
2538
        if (!empty($message['group_info'])) {
2539
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
2540
        }
2541
        $canEdit = ($currentUserId == $authorInfo['user_id'] || $currentUserId == $receiverInfo['user_id']) && empty($message['group_info']);
2542
2543
        if (!empty($message['thread_id'])) {
2544
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
2545
            $canEdit = false;
2546
        }
2547
2548
        $postAttachment = self::getPostAttachment($message);
2549
2550
        $html = '<div class="top-mediapost" >';
2551
        $html .= '<div class="pull-right btn-group btn-group-sm">';
2552
2553
        $html .= MessageManager::getLikesButton(
2554
            $message['id'],
2555
            $currentUserId,
2556
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
2557
        );
2558
2559
        if ($canEdit) {
2560
            $htmlDelete = Display::url(
2561
                Display::returnFontAwesomeIcon('trash', '', true),
2562
                'javascript:void(0)',
2563
                [
2564
                    'id' => 'message_'.$message['id'],
2565
                    'title' => get_lang('Delete comment'),
2566
                    'onclick' => 'deleteMessage('.$message['id'].')',
2567
                    'class' => 'btn btn-default',
2568
                ]
2569
            );
2570
2571
            $html .= $htmlDelete;
2572
        }
2573
        $html .= '</div>';
2574
2575
        $html .= '<div class="user-image" >';
2576
        $html .= '<a href="'.$urlAuthor.'">
2577
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
2578
        $html .= '</div>';
2579
        $html .= '<div class="user-data">';
2580
        $html .= $iconStatus;
2581
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
2582
        $html .= '<div class="post-date">'.$date.'</div>';
2583
        $html .= '</div>';
2584
        $html .= '<div class="msg-content">';
2585
        if (!empty($postAttachment)) {
2586
            $html .= '<div class="post-attachment thumbnail">';
2587
            $html .= $postAttachment;
2588
            $html .= '</div>';
2589
        }
2590
        $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($message['content']) of type array|string 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

2590
        $html .= '<div>'./** @scrutinizer ignore-type */ Security::remove_XSS($message['content']).'</div>';
Loading history...
2591
        $html .= '</div>';
2592
        $html .= '</div>'; // end mediaPost
2593
2594
        // Popularity post functionality
2595
        $html .= '<div class="popularity-mediapost"></div>';
2596
2597
        return $html;
2598
    }
2599
}
2600