Passed
Push — 1.11.x ( e29810...924a34 )
by Julito
09:59
created

SocialManager::getHomeProfileTabs()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 42
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 26
c 1
b 0
f 0
nc 24
nop 1
dl 0
loc 42
rs 8.5706
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CourseBundle\Entity\CForumPost;
5
use Chamilo\CourseBundle\Entity\CForumThread;
6
use ChamiloSession as Session;
7
use Zend\Feed\Reader\Entry\Rss;
8
use Zend\Feed\Reader\Reader;
9
10
/**
11
 * Class SocialManager.
12
 *
13
 * This class provides methods for the social network management.
14
 * Include/require it in your code to use its features.
15
 */
16
class SocialManager extends UserManager
17
{
18
    const DEFAULT_WALL_POSTS = 10;
19
    const DEFAULT_SCROLL_NEW_POST = 5;
20
21
    /**
22
     * Constructor.
23
     */
24
    public function __construct()
25
    {
26
    }
27
28
    /**
29
     * Allow to see contacts list.
30
     *
31
     * @author isaac flores paz
32
     *
33
     * @return array
34
     */
35
    public static function show_list_type_friends()
36
    {
37
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
38
        $sql = 'SELECT id, title FROM '.$table.'
39
                WHERE id<>6
40
                ORDER BY id ASC';
41
        $result = Database::query($sql);
42
        $friend_relation_list = [];
43
        while ($row = Database::fetch_array($result, 'ASSOC')) {
44
            $friend_relation_list[] = $row;
45
        }
46
        $count_list = count($friend_relation_list);
47
        if ($count_list == 0) {
48
            $friend_relation_list[] = get_lang('Unknown');
49
        } else {
50
            return $friend_relation_list;
51
        }
52
    }
53
54
    /**
55
     * Get the kind of relation between contacts.
56
     *
57
     * @param int user id
58
     * @param int user friend id
59
     * @param string
60
     *
61
     * @return int
62
     *
63
     * @author isaac flores paz
64
     */
65
    public static function get_relation_between_contacts($user_id, $user_friend)
66
    {
67
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
68
        $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
69
        $sql = 'SELECT rt.id as id
70
                FROM '.$table.' rt
71
                WHERE rt.id = (
72
                    SELECT uf.relation_type
73
                    FROM '.$userRelUserTable.' uf
74
                    WHERE
75
                        user_id='.((int) $user_id).' AND
76
                        friend_user_id='.((int) $user_friend).' AND
77
                        uf.relation_type <> '.USER_RELATION_TYPE_RRHH.'
78
                    LIMIT 1
79
                )';
80
        $res = Database::query($sql);
81
        if (Database::num_rows($res) > 0) {
82
            $row = Database::fetch_array($res, 'ASSOC');
83
84
            return $row['id'];
85
        } else {
86
            return USER_UNKNOWN;
87
        }
88
    }
89
90
    /**
91
     * Get count of friends from user.
92
     *
93
     * @param int $userId
94
     *
95
     * @return int
96
     */
97
    public static function getCountFriends($userId)
98
    {
99
        $table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
100
        $userId = (int) $userId;
101
        if (empty($userId)) {
102
            return 0;
103
        }
104
105
        $sql = 'SELECT count(friend_user_id) count
106
                FROM '.$table.'
107
                WHERE
108
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
109
                    friend_user_id<>'.$userId.' AND
110
                    user_id='.$userId;
111
        $res = Database::query($sql);
112
        if (Database::num_rows($res)) {
113
            $row = Database::fetch_array($res, 'ASSOC');
114
115
            return (int) $row['count'];
116
        }
117
118
        return 0;
119
    }
120
121
    /**
122
     * Gets friends id list.
123
     *
124
     * @param int  user id
125
     * @param int group id
126
     * @param string name to search
127
     * @param bool true will load firstname, lastname, and image name
128
     *
129
     * @return array
130
     *
131
     * @author Julio Montoya <[email protected]> Cleaning code, function renamed, $load_extra_info option added
132
     * @author isaac flores paz
133
     */
134
    public static function get_friends(
135
        $user_id,
136
        $id_group = null,
137
        $search_name = null,
138
        $load_extra_info = true
139
    ) {
140
        $user_id = (int) $user_id;
141
142
        $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
143
        $tbl_my_user = Database::get_main_table(TABLE_MAIN_USER);
144
        $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
145
                WHERE
146
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
147
                    friend_user_id<>'.$user_id.' AND
148
                    user_id='.$user_id;
149
        if (isset($id_group) && $id_group > 0) {
150
            $sql .= ' AND relation_type='.$id_group;
151
        }
152
        if (isset($search_name)) {
153
            $search_name = trim($search_name);
154
            $search_name = str_replace(' ', '', $search_name);
155
            $sql .= ' AND friend_user_id IN (
156
                SELECT user_id FROM '.$tbl_my_user.'
157
                WHERE
158
                    firstName LIKE "%'.Database::escape_string($search_name).'%" OR
159
                    lastName LIKE "%'.Database::escape_string($search_name).'%" OR
160
                    '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
161
                ) ';
162
        }
163
164
        $res = Database::query($sql);
165
        $list = [];
166
        while ($row = Database::fetch_array($res, 'ASSOC')) {
167
            if ($load_extra_info) {
168
                $userInfo = api_get_user_info($row['friend_user_id']);
169
                $list[] = [
170
                    'friend_user_id' => $row['friend_user_id'],
171
                    'firstName' => $userInfo['firstName'],
172
                    'lastName' => $userInfo['lastName'],
173
                    'username' => $userInfo['username'],
174
                    'image' => $userInfo['avatar'],
175
                    'user_info' => $userInfo,
176
                ];
177
            } else {
178
                $list[] = $row;
179
            }
180
        }
181
182
        return $list;
183
    }
184
185
    /**
186
     * get web path of user invitate.
187
     *
188
     * @author isaac flores paz
189
     * @author Julio Montoya setting variable array
190
     *
191
     * @param int user id
192
     *
193
     * @return array
194
     */
195
    public static function get_list_web_path_user_invitation_by_user_id($user_id)
196
    {
197
        $list_ids = self::get_list_invitation_of_friends_by_user_id($user_id);
198
        $list = [];
199
        foreach ($list_ids as $values_ids) {
200
            $list[] = UserManager::get_user_picture_path_by_id(
201
                $values_ids['user_sender_id'],
202
                'web'
203
            );
204
        }
205
206
        return $list;
207
    }
208
209
    /**
210
     * Sends an invitation to contacts.
211
     *
212
     * @param int user id
213
     * @param int user friend id
214
     * @param string title of the message
215
     * @param string content of the message
216
     *
217
     * @return bool
218
     *
219
     * @author isaac flores paz
220
     * @author Julio Montoya <[email protected]> Cleaning code
221
     */
222
    public static function send_invitation_friend(
223
        $user_id,
224
        $friend_id,
225
        $message_title,
226
        $message_content
227
    ) {
228
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
229
        $user_id = (int) $user_id;
230
        $friend_id = (int) $friend_id;
231
232
        //Just in case we replace the and \n and \n\r while saving in the DB
233
        $message_content = str_replace(["\n", "\n\r"], '<br />', $message_content);
234
235
        $clean_message_content = Database::escape_string($message_content);
236
        $now = api_get_utc_datetime();
237
        $sql = 'SELECT COUNT(*) AS count FROM '.$tbl_message.'
238
                WHERE
239
                    user_sender_id='.$user_id.' AND
240
                    user_receiver_id='.$friend_id.' AND
241
                    msg_status IN('.MESSAGE_STATUS_INVITATION_PENDING.', '.MESSAGE_STATUS_INVITATION_ACCEPTED.', '.MESSAGE_STATUS_INVITATION_DENIED.');
242
                ';
243
        $res_exist = Database::query($sql);
244
        $row_exist = Database::fetch_array($res_exist, 'ASSOC');
245
246
        if ($row_exist['count'] == 0) {
247
            $params = [
248
                'user_sender_id' => $user_id,
249
                'user_receiver_id' => $friend_id,
250
                'msg_status' => MESSAGE_STATUS_INVITATION_PENDING,
251
                'send_date' => $now,
252
                'title' => $message_title,
253
                'content' => $message_content,
254
                'group_id' => 0,
255
                'parent_id' => 0,
256
                'update_date' => $now,
257
            ];
258
            $messageId = Database::insert($tbl_message, $params);
259
260
            $senderInfo = api_get_user_info($user_id);
261
            $notification = new Notification();
262
            $notification->saveNotification(
263
                $messageId,
264
                Notification::NOTIFICATION_TYPE_INVITATION,
265
                [$friend_id],
266
                $message_title,
267
                $message_content,
268
                $senderInfo
269
            );
270
271
            return true;
272
        } else {
273
            // invitation already exist
274
            $sql = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
275
                    WHERE
276
                        user_sender_id='.$user_id.' AND
277
                        user_receiver_id='.$friend_id.' AND
278
                        msg_status = 7';
279
            $res_if_exist = Database::query($sql);
280
            $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
281
            if ($row_if_exist['count'] == 1) {
282
                $sql = 'UPDATE '.$tbl_message.' SET
283
                            msg_status = 5, content = "'.$clean_message_content.'"
284
                        WHERE
285
                            user_sender_id='.$user_id.' AND
286
                            user_receiver_id='.$friend_id.' AND
287
                            msg_status = 7 ';
288
                Database::query($sql);
289
290
                return true;
291
            } else {
292
                return false;
293
            }
294
        }
295
    }
296
297
    /**
298
     * Get number messages of the inbox.
299
     *
300
     * @author isaac flores paz
301
     *
302
     * @param int $userId user receiver id
303
     *
304
     * @return int
305
     */
306
    public static function get_message_number_invitation_by_user_id($userId)
307
    {
308
        $table = Database::get_main_table(TABLE_MESSAGE);
309
        $userId = (int) $userId;
310
        $sql = 'SELECT COUNT(*) as count_message_in_box FROM '.$table.'
311
                WHERE
312
                    user_receiver_id='.$userId.' AND
313
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
314
        $res = Database::query($sql);
315
        $row = Database::fetch_array($res, 'ASSOC');
316
        if ($row) {
317
            return (int) $row['count_message_in_box'];
318
        }
319
320
        return 0;
321
    }
322
323
    /**
324
     * Get number of messages sent to other users.
325
     *
326
     * @param int $userId
327
     *
328
     * @return int
329
     */
330
    public static function getCountMessagesSent($userId)
331
    {
332
        $userId = (int) $userId;
333
        $table = Database::get_main_table(TABLE_MESSAGE);
334
        $sql = 'SELECT COUNT(*) FROM '.$table.'
335
                WHERE
336
                    user_sender_id='.$userId.' AND
337
                    msg_status < 5';
338
        $res = Database::query($sql);
339
        $row = Database::fetch_row($res);
340
341
        return $row[0];
342
    }
343
344
    /**
345
     * Get number of messages received from other users.
346
     *
347
     * @param int $receiver_id
348
     *
349
     * @return int
350
     */
351
    public static function getCountMessagesReceived($receiver_id)
352
    {
353
        $table = Database::get_main_table(TABLE_MESSAGE);
354
        $sql = 'SELECT COUNT(*) FROM '.$table.'
355
                WHERE
356
                    user_receiver_id='.intval($receiver_id).' AND
357
                    msg_status < 4';
358
        $res = Database::query($sql);
359
        $row = Database::fetch_row($res);
360
361
        return $row[0];
362
    }
363
364
    /**
365
     * Get number of messages posted on own wall.
366
     *
367
     * @param int $userId
368
     *
369
     * @return int
370
     */
371
    public static function getCountWallPostedMessages($userId)
372
    {
373
        $userId = (int) $userId;
374
375
        if (empty($userId)) {
376
            return 0;
377
        }
378
379
        $table = Database::get_main_table(TABLE_MESSAGE);
380
        $sql = 'SELECT COUNT(*)
381
                FROM '.$table.'
382
                WHERE
383
                    user_sender_id='.$userId.' AND
384
                    (msg_status = '.MESSAGE_STATUS_WALL.' OR
385
                    msg_status = '.MESSAGE_STATUS_WALL_POST.') AND
386
                    parent_id = 0';
387
        $res = Database::query($sql);
388
        $row = Database::fetch_row($res);
389
390
        return $row[0];
391
    }
392
393
    /**
394
     * Get invitation list received by user.
395
     *
396
     * @author isaac flores paz
397
     *
398
     * @param int $userId
399
     * @param int $limit
400
     *
401
     * @return array
402
     */
403
    public static function get_list_invitation_of_friends_by_user_id($userId, $limit = 0)
404
    {
405
        $userId = (int) $userId;
406
        $limit = (int) $limit;
407
408
        if (empty($userId)) {
409
            return [];
410
        }
411
412
        $table = Database::get_main_table(TABLE_MESSAGE);
413
        $sql = 'SELECT user_sender_id, send_date, title, content
414
                FROM '.$table.'
415
                WHERE
416
                    user_receiver_id = '.$userId.' AND
417
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
418
        if ($limit != null && $limit > 0) {
419
            $sql .= ' LIMIT '.$limit;
420
        }
421
        $res = Database::query($sql);
422
        $list = [];
423
        while ($row = Database::fetch_array($res, 'ASSOC')) {
424
            $list[] = $row;
425
        }
426
427
        return $list;
428
    }
429
430
    /**
431
     * Get invitation list sent by user.
432
     *
433
     * @author Julio Montoya <[email protected]>
434
     *
435
     * @param int $userId
436
     *
437
     * @return array
438
     */
439
    public static function get_list_invitation_sent_by_user_id($userId)
440
    {
441
        $userId = (int) $userId;
442
443
        if (empty($userId)) {
444
            return [];
445
        }
446
447
        $table = Database::get_main_table(TABLE_MESSAGE);
448
        $sql = 'SELECT user_receiver_id, send_date,title,content
449
                FROM '.$table.'
450
                WHERE
451
                    user_sender_id = '.$userId.' AND
452
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
453
        $res = Database::query($sql);
454
        $list = [];
455
        while ($row = Database::fetch_array($res, 'ASSOC')) {
456
            $list[$row['user_receiver_id']] = $row;
457
        }
458
459
        return $list;
460
    }
461
462
    /**
463
     * Get count invitation sent by user.
464
     *
465
     * @author Julio Montoya <[email protected]>
466
     *
467
     * @param int $userId
468
     *
469
     * @return int
470
     */
471
    public static function getCountInvitationSent($userId)
472
    {
473
        $userId = (int) $userId;
474
475
        if (empty($userId)) {
476
            return 0;
477
        }
478
479
        $table = Database::get_main_table(TABLE_MESSAGE);
480
        $sql = 'SELECT count(user_receiver_id) count
481
                FROM '.$table.'
482
                WHERE
483
                    user_sender_id = '.$userId.' AND
484
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
485
        $res = Database::query($sql);
486
        if (Database::num_rows($res)) {
487
            $row = Database::fetch_array($res, 'ASSOC');
488
489
            return (int) $row['count'];
490
        }
491
492
        return 0;
493
    }
494
495
    /**
496
     * Accepts invitation.
497
     *
498
     * @param int $user_send_id
499
     * @param int $user_receiver_id
500
     *
501
     * @return bool
502
     *
503
     * @author isaac flores paz
504
     * @author Julio Montoya <[email protected]> Cleaning code
505
     */
506
    public static function invitation_accepted($user_send_id, $user_receiver_id)
507
    {
508
        if (empty($user_send_id) || empty($user_receiver_id)) {
509
            return false;
510
        }
511
512
        $table = Database::get_main_table(TABLE_MESSAGE);
513
        $sql = "UPDATE $table
514
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
515
                WHERE
516
                    user_sender_id = ".((int) $user_send_id)." AND
517
                    user_receiver_id=".((int) $user_receiver_id)." AND
518
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
519
        Database::query($sql);
520
521
        return true;
522
    }
523
524
    /**
525
     * Denies invitation.
526
     *
527
     * @param int user sender id
528
     * @param int user receiver id
529
     *
530
     * @return bool
531
     *
532
     * @author isaac flores paz
533
     * @author Julio Montoya <[email protected]> Cleaning code
534
     */
535
    public static function invitation_denied($user_send_id, $user_receiver_id)
536
    {
537
        if (empty($user_send_id) || empty($user_receiver_id)) {
538
            return false;
539
        }
540
        $table = Database::get_main_table(TABLE_MESSAGE);
541
        $sql = 'DELETE FROM '.$table.'
542
                WHERE
543
                    user_sender_id =  '.((int) $user_send_id).' AND
544
                    user_receiver_id='.((int) $user_receiver_id).' AND
545
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
546
        Database::query($sql);
547
548
        return true;
549
    }
550
551
    /**
552
     * Get user's feeds.
553
     *
554
     * @param int $user  User ID
555
     * @param int $limit Limit of posts per feed
556
     *
557
     * @return string HTML section with all feeds included
558
     *
559
     * @author  Yannick Warnier
560
     *
561
     * @since   Dokeos 1.8.6.1
562
     */
563
    public static function getUserRssFeed($user, $limit = 5)
564
    {
565
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
566
567
        if (empty($feed)) {
568
            return '';
569
        }
570
        $feeds = explode(';', $feed['rssfeeds']);
571
        if (0 == count($feeds)) {
572
            return '';
573
        }
574
        $res = '';
575
        foreach ($feeds as $url) {
576
            if (empty($url)) {
577
                continue;
578
            }
579
            try {
580
                $channel = Reader::import($url);
581
                $i = 1;
582
                if (!empty($channel)) {
583
                    $iconRss = '';
584
                    if (!empty($feed)) {
585
                        $iconRss = Display::url(
586
                            Display::return_icon('social_rss.png', '', [], 22),
587
                            Security::remove_XSS($feed['rssfeeds']),
588
                            ['target' => '_blank']
589
                        );
590
                    }
591
592
                    $res .= '<h3 class="title-rss">'.$iconRss.' '.$channel->getTitle().'</h3>';
593
                    $res .= '<div class="rss-items">';
594
                    /** @var Rss $item */
595
                    foreach ($channel as $item) {
596
                        if ($limit >= 0 and $i > $limit) {
597
                            break;
598
                        }
599
                        $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
600
                        $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
601
                        $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
602
                        $i++;
603
                    }
604
                    $res .= '</div>';
605
                }
606
            } catch (Exception $e) {
607
                error_log($e->getMessage());
608
            }
609
        }
610
611
        return $res;
612
    }
613
614
    /**
615
     * Sends invitations to friends.
616
     *
617
     * @param int    $userId
618
     * @param string $subject
619
     * @param string $content
620
     *
621
     * @return bool
622
     */
623
    public static function sendInvitationToUser($userId, $subject = '', $content = '')
624
    {
625
        $user_info = api_get_user_info($userId);
626
        $success = get_lang('MessageSentTo');
627
        $success .= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
628
629
        if (isset($subject) && isset($content) && isset($userId)) {
630
            $result = MessageManager::send_message($userId, $subject, $content);
631
632
            if ($result) {
633
                Display::addFlash(
634
                    Display::return_message($success, 'normal', false)
635
                );
636
            } else {
637
                Display::addFlash(
638
                    Display::return_message(get_lang('ErrorSendingMessage'), 'error', false)
639
                );
640
            }
641
642
            return false;
643
        } elseif (isset($userId) && !isset($subject)) {
644
            if (isset($userId) && $userId > 0) {
645
                $count = self::send_invitation_friend(
646
                    api_get_user_id(),
647
                    $userId,
648
                    get_lang('Invitation'),
649
                    $content
650
                );
651
652
                if ($count) {
653
                    Display::addFlash(
654
                        Display::return_message(
655
                            api_htmlentities(get_lang('InvitationHasBeenSent')),
656
                            'normal',
657
                            false
658
                        )
659
                    );
660
                } else {
661
                    Display::addFlash(
662
                        Display::return_message(
663
                            api_htmlentities(get_lang('YouAlreadySentAnInvitation')),
664
                            'warning',
665
                            false
666
                        )
667
                    );
668
                }
669
            }
670
        }
671
    }
672
673
    /**
674
     * Helper functions definition.
675
     */
676
    public static function get_logged_user_course_html($my_course, $count)
677
    {
678
        $result = '';
679
        $count = (int) $count;
680
681
        // Table definitions
682
        $main_user_table = Database::get_main_table(TABLE_MAIN_USER);
683
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
684
        $course_directory = $my_course['course_info']['directory'];
685
        $course_title = $my_course['course_info']['title'];
686
        $course_visibility = $my_course['course_info']['visibility'];
687
688
        $user_in_course_status = CourseManager::getUserInCourseStatus(
689
            api_get_user_id(),
690
            $my_course['course_info']['real_id']
691
        );
692
693
        $course_path = api_get_path(SYS_COURSE_PATH).$course_directory; // course path
694
        if (api_get_setting('course_images_in_courses_list') === 'true') {
695
            if (file_exists($course_path.'/course-pic85x85.png')) {
696
                $image = $my_course['course_info']['course_image'];
697
                $imageCourse = Display::img($image, $course_title, ['class' => 'img-course']);
698
            } else {
699
                $imageCourse = Display::return_icon(
700
                    'session_default_small.png',
701
                    $course_title,
702
                    ['class' => 'img-course']
703
                );
704
            }
705
        } else {
706
            $imageCourse = Display::return_icon(
707
                'course.png',
708
                get_lang('Course'),
709
                ['class' => 'img-default']
710
            );
711
        }
712
713
        //display course entry
714
        if (api_get_setting('course_images_in_courses_list') === 'true') {
715
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:65px;">';
716
        } else {
717
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:44px;">';
718
        }
719
        $result .= $imageCourse;
720
721
        //show a hyperlink to the course, unless the course is closed and user is not course admin
722
        if ($course_visibility != COURSE_VISIBILITY_HIDDEN &&
723
            ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER)
724
        ) {
725
            $result .= '<span class="title">'.$course_title.'<span>';
726
        } else {
727
            $result .= $course_title.' '.get_lang('CourseClosed');
728
        }
729
730
        $result .= '</li>';
731
        $session = '';
732
        if (!empty($my_course['session_name']) && !empty($my_course['id_session'])) {
733
            // Request for the name of the general coach
734
            $sql = 'SELECT lastname, firstname
735
                    FROM '.$tbl_session.' ts
736
                    LEFT JOIN '.$main_user_table.' tu
737
                    ON ts.id_coach = tu.user_id
738
                    WHERE ts.id='.(int) $my_course['id_session'].' LIMIT 1';
739
            $rs = Database::query($sql);
740
            $sessioncoach = Database::store_result($rs);
741
            $sessioncoach = $sessioncoach[0];
742
743
            $session = [];
744
            $session['title'] = $my_course['session_name'];
745
            if ($my_course['access_start_date'] == '0000-00-00') {
746
                $session['dates'] = get_lang('WithoutTimeLimits');
747
                if (api_get_setting('show_session_coach') === 'true') {
748
                    $session['coach'] = get_lang('GeneralCoach').': '.
749
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
750
                }
751
            } else {
752
                $session['dates'] = ' - '.get_lang('From').' '.$my_course['access_start_date'].' '.get_lang('To').' '.$my_course['access_end_date'];
753
                if (api_get_setting('show_session_coach') === 'true') {
754
                    $session['coach'] = get_lang('GeneralCoach').': '.
755
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
756
                }
757
            }
758
        }
759
760
        $my_course['id_session'] = isset($my_course['id_session']) ? $my_course['id_session'] : 0;
761
        $output = [
762
            $my_course['user_course_cat'],
763
            $result,
764
            $my_course['id_session'],
765
            $session,
766
        ];
767
768
        return $output;
769
    }
770
771
    /**
772
     * Shows the avatar block in social pages.
773
     *
774
     * @param string $show     highlight link possible values:
775
     *                         group_add,
776
     *                         home,
777
     *                         messages,
778
     *                         messages_inbox,
779
     *                         messages_compose,
780
     *                         messages_outbox,
781
     *                         invitations,
782
     *                         shared_profile,
783
     *                         friends,
784
     *                         groups search
785
     * @param int    $group_id
786
     * @param int    $user_id
787
     */
788
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
789
    {
790
        $user_id = (int) $user_id;
791
        $group_id = (int) $group_id;
792
793
        if (empty($user_id)) {
794
            $user_id = api_get_user_id();
795
        }
796
797
        $show_groups = [
798
            'groups',
799
            'group_messages',
800
            'messages_list',
801
            'group_add',
802
            'mygroups',
803
            'group_edit',
804
            'member_list',
805
            'invite_friends',
806
            'waiting_list',
807
            'browse_groups',
808
        ];
809
810
        $template = new Template(null, false, false, false, false, false);
811
812
        if (in_array($show, $show_groups) && !empty($group_id)) {
813
            // Group image
814
            $userGroup = new UserGroup();
815
            $group_info = $userGroup->get($group_id);
816
817
            $userGroupImage = $userGroup->get_picture_group(
818
                $group_id,
819
                $group_info['picture'],
820
                128,
821
                GROUP_IMAGE_SIZE_BIG
822
            );
823
824
            $template->assign('show_group', true);
825
            $template->assign('group_id', $group_id);
826
            $template->assign('user_group_image', $userGroupImage);
827
            $template->assign(
828
                'user_is_group_admin',
829
                $userGroup->is_group_admin(
830
                    $group_id,
831
                    api_get_user_id()
832
                )
833
            );
834
        } else {
835
            $template->assign('show_group', false);
836
            $template->assign('show_user', true);
837
            $template->assign(
838
                'user_image',
839
                [
840
                    'big' => UserManager::getUserPicture(
841
                        $user_id,
842
                        USER_IMAGE_SIZE_BIG
843
                    ),
844
                    'normal' => UserManager::getUserPicture(
845
                        $user_id,
846
                        USER_IMAGE_SIZE_MEDIUM
847
                    ),
848
                ]
849
            );
850
        }
851
852
        return $template->fetch($template->get_template('social/avatar_block.tpl'));
853
    }
854
855
    /**
856
     * Shows the right menu of the Social Network tool.
857
     *
858
     * @param string $show                       highlight link possible values:
859
     *                                           group_add,
860
     *                                           home,
861
     *                                           messages,
862
     *                                           messages_inbox,
863
     *                                           messages_compose ,
864
     *                                           messages_outbox,
865
     *                                           invitations,
866
     *                                           shared_profile,
867
     *                                           friends,
868
     *                                           groups search
869
     * @param int    $group_id                   group id
870
     * @param int    $user_id                    user id
871
     * @param bool   $show_full_profile          show profile or not (show or hide the user image/information)
872
     * @param bool   $show_delete_account_button
873
     */
874
    public static function show_social_menu(
875
        $show = '',
876
        $group_id = 0,
877
        $user_id = 0,
878
        $show_full_profile = false,
879
        $show_delete_account_button = false
880
    ) {
881
        $user_id = (int) $user_id;
882
        $group_id = (int) $group_id;
883
884
        if (empty($user_id)) {
885
            $user_id = api_get_user_id();
886
        }
887
888
        $usergroup = new UserGroup();
889
        $show_groups = [
890
            'groups',
891
            'group_messages',
892
            'messages_list',
893
            'group_add',
894
            'mygroups',
895
            'group_edit',
896
            'member_list',
897
            'invite_friends',
898
            'waiting_list',
899
            'browse_groups',
900
        ];
901
902
        // get count unread message and total invitations
903
        $count_unread_message = MessageManager::getCountNewMessagesFromDB(api_get_user_id());
904
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
905
906
        $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
907
        $group_pending_invitations = $usergroup->get_groups_by_user(
908
            api_get_user_id(),
909
            GROUP_USER_PERMISSION_PENDING_INVITATION,
910
            false
911
        );
912
        $group_pending_invitations = count($group_pending_invitations);
913
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
914
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
915
916
        $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), null, ICON_SIZE_SMALL);
917
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), null, ICON_SIZE_SMALL);
918
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), null, ICON_SIZE_SMALL);
919
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), null, ICON_SIZE_SMALL);
920
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), null, ICON_SIZE_SMALL);
921
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), null, ICON_SIZE_SMALL);
922
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
923
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), null, ICON_SIZE_SMALL);
924
        $portfolioIcon = Display::return_icon('wiki_task.png', get_lang('Portfolio'));
925
        $personalDataIcon = Display::return_icon('database.png', get_lang('PersonalDataReport'));
926
        $messageSocialIcon = Display::return_icon('promoted_message.png', get_lang('PromotedMessages'));
927
928
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
929
        $groupUrl = api_get_path(WEB_CODE_PATH).'social/groups.php';
930
        if (!empty($forumCourseId)) {
931
            $courseInfo = api_get_course_info_by_id($forumCourseId);
932
            if (!empty($courseInfo)) {
933
                $groupUrl = api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code'];
934
            }
935
        }
936
937
        $html = '';
938
        $active = null;
939
        if (!in_array(
940
            $show,
941
            ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
942
        )) {
943
            $links = '<ul class="nav nav-pills nav-stacked">';
944
            $active = $show === 'home' ? 'active' : null;
945
            $links .= '
946
                <li class="home-icon '.$active.'">
947
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
948
                        '.$homeIcon.' '.get_lang('Home').'
949
                    </a>
950
                </li>';
951
            $active = $show === 'messages' ? 'active' : null;
952
            $links .= '
953
                <li class="messages-icon '.$active.'">
954
                    <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
955
                        '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
956
                    </a>
957
                </li>';
958
959
            // Invitations
960
            $active = $show === 'invitations' ? 'active' : null;
961
            $links .= '
962
                <li class="invitations-icon '.$active.'">
963
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
964
                        '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
965
                    </a>
966
                </li>';
967
968
            // Shared profile and groups
969
            $active = $show === 'shared_profile' ? 'active' : null;
970
            $links .= '
971
                <li class="shared-profile-icon'.$active.'">
972
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
973
                        '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
974
                    </a>
975
                </li>';
976
            $active = $show === 'friends' ? 'active' : null;
977
            $links .= '
978
                <li class="friends-icon '.$active.'">
979
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
980
                        '.$friendsIcon.' '.get_lang('Friends').'
981
                    </a>
982
                </li>';
983
            $active = $show === 'browse_groups' ? 'active' : null;
984
            $links .= '
985
                <li class="browse-groups-icon '.$active.'">
986
                    <a href="'.$groupUrl.'">
987
                        '.$groupsIcon.' '.get_lang('SocialGroups').'
988
                    </a>
989
                </li>';
990
991
            // Search users
992
            $active = $show === 'search' ? 'active' : null;
993
            $links .= '
994
                <li class="search-icon '.$active.'">
995
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
996
                        '.$searchIcon.' '.get_lang('Search').'
997
                    </a>
998
                </li>';
999
1000
            // My files
1001
            $active = $show === 'myfiles' ? 'active' : null;
1002
1003
            $myFiles = '
1004
                <li class="myfiles-icon '.$active.'">
1005
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1006
                        '.$filesIcon.' '.get_lang('MyFiles').'
1007
                    </a>
1008
                </li>';
1009
1010
            if (api_get_setting('allow_my_files') === 'false') {
1011
                $myFiles = '';
1012
            }
1013
            $links .= $myFiles;
1014
            if (api_get_configuration_value('allow_portfolio_tool')) {
1015
                $links .= '
1016
                    <li class="portoflio-icon '.($show === 'portfolio' ? 'active' : '').'">
1017
                        <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1018
                            '.$portfolioIcon.' '.get_lang('Portfolio').'
1019
                        </a>
1020
                    </li>
1021
                ';
1022
            }
1023
1024
            if (!api_get_configuration_value('disable_gdpr')) {
1025
                $active = $show === 'personal-data' ? 'active' : null;
1026
                $personalData = '
1027
                    <li class="personal-data-icon '.$active.'">
1028
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1029
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1030
                        </a>
1031
                    </li>';
1032
                $links .= $personalData;
1033
            }
1034
1035
            if (api_is_platform_admin()) {
1036
                $active = $show === 'promoted_messages' ? 'active' : null;
1037
                $personalData = '
1038
                    <li class="personal-data-icon '.$active.'">
1039
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/promoted_messages.php">
1040
                            '.$messageSocialIcon.' '.get_lang('PromotedMessages').'
1041
                        </a>
1042
                    </li>';
1043
                $links .= $personalData;
1044
            }
1045
            $links .= '</ul>';
1046
            $html .= Display::panelCollapse(
1047
                get_lang('SocialNetwork'),
1048
                $links,
1049
                'social-network-menu',
1050
                null,
1051
                'sn-sidebar',
1052
                'sn-sidebar-collapse'
1053
            );
1054
        }
1055
1056
        if (!empty($group_id) && in_array($show, $show_groups)) {
1057
            $html .= $usergroup->show_group_column_information(
1058
                $group_id,
1059
                api_get_user_id(),
1060
                $show
1061
            );
1062
        }
1063
1064
        if ($show === 'shared_profile') {
1065
            $links = '<ul class="nav nav-pills nav-stacked">';
1066
            // My own profile
1067
            if ($show_full_profile && $user_id == api_get_user_id()) {
1068
                $links .= '
1069
                    <li class="home-icon '.$active.'">
1070
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
1071
                            '.$homeIcon.' '.get_lang('Home').'
1072
                        </a>
1073
                    </li>
1074
                    <li class="messages-icon '.$active.'">
1075
                        <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
1076
                            '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
1077
                        </a>
1078
                    </li>';
1079
                $active = $show === 'invitations' ? 'active' : null;
1080
                $links .= '
1081
                    <li class="invitations-icon'.$active.'">
1082
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
1083
                            '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
1084
                        </a>
1085
                    </li>';
1086
1087
                $links .= '
1088
                    <li class="shared-profile-icon active">
1089
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1090
                            '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1091
                        </a>
1092
                    </li>
1093
                    <li class="friends-icon">
1094
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1095
                            '.$friendsIcon.' '.get_lang('Friends').'
1096
                        </a>
1097
                    </li>';
1098
1099
                $links .= '<li class="browse-groups-icon">
1100
                        <a href="'.$groupUrl.'">
1101
                            '.$groupsIcon.' '.get_lang('SocialGroups').'
1102
                        </a>
1103
                        </li>';
1104
1105
                $active = $show == 'search' ? 'active' : null;
1106
                $links .= '
1107
                    <li class="search-icon '.$active.'">
1108
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1109
                            '.$searchIcon.' '.get_lang('Search').'
1110
                        </a>
1111
                    </li>';
1112
                $active = $show == 'myfiles' ? 'active' : null;
1113
1114
                $myFiles = '
1115
                    <li class="myfiles-icon '.$active.'">
1116
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1117
                            '.$filesIcon.' '.get_lang('MyFiles').'
1118
                        </a>
1119
                    </li>';
1120
1121
                if (api_get_setting('allow_my_files') === 'false') {
1122
                    $myFiles = '';
1123
                }
1124
                $links .= $myFiles;
1125
1126
                if (api_get_configuration_value('allow_portfolio_tool')) {
1127
                    $links .= '
1128
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1129
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1130
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1131
                            </a>
1132
                        </li>
1133
                    ';
1134
                }
1135
1136
                if (!api_get_configuration_value('disable_gdpr')) {
1137
                    $active = $show == 'personal-data' ? 'active' : null;
1138
                    $personalData = '
1139
                    <li class="personal-data-icon '.$active.'">
1140
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1141
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1142
                        </a>
1143
                    </li>';
1144
                    $links .= $personalData;
1145
                    $links .= '</ul>';
1146
                }
1147
            }
1148
1149
            // My friend profile.
1150
            if ($user_id != api_get_user_id()) {
1151
                $sendMessageText = get_lang('SendMessage');
1152
                $sendMessageIcon = Display::return_icon(
1153
                    'new-message.png',
1154
                    $sendMessageText
1155
                );
1156
                $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
1157
                    'a' => 'get_user_popup',
1158
                    'user_id' => $user_id,
1159
                ]);
1160
1161
                $links .= '<li>';
1162
                $links .= Display::url(
1163
                    "$sendMessageIcon $sendMessageText",
1164
                    $sendMessageUrl,
1165
                    [
1166
                        'class' => 'ajax',
1167
                        'title' => $sendMessageText,
1168
                        'data-title' => $sendMessageText,
1169
                    ]
1170
                );
1171
                $links .= '</li>';
1172
1173
                if (api_get_configuration_value('allow_portfolio_tool')) {
1174
                    $links .= '
1175
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1176
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id.'">
1177
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1178
                            </a>
1179
                        </li>
1180
                    ';
1181
                }
1182
            }
1183
1184
            // Check if I already sent an invitation message
1185
            $invitationSentList = self::get_list_invitation_sent_by_user_id(api_get_user_id());
1186
1187
            if (isset($invitationSentList[$user_id]) && is_array($invitationSentList[$user_id]) &&
1188
                count($invitationSentList[$user_id]) > 0
1189
            ) {
1190
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
1191
                    Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
1192
                    .'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
1193
            } else {
1194
                if (!$show_full_profile) {
1195
                    $links .= '<li>
1196
                        <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('SendInvitation').'">'.
1197
                        Display::return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').
1198
                        '</a></li>';
1199
                }
1200
            }
1201
1202
            $links .= '</ul>';
1203
            $html .= Display::panelCollapse(
1204
                get_lang('SocialNetwork'),
1205
                $links,
1206
                'social-network-menu',
1207
                null,
1208
                'sn-sidebar',
1209
                'sn-sidebar-collapse'
1210
            );
1211
1212
            if ($show_full_profile && $user_id == api_get_user_id()) {
1213
                // Announcements
1214
                $announcements = [];
1215
                $announcementsByCourse = AnnouncementManager::getAnnoucementCourseTotalByUser($user_id);
1216
                if (!empty($announcementsByCourse)) {
1217
                    foreach ($announcementsByCourse as $announcement) {
1218
                        $url = Display::url(
1219
                            Display::return_icon(
1220
                                'announcement.png',
1221
                                get_lang('Announcements')
1222
                            ).$announcement['course']['name'].' ('.$announcement['count'].')',
1223
                            api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$announcement['course']['code']
1224
                        );
1225
                        $announcements[] = Display::tag('li', $url);
1226
                    }
1227
                }
1228
1229
                if (!empty($announcements)) {
1230
                    $html .= '<div class="social_menu_items">';
1231
                    $html .= '<ul>';
1232
                    foreach ($announcements as $announcement) {
1233
                        $html .= $announcement;
1234
                    }
1235
                    $html .= '</ul>';
1236
                    $html .= '</div>';
1237
                }
1238
            }
1239
        }
1240
1241
        if ($show_delete_account_button) {
1242
            $html .= '<div class="panel panel-default"><div class="panel-body">';
1243
            $html .= '<ul class="nav nav-pills nav-stacked"><li>';
1244
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
1245
            $html .= Display::url(
1246
                Display::return_icon(
1247
                    'delete.png',
1248
                    get_lang('Unsubscribe'),
1249
                    [],
1250
                    ICON_SIZE_TINY
1251
                ).get_lang('Unsubscribe'),
1252
                $url
1253
            );
1254
            $html .= '</li></ul>';
1255
            $html .= '</div></div>';
1256
        }
1257
        $html .= '';
1258
1259
        return $html;
1260
    }
1261
1262
    /**
1263
     * Displays a sortable table with the list of online users.
1264
     *
1265
     * @param array $user_list The list of users to be shown
1266
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
1267
     *
1268
     * @return string HTML block or null if and ID was defined
1269
     * @assert (null) === false
1270
     */
1271
    public static function display_user_list($user_list, $wrap = true)
1272
    {
1273
        $html = '';
1274
1275
        if (isset($_GET['id']) || count($user_list) < 1) {
1276
            return false;
1277
        }
1278
1279
        $course_url = '';
1280
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1281
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
1282
        }
1283
1284
        $hide = api_get_configuration_value('hide_complete_name_in_whoisonline');
1285
        foreach ($user_list as $uid) {
1286
            $user_info = api_get_user_info($uid, true);
1287
            $lastname = $user_info['lastname'];
1288
            $firstname = $user_info['firstname'];
1289
            $completeName = $firstname.', '.$lastname;
1290
            $user_rol = $user_info['status'] == 1 ? Display::return_icon('teacher.png', get_lang('Teacher'), null, ICON_SIZE_TINY) : Display::return_icon('user.png', get_lang('Student'), null, ICON_SIZE_TINY);
1291
            $status_icon_chat = null;
1292
            if (isset($user_info['user_is_online_in_chat']) && $user_info['user_is_online_in_chat'] == 1) {
1293
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1294
            } else {
1295
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1296
            }
1297
1298
            $userPicture = $user_info['avatar'];
1299
            $officialCode = '';
1300
            if (api_get_setting('show_official_code_whoisonline') == 'true') {
1301
                $officialCode .= '<div class="items-user-official-code"><p style="min-height: 30px;" title="'.get_lang('OfficialCode').'">'.$user_info['official_code'].'</p></div>';
1302
            }
1303
1304
            if ($hide === true) {
1305
                $completeName = '';
1306
                $firstname = '';
1307
                $lastname = '';
1308
            }
1309
1310
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1311
1312
            $url = null;
1313
            // Anonymous users can't have access to the profile
1314
            if (!api_is_anonymous()) {
1315
                if (api_get_setting('allow_social_tool') === 'true') {
1316
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1317
                } else {
1318
                    $url = '?id='.$uid.$course_url;
1319
                }
1320
            } else {
1321
                $url = null;
1322
            }
1323
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1324
1325
            $html .= '<div class="col-xs-6 col-md-2">
1326
                        <div class="items-user">
1327
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1328
                            <div class="items-user-name">
1329
                            '.$name.'
1330
                            </div>
1331
                            '.$officialCode.'
1332
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1333
                        </div>
1334
                      </div>';
1335
        }
1336
1337
        return $html;
1338
    }
1339
1340
    /**
1341
     * Displays the information of an individual user.
1342
     *
1343
     * @param int $user_id
1344
     *
1345
     * @return string
1346
     */
1347
    public static function display_individual_user($user_id)
1348
    {
1349
        global $interbreadcrumb;
1350
        $safe_user_id = (int) $user_id;
1351
        $currentUserId = api_get_user_id();
1352
1353
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1354
        $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
1355
        $result = Database::query($sql);
1356
        $html = null;
1357
        if (Database::num_rows($result) == 1) {
1358
            $user_object = Database::fetch_object($result);
1359
            $userInfo = api_get_user_info($user_id);
1360
            $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
1361
            $status = get_status_from_code($user_object->status);
1362
            $interbreadcrumb[] = ['url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList')];
1363
1364
            $html .= '<div class ="thumbnail">';
1365
            $fullurl = $userInfo['avatar'];
1366
1367
            $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
1368
1369
            if (!empty($status)) {
1370
                $html .= '<div class="caption">'.$status.'</div>';
1371
            }
1372
            $html .= '</div>';
1373
1374
            if (api_get_setting('show_email_addresses') == 'true') {
1375
                $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
1376
            }
1377
1378
            if ($user_object->competences) {
1379
                $html .= Display::page_subheader(get_lang('MyCompetences'));
1380
                $html .= '<p>'.$user_object->competences.'</p>';
1381
            }
1382
            if ($user_object->diplomas) {
1383
                $html .= Display::page_subheader(get_lang('MyDiplomas'));
1384
                $html .= '<p>'.$user_object->diplomas.'</p>';
1385
            }
1386
            if ($user_object->teach) {
1387
                $html .= Display::page_subheader(get_lang('MyTeach'));
1388
                $html .= '<p>'.$user_object->teach.'</p>';
1389
            }
1390
            self::display_productions($user_object->user_id);
1391
            if ($user_object->openarea) {
1392
                $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
1393
                $html .= '<p>'.$user_object->openarea.'</p>';
1394
            }
1395
        } else {
1396
            $html .= '<div class="actions-title">';
1397
            $html .= get_lang('UsersOnLineList');
1398
            $html .= '</div>';
1399
        }
1400
1401
        return $html;
1402
    }
1403
1404
    /**
1405
     * Display productions in who is online.
1406
     *
1407
     * @param int $user_id User id
1408
     */
1409
    public static function display_productions($user_id)
1410
    {
1411
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1412
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1413
        $webdir = UserManager::getUserPathById($user_id, 'web');
1414
1415
        if (!is_dir($sysdir)) {
1416
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1417
        }
1418
1419
        $productions = UserManager::get_user_productions($user_id);
1420
1421
        if (count($productions) > 0) {
1422
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1423
            echo '<dd><ul>';
1424
            foreach ($productions as $file) {
1425
                // Only display direct file links to avoid browsing an empty directory
1426
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1427
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1428
                }
1429
                // Real productions are under a subdirectory by the User's id
1430
                if (is_dir($sysdir.$file)) {
1431
                    $subs = scandir($sysdir.$file);
1432
                    foreach ($subs as $my => $sub) {
1433
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1434
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1435
                        }
1436
                    }
1437
                }
1438
            }
1439
            echo '</ul></dd>';
1440
        }
1441
    }
1442
1443
    /**
1444
     * @param string $content
1445
     * @param string $span_count
1446
     *
1447
     * @return string
1448
     */
1449
    public static function social_wrapper_div($content, $span_count)
1450
    {
1451
        $span_count = (int) $span_count;
1452
        $html = '<div class="span'.$span_count.'">';
1453
        $html .= '<div class="well_border">';
1454
        $html .= $content;
1455
        $html .= '</div></div>';
1456
1457
        return $html;
1458
    }
1459
1460
    /**
1461
     * Dummy function.
1462
     */
1463
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1464
    {
1465
        $content = '';
1466
        switch ($place) {
1467
            case SOCIAL_CENTER_PLUGIN:
1468
                $social_plugins = [1, 2];
1469
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1470
                    $content .= '<div id="social-plugins">';
1471
                    foreach ($social_plugins as $plugin) {
1472
                        $content .= '<div class="social-plugin-item">';
1473
                        $content .= $plugin;
1474
                        $content .= '</div>';
1475
                    }
1476
                    $content .= '</div>';
1477
                }
1478
                break;
1479
            case SOCIAL_LEFT_PLUGIN:
1480
                break;
1481
            case SOCIAL_RIGHT_PLUGIN:
1482
                break;
1483
        }
1484
1485
        return $content;
1486
    }
1487
1488
    /**
1489
     * Sends a message to someone's wall.
1490
     *
1491
     * @param int    $userId         id of author
1492
     * @param int    $friendId       id where we send the message
1493
     * @param string $messageContent of the message
1494
     * @param int    $messageId      id parent
1495
     * @param string $messageStatus  status type of message
1496
     *
1497
     * @return int
1498
     *
1499
     * @author Yannick Warnier
1500
     */
1501
    public static function sendWallMessage(
1502
        $userId,
1503
        $friendId,
1504
        $messageContent,
1505
        $messageId = 0,
1506
        $messageStatus = ''
1507
    ) {
1508
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1509
        $userId = (int) $userId;
1510
        $friendId = (int) $friendId;
1511
        $messageId = (int) $messageId;
1512
1513
        if (empty($userId) || empty($friendId)) {
1514
            return 0;
1515
        }
1516
1517
        // Just in case we replace the and \n and \n\r while saving in the DB
1518
        $messageContent = str_replace(["\n", "\n\r"], '<br />', $messageContent);
1519
        $now = api_get_utc_datetime();
1520
1521
        $attributes = [
1522
            'user_sender_id' => $userId,
1523
            'user_receiver_id' => $friendId,
1524
            'msg_status' => $messageStatus,
1525
            'send_date' => $now,
1526
            'title' => '',
1527
            'content' => $messageContent,
1528
            'parent_id' => $messageId,
1529
            'group_id' => 0,
1530
            'update_date' => $now,
1531
        ];
1532
1533
        return Database::insert($tblMessage, $attributes);
0 ignored issues
show
Bug Best Practice introduced by
The expression return Database::insert($tblMessage, $attributes) could also return false which is incompatible with the documented return type integer. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
1534
    }
1535
1536
    /**
1537
     * Send File attachment (jpg,png).
1538
     *
1539
     * @author Anibal Copitan
1540
     *
1541
     * @param int    $userId      id user
1542
     * @param array  $fileAttach
1543
     * @param int    $messageId   id message (relation with main message)
1544
     * @param string $fileComment description attachment file
1545
     *
1546
     * @return bool|int
1547
     */
1548
    public static function sendWallMessageAttachmentFile(
1549
        $userId,
1550
        $fileAttach,
1551
        $messageId,
1552
        $fileComment = ''
1553
    ) {
1554
        $safeFileName = Database::escape_string($fileAttach['name']);
1555
1556
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1557
        $allowedTypes = api_get_supported_image_extensions();
1558
1559
        $allowedTypes[] = 'mp4';
1560
        $allowedTypes[] = 'webm';
1561
        $allowedTypes[] = 'ogg';
1562
1563
        if (in_array($extension, $allowedTypes)) {
1564
            return MessageManager::saveMessageAttachmentFile($fileAttach, $fileComment, $messageId, $userId);
1565
        }
1566
1567
        return false;
1568
    }
1569
1570
    /**
1571
     * Gets all messages from someone's wall (within specific limits).
1572
     *
1573
     * @param int        $userId     id of wall shown
1574
     * @param int|string $parentId   id message (Post main)
1575
     * @param int|array  $groupId
1576
     * @param int|array  $friendId
1577
     * @param string     $startDate  Date from which we want to show the messages, in UTC time
1578
     * @param int        $start      Limit for the number of parent messages we want to show
1579
     * @param int        $length     Wall message query offset
1580
     * @param bool       $getCount
1581
     * @param array      $threadList
1582
     *
1583
     * @return array|int
1584
     *
1585
     * @author Yannick Warnier
1586
     */
1587
    public static function getWallMessages(
1588
        $userId,
1589
        $parentId = 0,
1590
        $groupId = 0,
1591
        $friendId = 0,
1592
        $startDate = '',
1593
        $start = 0,
1594
        $length = 10,
1595
        $getCount = false,
1596
        $threadList = []
1597
    ) {
1598
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1599
1600
        $parentId = (int) $parentId;
1601
        $userId = (int) $userId;
1602
        $start = (int) $start;
1603
        $length = (int) $length;
1604
1605
        $select = " SELECT
1606
                    id,
1607
                    user_sender_id,
1608
                    user_receiver_id,
1609
                    send_date,
1610
                    content,
1611
                    parent_id,
1612
                    msg_status,
1613
                    group_id,
1614
                    '' as forum_id,
1615
                    '' as thread_id,
1616
                    '' as c_id
1617
                  ";
1618
1619
        if ($getCount) {
1620
            $select = ' SELECT count(id) as count_items ';
1621
        }
1622
1623
        $sqlBase = "$select FROM $tblMessage m WHERE ";
1624
        $sql = [];
1625
        $sql[1] = $sqlBase."msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
1626
1627
        // Get my own posts
1628
        $userReceiverCondition = ' (
1629
            user_receiver_id = '.$userId.' AND
1630
            msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
1631
            parent_id = '.$parentId.'
1632
        )';
1633
1634
        $sql[1] .= $userReceiverCondition;
1635
1636
        $sql[2] = $sqlBase.' msg_status = '.MESSAGE_STATUS_PROMOTED.' ';
1637
1638
        // Get my group posts
1639
        $groupCondition = '';
1640
        if (!empty($groupId)) {
1641
            if (is_array($groupId)) {
1642
                $groupId = array_map('intval', $groupId);
1643
                $groupId = implode(",", $groupId);
1644
                $groupCondition = " ( group_id IN ($groupId) ";
1645
            } else {
1646
                $groupId = (int) $groupId;
1647
                $groupCondition = " ( group_id = $groupId ";
1648
            }
1649
            $groupCondition .= ' AND (msg_status = '.MESSAGE_STATUS_NEW.' OR msg_status = '.MESSAGE_STATUS_UNREAD.')) ';
1650
        }
1651
        if (!empty($groupCondition)) {
1652
            $sql[3] = $sqlBase.$groupCondition;
1653
        }
1654
1655
        // Get my friend posts
1656
        $friendCondition = '';
1657
        if (!empty($friendId)) {
1658
            if (is_array($friendId)) {
1659
                $friendId = array_map('intval', $friendId);
1660
                $friendId = implode(",", $friendId);
1661
                $friendCondition = " ( user_receiver_id IN ($friendId) ";
1662
            } else {
1663
                $friendId = (int) $friendId;
1664
                $friendCondition = " ( user_receiver_id = $friendId ";
1665
            }
1666
            $friendCondition .= ' AND msg_status = '.MESSAGE_STATUS_WALL_POST.' AND parent_id = 0) ';
1667
        }
1668
        if (!empty($friendCondition)) {
1669
            $sql[4] = $sqlBase.$friendCondition;
1670
        }
1671
1672
        if (!empty($threadList)) {
1673
            if ($getCount) {
1674
                $select = ' SELECT count(iid) count_items ';
1675
            } else {
1676
                $select = " SELECT
1677
                                iid as id,
1678
                                poster_id as user_sender_id,
1679
                                '' as user_receiver_id,
1680
                                post_date as send_date,
1681
                                post_text as content,
1682
                                '' as parent_id,
1683
                                ".MESSAGE_STATUS_FORUM." as msg_status,
1684
                                '' as group_id,
1685
                                forum_id,
1686
                                thread_id,
1687
                                c_id
1688
                            ";
1689
            }
1690
1691
            $threadList = array_map('intval', $threadList);
1692
            $threadList = implode("','", $threadList);
1693
            $condition = " thread_id IN ('$threadList') ";
1694
            $sql[5] = "$select
1695
                    FROM c_forum_post
1696
                    WHERE $condition
1697
                ";
1698
        }
1699
1700
        if ($getCount) {
1701
            $count = 0;
1702
            foreach ($sql as $oneQuery) {
1703
                if (!empty($oneQuery)) {
1704
                    $res = Database::query($oneQuery);
1705
                    $row = Database::fetch_array($res);
1706
                    $count += (int) $row['count_items'];
1707
                }
1708
            }
1709
1710
            return $count;
1711
        }
1712
1713
        $sqlOrder = ' ORDER BY send_date DESC ';
1714
        $sqlLimit = " LIMIT $start, $length ";
1715
        $messages = [];
1716
        foreach ($sql as $index => $oneQuery) {
1717
            if ($index === 5) {
1718
                // Exception only for the forum query above (field name change)
1719
                $oneQuery .= ' ORDER BY post_date DESC '.$sqlLimit;
1720
            } else {
1721
                $oneQuery .= $sqlOrder.$sqlLimit;
1722
            }
1723
            $res = Database::query($oneQuery);
1724
            $em = Database::getManager();
1725
            if (Database::num_rows($res) > 0) {
1726
                $repo = $em->getRepository('ChamiloCourseBundle:CForumPost');
1727
                $repoThread = $em->getRepository('ChamiloCourseBundle:CForumThread');
1728
                $groups = [];
1729
                $userGroup = new UserGroup();
1730
                $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
1731
                while ($row = Database::fetch_array($res, 'ASSOC')) {
1732
                    $row['group_info'] = [];
1733
                    if (!empty($row['group_id'])) {
1734
                        if (!in_array($row['group_id'], $groups)) {
1735
                            $group = $userGroup->get($row['group_id']);
1736
                            $group['url'] = $urlGroup.$group['id'];
1737
                            $groups[$row['group_id']] = $group;
1738
                            $row['group_info'] = $group;
1739
                        } else {
1740
                            $row['group_info'] = $groups[$row['group_id']];
1741
                        }
1742
                    }
1743
1744
                    // Forums
1745
                    $row['post_title'] = '';
1746
                    $row['forum_title'] = '';
1747
                    $row['thread_url'] = '';
1748
                    if ($row['msg_status'] == MESSAGE_STATUS_FORUM) {
1749
                        /** @var CForumPost $post */
1750
                        $post = $repo->find($row['id']);
1751
                        /** @var CForumThread $thread */
1752
                        $thread = $repoThread->find($row['thread_id']);
1753
                        if ($post && $thread) {
1754
                            $courseInfo = api_get_course_info_by_id($post->getCId());
1755
                            $row['post_title'] = $post->getForumId();
1756
                            $row['forum_title'] = $thread->getThreadTitle();
1757
                            $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
1758
                                    'cidReq' => $courseInfo['code'],
1759
                                    'forum' => $post->getForumId(),
1760
                                    'thread' => $post->getThreadId(),
1761
                                    'post_id' => $post->getIid(),
1762
                                ]).'#post_id_'.$post->getIid();
1763
                        }
1764
                    }
1765
1766
                    $messages[$row['id']] = $row;
1767
                }
1768
            }
1769
        }
1770
        // Reordering messages by ID (reverse order) is enough to have the
1771
        // latest first, as there is currently no option to edit messages
1772
        // afterwards
1773
        krsort($messages);
1774
1775
        return $messages;
1776
    }
1777
1778
    /**
1779
     * Gets all messages from someone's wall (within specific limits), formatted.
1780
     *
1781
     * @param int    $userId      USER ID of the person's wall
1782
     * @param array  $messageInfo
1783
     * @param string $start       Start date (from when we want the messages until today)
1784
     * @param int    $limit       Limit to the number of messages we want
1785
     * @param int    $offset      Wall messages offset
1786
     *
1787
     * @return string HTML formatted string to show messages
1788
     */
1789
    public static function getWallPostComments(
1790
        $userId,
1791
        $messageInfo,
1792
        $start = null,
1793
        $limit = 10,
1794
        $offset = 0
1795
    ) {
1796
        $messageId = $messageInfo['id'];
1797
        $messages = MessageManager::getMessagesByParent($messageInfo['id'], 0, $offset, $limit);
1798
        $formattedList = '<div class="sub-mediapost row">';
1799
        $users = [];
1800
1801
        // The messages are ordered by date descendant, for comments we need ascendant
1802
        krsort($messages);
1803
        foreach ($messages as $message) {
1804
            $userIdLoop = $message['user_sender_id'];
1805
            if (!isset($users[$userIdLoop])) {
1806
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1807
            }
1808
            $media = self::processPostComment($message, $users);
1809
            $formattedList .= $media;
1810
        }
1811
1812
        $formattedList .= '</div>';
1813
        $formattedList .= '<div class="mediapost-form row">';
1814
        $formattedList .= '<form class="form-horizontal" id="form_comment_'.$messageId.'" name="post_comment" method="POST">
1815
                <div class="col-sm-9">
1816
                <label for="comment" class="hide">'.get_lang('SocialWriteNewComment').'</label>
1817
                <input type="hidden" name = "messageId" value="'.$messageId.'" />
1818
                <textarea rows="3" class="form-control" placeholder="'.get_lang('SocialWriteNewComment').'" name="comment" rows="1" ></textarea>
1819
                </div>
1820
                <div class="col-sm-3 pull-right">
1821
                <a onclick="submitComment('.$messageId.');" href="javascript:void(0);" name="social_wall_new_msg_submit" class="btn btn-default btn-post">
1822
                    <em class="fa fa-pencil"></em> '.get_lang('Post').'
1823
                </a>
1824
                </div>
1825
                </form>';
1826
        $formattedList .= '</div>';
1827
1828
        return $formattedList;
1829
    }
1830
1831
    /**
1832
     * @param array $message
1833
     * @param array $users
1834
     *
1835
     * @return string
1836
     */
1837
    public static function processPostComment($message, $users = [])
1838
    {
1839
        if (empty($message)) {
1840
            return false;
1841
        }
1842
1843
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
1844
        $currentUserId = api_get_user_id();
1845
        $userIdLoop = $message['user_sender_id'];
1846
        $receiverId = $message['user_receiver_id'];
1847
1848
        if (!isset($users[$userIdLoop])) {
1849
            $users[$userIdLoop] = api_get_user_info($userIdLoop);
1850
        }
1851
1852
        $iconStatus = $users[$userIdLoop]['icon_status'];
1853
        $nameComplete = $users[$userIdLoop]['complete_name'];
1854
        $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$userIdLoop;
1855
1856
        $comment = '<div class="rep-post col-md-12">';
1857
        $comment .= '<div class="col-md-2 col-xs-2 social-post-answers">';
1858
        $comment .= '<div class="user-image pull-right">';
1859
        $comment .= '<a href="'.$url.'">
1860
                        <img src="'.$users[$userIdLoop]['avatar'].'"
1861
                        alt="'.$users[$userIdLoop]['complete_name'].'"
1862
                        class="avatar-thumb">
1863
                     </a>';
1864
        $comment .= '</div>';
1865
        $comment .= '</div>';
1866
        $comment .= '<div class="col-md-7 col-xs-7 social-post-answers">';
1867
        $comment .= '<div class="user-data">';
1868
        $comment .= $iconStatus;
1869
        $comment .= '<div class="username"><a href="'.$url.'">'.$nameComplete.'</a>
1870
                        <span>'.Security::remove_XSS($message['content']).'</span>
1871
                       </div>';
1872
        $comment .= '<div>'.$date.'</div>';
1873
        $comment .= '<br />';
1874
        $comment .= '</div>';
1875
        $comment .= '</div>';
1876
1877
        $comment .= '<div class="col-md-3 col-xs-3 social-post-answers">';
1878
        $comment .= '<div class="pull-right btn-group btn-group-sm">';
1879
1880
        $comment .= MessageManager::getLikesButton(
1881
            $message['id'],
1882
            $currentUserId
1883
        );
1884
1885
        $isOwnWall = $currentUserId == $userIdLoop || $currentUserId == $receiverId;
1886
        if ($isOwnWall) {
1887
            $comment .= Display::url(
1888
                    Display::returnFontAwesomeIcon('trash', '', true),
1889
                'javascript:void(0)',
1890
                [
1891
                    'id' => 'message_'.$message['id'],
1892
                    'title' => get_lang('SocialMessageDelete'),
1893
                    'onclick' => 'deleteComment('.$message['id'].')',
1894
                    'class' => 'btn btn-default',
1895
                ]
1896
            );
1897
        }
1898
        $comment .= '</div>';
1899
        $comment .= '</div>';
1900
        $comment .= '</div>';
1901
1902
        return $comment;
1903
    }
1904
1905
    /**
1906
     * @param array $message
1907
     *
1908
     * @return array
1909
     */
1910
    public static function getAttachmentPreviewList($message)
1911
    {
1912
        $messageId = $message['id'];
1913
1914
        $list = [];
1915
1916
        if (empty($message['group_id'])) {
1917
            $files = MessageManager::getAttachmentList($messageId);
1918
            if ($files) {
1919
                $downloadUrl = api_get_path(WEB_CODE_PATH).'social/download.php?message_id='.$messageId;
1920
                foreach ($files as $row_file) {
1921
                    $url = $downloadUrl.'&attachment_id='.$row_file['id'];
1922
                    $display = Display::fileHtmlGuesser($row_file['filename'], $url);
1923
                    $list[] = $display;
1924
                }
1925
            }
1926
        } else {
1927
            $list = MessageManager::getAttachmentLinkList($messageId, 0);
1928
        }
1929
1930
        return $list;
1931
    }
1932
1933
    /**
1934
     * @param array $message
1935
     *
1936
     * @return string
1937
     */
1938
    public static function getPostAttachment($message)
1939
    {
1940
        $previews = self::getAttachmentPreviewList($message);
1941
1942
        if (empty($previews)) {
1943
            return '';
1944
        }
1945
1946
        return implode('', $previews);
1947
    }
1948
1949
    /**
1950
     * @param array $messages
1951
     *
1952
     * @return array
1953
     */
1954
    public static function formatWallMessages($messages)
1955
    {
1956
        $data = [];
1957
        $users = [];
1958
        foreach ($messages as $key => $message) {
1959
            $userIdLoop = $message['user_sender_id'];
1960
            $userFriendIdLoop = $message['user_receiver_id'];
1961
            if (!isset($users[$userIdLoop])) {
1962
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1963
            }
1964
1965
            if (!isset($users[$userFriendIdLoop])) {
1966
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
1967
            }
1968
1969
            $html = self::headerMessagePost(
1970
                $users[$userIdLoop],
1971
                $users[$userFriendIdLoop],
1972
                $message
1973
            );
1974
1975
            $data[$key] = $message;
1976
            $data[$key]['html'] = $html;
1977
        }
1978
1979
        return $data;
1980
    }
1981
1982
    /**
1983
     * get html data with OpenGrap passing the URL.
1984
     *
1985
     * @param $link url
1986
     *
1987
     * @return string data html
1988
     */
1989
    public static function readContentWithOpenGraph($link)
1990
    {
1991
        if (strpos($link, "://") === false && substr($link, 0, 1) != "/") {
1992
            $link = "http://".$link;
1993
        }
1994
        $graph = OpenGraph::fetch($link);
1995
        $link = parse_url($link);
1996
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
1997
        if (!$graph) {
1998
            return false;
1999
        }
2000
        $url = $graph->url;
2001
        $image = $graph->image;
2002
        $description = $graph->description;
2003
        $title = $graph->title;
2004
        $html = '<div class="thumbnail social-thumbnail">';
2005
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
2006
                <img class="img-responsive social-image" src="'.$image.'" /></a>';
2007
        $html .= '<div class="social-description">';
2008
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
2009
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
2010
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
2011
        $html .= '</div>';
2012
        $html .= '</div>';
2013
2014
        return $html;
2015
    }
2016
2017
    /**
2018
     * verify if Url Exist - Using Curl.
2019
     *
2020
     * @param $uri url
2021
     *
2022
     * @return bool
2023
     */
2024
    public static function verifyUrl($uri)
2025
    {
2026
        $curl = curl_init($uri);
2027
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
2028
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
2029
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2030
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
2031
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
2032
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
2033
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
2034
        $response = curl_exec($curl);
2035
        curl_close($curl);
2036
        if (!empty($response)) {
2037
            return true;
2038
        }
2039
2040
        return false;
2041
    }
2042
2043
    /**
2044
     * Soft delete a message and his chidren.
2045
     *
2046
     * @param int $id id message to delete
2047
     *
2048
     * @return bool status query
2049
     */
2050
    public static function deleteMessage($id)
2051
    {
2052
        $id = (int) $id;
2053
        $messageInfo = MessageManager::get_message_by_id($id);
2054
        if (!empty($messageInfo)) {
2055
            // Delete comments too
2056
            $messages = MessageManager::getMessagesByParent($id);
2057
            if (!empty($messages)) {
2058
                foreach ($messages as $message) {
2059
                    self::deleteMessage($message['id']);
2060
                }
2061
            }
2062
2063
            // Soft delete message
2064
            $tblMessage = Database::get_main_table(TABLE_MESSAGE);
2065
            $statusMessage = MESSAGE_STATUS_WALL_DELETE;
2066
            $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
2067
            Database::query($sql);
2068
2069
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_sender_id']);
2070
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_receiver_id']);
2071
2072
            return true;
2073
        }
2074
2075
        return false;
2076
    }
2077
2078
    /**
2079
     * Generate the social block for a user.
2080
     *
2081
     * @param int    $userId            The user id
2082
     * @param string $groupBlock        Optional. Highlight link possible values:
2083
     *                                  group_add, home, messages, messages_inbox, messages_compose,
2084
     *                                  messages_outbox, invitations, shared_profile, friends, groups, search
2085
     * @param int    $groupId           Optional. Group ID
2086
     * @param bool   $show_full_profile
2087
     *
2088
     * @return string The HTML code with the social block
2089
     */
2090
    public static function setSocialUserBlock(
2091
        Template $template,
2092
        $userId,
2093
        $groupBlock = '',
2094
        $groupId = 0,
2095
        $show_full_profile = true
2096
    ) {
2097
        if (api_get_setting('allow_social_tool') !== 'true') {
2098
            return '';
2099
        }
2100
2101
        $currentUserId = api_get_user_id();
2102
        $userId = (int) $userId;
2103
        $userRelationType = 0;
2104
2105
        $socialAvatarBlock = self::show_social_avatar_block(
2106
            $groupBlock,
2107
            $groupId,
2108
            $userId
2109
        );
2110
2111
        $profileEditionLink = null;
2112
        if ($currentUserId === $userId) {
2113
            $profileEditionLink = Display::getProfileEditionLink($userId);
2114
        } else {
2115
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
2116
        }
2117
2118
        $options = api_get_configuration_value('profile_fields_visibility');
2119
        if (isset($options['options'])) {
2120
            $options = $options['options'];
2121
        }
2122
2123
        $vCardUserLink = Display::getVCardUserLink($userId);
2124
        if (isset($options['vcard']) && $options['vcard'] === false) {
2125
            $vCardUserLink = '';
2126
        }
2127
2128
        $userInfo = api_get_user_info($userId, true, false, true, true);
2129
2130
        if (isset($options['firstname']) && $options['firstname'] === false) {
2131
            $userInfo['firstname'] = '';
2132
        }
2133
        if (isset($options['lastname']) && $options['lastname'] === false) {
2134
            $userInfo['lastname'] = '';
2135
        }
2136
2137
        if (isset($options['email']) && $options['email'] === false) {
2138
            $userInfo['email'] = '';
2139
        }
2140
2141
        // Ofaj
2142
        $hasCertificates = Certificate::getCertificateByUser($userId);
2143
        $userInfo['has_certificates'] = 0;
2144
        if (!empty($hasCertificates)) {
2145
            $userInfo['has_certificates'] = 1;
2146
        }
2147
2148
        $userInfo['is_admin'] = UserManager::is_admin($userId);
2149
2150
        $languageId = api_get_language_id($userInfo['language']);
2151
        $languageInfo = api_get_language_info($languageId);
2152
        if ($languageInfo) {
2153
            $userInfo['language'] = [
2154
                'label' => $languageInfo['original_name'],
2155
                'value' => $languageInfo['english_name'],
2156
                'code' => $languageInfo['isocode'],
2157
            ];
2158
        }
2159
2160
        if (isset($options['language']) && $options['language'] === false) {
2161
            $userInfo['language'] = '';
2162
        }
2163
2164
        if (isset($options['photo']) && $options['photo'] === false) {
2165
            $socialAvatarBlock = '';
2166
        }
2167
2168
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
2169
        $showLanguageFlag = api_get_configuration_value('social_show_language_flag_in_profile');
2170
2171
        $template->assign('user', $userInfo);
2172
        $template->assign('show_language_flag', $showLanguageFlag);
2173
        $template->assign('extra_info', $extraFieldBlock);
2174
        $template->assign('social_avatar_block', $socialAvatarBlock);
2175
        $template->assign('profile_edition_link', $profileEditionLink);
2176
        //Added the link to export the vCard to the Template
2177
2178
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
2179
        if ($show_full_profile) {
2180
            $template->assign('vcard_user_link', $vCardUserLink);
2181
        }
2182
2183
        if (api_get_setting('gamification_mode') === '1') {
2184
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
2185
                $userId,
2186
                $userInfo['status']
2187
            );
2188
2189
            $template->assign('gamification_points', $gamificationPoints);
2190
        }
2191
        $chatEnabled = api_is_global_chat_enabled();
2192
2193
        if (isset($options['chat']) && $options['chat'] === false) {
2194
            $chatEnabled = '';
2195
        }
2196
2197
        $template->assign('chat_enabled', $chatEnabled);
2198
        $template->assign('user_relation', $userRelationType);
2199
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
2200
        $template->assign('show_full_profile', $show_full_profile);
2201
2202
        $templateName = $template->get_template('social/user_block.tpl');
2203
2204
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
2205
            $templateName = $template->get_template('social/group_block.tpl');
2206
        }
2207
2208
        $template->assign('social_avatar_block', $template->fetch($templateName));
2209
    }
2210
2211
    /**
2212
     * @param int $user_id
2213
     * @param $link_shared
2214
     * @param bool $showLinkToChat
2215
     *
2216
     * @return string
2217
     */
2218
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
2219
    {
2220
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
2221
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
2222
        $numberFriends = count($friends);
2223
        $friendHtml = '';
2224
2225
        if (!empty($numberFriends)) {
2226
            $friendHtml .= '<div class="list-group contact-list">';
2227
            $j = 1;
2228
2229
            usort(
2230
                $friends,
2231
                function ($a, $b) {
2232
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
2233
                }
2234
            );
2235
2236
            foreach ($friends as $friend) {
2237
                if ($j > $numberFriends) {
2238
                    break;
2239
                }
2240
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2241
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2242
2243
                $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
2244
                $status = 0;
2245
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
2246
                    $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
2247
                    $status = 1;
2248
                }
2249
2250
                $friendAvatarMedium = UserManager::getUserPicture(
2251
                    $friend['friend_user_id'],
2252
                    USER_IMAGE_SIZE_MEDIUM
2253
                );
2254
                $friendAvatarSmall = UserManager::getUserPicture(
2255
                    $friend['friend_user_id'],
2256
                    USER_IMAGE_SIZE_SMALL
2257
                );
2258
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
2259
2260
                $relation = self::get_relation_between_contacts(
2261
                    $friend['friend_user_id'],
2262
                    api_get_user_id()
2263
                );
2264
2265
                if ($showLinkToChat) {
2266
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
2267
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2268
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2269
                } else {
2270
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
2271
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
2272
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2273
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2274
                }
2275
2276
                $friendHtml .= '</a>';
2277
2278
                $j++;
2279
            }
2280
            $friendHtml .= '</div>';
2281
        } else {
2282
            $friendHtml = Display::return_message(get_lang('NoFriendsInYourContactList'), 'warning');
2283
        }
2284
2285
        return $friendHtml;
2286
    }
2287
2288
    /**
2289
     * @return string Get the JS code necessary for social wall to load open graph from URLs.
2290
     */
2291
    public static function getScriptToGetOpenGraph()
2292
    {
2293
        return '<script>
2294
            $(function() {
2295
                $("[name=\'social_wall_new_msg_main\']").on("paste", function(e) {
2296
                    $.ajax({
2297
                        contentType: "application/x-www-form-urlencoded",
2298
                        beforeSend: function() {
2299
                            $("[name=\'wall_post_button\']").prop( "disabled", true );
2300
                            $(".panel-preview").hide();
2301
                            $(".spinner").html("'
2302
                                .'<div class=\'text-center\'>'
2303
                                .'<em class=\'fa fa-spinner fa-pulse fa-1x\'></em>'
2304
                                .'<p>'.get_lang('Loading').' '.get_lang('Preview').'</p>'
2305
                                .'</div>'
2306
                            .'");
2307
                        },
2308
                        type: "POST",
2309
                        url: "'.api_get_path(WEB_AJAX_PATH).'social.ajax.php?a=read_url_with_open_graph",
2310
                        data: "social_wall_new_msg_main=" + e.originalEvent.clipboardData.getData("text"),
2311
                        success: function(response) {
2312
                            $("[name=\'wall_post_button\']").prop("disabled", false);
2313
                            if (!response == false) {
2314
                                $(".spinner").html("");
2315
                                $(".panel-preview").show();
2316
                                $(".url_preview").html(response);
2317
                                $("[name=\'url_content\']").val(response);
2318
                                $(".url_preview img").addClass("img-responsive");
2319
                            } else {
2320
                                $(".spinner").html("");
2321
                            }
2322
                        }
2323
                    });
2324
                });
2325
            });
2326
        </script>';
2327
    }
2328
2329
    /**
2330
     * @param string $urlForm
2331
     *
2332
     * @return string
2333
     */
2334
    public static function getWallForm($urlForm)
2335
    {
2336
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
2337
        $form = new FormValidator(
2338
            'social_wall_main',
2339
            'post',
2340
            $urlForm.$userId,
2341
            null,
2342
            ['enctype' => 'multipart/form-data'],
2343
            FormValidator::LAYOUT_HORIZONTAL
2344
        );
2345
2346
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
2347
            'SocialWallWhatAreYouThinkingAbout'
2348
        );
2349
2350
        $form->addTextarea(
2351
            'social_wall_new_msg_main',
2352
            null,
2353
            [
2354
                'placeholder' => $socialWallPlaceholder,
2355
                'cols-size' => [1, 12, 1],
2356
                'aria-label' => $socialWallPlaceholder,
2357
            ]
2358
        );
2359
        $form->addHtml('<div class="form-group">');
2360
        $form->addHtml('<div class="col-sm-6">');
2361
        $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
2362
        $form->addHtml('</div>');
2363
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
2364
        $form->addButtonSend(
2365
            get_lang('Post'),
2366
            'wall_post_button',
2367
            false,
2368
            [
2369
                'cols-size' => [1, 10, 1],
2370
                'custom' => true,
2371
            ]
2372
        );
2373
        $form->addHtml('</div></div>');
2374
        $form->addHtml('</div>');
2375
        $form->addHidden('url_content', '');
2376
        $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
2377
2378
        return $html;
2379
    }
2380
2381
    /**
2382
     * @param int   $userId
2383
     * @param int   $start
2384
     * @param int   $length
2385
     * @param array $threadList
2386
     *
2387
     * @return array
2388
     */
2389
    public static function getMyWallMessages($userId, $start = 0, $length = 10, $threadList = [])
2390
    {
2391
        $userGroup = new UserGroup();
2392
        $groups = $userGroup->get_groups_by_user($userId, [GROUP_USER_PERMISSION_READER, GROUP_USER_PERMISSION_ADMIN]);
2393
        $groupList = [];
2394
        if (!empty($groups)) {
2395
            $groupList = array_column($groups, 'id');
2396
        }
2397
2398
        $friends = self::get_friends($userId, USER_RELATION_TYPE_FRIEND);
2399
        $friendList = [];
2400
        if (!empty($friends)) {
2401
            $friendList = array_column($friends, 'friend_user_id');
2402
        }
2403
2404
        $messages = self::getWallMessages(
2405
            $userId,
2406
            0,
2407
            $groupList,
2408
            $friendList,
2409
            '',
2410
            $start,
2411
            $length,
2412
            false,
2413
            $threadList
2414
        );
2415
2416
        $countPost = self::getCountWallMessagesByUser($userId, $groupList, $friendList, $threadList);
2417
        $messages = self::formatWallMessages($messages);
2418
2419
        $html = '';
2420
        foreach ($messages as $message) {
2421
            $post = $message['html'];
2422
            $comments = '';
2423
            if (in_array($message['msg_status'], [MESSAGE_STATUS_WALL_POST, MESSAGE_STATUS_PROMOTED])) {
2424
                $comments = self::getWallPostComments($userId, $message);
2425
            }
2426
2427
            $html .= self::wrapPost($message, $post.$comments);
2428
        }
2429
2430
        return [
2431
            'posts' => $html,
2432
            'count' => $countPost,
2433
        ];
2434
    }
2435
2436
    /**
2437
     * @param string $message
2438
     * @param string $content
2439
     *
2440
     * @return string
2441
     */
2442
    public static function wrapPost($message, $content)
2443
    {
2444
        $class = '';
2445
        if ($message['msg_status'] === MESSAGE_STATUS_PROMOTED) {
2446
            $class = 'promoted_post';
2447
        }
2448
2449
        return Display::panel($content, '',
2450
            '',
2451
            'default',
2452
            '',
2453
            'post_'.$message['id'],
2454
            null,
2455
            $class
2456
        );
2457
    }
2458
2459
    /**
2460
     * @param int   $userId
2461
     * @param array $groupList
2462
     * @param array $friendList
2463
     * @param array $threadList
2464
     *
2465
     * @return int
2466
     */
2467
    public static function getCountWallMessagesByUser($userId, $groupList = [], $friendList = [], $threadList = [])
2468
    {
2469
        $count = self::getWallMessages(
2470
            $userId,
2471
            0,
2472
            $groupList,
2473
            $friendList,
2474
            '',
2475
            0,
2476
            0,
2477
            true,
2478
            $threadList
2479
        );
2480
2481
        return $count;
2482
    }
2483
2484
    /**
2485
     * @param int $userId
2486
     *
2487
     * @return string
2488
     */
2489
    public static function getWallMessagesByUser($userId)
2490
    {
2491
        $messages = self::getWallMessages($userId);
2492
        $messages = self::formatWallMessages($messages);
2493
2494
        $html = '';
2495
        foreach ($messages as $message) {
2496
            $post = $message['html'];
2497
            $comments = self::getWallPostComments($userId, $message);
2498
            $html .= self::wrapPost($message, $post.$comments);
2499
        }
2500
2501
        return $html;
2502
    }
2503
2504
    /**
2505
     * Get HTML code block for user skills.
2506
     *
2507
     * @param int    $userId      The user ID
2508
     * @param string $orientation
2509
     *
2510
     * @return string
2511
     */
2512
    public static function getSkillBlock($userId, $orientation = 'horizontal')
2513
    {
2514
        if (Skill::isAllowed($userId, false) === false) {
2515
            return '';
2516
        }
2517
2518
        $skill = new Skill();
2519
        $ranking = $skill->getUserSkillRanking($userId);
2520
2521
        $template = new Template(null, false, false, false, false, false);
2522
        $template->assign('ranking', $ranking);
2523
        $template->assign('orientation', $orientation);
2524
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
2525
        $template->assign('user_id', $userId);
2526
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
2527
2528
        $skillBlock = $template->get_template('social/skills_block.tpl');
2529
2530
        return $template->fetch($skillBlock);
2531
    }
2532
2533
    /**
2534
     * @param int  $user_id
2535
     * @param bool $isArray
2536
     *
2537
     * @return string|array
2538
     */
2539
    public static function getExtraFieldBlock($user_id, $isArray = false)
2540
    {
2541
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
2542
        $fieldVisibilityKeys = [];
2543
        if (isset($fieldVisibility['options'])) {
2544
            $fieldVisibility = $fieldVisibility['options'];
2545
            $fieldVisibilityKeys = array_keys($fieldVisibility);
2546
        }
2547
2548
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
2549
        $extra_user_data = UserManager::get_extra_user_data($user_id);
2550
2551
        $extra_information = '';
2552
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
2553
            $extra_information_value = '';
2554
            $extraField = new ExtraField('user');
2555
            $listType = [];
2556
            $extraFieldItem = [];
2557
            foreach ($extra_user_data as $key => $data) {
2558
                if (empty($data)) {
2559
                    continue;
2560
                }
2561
                if (in_array($key, $fieldVisibilityKeys) && $fieldVisibility[$key] === false) {
2562
                    continue;
2563
                }
2564
2565
                // Avoiding parameters
2566
                if (in_array(
2567
                    $key,
2568
                    [
2569
                        'mail_notify_invitation',
2570
                        'mail_notify_message',
2571
                        'mail_notify_group_message',
2572
                    ]
2573
                )) {
2574
                    continue;
2575
                }
2576
                // get display text, visibility and type from user_field table
2577
                $field_variable = str_replace('extra_', '', $key);
2578
2579
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2580
                    $field_variable
2581
                );
2582
2583
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
2584
                    continue;
2585
                }
2586
2587
                // if is not visible skip
2588
                if ($extraFieldInfo['visible_to_self'] != 1) {
2589
                    continue;
2590
                }
2591
2592
                // if is not visible to others skip also
2593
                if ($extraFieldInfo['visible_to_others'] != 1) {
2594
                    continue;
2595
                }
2596
2597
                if (is_array($data)) {
2598
                    switch ($extraFieldInfo['field_type']) {
2599
                        case ExtraField::FIELD_TYPE_RADIO:
2600
                            $objEfOption = new ExtraFieldOption('user');
2601
                            $value = $data['extra_'.$extraFieldInfo['variable']];
2602
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
2603
                                $extraFieldInfo['id'],
2604
                                $value
2605
                            );
2606
2607
                            if ($optionInfo && isset($optionInfo[0])) {
2608
                                $optionInfo = $optionInfo[0];
2609
                                $extraFieldItem = [
2610
                                    'variable' => $extraFieldInfo['variable'],
2611
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2612
                                    'value' => $optionInfo['display_text'],
2613
                                ];
2614
                            } else {
2615
                                $extraFieldItem = [
2616
                                    'variable' => $extraFieldInfo['variable'],
2617
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2618
                                    'value' => implode(',', $data),
2619
                                ];
2620
                            }
2621
                            break;
2622
                        default:
2623
                            $extra_information_value .=
2624
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
2625
                                .' '.implode(',', $data).'</li>';
2626
                            $extraFieldItem = [
2627
                                'variable' => $extraFieldInfo['variable'],
2628
                                'label' => ucfirst($extraFieldInfo['display_text']),
2629
                                'value' => implode(',', $data),
2630
                            ];
2631
                            break;
2632
                    }
2633
                } else {
2634
                    switch ($extraFieldInfo['field_type']) {
2635
                        case ExtraField::FIELD_TYPE_RADIO:
2636
                            $objEfOption = new ExtraFieldOption('user');
2637
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
2638
                            break;
2639
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
2640
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
2641
                            $data = explode('::', $data);
2642
                            $data = $data[0];
2643
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2644
                            $extraFieldItem = [
2645
                                'variable' => $extraFieldInfo['variable'],
2646
                                'label' => ucfirst($extraFieldInfo['display_text']),
2647
                                'value' => $data,
2648
                            ];
2649
                            break;
2650
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
2651
                            $id_options = explode('::', $data);
2652
                            $value_options = [];
2653
                            // get option display text from user_field_options table
2654
                            foreach ($id_options as $id_option) {
2655
                                $sql = "SELECT display_text
2656
                                    FROM $t_ufo
2657
                                    WHERE id = '$id_option'";
2658
                                $res_options = Database::query($sql);
2659
                                $row_options = Database::fetch_row($res_options);
2660
                                $value_options[] = $row_options[0];
2661
                            }
2662
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2663
                                .' '.implode(' ', $value_options).'</li>';
2664
                            $extraFieldItem = [
2665
                                'variable' => $extraFieldInfo['variable'],
2666
                                'label' => ucfirst($extraFieldInfo['display_text']),
2667
                                'value' => $value_options,
2668
                            ];
2669
                            break;
2670
                        case ExtraField::FIELD_TYPE_TAG:
2671
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
2672
2673
                            $tag_tmp = '';
2674
                            foreach ($user_tags as $tags) {
2675
                                $tag_tmp .= '<a class="label label_tag"'
2676
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
2677
                                    .$tags['tag']
2678
                                    .'</a>';
2679
                            }
2680
                            if (is_array($user_tags) && count($user_tags) > 0) {
2681
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2682
                                    .' '.$tag_tmp.'</li>';
2683
                            }
2684
                            $extraFieldItem = [
2685
                                'variable' => $extraFieldInfo['variable'],
2686
                                'label' => ucfirst($extraFieldInfo['display_text']),
2687
                                'value' => $tag_tmp,
2688
                            ];
2689
                            break;
2690
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
2691
                            $icon_path = UserManager::get_favicon_from_url($data);
2692
                            if (self::verifyUrl($icon_path) == false) {
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...
2693
                                break;
2694
                            }
2695
                            $bottom = '0.2';
2696
                            //quick hack for hi5
2697
                            $domain = parse_url($icon_path, PHP_URL_HOST);
2698
                            if ($domain == 'www.hi5.com' || $domain == 'hi5.com') {
2699
                                $bottom = '-0.8';
2700
                            }
2701
                            $data = '<a href="'.$data.'">'
2702
                                .'<img src="'.$icon_path.'" alt="icon"'
2703
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
2704
                                .$extraFieldInfo['display_text']
2705
                                .'</a>';
2706
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
2707
                            $extraFieldItem = [
2708
                                'variable' => $extraFieldInfo['variable'],
2709
                                'label' => ucfirst($extraFieldInfo['display_text']),
2710
                                'value' => $data,
2711
                            ];
2712
                            break;
2713
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
2714
                            $parsedData = explode('::', $data);
2715
2716
                            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...
2717
                                break;
2718
                            }
2719
2720
                            $objEfOption = new ExtraFieldOption('user');
2721
                            $optionInfo = $objEfOption->get($parsedData[0]);
2722
2723
                            $extra_information_value .= '<li class="list-group-item">'
2724
                                .$optionInfo['display_text'].': '
2725
                                .$parsedData[1].'</li>';
2726
                            $extraFieldItem = [
2727
                                'variable' => $extraFieldInfo['variable'],
2728
                                'label' => ucfirst($extraFieldInfo['display_text']),
2729
                                'value' => $parsedData[1],
2730
                            ];
2731
                            break;
2732
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
2733
                            $optionIds = explode(';', $data);
2734
                            $optionValues = [];
2735
2736
                            foreach ($optionIds as $optionId) {
2737
                                $objEfOption = new ExtraFieldOption('user');
2738
                                $optionInfo = $objEfOption->get($optionId);
2739
2740
                                $optionValues[] = $optionInfo['display_text'];
2741
                            }
2742
                            $extra_information_value .= '<li class="list-group-item">'
2743
                                .ucfirst($extraFieldInfo['display_text']).': '
2744
                                .implode(' ', $optionValues).'</li>';
2745
                            $extraFieldItem = [
2746
                                'variable' => $extraFieldInfo['variable'],
2747
                                'label' => ucfirst($extraFieldInfo['display_text']),
2748
                                'value' => implode(' ', $optionValues),
2749
                            ];
2750
                            break;
2751
                        default:
2752
                            // Ofaj
2753
                            // Converts "Date of birth" into "age"
2754
                            if ($key === 'terms_datedenaissance') {
2755
                                $dataArray = date_to_str_ago($data, 'UTC', true);
2756
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
2757
                                if (!empty($dataToString)) {
2758
                                    $data = $dataToString;
2759
                                    $extraFieldInfo['display_text'] = get_lang('Age');
2760
                                }
2761
                            }
2762
2763
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2764
                            $extraFieldItem = [
2765
                                'variable' => $extraFieldInfo['variable'],
2766
                                'label' => ucfirst($extraFieldInfo['display_text']),
2767
                                'value' => $data,
2768
                            ];
2769
                            break;
2770
                    }
2771
                }
2772
2773
                $listType[] = $extraFieldItem;
2774
            }
2775
2776
            if ($isArray) {
2777
                return $listType;
2778
            } else {
2779
                // if there are information to show
2780
                if (!empty($extra_information_value)) {
2781
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
2782
                    $extra_information .= Display::panelCollapse(
2783
                        get_lang('ExtraInformation'),
2784
                        $extra_information_value,
2785
                        'sn-extra-information',
2786
                        null,
2787
                        'sn-extra-accordion',
2788
                        'sn-extra-collapse'
2789
                    );
2790
                }
2791
            }
2792
        }
2793
2794
        return $extra_information;
2795
    }
2796
2797
    /**
2798
     * @param string $url
2799
     */
2800
    public static function handlePosts($url)
2801
    {
2802
        $friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
2803
        $url = Security::remove_XSS($url);
2804
2805
        // Main post
2806
        if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
2807
            $messageContent = $_POST['social_wall_new_msg_main'];
2808
            if (!empty($_POST['url_content'])) {
2809
                $messageContent = $_POST['social_wall_new_msg_main'].'<br /><br />'.$_POST['url_content'];
2810
            }
2811
2812
            $messageId = self::sendWallMessage(
2813
                api_get_user_id(),
2814
                $friendId,
2815
                $messageContent,
2816
                0,
2817
                MESSAGE_STATUS_WALL_POST
2818
            );
2819
2820
            if ($messageId && !empty($_FILES['picture']['tmp_name'])) {
2821
                self::sendWallMessageAttachmentFile(
2822
                    api_get_user_id(),
2823
                    $_FILES['picture'],
2824
                    $messageId
2825
                );
2826
            }
2827
2828
            Display::addFlash(Display::return_message(get_lang('MessageSent')));
2829
            header('Location: '.$url);
2830
            exit;
2831
        }
2832
    }
2833
2834
    /**
2835
     * @param int   $countPost
2836
     * @param array $htmlHeadXtra
2837
     */
2838
    public static function getScrollJs($countPost, &$htmlHeadXtra)
2839
    {
2840
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
2841
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
2842
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
2843
        $locale = api_get_language_isocode();
2844
2845
        // Add Jquery scroll pagination plugin
2846
        $htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
2847
        // Add Jquery Time ago plugin
2848
        $htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
2849
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
2850
        if (file_exists($timeAgoLocaleDir)) {
2851
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
2852
        }
2853
2854
        if ($countPost > self::DEFAULT_WALL_POSTS) {
2855
            $htmlHeadXtra[] = '<script>
2856
            $(function() {
2857
                var container = $("#wallMessages");
2858
                container.jscroll({
2859
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
2860
                    nextSelector: "a.nextPage:last",
2861
                    contentSelector: "",
2862
                    callback: timeAgo
2863
                });
2864
            });
2865
            </script>';
2866
        }
2867
2868
        $htmlHeadXtra[] = '<script>
2869
            function deleteMessage(id)
2870
            {
2871
                $.ajax({
2872
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2873
                    success: function (result) {
2874
                        if (result) {
2875
                            $("#message_" + id).parent().parent().parent().parent().html(result);
2876
                        }
2877
                    }
2878
                });
2879
            }
2880
2881
            function deleteComment(id)
2882
            {
2883
                $.ajax({
2884
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2885
                    success: function (result) {
2886
                        if (result) {
2887
                            $("#message_" + id).parent().parent().parent().html(result);
2888
                        }
2889
                    }
2890
                });
2891
            }
2892
2893
            function submitComment(messageId)
2894
            {
2895
                var data = $("#form_comment_"+messageId).serializeArray();
2896
                $.ajax({
2897
                    type : "POST",
2898
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
2899
                    data: data,
2900
                    success: function (result) {
2901
                        if (result) {
2902
                            $("#post_" + messageId + " textarea").val("");
2903
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
2904
                            $("#post_" + messageId + " .sub-mediapost").append(
2905
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved')).'</div>\')
2906
                            );
2907
2908
                            $("#result_" + messageId + "").fadeIn("fast", function() {
2909
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
2910
                                    $(this).remove();
2911
                                });
2912
                            });
2913
                        }
2914
                    }
2915
                });
2916
            }
2917
2918
            $(function() {
2919
                timeAgo();
2920
2921
                /*$(".delete_message").on("click", function() {
2922
                    var id = $(this).attr("id");
2923
                    id = id.split("_")[1];
2924
                    $.ajax({
2925
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2926
                        success: function (result) {
2927
                            if (result) {
2928
                                $("#message_" + id).parent().parent().parent().parent().html(result);
2929
                            }
2930
                        }
2931
                    });
2932
                });
2933
2934
2935
                $(".delete_comment").on("click", function() {
2936
                    var id = $(this).attr("id");
2937
                    id = id.split("_")[1];
2938
                    $.ajax({
2939
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2940
                        success: function (result) {
2941
                            if (result) {
2942
                                $("#message_" + id).parent().parent().parent().html(result);
2943
                            }
2944
                        }
2945
                    });
2946
                });
2947
                */
2948
            });
2949
2950
            function timeAgo() {
2951
                $(".timeago").timeago();
2952
            }
2953
            </script>';
2954
    }
2955
2956
    /**
2957
     * @param int $userId
2958
     * @param int $countPost
2959
     *
2960
     * @return string
2961
     */
2962
    public static function getAutoExtendLink($userId, $countPost)
2963
    {
2964
        $userId = (int) $userId;
2965
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
2966
        $socialAutoExtendLink = '';
2967
        if ($countPost > self::DEFAULT_WALL_POSTS) {
2968
            $socialAutoExtendLink = Display::url(
2969
                get_lang('SeeMore'),
2970
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
2971
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
2972
                [
2973
                    'class' => 'nextPage next',
2974
                ]
2975
            );
2976
        }
2977
2978
        return $socialAutoExtendLink;
2979
    }
2980
2981
    /**
2982
     * @param int $userId
2983
     *
2984
     * @return array
2985
     */
2986
    public static function getThreadList($userId)
2987
    {
2988
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
2989
2990
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
2991
2992
        $threads = [];
2993
        if (!empty($forumCourseId)) {
2994
            $courseInfo = api_get_course_info_by_id($forumCourseId);
2995
            getNotificationsPerUser($userId, true, $forumCourseId);
2996
            $notification = Session::read('forum_notification');
2997
            Session::erase('forum_notification');
2998
2999
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
3000
                'cidReq' => $courseInfo['code'],
3001
            ]).'&';
3002
            if (isset($notification['thread']) && !empty($notification['thread'])) {
3003
                $threadList = array_filter(array_unique($notification['thread']));
3004
                $em = Database::getManager();
3005
                $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
3006
                foreach ($threadList as $threadId) {
3007
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
3008
                    $thread = $repo->find($threadId);
3009
                    if ($thread) {
3010
                        $threadUrl = $threadUrlBase.http_build_query([
3011
                            'forum' => $thread->getForumId(),
3012
                            'thread' => $thread->getIid(),
3013
                        ]);
3014
                        $threads[] = [
3015
                            'id' => $threadId,
3016
                            'url' => Display::url(
3017
                                $thread->getThreadTitle(),
3018
                                $threadUrl
3019
                            ),
3020
                            'name' => Display::url(
3021
                                $thread->getThreadTitle(),
3022
                                $threadUrl
3023
                            ),
3024
                            'description' => '',
3025
                        ];
3026
                    }
3027
                }
3028
            }
3029
        }
3030
3031
        return $threads;
3032
    }
3033
3034
    /**
3035
     * @param int $userId
3036
     *
3037
     * @return string
3038
     */
3039
    public static function getGroupBlock($userId)
3040
    {
3041
        $threadList = self::getThreadList($userId);
3042
        $userGroup = new UserGroup();
3043
3044
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3045
        $courseInfo = null;
3046
        if (!empty($forumCourseId)) {
3047
            $courseInfo = api_get_course_info_by_id($forumCourseId);
3048
        }
3049
3050
        $social_group_block = '';
3051
        if (!empty($courseInfo)) {
3052
            if (!empty($threadList)) {
3053
                $social_group_block .= '<div class="list-group">';
3054
                foreach ($threadList as $group) {
3055
                    $social_group_block .= ' <li class="list-group-item">';
3056
                    $social_group_block .= $group['name'];
3057
                    $social_group_block .= '</li>';
3058
                }
3059
                $social_group_block .= '</div>';
3060
            }
3061
3062
            $social_group_block .= Display::url(
3063
                get_lang('SeeAllCommunities'),
3064
                api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code']
3065
            );
3066
3067
            if (!empty($social_group_block)) {
3068
                $social_group_block = Display::panelCollapse(
3069
                    get_lang('MyCommunities'),
3070
                    $social_group_block,
3071
                    'sm-groups',
3072
                    null,
3073
                    'grups-acordion',
3074
                    'groups-collapse'
3075
                );
3076
            }
3077
        } else {
3078
            // Load my groups
3079
            $results = $userGroup->get_groups_by_user(
3080
                $userId,
3081
                [
3082
                    GROUP_USER_PERMISSION_ADMIN,
3083
                    GROUP_USER_PERMISSION_READER,
3084
                    GROUP_USER_PERMISSION_MODERATOR,
3085
                    GROUP_USER_PERMISSION_HRM,
3086
                ]
3087
            );
3088
3089
            $myGroups = [];
3090
            if (!empty($results)) {
3091
                foreach ($results as $result) {
3092
                    $id = $result['id'];
3093
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
3094
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
3095
3096
                    $group_url = "group_view.php?id=$id";
3097
3098
                    $link = Display::url(
3099
                        api_ucwords(cut($result['name'], 40, true)),
3100
                        $group_url
3101
                    );
3102
3103
                    $result['name'] = $link;
3104
3105
                    $picture = $userGroup->get_picture_group(
3106
                        $id,
3107
                        $result['picture'],
3108
                        null,
3109
                        GROUP_IMAGE_SIZE_BIG
3110
                    );
3111
3112
                    $result['picture'] = '<img class="img-responsive" src="'.$picture['file'].'" />';
3113
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
3114
                        get_lang('SeeMore').'</a></div>';
3115
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
3116
                    $myGroups[] = [
3117
                        'url' => Display::url(
3118
                            $result['picture'],
3119
                            $group_url
3120
                        ),
3121
                        'name' => $result['name'],
3122
                        'description' => $group_info.$group_actions,
3123
                    ];
3124
                }
3125
3126
                $social_group_block .= '<div class="list-group">';
3127
                foreach ($myGroups as $group) {
3128
                    $social_group_block .= ' <li class="list-group-item">';
3129
                    $social_group_block .= $group['name'];
3130
                    $social_group_block .= '</li>';
3131
                }
3132
                $social_group_block .= '</div>';
3133
3134
                $form = new FormValidator(
3135
                    'find_groups_form',
3136
                    'get',
3137
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
3138
                    null,
3139
                    null,
3140
                    FormValidator::LAYOUT_BOX_NO_LABEL
3141
                );
3142
                $form->addHidden('search_type', 2);
3143
3144
                $form->addText(
3145
                    'q',
3146
                    get_lang('Search'),
3147
                    false,
3148
                    [
3149
                        'aria-label' => get_lang('Search'),
3150
                        'custom' => true,
3151
                        'placeholder' => get_lang('Search'),
3152
                    ]
3153
                );
3154
3155
                $social_group_block .= $form->returnForm();
3156
3157
                if (!empty($social_group_block)) {
3158
                    $social_group_block = Display::panelCollapse(
3159
                        get_lang('MyGroups'),
3160
                        $social_group_block,
3161
                        'sm-groups',
3162
                        null,
3163
                        'grups-acordion',
3164
                        'groups-collapse'
3165
                    );
3166
                }
3167
            }
3168
        }
3169
3170
        return $social_group_block;
3171
    }
3172
3173
    /**
3174
     * Returns the formatted header message post.
3175
     *
3176
     * @param int   $authorInfo
3177
     * @param int   $receiverInfo
3178
     * @param array $message      Message data
3179
     *
3180
     * @return string $html       The formatted header message post
3181
     */
3182
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
3183
    {
3184
        $currentUserId = api_get_user_id();
3185
        $authorId = (int) $authorInfo['user_id'];
3186
        $receiverId = (int) $receiverInfo['user_id'];
3187
        $iconStatus = $authorInfo['icon_status'];
3188
3189
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
3190
        $avatarAuthor = $authorInfo['avatar'];
3191
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
3192
        $nameCompleteAuthor = $authorInfo['complete_name'];
3193
3194
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
3195
        $nameCompleteReceiver = $receiverInfo['complete_name'];
3196
3197
        $htmlReceiver = '';
3198
        if ($authorId !== $receiverId) {
3199
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
3200
        }
3201
3202
        if (!empty($message['group_info'])) {
3203
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
3204
        }
3205
        $canEdit = ($currentUserId == $authorInfo['user_id'] || $currentUserId == $receiverInfo['user_id']) && empty($message['group_info']);
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: $canEdit = ($currentUser...message['group_info'])), Probably Intended Meaning: $canEdit = $currentUserI...message['group_info']))
Loading history...
3206
3207
        if (!empty($message['thread_id'])) {
3208
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
3209
            $canEdit = false;
3210
        }
3211
3212
        $postAttachment = self::getPostAttachment($message);
3213
3214
        $html = '<div class="top-mediapost" >';
3215
        $html .= '<div class="pull-right btn-group btn-group-sm">';
3216
3217
        $html .= MessageManager::getLikesButton(
3218
            $message['id'],
3219
            $currentUserId,
3220
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
3221
        );
3222
3223
        if ($canEdit) {
3224
            $htmlDelete = Display::url(
3225
                Display::returnFontAwesomeIcon('trash', '', true),
3226
                'javascript:void(0)',
3227
                [
3228
                    'id' => 'message_'.$message['id'],
3229
                    'title' => get_lang('SocialMessageDelete'),
3230
                    'onclick' => 'deleteMessage('.$message['id'].')',
3231
                    'class' => 'btn btn-default',
3232
                ]
3233
            );
3234
3235
            $html .= $htmlDelete;
3236
        }
3237
        $html .= '</div>';
3238
3239
        $html .= '<div class="user-image" >';
3240
        $html .= '<a href="'.$urlAuthor.'">
3241
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
3242
        $html .= '</div>';
3243
        $html .= '<div class="user-data">';
3244
        $html .= $iconStatus;
3245
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
3246
        $html .= '<div class="post-date">'.$date.'</div>';
3247
        $html .= '</div>';
3248
        $html .= '<div class="msg-content">';
3249
        if (!empty($postAttachment)) {
3250
            $html .= '<div class="post-attachment thumbnail">';
3251
            $html .= $postAttachment;
3252
            $html .= '</div>';
3253
        }
3254
        $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
3255
        $html .= '</div>';
3256
        $html .= '</div>'; // end mediaPost
3257
3258
        // Popularity post functionality
3259
        $html .= '<div class="popularity-mediapost"></div>';
3260
3261
        return $html;
3262
    }
3263
3264
    public static function getHomeProfileTabs($selected = 'home')
3265
    {
3266
        $headers = [
3267
            [
3268
                'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
3269
                'content' => get_lang('Profile'),
3270
            ]
3271
        ];
3272
        $allowJustification = api_get_plugin_setting('justification', 'tool_enable') === 'true';
3273
        if ($allowJustification) {
3274
            $plugin = Justification::create();
3275
            $headers[] = [
3276
                'url' => api_get_path(WEB_CODE_PATH).'auth/justification.php',
3277
                'content' => $plugin->get_lang('Justification'),
3278
            ];
3279
        }
3280
3281
        $allowPauseTraining = api_get_plugin_setting('pausetraining', 'tool_enable') === 'true';
3282
        $allowEdit = api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation') === 'true';
3283
        if ($allowPauseTraining && $allowEdit) {
3284
            $plugin = PauseTraining::create();
3285
            $headers[] = [
3286
                'url' => api_get_path(WEB_CODE_PATH).'auth/pausetraining.php',
3287
                'content' => $plugin->get_lang('PauseTraining'),
3288
            ];
3289
        }
3290
3291
        $selectedItem = 1;
3292
        foreach ($headers as $header) {
3293
            $info = pathinfo($header['url']);
3294
            if ($selected === $info['filename']) {
3295
                break;
3296
            }
3297
            $selectedItem++;
3298
        }
3299
3300
        $tabs = '';
3301
        if (count($headers) > 1) {
3302
            $tabs = Display::tabsOnlyLink($headers, $selectedItem);
3303
        }
3304
3305
        return $tabs;
3306
    }
3307
}
3308