Passed
Pull Request — 1.11.x (#3931)
by Angel Fernando Quiroz
24:49 queued 15:46
created

SocialManager::display_individual_user()   B

Complexity

Conditions 9
Paths 129

Size

Total Lines 59
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 39
nc 129
nop 1
dl 0
loc 59
rs 7.5471
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CForumPost;
6
use Chamilo\CourseBundle\Entity\CForumThread;
7
use ChamiloSession as Session;
8
use Zend\Feed\Reader\Entry\Rss;
9
use Zend\Feed\Reader\Reader;
10
11
/**
12
 * Class SocialManager.
13
 *
14
 * This class provides methods for the social network management.
15
 * Include/require it in your code to use its features.
16
 */
17
class SocialManager extends UserManager
18
{
19
    const DEFAULT_WALL_POSTS = 10;
20
    const DEFAULT_SCROLL_NEW_POST = 5;
21
22
    /**
23
     * Constructor.
24
     */
25
    public function __construct()
26
    {
27
    }
28
29
    /**
30
     * Allow to see contacts list.
31
     *
32
     * @author isaac flores paz
33
     *
34
     * @return array
35
     */
36
    public static function show_list_type_friends()
37
    {
38
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
39
        $sql = 'SELECT id, title FROM '.$table.'
40
                WHERE id<>6
41
                ORDER BY id ASC';
42
        $result = Database::query($sql);
43
        $friend_relation_list = [];
44
        while ($row = Database::fetch_array($result, 'ASSOC')) {
45
            $friend_relation_list[] = $row;
46
        }
47
        $count_list = count($friend_relation_list);
48
        if ($count_list == 0) {
49
            $friend_relation_list[] = get_lang('Unknown');
50
        } else {
51
            return $friend_relation_list;
52
        }
53
    }
54
55
    /**
56
     * Get the kind of relation between contacts.
57
     *
58
     * @param int  $user_id     user id
59
     * @param int  $user_friend user friend id
60
     * @param bool $includeRH   include the RH relationship
61
     *
62
     * @return int
63
     *
64
     * @author isaac flores paz
65
     */
66
    public static function get_relation_between_contacts($user_id, $user_friend, $includeRH = false)
67
    {
68
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
69
        $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
70
        if ($includeRH == 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...
71
            $sql = 'SELECT rt.id as id
72
                FROM '.$table.' rt
73
                WHERE rt.id = (
74
                    SELECT uf.relation_type
75
                    FROM '.$userRelUserTable.' uf
76
                    WHERE
77
                        user_id='.((int) $user_id).' AND
78
                        friend_user_id='.((int) $user_friend).' AND
79
                        uf.relation_type <> '.USER_RELATION_TYPE_RRHH.'
80
                    LIMIT 1
81
                )';
82
        } else {
83
            $sql = 'SELECT rt.id as id
84
                FROM '.$table.' rt
85
                WHERE rt.id = (
86
                    SELECT uf.relation_type
87
                    FROM '.$userRelUserTable.' uf
88
                    WHERE
89
                        user_id='.((int) $user_id).' AND
90
                        friend_user_id='.((int) $user_friend).'
91
                    LIMIT 1
92
                )';
93
        }
94
        $res = Database::query($sql);
95
        if (Database::num_rows($res) > 0) {
96
            $row = Database::fetch_array($res, 'ASSOC');
97
98
            return (int) $row['id'];
99
        } else {
100
            if (api_get_configuration_value('social_make_teachers_friend_all')) {
101
                $adminsList = UserManager::get_all_administrators();
102
                foreach ($adminsList as $admin) {
103
                    if (api_get_user_id() == $admin['user_id']) {
104
                        return USER_RELATION_TYPE_GOODFRIEND;
105
                    }
106
                }
107
                $targetUserCoursesList = CourseManager::get_courses_list_by_user_id(
108
                    $user_id,
109
                    true,
110
                    false
111
                );
112
                $currentUserId = api_get_user_id();
113
                foreach ($targetUserCoursesList as $course) {
114
                    $teachersList = CourseManager::get_teacher_list_from_course_code($course['code']);
115
                    foreach ($teachersList as $teacher) {
116
                        if ($currentUserId == $teacher['user_id']) {
117
                            return USER_RELATION_TYPE_GOODFRIEND;
118
                        }
119
                    }
120
                }
121
            } else {
122
                return USER_UNKNOWN;
123
            }
124
        }
125
    }
126
127
    /**
128
     * Get count of friends from user.
129
     *
130
     * @param int $userId
131
     *
132
     * @return int
133
     */
134
    public static function getCountFriends($userId)
135
    {
136
        $table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
137
        $userId = (int) $userId;
138
        if (empty($userId)) {
139
            return 0;
140
        }
141
142
        $sql = 'SELECT count(friend_user_id) count
143
                FROM '.$table.'
144
                WHERE
145
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
146
                    friend_user_id<>'.$userId.' AND
147
                    user_id='.$userId;
148
        $res = Database::query($sql);
149
        if (Database::num_rows($res)) {
150
            $row = Database::fetch_array($res, 'ASSOC');
151
152
            return (int) $row['count'];
153
        }
154
155
        return 0;
156
    }
157
158
    /**
159
     * Gets friends id list.
160
     *
161
     * @param int  user id
162
     * @param int group id
163
     * @param string name to search
164
     * @param bool true will load firstname, lastname, and image name
165
     *
166
     * @return array
167
     *
168
     * @author Julio Montoya <[email protected]> Cleaning code, function renamed, $load_extra_info option added
169
     * @author isaac flores paz
170
     */
171
    public static function get_friends(
172
        $user_id,
173
        $id_group = null,
174
        $search_name = null,
175
        $load_extra_info = true
176
    ) {
177
        $user_id = (int) $user_id;
178
179
        $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
180
        $tbl_my_user = Database::get_main_table(TABLE_MAIN_USER);
181
        $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
182
                WHERE
183
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
184
                    friend_user_id<>'.$user_id.' AND
185
                    user_id='.$user_id;
186
        if (isset($id_group) && $id_group > 0) {
187
            $sql .= ' AND relation_type='.$id_group;
188
        }
189
        if (isset($search_name)) {
190
            $search_name = trim($search_name);
191
            $search_name = str_replace(' ', '', $search_name);
192
            $sql .= ' AND friend_user_id IN (
193
                SELECT user_id FROM '.$tbl_my_user.'
194
                WHERE
195
                    firstName LIKE "%'.Database::escape_string($search_name).'%" OR
196
                    lastName LIKE "%'.Database::escape_string($search_name).'%" OR
197
                    '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
198
                ) ';
199
        }
200
201
        $res = Database::query($sql);
202
        $list = [];
203
        while ($row = Database::fetch_array($res, 'ASSOC')) {
204
            if ($load_extra_info) {
205
                $userInfo = api_get_user_info($row['friend_user_id']);
206
                $list[] = [
207
                    'friend_user_id' => $row['friend_user_id'],
208
                    'firstName' => $userInfo['firstName'],
209
                    'lastName' => $userInfo['lastName'],
210
                    'username' => $userInfo['username'],
211
                    'image' => $userInfo['avatar'],
212
                    'user_info' => $userInfo,
213
                ];
214
            } else {
215
                $list[] = $row;
216
            }
217
        }
218
219
        return $list;
220
    }
221
222
    /**
223
     * get web path of user invitate.
224
     *
225
     * @author isaac flores paz
226
     * @author Julio Montoya setting variable array
227
     *
228
     * @param int user id
229
     *
230
     * @return array
231
     */
232
    public static function get_list_web_path_user_invitation_by_user_id($user_id)
233
    {
234
        $list_ids = self::get_list_invitation_of_friends_by_user_id($user_id);
235
        $list = [];
236
        foreach ($list_ids as $values_ids) {
237
            $list[] = UserManager::get_user_picture_path_by_id(
238
                $values_ids['user_sender_id'],
239
                'web'
240
            );
241
        }
242
243
        return $list;
244
    }
245
246
    /**
247
     * Sends an invitation to contacts.
248
     *
249
     * @param int user id
250
     * @param int user friend id
251
     * @param string title of the message
252
     * @param string content of the message
253
     *
254
     * @return bool
255
     *
256
     * @author isaac flores paz
257
     * @author Julio Montoya <[email protected]> Cleaning code
258
     */
259
    public static function send_invitation_friend(
260
        $user_id,
261
        $friend_id,
262
        $message_title,
263
        $message_content
264
    ) {
265
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
266
        $user_id = (int) $user_id;
267
        $friend_id = (int) $friend_id;
268
269
        //Just in case we replace the and \n and \n\r while saving in the DB
270
        $message_content = str_replace(["\n", "\n\r"], '<br />', $message_content);
271
272
        $clean_message_content = Database::escape_string($message_content);
273
        $now = api_get_utc_datetime();
274
        $sql = 'SELECT COUNT(*) AS count FROM '.$tbl_message.'
275
                WHERE
276
                    user_sender_id='.$user_id.' AND
277
                    user_receiver_id='.$friend_id.' AND
278
                    msg_status IN('.MESSAGE_STATUS_INVITATION_PENDING.', '.MESSAGE_STATUS_INVITATION_ACCEPTED.', '.MESSAGE_STATUS_INVITATION_DENIED.');
279
                ';
280
        $res_exist = Database::query($sql);
281
        $row_exist = Database::fetch_array($res_exist, 'ASSOC');
282
283
        if ($row_exist['count'] == 0) {
284
            $params = [
285
                'user_sender_id' => $user_id,
286
                'user_receiver_id' => $friend_id,
287
                'msg_status' => MESSAGE_STATUS_INVITATION_PENDING,
288
                'send_date' => $now,
289
                'title' => $message_title,
290
                'content' => $message_content,
291
                'group_id' => 0,
292
                'parent_id' => 0,
293
                'update_date' => $now,
294
            ];
295
            $messageId = Database::insert($tbl_message, $params);
296
297
            $senderInfo = api_get_user_info($user_id);
298
            $notification = new Notification();
299
            $notification->saveNotification(
300
                $messageId,
301
                Notification::NOTIFICATION_TYPE_INVITATION,
302
                [$friend_id],
303
                $message_title,
304
                $message_content,
305
                $senderInfo
306
            );
307
308
            return true;
309
        } else {
310
            // invitation already exist
311
            $sql = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
312
                    WHERE
313
                        user_sender_id='.$user_id.' AND
314
                        user_receiver_id='.$friend_id.' AND
315
                        msg_status = 7';
316
            $res_if_exist = Database::query($sql);
317
            $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
318
            if ($row_if_exist['count'] == 1) {
319
                $sql = 'UPDATE '.$tbl_message.' SET
320
                            msg_status = 5, content = "'.$clean_message_content.'"
321
                        WHERE
322
                            user_sender_id='.$user_id.' AND
323
                            user_receiver_id='.$friend_id.' AND
324
                            msg_status = 7 ';
325
                Database::query($sql);
326
327
                return true;
328
            } else {
329
                return false;
330
            }
331
        }
332
    }
333
334
    /**
335
     * Get number messages of the inbox.
336
     *
337
     * @author isaac flores paz
338
     *
339
     * @param int $userId user receiver id
340
     *
341
     * @return int
342
     */
343
    public static function get_message_number_invitation_by_user_id($userId)
344
    {
345
        $table = Database::get_main_table(TABLE_MESSAGE);
346
        $userId = (int) $userId;
347
        $sql = 'SELECT COUNT(*) as count_message_in_box FROM '.$table.'
348
                WHERE
349
                    user_receiver_id='.$userId.' AND
350
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
351
        $res = Database::query($sql);
352
        $row = Database::fetch_array($res, 'ASSOC');
353
        if ($row) {
354
            return (int) $row['count_message_in_box'];
355
        }
356
357
        return 0;
358
    }
359
360
    /**
361
     * Get number of messages sent to other users.
362
     *
363
     * @param int $userId
364
     *
365
     * @return int
366
     */
367
    public static function getCountMessagesSent($userId)
368
    {
369
        $userId = (int) $userId;
370
        $table = Database::get_main_table(TABLE_MESSAGE);
371
        $sql = 'SELECT COUNT(*) FROM '.$table.'
372
                WHERE
373
                    user_sender_id='.$userId.' AND
374
                    msg_status < 5';
375
        $res = Database::query($sql);
376
        $row = Database::fetch_row($res);
377
378
        return $row[0];
379
    }
380
381
    /**
382
     * Get number of messages received from other users.
383
     *
384
     * @param int $receiver_id
385
     *
386
     * @return int
387
     */
388
    public static function getCountMessagesReceived($receiver_id)
389
    {
390
        $table = Database::get_main_table(TABLE_MESSAGE);
391
        $sql = 'SELECT COUNT(*) FROM '.$table.'
392
                WHERE
393
                    user_receiver_id='.intval($receiver_id).' AND
394
                    msg_status < 4';
395
        $res = Database::query($sql);
396
        $row = Database::fetch_row($res);
397
398
        return $row[0];
399
    }
400
401
    /**
402
     * Get number of messages posted on own wall.
403
     *
404
     * @param int $userId
405
     *
406
     * @return int
407
     */
408
    public static function getCountWallPostedMessages($userId)
409
    {
410
        $userId = (int) $userId;
411
412
        if (empty($userId)) {
413
            return 0;
414
        }
415
416
        $table = Database::get_main_table(TABLE_MESSAGE);
417
        $sql = 'SELECT COUNT(*)
418
                FROM '.$table.'
419
                WHERE
420
                    user_sender_id='.$userId.' AND
421
                    (msg_status = '.MESSAGE_STATUS_WALL.' OR
422
                    msg_status = '.MESSAGE_STATUS_WALL_POST.') AND
423
                    parent_id = 0';
424
        $res = Database::query($sql);
425
        $row = Database::fetch_row($res);
426
427
        return $row[0];
428
    }
429
430
    /**
431
     * Get invitation list received by user.
432
     *
433
     * @author isaac flores paz
434
     *
435
     * @param int $userId
436
     * @param int $limit
437
     *
438
     * @return array
439
     */
440
    public static function get_list_invitation_of_friends_by_user_id($userId, $limit = 0)
441
    {
442
        $userId = (int) $userId;
443
        $limit = (int) $limit;
444
445
        if (empty($userId)) {
446
            return [];
447
        }
448
449
        $table = Database::get_main_table(TABLE_MESSAGE);
450
        $sql = 'SELECT user_sender_id, send_date, title, content
451
                FROM '.$table.'
452
                WHERE
453
                    user_receiver_id = '.$userId.' AND
454
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
455
        if ($limit != null && $limit > 0) {
456
            $sql .= ' LIMIT '.$limit;
457
        }
458
        $res = Database::query($sql);
459
        $list = [];
460
        while ($row = Database::fetch_array($res, 'ASSOC')) {
461
            $list[] = $row;
462
        }
463
464
        return $list;
465
    }
466
467
    /**
468
     * Get invitation list sent by user.
469
     *
470
     * @author Julio Montoya <[email protected]>
471
     *
472
     * @param int $userId
473
     *
474
     * @return array
475
     */
476
    public static function get_list_invitation_sent_by_user_id($userId)
477
    {
478
        $userId = (int) $userId;
479
480
        if (empty($userId)) {
481
            return [];
482
        }
483
484
        $table = Database::get_main_table(TABLE_MESSAGE);
485
        $sql = 'SELECT user_receiver_id, send_date,title,content
486
                FROM '.$table.'
487
                WHERE
488
                    user_sender_id = '.$userId.' AND
489
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
490
        $res = Database::query($sql);
491
        $list = [];
492
        while ($row = Database::fetch_array($res, 'ASSOC')) {
493
            $list[$row['user_receiver_id']] = $row;
494
        }
495
496
        return $list;
497
    }
498
499
    /**
500
     * Get count invitation sent by user.
501
     *
502
     * @author Julio Montoya <[email protected]>
503
     *
504
     * @param int $userId
505
     *
506
     * @return int
507
     */
508
    public static function getCountInvitationSent($userId)
509
    {
510
        $userId = (int) $userId;
511
512
        if (empty($userId)) {
513
            return 0;
514
        }
515
516
        $table = Database::get_main_table(TABLE_MESSAGE);
517
        $sql = 'SELECT count(user_receiver_id) count
518
                FROM '.$table.'
519
                WHERE
520
                    user_sender_id = '.$userId.' AND
521
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
522
        $res = Database::query($sql);
523
        if (Database::num_rows($res)) {
524
            $row = Database::fetch_array($res, 'ASSOC');
525
526
            return (int) $row['count'];
527
        }
528
529
        return 0;
530
    }
531
532
    /**
533
     * Accepts invitation.
534
     *
535
     * @param int $user_send_id
536
     * @param int $user_receiver_id
537
     *
538
     * @return bool
539
     *
540
     * @author isaac flores paz
541
     * @author Julio Montoya <[email protected]> Cleaning code
542
     */
543
    public static function invitation_accepted($user_send_id, $user_receiver_id)
544
    {
545
        if (empty($user_send_id) || empty($user_receiver_id)) {
546
            return false;
547
        }
548
549
        $table = Database::get_main_table(TABLE_MESSAGE);
550
        $sql = "UPDATE $table
551
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
552
                WHERE
553
                    user_sender_id = ".((int) $user_send_id)." AND
554
                    user_receiver_id=".((int) $user_receiver_id)." AND
555
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
556
        Database::query($sql);
557
558
        return true;
559
    }
560
561
    /**
562
     * Denies invitation.
563
     *
564
     * @param int user sender id
565
     * @param int user receiver id
566
     *
567
     * @return bool
568
     *
569
     * @author isaac flores paz
570
     * @author Julio Montoya <[email protected]> Cleaning code
571
     */
572
    public static function invitation_denied($user_send_id, $user_receiver_id)
573
    {
574
        if (empty($user_send_id) || empty($user_receiver_id)) {
575
            return false;
576
        }
577
        $table = Database::get_main_table(TABLE_MESSAGE);
578
        $sql = 'DELETE FROM '.$table.'
579
                WHERE
580
                    user_sender_id =  '.((int) $user_send_id).' AND
581
                    user_receiver_id='.((int) $user_receiver_id).' AND
582
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
583
        Database::query($sql);
584
585
        return true;
586
    }
587
588
    /**
589
     * Get user's feeds.
590
     *
591
     * @param int $user  User ID
592
     * @param int $limit Limit of posts per feed
593
     *
594
     * @return string HTML section with all feeds included
595
     *
596
     * @author  Yannick Warnier
597
     *
598
     * @since   Dokeos 1.8.6.1
599
     */
600
    public static function getUserRssFeed($user, $limit = 5)
601
    {
602
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
603
604
        if (empty($feed)) {
605
            return '';
606
        }
607
        $feeds = explode(';', $feed['rssfeeds']);
608
        if (0 == count($feeds)) {
609
            return '';
610
        }
611
        $res = '';
612
        foreach ($feeds as $url) {
613
            if (empty($url)) {
614
                continue;
615
            }
616
            try {
617
                $channel = Reader::import($url);
618
                $i = 1;
619
                if (!empty($channel)) {
620
                    $iconRss = '';
621
                    if (!empty($feed)) {
622
                        $iconRss = Display::url(
623
                            Display::return_icon('social_rss.png', '', [], 22),
624
                            Security::remove_XSS($feed['rssfeeds']),
625
                            ['target' => '_blank']
626
                        );
627
                    }
628
629
                    $res .= '<h3 class="title-rss">'.$iconRss.' '.$channel->getTitle().'</h3>';
630
                    $res .= '<div class="rss-items">';
631
                    /** @var Rss $item */
632
                    foreach ($channel as $item) {
633
                        if ($limit >= 0 and $i > $limit) {
634
                            break;
635
                        }
636
                        $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
637
                        $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
638
                        $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
639
                        $i++;
640
                    }
641
                    $res .= '</div>';
642
                }
643
            } catch (Exception $e) {
644
                error_log($e->getMessage());
645
            }
646
        }
647
648
        return $res;
649
    }
650
651
    /**
652
     * Sends invitations to friends.
653
     *
654
     * @param int    $userId
655
     * @param string $subject
656
     * @param string $content
657
     *
658
     * @return bool
659
     */
660
    public static function sendInvitationToUser($userId, $subject = '', $content = '')
661
    {
662
        $user_info = api_get_user_info($userId);
663
        $success = get_lang('MessageSentTo');
664
        $success .= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
665
        $content = strip_tags($content);
666
667
        if (isset($subject) && isset($content) && isset($userId)) {
668
            $result = MessageManager::send_message($userId, $subject, $content);
669
670
            if ($result) {
671
                Display::addFlash(
672
                    Display::return_message($success, 'normal', false)
673
                );
674
            } else {
675
                Display::addFlash(
676
                    Display::return_message(get_lang('ErrorSendingMessage'), 'error', false)
677
                );
678
            }
679
680
            return false;
681
        } elseif (isset($userId) && !isset($subject)) {
682
            if (isset($userId) && $userId > 0) {
683
                $count = self::send_invitation_friend(
684
                    api_get_user_id(),
685
                    $userId,
686
                    get_lang('Invitation'),
687
                    $content
688
                );
689
690
                if ($count) {
691
                    Display::addFlash(
692
                        Display::return_message(
693
                            api_htmlentities(get_lang('InvitationHasBeenSent')),
694
                            'normal',
695
                            false
696
                        )
697
                    );
698
                } else {
699
                    Display::addFlash(
700
                        Display::return_message(
701
                            api_htmlentities(get_lang('YouAlreadySentAnInvitation')),
702
                            'warning',
703
                            false
704
                        )
705
                    );
706
                }
707
            }
708
        }
709
    }
710
711
    /**
712
     * Helper functions definition.
713
     */
714
    public static function get_logged_user_course_html($my_course, $count)
715
    {
716
        $result = '';
717
        $count = (int) $count;
718
719
        // Table definitions
720
        $main_user_table = Database::get_main_table(TABLE_MAIN_USER);
721
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
722
        $course_directory = $my_course['course_info']['directory'];
723
        $course_title = $my_course['course_info']['title'];
724
        $course_visibility = $my_course['course_info']['visibility'];
725
726
        $user_in_course_status = CourseManager::getUserInCourseStatus(
727
            api_get_user_id(),
728
            $my_course['course_info']['real_id']
729
        );
730
731
        $course_path = api_get_path(SYS_COURSE_PATH).$course_directory; // course path
732
        if (api_get_setting('course_images_in_courses_list') === 'true') {
733
            if (file_exists($course_path.'/course-pic85x85.png')) {
734
                $image = $my_course['course_info']['course_image'];
735
                $imageCourse = Display::img($image, $course_title, ['class' => 'img-course']);
736
            } else {
737
                $imageCourse = Display::return_icon(
738
                    'session_default_small.png',
739
                    $course_title,
740
                    ['class' => 'img-course']
741
                );
742
            }
743
        } else {
744
            $imageCourse = Display::return_icon(
745
                'course.png',
746
                get_lang('Course'),
747
                ['class' => 'img-default']
748
            );
749
        }
750
751
        //display course entry
752
        if (api_get_setting('course_images_in_courses_list') === 'true') {
753
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:65px;">';
754
        } else {
755
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:44px;">';
756
        }
757
        $result .= $imageCourse;
758
759
        //show a hyperlink to the course, unless the course is closed and user is not course admin
760
        if ($course_visibility != COURSE_VISIBILITY_HIDDEN &&
761
            ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER)
762
        ) {
763
            $result .= '<span class="title">'.$course_title.'<span>';
764
        } else {
765
            $result .= $course_title.' '.get_lang('CourseClosed');
766
        }
767
768
        $result .= '</li>';
769
        $session = '';
770
        if (!empty($my_course['session_name']) && !empty($my_course['id_session'])) {
771
            // Request for the name of the general coach
772
            $sql = 'SELECT lastname, firstname
773
                    FROM '.$tbl_session.' ts
774
                    LEFT JOIN '.$main_user_table.' tu
775
                    ON ts.id_coach = tu.user_id
776
                    WHERE ts.id='.(int) $my_course['id_session'].' LIMIT 1';
777
            $rs = Database::query($sql);
778
            $sessioncoach = Database::store_result($rs);
779
            $sessioncoach = $sessioncoach[0];
780
781
            $session = [];
782
            $session['title'] = $my_course['session_name'];
783
            if ($my_course['access_start_date'] == '0000-00-00') {
784
                $session['dates'] = get_lang('WithoutTimeLimits');
785
                if (api_get_setting('show_session_coach') === 'true') {
786
                    $session['coach'] = get_lang('GeneralCoach').': '.
787
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
788
                }
789
            } else {
790
                $session['dates'] = ' - '.get_lang('From').' '.$my_course['access_start_date'].' '.get_lang('To').' '.$my_course['access_end_date'];
791
                if (api_get_setting('show_session_coach') === 'true') {
792
                    $session['coach'] = get_lang('GeneralCoach').': '.
793
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
794
                }
795
            }
796
        }
797
798
        $my_course['id_session'] = isset($my_course['id_session']) ? $my_course['id_session'] : 0;
799
        $output = [
800
            $my_course['user_course_cat'],
801
            $result,
802
            $my_course['id_session'],
803
            $session,
804
        ];
805
806
        return $output;
807
    }
808
809
    /**
810
     * Shows the avatar block in social pages.
811
     *
812
     * @param string $show     highlight link possible values:
813
     *                         group_add,
814
     *                         home,
815
     *                         messages,
816
     *                         messages_inbox,
817
     *                         messages_compose,
818
     *                         messages_outbox,
819
     *                         invitations,
820
     *                         shared_profile,
821
     *                         friends,
822
     *                         groups search
823
     * @param int    $group_id
824
     * @param int    $user_id
825
     */
826
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
827
    {
828
        $user_id = (int) $user_id;
829
        $group_id = (int) $group_id;
830
831
        if (empty($user_id)) {
832
            $user_id = api_get_user_id();
833
        }
834
835
        $show_groups = [
836
            'groups',
837
            'group_messages',
838
            'messages_list',
839
            'group_add',
840
            'mygroups',
841
            'group_edit',
842
            'member_list',
843
            'invite_friends',
844
            'waiting_list',
845
            'browse_groups',
846
        ];
847
848
        $template = new Template(null, false, false, false, false, false);
849
850
        if (in_array($show, $show_groups) && !empty($group_id)) {
851
            // Group image
852
            $userGroup = new UserGroup();
853
            $group_info = $userGroup->get($group_id);
854
855
            $userGroupImage = $userGroup->get_picture_group(
856
                $group_id,
857
                $group_info['picture'],
858
                128,
859
                GROUP_IMAGE_SIZE_BIG
860
            );
861
862
            $template->assign('show_group', true);
863
            $template->assign('group_id', $group_id);
864
            $template->assign('user_group_image', $userGroupImage);
865
            $template->assign(
866
                'user_is_group_admin',
867
                $userGroup->is_group_admin(
868
                    $group_id,
869
                    api_get_user_id()
870
                )
871
            );
872
        } else {
873
            $template->assign('show_group', false);
874
            $template->assign('show_user', true);
875
            $template->assign(
876
                'user_image',
877
                [
878
                    'big' => UserManager::getUserPicture(
879
                        $user_id,
880
                        USER_IMAGE_SIZE_BIG
881
                    ),
882
                    'normal' => UserManager::getUserPicture(
883
                        $user_id,
884
                        USER_IMAGE_SIZE_MEDIUM
885
                    ),
886
                ]
887
            );
888
        }
889
890
        return $template->fetch($template->get_template('social/avatar_block.tpl'));
891
    }
892
893
    /**
894
     * Shows the right menu of the Social Network tool.
895
     *
896
     * @param string $show                       highlight link possible values:
897
     *                                           group_add,
898
     *                                           home,
899
     *                                           messages,
900
     *                                           messages_inbox,
901
     *                                           messages_compose ,
902
     *                                           messages_outbox,
903
     *                                           invitations,
904
     *                                           shared_profile,
905
     *                                           friends,
906
     *                                           groups search
907
     * @param int    $group_id                   group id
908
     * @param int    $user_id                    user id
909
     * @param bool   $show_full_profile          show profile or not (show or hide the user image/information)
910
     * @param bool   $show_delete_account_button
911
     */
912
    public static function show_social_menu(
913
        $show = '',
914
        $group_id = 0,
915
        $user_id = 0,
916
        $show_full_profile = false,
917
        $show_delete_account_button = false
918
    ) {
919
        $user_id = (int) $user_id;
920
        $group_id = (int) $group_id;
921
        $settingExtendedProfileEnabled = api_get_setting('extended_profile');
922
923
        if (empty($user_id)) {
924
            $user_id = api_get_user_id();
925
        }
926
927
        $myExtendedProfileEdit = '';
928
        if ($user_id == api_get_user_id()) {
929
            $myExtendedProfileEdit .= '<a href="/main/auth/profile.php?type=extended#openarea" style="display:initial">'.
930
                Display::return_icon('edit.png', get_lang('EditExtendProfile'), '', 16).'</a>';
931
        }
932
        $usergroup = new UserGroup();
933
        $show_groups = [
934
            'groups',
935
            'group_messages',
936
            'messages_list',
937
            'group_add',
938
            'mygroups',
939
            'group_edit',
940
            'member_list',
941
            'invite_friends',
942
            'waiting_list',
943
            'browse_groups',
944
        ];
945
946
        // get count unread message and total invitations
947
        $count_unread_message = MessageManager::getCountNewMessagesFromDB(api_get_user_id());
948
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
949
950
        $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
951
        $group_pending_invitations = $usergroup->get_groups_by_user(
952
            api_get_user_id(),
953
            GROUP_USER_PERMISSION_PENDING_INVITATION,
954
            false
955
        );
956
        $group_pending_invitations = count($group_pending_invitations);
957
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
958
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
959
960
        $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), null, ICON_SIZE_SMALL);
961
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), null, ICON_SIZE_SMALL);
962
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), null, ICON_SIZE_SMALL);
963
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), null, ICON_SIZE_SMALL);
964
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), null, ICON_SIZE_SMALL);
965
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), null, ICON_SIZE_SMALL);
966
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
967
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), null, ICON_SIZE_SMALL);
968
        $portfolioIcon = Display::return_icon('wiki_task.png', get_lang('Portfolio'));
969
        $personalDataIcon = Display::return_icon('database.png', get_lang('PersonalDataReport'));
970
        $messageSocialIcon = Display::return_icon('promoted_message.png', get_lang('PromotedMessages'));
971
        $portfolio = Display::return_icon('portfolio.png', get_lang('Portfolio '));
972
973
        $allowPortfolioTool = api_get_configuration_value('allow_portfolio_tool');
974
975
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
976
        $groupUrl = api_get_path(WEB_CODE_PATH).'social/groups.php';
977
        if (!empty($forumCourseId)) {
978
            $courseInfo = api_get_course_info_by_id($forumCourseId);
979
            if (!empty($courseInfo)) {
980
                $groupUrl = api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code'];
981
            }
982
        }
983
984
        $html = '';
985
        $active = null;
986
        if (!in_array(
987
            $show,
988
            ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
989
        )) {
990
            $links = '<ul class="nav nav-pills nav-stacked">';
991
            $active = $show === 'home' ? 'active' : null;
992
            $links .= '
993
                <li class="home-icon '.$active.'">
994
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
995
                        '.$homeIcon.' '.get_lang('Home').'
996
                    </a>
997
                </li>';
998
            $active = $show === 'messages' ? 'active' : null;
999
            $links .= '
1000
                <li class="messages-icon '.$active.'">
1001
                    <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
1002
                        '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
1003
                    </a>
1004
                </li>';
1005
            if ($allowPortfolioTool) {
1006
                $links .= '
1007
                    <li class="portoflio-icon '.($show === 'portfolio' ? 'active' : '').'">
1008
                        <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1009
                            '.$portfolioIcon.' '.get_lang('Portfolio').'
1010
                        </a>
1011
                    </li>
1012
                ';
1013
            } else {
1014
                if ($settingExtendedProfileEnabled == true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $settingExtendedProfileEnabled of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
1015
                    $active = $show === 'portfolio' ? 'active' : null;
1016
                    $links .= '
1017
                <li class="portfolio-icon '.$active.'">
1018
                      <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id.'&p=1">
1019
                        '.$portfolio.' '.get_lang('Portfolio').'
1020
                    </a>
1021
                </li>';
1022
                }
1023
            }
1024
1025
            // Invitations
1026
            $active = $show === 'invitations' ? 'active' : null;
1027
            $links .= '
1028
                <li class="invitations-icon '.$active.'">
1029
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
1030
                        '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
1031
                    </a>
1032
                </li>';
1033
1034
            // Shared profile and groups
1035
            $active = $show === 'shared_profile' ? 'active' : null;
1036
            $links .= '
1037
                <li class="shared-profile-icon'.$active.'">
1038
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1039
                        '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1040
                    </a>
1041
                </li>';
1042
            $active = $show === 'friends' ? 'active' : null;
1043
            $links .= '
1044
                <li class="friends-icon '.$active.'">
1045
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1046
                        '.$friendsIcon.' '.get_lang('Friends').'
1047
                    </a>
1048
                </li>';
1049
            $active = $show === 'browse_groups' ? 'active' : null;
1050
            $links .= '
1051
                <li class="browse-groups-icon '.$active.'">
1052
                    <a href="'.$groupUrl.'">
1053
                        '.$groupsIcon.' '.get_lang('SocialGroups').'
1054
                    </a>
1055
                </li>';
1056
1057
            // Search users
1058
            $active = $show === 'search' ? 'active' : null;
1059
            $links .= '
1060
                <li class="search-icon '.$active.'">
1061
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1062
                        '.$searchIcon.' '.get_lang('Search').'
1063
                    </a>
1064
                </li>';
1065
1066
            // My files
1067
            $active = $show === 'myfiles' ? 'active' : null;
1068
1069
            $myFiles = '
1070
                <li class="myfiles-icon '.$active.'">
1071
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1072
                        '.$filesIcon.' '.get_lang('MyFiles').'
1073
                    </a>
1074
                </li>';
1075
1076
            if (api_get_setting('allow_my_files') === 'false') {
1077
                $myFiles = '';
1078
            }
1079
            $links .= $myFiles;
1080
1081
            if (!api_get_configuration_value('disable_gdpr')) {
1082
                $active = $show === 'personal-data' ? 'active' : null;
1083
                $personalData = '
1084
                    <li class="personal-data-icon '.$active.'">
1085
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1086
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1087
                        </a>
1088
                    </li>';
1089
                $links .= $personalData;
1090
            }
1091
1092
            if (api_is_platform_admin()) {
1093
                $active = $show === 'promoted_messages' ? 'active' : null;
1094
                $personalData = '
1095
                    <li class="personal-data-icon '.$active.'">
1096
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/promoted_messages.php">
1097
                            '.$messageSocialIcon.' '.get_lang('PromotedMessages').'
1098
                        </a>
1099
                    </li>';
1100
                $links .= $personalData;
1101
            }
1102
            $links .= '</ul>';
1103
            $html .= Display::panelCollapse(
1104
                get_lang('SocialNetwork'),
1105
                $links,
1106
                'social-network-menu',
1107
                null,
1108
                'sn-sidebar',
1109
                'sn-sidebar-collapse'
1110
            );
1111
        }
1112
1113
        if (!empty($group_id) && in_array($show, $show_groups)) {
1114
            $html .= $usergroup->show_group_column_information(
1115
                $group_id,
1116
                api_get_user_id(),
1117
                $show
1118
            );
1119
        }
1120
1121
        if ($show === 'shared_profile') {
1122
            $links = '<ul class="nav nav-pills nav-stacked">';
1123
            // My own profile
1124
            if ($show_full_profile && $user_id == api_get_user_id()) {
1125
                $links .= '
1126
                    <li class="home-icon '.$active.'">
1127
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
1128
                            '.$homeIcon.' '.get_lang('Home').'
1129
                        </a>
1130
                    </li>
1131
                    <li class="messages-icon '.$active.'">
1132
                        <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
1133
                            '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
1134
                        </a>
1135
                    </li>';
1136
                if ($allowPortfolioTool) {
1137
                    $links .= '
1138
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1139
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1140
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1141
                            </a>
1142
                        </li>
1143
                    ';
1144
                } else {
1145
                    if ($settingExtendedProfileEnabled == true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $settingExtendedProfileEnabled of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
1146
                        $active = $show === 'portfolio' ? 'active' : null;
1147
                        $links .= '
1148
                <li class="portfolio-icon '.$active.'">
1149
                      <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id.'&p=1">
1150
                      '.$portfolio.' '.get_lang('Portfolio').'
1151
                    </a>
1152
                </li>';
1153
                    }
1154
                }
1155
                $active = $show === 'invitations' ? 'active' : null;
1156
                $links .= '
1157
                    <li class="invitations-icon'.$active.'">
1158
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
1159
                            '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
1160
                        </a>
1161
                    </li>';
1162
1163
                $links .= '
1164
                    <li class="shared-profile-icon active">
1165
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1166
                            '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1167
                        </a>
1168
                    </li>
1169
                    <li class="friends-icon">
1170
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1171
                            '.$friendsIcon.' '.get_lang('Friends').'
1172
                        </a>
1173
                    </li>';
1174
1175
                $links .= '<li class="browse-groups-icon">
1176
                        <a href="'.$groupUrl.'">
1177
                            '.$groupsIcon.' '.get_lang('SocialGroups').'
1178
                        </a>
1179
                        </li>';
1180
1181
                $active = $show == 'search' ? 'active' : null;
1182
                $links .= '
1183
                    <li class="search-icon '.$active.'">
1184
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1185
                            '.$searchIcon.' '.get_lang('Search').'
1186
                        </a>
1187
                    </li>';
1188
                $active = $show == 'myfiles' ? 'active' : null;
1189
1190
                $myFiles = '
1191
                    <li class="myfiles-icon '.$active.'">
1192
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1193
                            '.$filesIcon.' '.get_lang('MyFiles').'
1194
                        </a>
1195
                    </li>';
1196
1197
                if (api_get_setting('allow_my_files') === 'false') {
1198
                    $myFiles = '';
1199
                }
1200
                $links .= $myFiles;
1201
1202
                if (!api_get_configuration_value('disable_gdpr')) {
1203
                    $active = $show == 'personal-data' ? 'active' : null;
1204
                    $personalData = '
1205
                    <li class="personal-data-icon '.$active.'">
1206
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1207
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1208
                        </a>
1209
                    </li>';
1210
                    $links .= $personalData;
1211
                    $links .= '</ul>';
1212
                }
1213
            }
1214
1215
            // My friend profile.
1216
            if ($user_id != api_get_user_id()) {
1217
                $sendMessageText = get_lang('SendMessage');
1218
                $sendMessageIcon = Display::return_icon(
1219
                    'new-message.png',
1220
                    $sendMessageText
1221
                );
1222
                $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
1223
                    'a' => 'get_user_popup',
1224
                    'user_id' => $user_id,
1225
                ]);
1226
1227
                $links .= '<li>';
1228
                $links .= Display::url(
1229
                    "$sendMessageIcon $sendMessageText",
1230
                    $sendMessageUrl,
1231
                    [
1232
                        'class' => 'ajax',
1233
                        'title' => $sendMessageText,
1234
                        'data-title' => $sendMessageText,
1235
                    ]
1236
                );
1237
                if ($allowPortfolioTool) {
1238
                    $links .= '
1239
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1240
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id.'">
1241
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1242
                            </a>
1243
                        </li>
1244
                    ';
1245
                } else {
1246
                    if ($settingExtendedProfileEnabled == true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $settingExtendedProfileEnabled of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
1247
                        $active = $show === 'portfolio' ? 'active' : null;
1248
                        $links .= '
1249
                <li class="portfolio-icon '.$active.'">
1250
                      <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user_id.'&p=1">
1251
                        '.$portfolio.' '.get_lang('Portfolio').'
1252
                    </a>
1253
                </li>';
1254
                    }
1255
                }
1256
            }
1257
1258
            // Check if I already sent an invitation message
1259
            $invitationSentList = self::get_list_invitation_sent_by_user_id(api_get_user_id());
1260
1261
            if (isset($invitationSentList[$user_id]) && is_array($invitationSentList[$user_id]) &&
1262
                count($invitationSentList[$user_id]) > 0
1263
            ) {
1264
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
1265
                    Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
1266
                    .'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
1267
            } else {
1268
                if (!$show_full_profile) {
1269
                    $links .= '<li>
1270
                        <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('SendInvitation').'">'.
1271
                        Display::return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').
1272
                        '</a></li>';
1273
                }
1274
            }
1275
1276
            $links .= '</ul>';
1277
            $html .= Display::panelCollapse(
1278
                get_lang('SocialNetwork'),
1279
                $links,
1280
                'social-network-menu',
1281
                null,
1282
                'sn-sidebar',
1283
                'sn-sidebar-collapse'
1284
            );
1285
1286
            if ($show_full_profile && $user_id == api_get_user_id()) {
1287
                // Announcements
1288
                $announcements = [];
1289
                $announcementsByCourse = AnnouncementManager::getAnnoucementCourseTotalByUser($user_id);
1290
                if (!empty($announcementsByCourse)) {
1291
                    foreach ($announcementsByCourse as $announcement) {
1292
                        $url = Display::url(
1293
                            Display::return_icon(
1294
                                'announcement.png',
1295
                                get_lang('Announcements')
1296
                            ).$announcement['course']['name'].' ('.$announcement['count'].')',
1297
                            api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$announcement['course']['code']
1298
                        );
1299
                        $announcements[] = Display::tag('li', $url);
1300
                    }
1301
                }
1302
1303
                if (!empty($announcements)) {
1304
                    $html .= '<div class="social_menu_items">';
1305
                    $html .= '<ul>';
1306
                    foreach ($announcements as $announcement) {
1307
                        $html .= $announcement;
1308
                    }
1309
                    $html .= '</ul>';
1310
                    $html .= '</div>';
1311
                }
1312
            }
1313
        }
1314
1315
        if ($show_delete_account_button) {
1316
            $html .= '<div class="panel panel-default"><div class="panel-body">';
1317
            $html .= '<ul class="nav nav-pills nav-stacked"><li>';
1318
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
1319
            $html .= Display::url(
1320
                Display::return_icon(
1321
                    'delete.png',
1322
                    get_lang('Unsubscribe'),
1323
                    [],
1324
                    ICON_SIZE_TINY
1325
                ).get_lang('Unsubscribe'),
1326
                $url
1327
            );
1328
            $html .= '</li></ul>';
1329
            $html .= '</div></div>';
1330
        }
1331
        $html .= '';
1332
1333
        return $html;
1334
    }
1335
1336
    /**
1337
     * Displays a sortable table with the list of online users.
1338
     *
1339
     * @param array $user_list The list of users to be shown
1340
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
1341
     *
1342
     * @return string HTML block or null if and ID was defined
1343
     * @assert (null) === false
1344
     */
1345
    public static function display_user_list($user_list, $wrap = true)
1346
    {
1347
        $html = '';
1348
1349
        if (isset($_GET['id']) || count($user_list) < 1) {
1350
            return false;
1351
        }
1352
1353
        $course_url = '';
1354
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1355
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
1356
        }
1357
1358
        $hide = api_get_configuration_value('hide_complete_name_in_whoisonline');
1359
        foreach ($user_list as $uid) {
1360
            $user_info = api_get_user_info($uid, true);
1361
            $lastname = $user_info['lastname'];
1362
            $firstname = $user_info['firstname'];
1363
            $completeName = $firstname.', '.$lastname;
1364
            $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);
1365
            $status_icon_chat = null;
1366
            if (isset($user_info['user_is_online_in_chat']) && $user_info['user_is_online_in_chat'] == 1) {
1367
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1368
            } else {
1369
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1370
            }
1371
1372
            $userPicture = $user_info['avatar'];
1373
            $officialCode = '';
1374
            if (api_get_setting('show_official_code_whoisonline') == 'true') {
1375
                $officialCode .= '<div class="items-user-official-code"><p style="min-height: 30px;" title="'.get_lang('OfficialCode').'">'.$user_info['official_code'].'</p></div>';
1376
            }
1377
1378
            if ($hide === true) {
1379
                $completeName = '';
1380
                $firstname = '';
1381
                $lastname = '';
1382
            }
1383
1384
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1385
1386
            $url = null;
1387
            // Anonymous users can't have access to the profile
1388
            if (!api_is_anonymous()) {
1389
                if (api_get_setting('allow_social_tool') === 'true') {
1390
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1391
                } else {
1392
                    $url = '?id='.$uid.$course_url;
1393
                }
1394
            } else {
1395
                $url = null;
1396
            }
1397
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1398
1399
            $html .= '<div class="col-xs-6 col-md-2">
1400
                        <div class="items-user">
1401
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1402
                            <div class="items-user-name">
1403
                            '.$name.'
1404
                            </div>
1405
                            '.$officialCode.'
1406
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1407
                        </div>
1408
                      </div>';
1409
        }
1410
1411
        return $html;
1412
    }
1413
1414
    /**
1415
     * Displays the information of an individual user.
1416
     *
1417
     * @param int $user_id
1418
     *
1419
     * @return string
1420
     */
1421
    public static function display_individual_user($user_id)
1422
    {
1423
        global $interbreadcrumb;
1424
        $safe_user_id = (int) $user_id;
1425
        $currentUserId = api_get_user_id();
1426
1427
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1428
        $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
1429
        $result = Database::query($sql);
1430
        $html = null;
1431
        if (Database::num_rows($result) == 1) {
1432
            $user_object = Database::fetch_object($result);
1433
            $userInfo = api_get_user_info($user_id);
1434
            $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
1435
            $status = get_status_from_code($user_object->status);
1436
            $interbreadcrumb[] = ['url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList')];
1437
1438
            $html .= '<div class ="thumbnail">';
1439
            $fullurl = $userInfo['avatar'];
1440
1441
            $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
1442
1443
            if (!empty($status)) {
1444
                $html .= '<div class="caption">'.$status.'</div>';
1445
            }
1446
            $html .= '</div>';
1447
1448
            if (api_get_setting('show_email_addresses') == 'true') {
1449
                $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
1450
            }
1451
            //    MY PERSONAL OPEN AREA
1452
            if ($user_object->openarea) {
1453
                $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
1454
                $html .= '<p>'.$user_object->openarea.'</p>';
1455
            }
1456
            //    MY COMPETENCES
1457
            if ($user_object->competences) {
1458
                $html .= Display::page_subheader(get_lang('MyCompetences'));
1459
                $html .= '<p>'.$user_object->competences.'</p>';
1460
            }
1461
            //    MY DIPLOMAS
1462
            if ($user_object->diplomas) {
1463
                $html .= Display::page_subheader(get_lang('MyDiplomas'));
1464
                $html .= '<p>'.$user_object->diplomas.'</p>';
1465
            }
1466
            // WHAT I AM ABLE TO TEACH
1467
            if ($user_object->teach) {
1468
                $html .= Display::page_subheader(get_lang('MyTeach'));
1469
                $html .= '<p>'.$user_object->teach.'</p>';
1470
            }
1471
            //    MY PRODUCTIONS
1472
            self::display_productions($user_object->user_id);
1473
        } else {
1474
            $html .= '<div class="actions-title">';
1475
            $html .= get_lang('UsersOnLineList');
1476
            $html .= '</div>';
1477
        }
1478
1479
        return $html;
1480
    }
1481
1482
    /**
1483
     * Display productions in who is online.
1484
     *
1485
     * @param int $user_id User id
1486
     */
1487
    public static function display_productions($user_id)
1488
    {
1489
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1490
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1491
        $webdir = UserManager::getUserPathById($user_id, 'web');
1492
1493
        if (!is_dir($sysdir)) {
1494
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1495
        }
1496
1497
        $productions = UserManager::get_user_productions($user_id);
1498
1499
        if (count($productions) > 0) {
1500
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1501
            echo '<dd><ul>';
1502
            foreach ($productions as $file) {
1503
                // Only display direct file links to avoid browsing an empty directory
1504
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1505
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1506
                }
1507
                // Real productions are under a subdirectory by the User's id
1508
                if (is_dir($sysdir.$file)) {
1509
                    $subs = scandir($sysdir.$file);
1510
                    foreach ($subs as $my => $sub) {
1511
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1512
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1513
                        }
1514
                    }
1515
                }
1516
            }
1517
            echo '</ul></dd>';
1518
        }
1519
    }
1520
1521
    /**
1522
     * @param string $content
1523
     * @param string $span_count
1524
     *
1525
     * @return string
1526
     */
1527
    public static function social_wrapper_div($content, $span_count)
1528
    {
1529
        $span_count = (int) $span_count;
1530
        $html = '<div class="span'.$span_count.'">';
1531
        $html .= '<div class="well_border">';
1532
        $html .= $content;
1533
        $html .= '</div></div>';
1534
1535
        return $html;
1536
    }
1537
1538
    /**
1539
     * Dummy function.
1540
     */
1541
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1542
    {
1543
        $content = '';
1544
        switch ($place) {
1545
            case SOCIAL_CENTER_PLUGIN:
1546
                $social_plugins = [1, 2];
1547
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1548
                    $content .= '<div id="social-plugins">';
1549
                    foreach ($social_plugins as $plugin) {
1550
                        $content .= '<div class="social-plugin-item">';
1551
                        $content .= $plugin;
1552
                        $content .= '</div>';
1553
                    }
1554
                    $content .= '</div>';
1555
                }
1556
                break;
1557
            case SOCIAL_LEFT_PLUGIN:
1558
                break;
1559
            case SOCIAL_RIGHT_PLUGIN:
1560
                break;
1561
        }
1562
1563
        return $content;
1564
    }
1565
1566
    /**
1567
     * Sends a message to someone's wall.
1568
     *
1569
     * @param int    $userId         id of author
1570
     * @param int    $friendId       id where we send the message
1571
     * @param string $messageContent of the message
1572
     * @param int    $messageId      id parent
1573
     * @param string $messageStatus  status type of message
1574
     *
1575
     * @return int
1576
     *
1577
     * @author Yannick Warnier
1578
     */
1579
    public static function sendWallMessage(
1580
        $userId,
1581
        $friendId,
1582
        $messageContent,
1583
        $messageId = 0,
1584
        $messageStatus = ''
1585
    ) {
1586
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1587
        $userId = (int) $userId;
1588
        $friendId = (int) $friendId;
1589
        $messageId = (int) $messageId;
1590
1591
        if (empty($userId) || empty($friendId)) {
1592
            return 0;
1593
        }
1594
1595
        // Just in case we replace the and \n and \n\r while saving in the DB
1596
        $messageContent = str_replace(["\n", "\n\r"], '<br />', $messageContent);
1597
        $now = api_get_utc_datetime();
1598
1599
        $attributes = [
1600
            'user_sender_id' => $userId,
1601
            'user_receiver_id' => $friendId,
1602
            'msg_status' => $messageStatus,
1603
            'send_date' => $now,
1604
            'title' => '',
1605
            'content' => $messageContent,
1606
            'parent_id' => $messageId,
1607
            'group_id' => 0,
1608
            'update_date' => $now,
1609
        ];
1610
1611
        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...
1612
    }
1613
1614
    /**
1615
     * Send File attachment (jpg,png).
1616
     *
1617
     * @author Anibal Copitan
1618
     *
1619
     * @param int    $userId      id user
1620
     * @param array  $fileAttach
1621
     * @param int    $messageId   id message (relation with main message)
1622
     * @param string $fileComment description attachment file
1623
     *
1624
     * @return bool|int
1625
     */
1626
    public static function sendWallMessageAttachmentFile(
1627
        $userId,
1628
        $fileAttach,
1629
        $messageId,
1630
        $fileComment = ''
1631
    ) {
1632
        $safeFileName = Database::escape_string($fileAttach['name']);
1633
1634
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1635
        $allowedTypes = api_get_supported_image_extensions();
1636
1637
        $allowedTypes[] = 'mp4';
1638
        $allowedTypes[] = 'webm';
1639
        $allowedTypes[] = 'ogg';
1640
1641
        if (in_array($extension, $allowedTypes)) {
1642
            return MessageManager::saveMessageAttachmentFile($fileAttach, $fileComment, $messageId, $userId);
1643
        }
1644
1645
        return false;
1646
    }
1647
1648
    /**
1649
     * Gets all messages from someone's wall (within specific limits).
1650
     *
1651
     * @param int        $userId     id of wall shown
1652
     * @param int|string $parentId   id message (Post main)
1653
     * @param int|array  $groupId
1654
     * @param int|array  $friendId
1655
     * @param string     $startDate  Date from which we want to show the messages, in UTC time
1656
     * @param int        $start      Limit for the number of parent messages we want to show
1657
     * @param int        $length     Wall message query offset
1658
     * @param bool       $getCount
1659
     * @param array      $threadList
1660
     *
1661
     * @return array|int
1662
     *
1663
     * @author Yannick Warnier
1664
     */
1665
    public static function getWallMessages(
1666
        $userId,
1667
        $parentId = 0,
1668
        $groupId = 0,
1669
        $friendId = 0,
1670
        $startDate = '',
1671
        $start = 0,
1672
        $length = 10,
1673
        $getCount = false,
1674
        $threadList = []
1675
    ) {
1676
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1677
1678
        $parentId = (int) $parentId;
1679
        $userId = (int) $userId;
1680
        $start = (int) $start;
1681
        $length = (int) $length;
1682
1683
        $select = " SELECT
1684
                    id,
1685
                    user_sender_id,
1686
                    user_receiver_id,
1687
                    send_date,
1688
                    content,
1689
                    parent_id,
1690
                    msg_status,
1691
                    group_id,
1692
                    '' as forum_id,
1693
                    '' as thread_id,
1694
                    '' as c_id
1695
                  ";
1696
1697
        if ($getCount) {
1698
            $select = ' SELECT count(id) as count_items ';
1699
        }
1700
1701
        $sqlBase = "$select FROM $tblMessage m WHERE ";
1702
        $sql = [];
1703
        $sql[1] = $sqlBase."msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
1704
1705
        // Get my own posts
1706
        $userReceiverCondition = ' (
1707
            user_receiver_id = '.$userId.' AND
1708
            msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
1709
            parent_id = '.$parentId.'
1710
        )';
1711
1712
        $sql[1] .= $userReceiverCondition;
1713
1714
        $sql[2] = $sqlBase.' msg_status = '.MESSAGE_STATUS_PROMOTED.' ';
1715
1716
        // Get my group posts
1717
        $groupCondition = '';
1718
        if (!empty($groupId)) {
1719
            if (is_array($groupId)) {
1720
                $groupId = array_map('intval', $groupId);
1721
                $groupId = implode(",", $groupId);
1722
                $groupCondition = " ( group_id IN ($groupId) ";
1723
            } else {
1724
                $groupId = (int) $groupId;
1725
                $groupCondition = " ( group_id = $groupId ";
1726
            }
1727
            $groupCondition .= ' AND (msg_status = '.MESSAGE_STATUS_NEW.' OR msg_status = '.MESSAGE_STATUS_UNREAD.')) ';
1728
        }
1729
        if (!empty($groupCondition)) {
1730
            $sql[3] = $sqlBase.$groupCondition;
1731
        }
1732
1733
        // Get my friend posts
1734
        $friendCondition = '';
1735
        if (!empty($friendId)) {
1736
            if (is_array($friendId)) {
1737
                $friendId = array_map('intval', $friendId);
1738
                $friendId = implode(",", $friendId);
1739
                $friendCondition = " ( user_receiver_id IN ($friendId) ";
1740
            } else {
1741
                $friendId = (int) $friendId;
1742
                $friendCondition = " ( user_receiver_id = $friendId ";
1743
            }
1744
            $friendCondition .= ' AND msg_status = '.MESSAGE_STATUS_WALL_POST.' AND parent_id = 0) ';
1745
        }
1746
        if (!empty($friendCondition)) {
1747
            $sql[4] = $sqlBase.$friendCondition;
1748
        }
1749
1750
        if (!empty($threadList)) {
1751
            if ($getCount) {
1752
                $select = ' SELECT count(iid) count_items ';
1753
            } else {
1754
                $select = " SELECT
1755
                                iid as id,
1756
                                poster_id as user_sender_id,
1757
                                '' as user_receiver_id,
1758
                                post_date as send_date,
1759
                                post_text as content,
1760
                                '' as parent_id,
1761
                                ".MESSAGE_STATUS_FORUM." as msg_status,
1762
                                '' as group_id,
1763
                                forum_id,
1764
                                thread_id,
1765
                                c_id
1766
                            ";
1767
            }
1768
1769
            $threadList = array_map('intval', $threadList);
1770
            $threadList = implode("','", $threadList);
1771
            $condition = " thread_id IN ('$threadList') ";
1772
            $sql[5] = "$select
1773
                    FROM c_forum_post
1774
                    WHERE $condition
1775
                ";
1776
        }
1777
1778
        if ($getCount) {
1779
            $count = 0;
1780
            foreach ($sql as $oneQuery) {
1781
                if (!empty($oneQuery)) {
1782
                    $res = Database::query($oneQuery);
1783
                    $row = Database::fetch_array($res);
1784
                    $count += (int) $row['count_items'];
1785
                }
1786
            }
1787
1788
            return $count;
1789
        }
1790
1791
        $sqlOrder = ' ORDER BY send_date DESC ';
1792
        $sqlLimit = " LIMIT $start, $length ";
1793
        $messages = [];
1794
        foreach ($sql as $index => $oneQuery) {
1795
            if ($index === 5) {
1796
                // Exception only for the forum query above (field name change)
1797
                $oneQuery .= ' ORDER BY post_date DESC '.$sqlLimit;
1798
            } else {
1799
                $oneQuery .= $sqlOrder.$sqlLimit;
1800
            }
1801
            $res = Database::query($oneQuery);
1802
            $em = Database::getManager();
1803
            if (Database::num_rows($res) > 0) {
1804
                $repo = $em->getRepository('ChamiloCourseBundle:CForumPost');
1805
                $repoThread = $em->getRepository('ChamiloCourseBundle:CForumThread');
1806
                $groups = [];
1807
                $userGroup = new UserGroup();
1808
                $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
1809
                while ($row = Database::fetch_array($res, 'ASSOC')) {
1810
                    $row['group_info'] = [];
1811
                    if (!empty($row['group_id'])) {
1812
                        if (!in_array($row['group_id'], $groups)) {
1813
                            $group = $userGroup->get($row['group_id']);
1814
                            $group['url'] = $urlGroup.$group['id'];
1815
                            $groups[$row['group_id']] = $group;
1816
                            $row['group_info'] = $group;
1817
                        } else {
1818
                            $row['group_info'] = $groups[$row['group_id']];
1819
                        }
1820
                    }
1821
1822
                    // Forums
1823
                    $row['post_title'] = '';
1824
                    $row['forum_title'] = '';
1825
                    $row['thread_url'] = '';
1826
                    if ($row['msg_status'] == MESSAGE_STATUS_FORUM) {
1827
                        /** @var CForumPost $post */
1828
                        $post = $repo->find($row['id']);
1829
                        /** @var CForumThread $thread */
1830
                        $thread = $repoThread->find($row['thread_id']);
1831
                        if ($post && $thread) {
1832
                            $courseInfo = api_get_course_info_by_id($post->getCId());
1833
                            $row['post_title'] = $post->getForumId();
1834
                            $row['forum_title'] = $thread->getThreadTitle();
1835
                            $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
1836
                                    'cidReq' => $courseInfo['code'],
1837
                                    'forum' => $post->getForumId(),
1838
                                    'thread' => $post->getThreadId(),
1839
                                    'post_id' => $post->getIid(),
1840
                                ]).'#post_id_'.$post->getIid();
1841
                        }
1842
                    }
1843
1844
                    $messages[$row['id']] = $row;
1845
                }
1846
            }
1847
        }
1848
        // Reordering messages by ID (reverse order) is enough to have the
1849
        // latest first, as there is currently no option to edit messages
1850
        // afterwards
1851
        krsort($messages);
1852
1853
        return $messages;
1854
    }
1855
1856
    /**
1857
     * Gets all messages from someone's wall (within specific limits), formatted.
1858
     *
1859
     * @param int    $userId      USER ID of the person's wall
1860
     * @param array  $messageInfo
1861
     * @param string $start       Start date (from when we want the messages until today)
1862
     * @param int    $limit       Limit to the number of messages we want
1863
     * @param int    $offset      Wall messages offset
1864
     *
1865
     * @return string HTML formatted string to show messages
1866
     */
1867
    public static function getWallPostComments(
1868
        $userId,
1869
        $messageInfo,
1870
        $start = null,
1871
        $limit = 10,
1872
        $offset = 0
1873
    ) {
1874
        $messageId = $messageInfo['id'];
1875
        $messages = MessageManager::getMessagesByParent($messageInfo['id'], 0, $offset, $limit);
1876
        $formattedList = '<div class="sub-mediapost row">';
1877
        $users = [];
1878
1879
        // The messages are ordered by date descendant, for comments we need ascendant
1880
        krsort($messages);
1881
        foreach ($messages as $message) {
1882
            $userIdLoop = $message['user_sender_id'];
1883
            if (!isset($users[$userIdLoop])) {
1884
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1885
            }
1886
            $media = self::processPostComment($message, $users);
1887
            $formattedList .= $media;
1888
        }
1889
1890
        $formattedList .= '</div>';
1891
        $formattedList .= '<div class="mediapost-form row">';
1892
        $formattedList .= '<form class="form-horizontal" id="form_comment_'.$messageId.'" name="post_comment" method="POST">
1893
                <div class="col-sm-9">
1894
                <label for="comment" class="hide">'.get_lang('SocialWriteNewComment').'</label>
1895
                <input type="hidden" name = "messageId" value="'.$messageId.'" />
1896
                <textarea rows="3" class="form-control" placeholder="'.get_lang('SocialWriteNewComment').'" name="comment" rows="1" ></textarea>
1897
                </div>
1898
                <div class="col-sm-3 pull-right">
1899
                <a onclick="submitComment('.$messageId.');" href="javascript:void(0);" name="social_wall_new_msg_submit" class="btn btn-default btn-post">
1900
                    <em class="fa fa-pencil"></em> '.get_lang('Post').'
1901
                </a>
1902
                </div>
1903
                </form>';
1904
        $formattedList .= '</div>';
1905
1906
        return $formattedList;
1907
    }
1908
1909
    /**
1910
     * @param array $message
1911
     * @param array $users
1912
     *
1913
     * @return string
1914
     */
1915
    public static function processPostComment($message, $users = [])
1916
    {
1917
        if (empty($message)) {
1918
            return false;
1919
        }
1920
1921
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
1922
        $currentUserId = api_get_user_id();
1923
        $userIdLoop = $message['user_sender_id'];
1924
        $receiverId = $message['user_receiver_id'];
1925
1926
        if (!isset($users[$userIdLoop])) {
1927
            $users[$userIdLoop] = api_get_user_info($userIdLoop);
1928
        }
1929
1930
        $iconStatus = $users[$userIdLoop]['icon_status'];
1931
        $nameComplete = $users[$userIdLoop]['complete_name'];
1932
        $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$userIdLoop;
1933
1934
        $comment = '<div class="rep-post col-md-12">';
1935
        $comment .= '<div class="col-md-2 col-xs-2 social-post-answers">';
1936
        $comment .= '<div class="user-image pull-right">';
1937
        $comment .= '<a href="'.$url.'">
1938
                        <img src="'.$users[$userIdLoop]['avatar'].'"
1939
                        alt="'.$users[$userIdLoop]['complete_name'].'"
1940
                        class="avatar-thumb">
1941
                     </a>';
1942
        $comment .= '</div>';
1943
        $comment .= '</div>';
1944
        $comment .= '<div class="col-md-7 col-xs-7 social-post-answers">';
1945
        $comment .= '<div class="user-data">';
1946
        $comment .= $iconStatus;
1947
        $comment .= '<div class="username"><a href="'.$url.'">'.$nameComplete.'</a>
1948
                        <span>'.Security::remove_XSS($message['content']).'</span>
1949
                       </div>';
1950
        $comment .= '<div>'.$date.'</div>';
1951
        $comment .= '<br />';
1952
        $comment .= '</div>';
1953
        $comment .= '</div>';
1954
1955
        $comment .= '<div class="col-md-3 col-xs-3 social-post-answers">';
1956
        $comment .= '<div class="pull-right btn-group btn-group-sm">';
1957
1958
        $comment .= MessageManager::getLikesButton(
1959
            $message['id'],
1960
            $currentUserId
1961
        );
1962
1963
        $isOwnWall = $currentUserId == $userIdLoop || $currentUserId == $receiverId;
1964
        if ($isOwnWall) {
1965
            $comment .= Display::url(
1966
                    Display::returnFontAwesomeIcon('trash', '', true),
1967
                'javascript:void(0)',
1968
                [
1969
                    'id' => 'message_'.$message['id'],
1970
                    'title' => get_lang('SocialMessageDelete'),
1971
                    'onclick' => 'deleteComment('.$message['id'].')',
1972
                    'class' => 'btn btn-default',
1973
                ]
1974
            );
1975
        }
1976
        $comment .= '</div>';
1977
        $comment .= '</div>';
1978
        $comment .= '</div>';
1979
1980
        return $comment;
1981
    }
1982
1983
    /**
1984
     * @param array $message
1985
     *
1986
     * @return array
1987
     */
1988
    public static function getAttachmentPreviewList($message)
1989
    {
1990
        $messageId = $message['id'];
1991
1992
        $list = [];
1993
1994
        if (empty($message['group_id'])) {
1995
            $files = MessageManager::getAttachmentList($messageId);
1996
            if ($files) {
1997
                $downloadUrl = api_get_path(WEB_CODE_PATH).'social/download.php?message_id='.$messageId;
1998
                foreach ($files as $row_file) {
1999
                    $url = $downloadUrl.'&attachment_id='.$row_file['id'];
2000
                    $display = Display::fileHtmlGuesser($row_file['filename'], $url);
2001
                    $list[] = $display;
2002
                }
2003
            }
2004
        } else {
2005
            $list = MessageManager::getAttachmentLinkList($messageId, 0);
2006
        }
2007
2008
        return $list;
2009
    }
2010
2011
    /**
2012
     * @param array $message
2013
     *
2014
     * @return string
2015
     */
2016
    public static function getPostAttachment($message)
2017
    {
2018
        $previews = self::getAttachmentPreviewList($message);
2019
2020
        if (empty($previews)) {
2021
            return '';
2022
        }
2023
2024
        return implode('', $previews);
2025
    }
2026
2027
    /**
2028
     * @param array $messages
2029
     *
2030
     * @return array
2031
     */
2032
    public static function formatWallMessages($messages)
2033
    {
2034
        $data = [];
2035
        $users = [];
2036
        foreach ($messages as $key => $message) {
2037
            $userIdLoop = $message['user_sender_id'];
2038
            $userFriendIdLoop = $message['user_receiver_id'];
2039
            if (!isset($users[$userIdLoop])) {
2040
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
2041
            }
2042
2043
            if (!isset($users[$userFriendIdLoop])) {
2044
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
2045
            }
2046
2047
            $html = self::headerMessagePost(
2048
                $users[$userIdLoop],
2049
                $users[$userFriendIdLoop],
2050
                $message
2051
            );
2052
2053
            $data[$key] = $message;
2054
            $data[$key]['html'] = $html;
2055
        }
2056
2057
        return $data;
2058
    }
2059
2060
    /**
2061
     * get html data with OpenGrap passing the URL.
2062
     *
2063
     * @param $link url
2064
     *
2065
     * @return string data html
2066
     */
2067
    public static function readContentWithOpenGraph($link)
2068
    {
2069
        if (strpos($link, "://") === false && substr($link, 0, 1) != "/") {
2070
            $link = "http://".$link;
2071
        }
2072
        $graph = OpenGraph::fetch($link);
2073
        $link = parse_url($link);
2074
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
2075
        if (!$graph) {
2076
            return false;
2077
        }
2078
        $url = $graph->url;
2079
        $image = $graph->image;
2080
        $description = $graph->description;
2081
        $title = $graph->title;
2082
        $html = '<div class="thumbnail social-thumbnail">';
2083
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
2084
                <img class="img-responsive social-image" src="'.$image.'" /></a>';
2085
        $html .= '<div class="social-description">';
2086
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
2087
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
2088
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
2089
        $html .= '</div>';
2090
        $html .= '</div>';
2091
2092
        return $html;
2093
    }
2094
2095
    /**
2096
     * verify if Url Exist - Using Curl.
2097
     *
2098
     * @param $uri url
2099
     *
2100
     * @return bool
2101
     */
2102
    public static function verifyUrl($uri)
2103
    {
2104
        $curl = curl_init($uri);
2105
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
2106
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
2107
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2108
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
2109
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
2110
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
2111
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
2112
        $response = curl_exec($curl);
2113
        curl_close($curl);
2114
        if (!empty($response)) {
2115
            return true;
2116
        }
2117
2118
        return false;
2119
    }
2120
2121
    /**
2122
     * Soft delete a message and his chidren.
2123
     *
2124
     * @param int $id id message to delete
2125
     *
2126
     * @return bool status query
2127
     */
2128
    public static function deleteMessage($id)
2129
    {
2130
        $id = (int) $id;
2131
        $messageInfo = MessageManager::get_message_by_id($id);
2132
        if (!empty($messageInfo)) {
2133
            // Delete comments too
2134
            $messages = MessageManager::getMessagesByParent($id);
2135
            if (!empty($messages)) {
2136
                foreach ($messages as $message) {
2137
                    self::deleteMessage($message['id']);
2138
                }
2139
            }
2140
2141
            // Soft delete message
2142
            $tblMessage = Database::get_main_table(TABLE_MESSAGE);
2143
            $statusMessage = MESSAGE_STATUS_WALL_DELETE;
2144
            $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
2145
            Database::query($sql);
2146
2147
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_sender_id']);
2148
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_receiver_id']);
2149
2150
            return true;
2151
        }
2152
2153
        return false;
2154
    }
2155
2156
    /**
2157
     * Generate the social block for a user.
2158
     *
2159
     * @param int    $userId            The user id
2160
     * @param string $groupBlock        Optional. Highlight link possible values:
2161
     *                                  group_add, home, messages, messages_inbox, messages_compose,
2162
     *                                  messages_outbox, invitations, shared_profile, friends, groups, search
2163
     * @param int    $groupId           Optional. Group ID
2164
     * @param bool   $show_full_profile
2165
     *
2166
     * @return string The HTML code with the social block
2167
     */
2168
    public static function setSocialUserBlock(
2169
        Template $template,
2170
        $userId,
2171
        $groupBlock = '',
2172
        $groupId = 0,
2173
        $show_full_profile = true
2174
    ) {
2175
        if (api_get_setting('allow_social_tool') !== 'true') {
2176
            return '';
2177
        }
2178
2179
        $currentUserId = api_get_user_id();
2180
        $userId = (int) $userId;
2181
        $userRelationType = 0;
2182
2183
        $socialAvatarBlock = self::show_social_avatar_block(
2184
            $groupBlock,
2185
            $groupId,
2186
            $userId
2187
        );
2188
2189
        $profileEditionLink = null;
2190
        if ($currentUserId === $userId) {
2191
            $profileEditionLink = Display::getProfileEditionLink($userId);
2192
        } else {
2193
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
2194
        }
2195
2196
        $options = api_get_configuration_value('profile_fields_visibility');
2197
        if (isset($options['options'])) {
2198
            $options = $options['options'];
2199
        }
2200
2201
        $vCardUserLink = Display::getVCardUserLink($userId);
2202
        if (isset($options['vcard']) && $options['vcard'] === false) {
2203
            $vCardUserLink = '';
2204
        }
2205
2206
        $userInfo = api_get_user_info($userId, true, false, true, true);
2207
2208
        if (isset($options['firstname']) && $options['firstname'] === false) {
2209
            $userInfo['firstname'] = '';
2210
        }
2211
        if (isset($options['lastname']) && $options['lastname'] === false) {
2212
            $userInfo['lastname'] = '';
2213
        }
2214
2215
        if (isset($options['email']) && $options['email'] === false) {
2216
            $userInfo['email'] = '';
2217
        }
2218
2219
        // Ofaj
2220
        $hasCertificates = Certificate::getCertificateByUser($userId);
2221
        $userInfo['has_certificates'] = 0;
2222
        if (!empty($hasCertificates)) {
2223
            $userInfo['has_certificates'] = 1;
2224
        }
2225
2226
        $userInfo['is_admin'] = UserManager::is_admin($userId);
2227
2228
        $languageId = api_get_language_id($userInfo['language']);
2229
        $languageInfo = api_get_language_info($languageId);
2230
        if ($languageInfo) {
2231
            $userInfo['language'] = [
2232
                'label' => $languageInfo['original_name'],
2233
                'value' => $languageInfo['english_name'],
2234
                'code' => $languageInfo['isocode'],
2235
            ];
2236
        }
2237
2238
        if (isset($options['language']) && $options['language'] === false) {
2239
            $userInfo['language'] = '';
2240
        }
2241
2242
        if (isset($options['photo']) && $options['photo'] === false) {
2243
            $socialAvatarBlock = '';
2244
        }
2245
2246
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
2247
        $showLanguageFlag = api_get_configuration_value('social_show_language_flag_in_profile');
2248
2249
        $template->assign('user', $userInfo);
2250
        $template->assign('show_language_flag', $showLanguageFlag);
2251
        $template->assign('extra_info', $extraFieldBlock);
2252
        $template->assign('social_avatar_block', $socialAvatarBlock);
2253
        $template->assign('profile_edition_link', $profileEditionLink);
2254
        //Added the link to export the vCard to the Template
2255
2256
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
2257
        if ($show_full_profile) {
2258
            $template->assign('vcard_user_link', $vCardUserLink);
2259
        }
2260
2261
        if (api_get_setting('gamification_mode') === '1') {
2262
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
2263
                $userId,
2264
                $userInfo['status']
2265
            );
2266
2267
            $template->assign('gamification_points', $gamificationPoints);
2268
        }
2269
        $chatEnabled = api_is_global_chat_enabled();
2270
2271
        if (isset($options['chat']) && $options['chat'] === false) {
2272
            $chatEnabled = '';
2273
        }
2274
2275
        $template->assign('chat_enabled', $chatEnabled);
2276
        $template->assign('user_relation', $userRelationType);
2277
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
2278
        $template->assign('show_full_profile', $show_full_profile);
2279
2280
        $templateName = $template->get_template('social/user_block.tpl');
2281
2282
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
2283
            $templateName = $template->get_template('social/group_block.tpl');
2284
        }
2285
2286
        $template->assign('social_avatar_block', $template->fetch($templateName));
2287
    }
2288
2289
    /**
2290
     * @param int $user_id
2291
     * @param $link_shared
2292
     * @param bool $showLinkToChat
2293
     *
2294
     * @return string
2295
     */
2296
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
2297
    {
2298
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
2299
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
2300
        $numberFriends = count($friends);
2301
        $friendHtml = '';
2302
2303
        if (!empty($numberFriends)) {
2304
            $friendHtml .= '<div class="list-group contact-list">';
2305
            $j = 1;
2306
2307
            usort(
2308
                $friends,
2309
                function ($a, $b) {
2310
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
2311
                }
2312
            );
2313
2314
            foreach ($friends as $friend) {
2315
                if ($j > $numberFriends) {
2316
                    break;
2317
                }
2318
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2319
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2320
2321
                $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
2322
                $status = 0;
2323
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
2324
                    $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
2325
                    $status = 1;
2326
                }
2327
2328
                $friendAvatarMedium = UserManager::getUserPicture(
2329
                    $friend['friend_user_id'],
2330
                    USER_IMAGE_SIZE_MEDIUM
2331
                );
2332
                $friendAvatarSmall = UserManager::getUserPicture(
2333
                    $friend['friend_user_id'],
2334
                    USER_IMAGE_SIZE_SMALL
2335
                );
2336
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
2337
2338
                $relation = self::get_relation_between_contacts(
2339
                    $friend['friend_user_id'],
2340
                    api_get_user_id()
2341
                );
2342
2343
                if ($showLinkToChat) {
2344
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
2345
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2346
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2347
                } else {
2348
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
2349
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
2350
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2351
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2352
                }
2353
2354
                $friendHtml .= '</a>';
2355
2356
                $j++;
2357
            }
2358
            $friendHtml .= '</div>';
2359
        } else {
2360
            $friendHtml = Display::return_message(get_lang('NoFriendsInYourContactList'), 'warning');
2361
        }
2362
2363
        return $friendHtml;
2364
    }
2365
2366
    /**
2367
     * @return string Get the JS code necessary for social wall to load open graph from URLs.
2368
     */
2369
    public static function getScriptToGetOpenGraph()
2370
    {
2371
        return '<script>
2372
            $(function() {
2373
                $("[name=\'social_wall_new_msg_main\']").on("paste", function(e) {
2374
                    $.ajax({
2375
                        contentType: "application/x-www-form-urlencoded",
2376
                        beforeSend: function() {
2377
                            $("[name=\'wall_post_button\']").prop( "disabled", true );
2378
                            $(".panel-preview").hide();
2379
                            $(".spinner").html("'
2380
                                .'<div class=\'text-center\'>'
2381
                                .'<em class=\'fa fa-spinner fa-pulse fa-1x\'></em>'
2382
                                .'<p>'.get_lang('Loading').' '.get_lang('Preview').'</p>'
2383
                                .'</div>'
2384
                            .'");
2385
                        },
2386
                        type: "POST",
2387
                        url: "'.api_get_path(WEB_AJAX_PATH).'social.ajax.php?a=read_url_with_open_graph",
2388
                        data: "social_wall_new_msg_main=" + e.originalEvent.clipboardData.getData("text"),
2389
                        success: function(response) {
2390
                            $("[name=\'wall_post_button\']").prop("disabled", false);
2391
                            if (!response == false) {
2392
                                $(".spinner").html("");
2393
                                $(".panel-preview").show();
2394
                                $(".url_preview").html(response);
2395
                                $("[name=\'url_content\']").val(response);
2396
                                $(".url_preview img").addClass("img-responsive");
2397
                            } else {
2398
                                $(".spinner").html("");
2399
                            }
2400
                        }
2401
                    });
2402
                });
2403
            });
2404
        </script>';
2405
    }
2406
2407
    public static function displayWallForm(string $urlForm): string
2408
    {
2409
        $form = self::getWallForm($urlForm);
2410
        $form->protect();
2411
2412
        return Display::panel($form->returnForm(), get_lang('SocialWall'));
2413
    }
2414
2415
    /**
2416
     * Show middle section for Portfolio extended.
2417
     * Must be active on main/admin/settings.php?category=User into extended_profile.
2418
     *
2419
     * @param string $urlForm
2420
     *
2421
     * @return string
2422
     */
2423
    public static function getWallFormPortfolio($urlForm)
2424
    {
2425
        $userId = isset($_GET['u']) ? (int) $_GET['u'] : 0;
2426
        $userId = $userId !== 0 ? $userId : api_get_user_id();
2427
        $user_info = api_get_user_info($userId);
2428
        $friend = true;
2429
        $editPorfolioLink = '';
2430
        if ($userId != api_get_user_id()) {
2431
            $friend = self::get_relation_between_contacts(api_get_user_id(), $userId);
2432
        } else {
2433
            $editPorfolioLink .= "<div class=\"pull-right\" style='margin-top: -5px'>".
2434
                '<a href="/main/auth/profile.php?type=extended#openarea" class="btn btn-default btn-sm btn-social-edit">'.
2435
                "<i class=\"fa fa-pencil\" aria-hidden=\"true\"></i>".
2436
                '</a>'.
2437
                "</div>";
2438
        }
2439
        if ($friend == 0) {
2440
            /* if has not relation, get current user */
2441
            $userId = api_get_user_id();
2442
            $user_info = api_get_user_info($userId);
2443
        }
2444
        // Images uploaded by course
2445
        $more_info = '';
2446
2447
        // Productions
2448
        $production_list = UserManager::build_production_list($userId);
2449
2450
        $form = new FormValidator(
2451
            'social_wall_main',
2452
            'post',
2453
            $urlForm.$userId,
2454
            null,
2455
            ['enctype' => 'multipart/form-data'],
2456
            FormValidator::LAYOUT_HORIZONTAL
2457
        );
2458
2459
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
2460
            'SocialWallWhatAreYouThinkingAbout'
2461
        );
2462
2463
        if (!empty($user_info['competences']) || !empty($user_info['diplomas'])
2464
            || !empty($user_info['openarea']) || !empty($user_info['teach'])) {
2465
            // $more_info .= '<div><h3>'.get_lang('MoreInformation').'</h3></div>';
2466
            //    MY PERSONAL OPEN AREA
2467
            if (!empty($user_info['openarea'])) {
2468
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyPersonalOpenArea').'</strong></div>';
2469
                $more_info .= '<div class="social-profile-extended">'.$user_info['openarea'].'</div>';
2470
                $more_info .= '<br />';
2471
            }
2472
            //    MY COMPETENCES
2473
            if (!empty($user_info['competences'])) {
2474
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyCompetences').'</strong></div>';
2475
                $more_info .= '<div class="social-profile-extended">'.$user_info['competences'].'</div>';
2476
                $more_info .= '<br />';
2477
            }
2478
            //    MY DIPLOMAS
2479
            if (!empty($user_info['diplomas'])) {
2480
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyDiplomas').'</strong></div>';
2481
                $more_info .= '<div class="social-profile-extended">'.$user_info['diplomas'].'</div>';
2482
                $more_info .= '<br />';
2483
            }
2484
            //    MY PRODUCTIONS
2485
            if (!empty($production_list)) {
2486
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyProductions').'</strong></div>';
2487
                $more_info .= '<div class="social-profile-extended">'.$production_list.'</div>';
2488
                $more_info .= '<br />';
2489
            }
2490
            // WHAT I AM ABLE TO TEACH
2491
            if (!empty($user_info['teach'])) {
2492
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyTeach').'</strong></div>';
2493
                $more_info .= '<div class="social-profile-extended">'.$user_info['teach'].'</div>';
2494
                $more_info .= '<br />';
2495
            }
2496
        }
2497
2498
        $form->addTextarea(
2499
            'social_wall_new_msg_main',
2500
            null,
2501
            [
2502
                'placeholder' => $socialWallPlaceholder,
2503
                'cols-size' => [1, 12, 1],
2504
                'aria-label' => $socialWallPlaceholder,
2505
            ]
2506
        );
2507
        $form->addHtml('<div class="form-group">');
2508
        $form->addHtml('<div class="col-sm-6">');
2509
        $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
2510
        $form->addHtml('</div>');
2511
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
2512
        $form->addButtonSend(
2513
            get_lang('Post'),
2514
            'wall_post_button',
2515
            false,
2516
            [
2517
                'cols-size' => [1, 10, 1],
2518
                'custom' => true,
2519
            ]
2520
        );
2521
        $form->addHtml('</div></div>');
2522
        $form->addHtml('</div>');
2523
        $form->addHidden('url_content', '');
2524
2525
        return Display::panel($more_info, get_lang('Portfolio').$editPorfolioLink);
2526
    }
2527
2528
    /**
2529
     * @param int   $userId
2530
     * @param int   $start
2531
     * @param int   $length
2532
     * @param array $threadList
2533
     *
2534
     * @return array
2535
     */
2536
    public static function getMyWallMessages($userId, $start = 0, $length = 10, $threadList = [])
2537
    {
2538
        $userGroup = new UserGroup();
2539
        $groups = $userGroup->get_groups_by_user($userId, [GROUP_USER_PERMISSION_READER, GROUP_USER_PERMISSION_ADMIN]);
2540
        $groupList = [];
2541
        if (!empty($groups)) {
2542
            $groupList = array_column($groups, 'id');
2543
        }
2544
2545
        $friends = self::get_friends($userId, USER_RELATION_TYPE_FRIEND);
2546
        $friendList = [];
2547
        if (!empty($friends)) {
2548
            $friendList = array_column($friends, 'friend_user_id');
2549
        }
2550
2551
        $messages = self::getWallMessages(
2552
            $userId,
2553
            0,
2554
            $groupList,
2555
            $friendList,
2556
            '',
2557
            $start,
2558
            $length,
2559
            false,
2560
            $threadList
2561
        );
2562
2563
        $countPost = self::getCountWallMessagesByUser($userId, $groupList, $friendList, $threadList);
2564
        $messages = self::formatWallMessages($messages);
2565
2566
        $html = '';
2567
        foreach ($messages as $message) {
2568
            $post = $message['html'];
2569
            $comments = '';
2570
            if (in_array($message['msg_status'], [MESSAGE_STATUS_WALL_POST, MESSAGE_STATUS_PROMOTED])) {
2571
                $comments = self::getWallPostComments($userId, $message);
2572
            }
2573
2574
            $html .= self::wrapPost($message, $post.$comments);
2575
        }
2576
2577
        return [
2578
            'posts' => $html,
2579
            'count' => $countPost,
2580
        ];
2581
    }
2582
2583
    /**
2584
     * @param string $message
2585
     * @param string $content
2586
     *
2587
     * @return string
2588
     */
2589
    public static function wrapPost($message, $content)
2590
    {
2591
        $class = '';
2592
        if ($message['msg_status'] === MESSAGE_STATUS_PROMOTED) {
2593
            $class = 'promoted_post';
2594
        }
2595
2596
        return Display::panel($content, '',
2597
            '',
2598
            'default',
2599
            '',
2600
            'post_'.$message['id'],
2601
            null,
2602
            $class
2603
        );
2604
    }
2605
2606
    /**
2607
     * @param int   $userId
2608
     * @param array $groupList
2609
     * @param array $friendList
2610
     * @param array $threadList
2611
     *
2612
     * @return int
2613
     */
2614
    public static function getCountWallMessagesByUser($userId, $groupList = [], $friendList = [], $threadList = [])
2615
    {
2616
        return self::getWallMessages(
2617
            $userId,
2618
            0,
2619
            $groupList,
2620
            $friendList,
2621
            '',
2622
            0,
2623
            0,
2624
            true,
2625
            $threadList
2626
        );
2627
    }
2628
2629
    /**
2630
     * @param int $userId
2631
     *
2632
     * @return string
2633
     */
2634
    public static function getWallMessagesByUser($userId)
2635
    {
2636
        $messages = self::getWallMessages($userId);
2637
        $messages = self::formatWallMessages($messages);
2638
2639
        $html = '';
2640
        foreach ($messages as $message) {
2641
            $post = $message['html'];
2642
            $comments = self::getWallPostComments($userId, $message);
2643
            $html .= self::wrapPost($message, $post.$comments);
2644
        }
2645
2646
        return $html;
2647
    }
2648
2649
    /**
2650
     * Get HTML code block for user skills.
2651
     *
2652
     * @param int    $userId      The user ID
2653
     * @param string $orientation
2654
     *
2655
     * @return string
2656
     */
2657
    public static function getSkillBlock($userId, $orientation = 'horizontal')
2658
    {
2659
        if (Skill::isAllowed($userId, false) === false) {
2660
            return '';
2661
        }
2662
2663
        $skill = new Skill();
2664
        $ranking = $skill->getUserSkillRanking($userId);
2665
2666
        $template = new Template(null, false, false, false, false, false);
2667
        $template->assign('ranking', $ranking);
2668
        $template->assign('orientation', $orientation);
2669
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
2670
        $template->assign('user_id', $userId);
2671
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
2672
2673
        $skillBlock = $template->get_template('social/skills_block.tpl');
2674
2675
        return $template->fetch($skillBlock);
2676
    }
2677
2678
    /**
2679
     * @param int  $user_id
2680
     * @param bool $isArray
2681
     *
2682
     * @return string|array
2683
     */
2684
    public static function getExtraFieldBlock($user_id, $isArray = false)
2685
    {
2686
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
2687
        $fieldVisibilityKeys = [];
2688
        if (isset($fieldVisibility['options'])) {
2689
            $fieldVisibility = $fieldVisibility['options'];
2690
            $fieldVisibilityKeys = array_keys($fieldVisibility);
2691
        }
2692
2693
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
2694
        $extra_user_data = UserManager::get_extra_user_data($user_id);
2695
2696
        $extra_information = '';
2697
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
2698
            $extra_information_value = '';
2699
            $extraField = new ExtraField('user');
2700
            $listType = [];
2701
            $extraFieldItem = [];
2702
            foreach ($extra_user_data as $key => $data) {
2703
                if (empty($data)) {
2704
                    continue;
2705
                }
2706
                if (in_array($key, $fieldVisibilityKeys) && $fieldVisibility[$key] === false) {
2707
                    continue;
2708
                }
2709
2710
                // Avoiding parameters
2711
                if (in_array(
2712
                    $key,
2713
                    [
2714
                        'mail_notify_invitation',
2715
                        'mail_notify_message',
2716
                        'mail_notify_group_message',
2717
                    ]
2718
                )) {
2719
                    continue;
2720
                }
2721
                // get display text, visibility and type from user_field table
2722
                $field_variable = str_replace('extra_', '', $key);
2723
2724
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2725
                    $field_variable
2726
                );
2727
2728
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
2729
                    continue;
2730
                }
2731
2732
                // if is not visible skip
2733
                if ($extraFieldInfo['visible_to_self'] != 1) {
2734
                    continue;
2735
                }
2736
2737
                // if is not visible to others skip also
2738
                if ($extraFieldInfo['visible_to_others'] != 1) {
2739
                    continue;
2740
                }
2741
2742
                if (is_array($data)) {
2743
                    switch ($extraFieldInfo['field_type']) {
2744
                        case ExtraField::FIELD_TYPE_RADIO:
2745
                            $objEfOption = new ExtraFieldOption('user');
2746
                            $value = $data['extra_'.$extraFieldInfo['variable']];
2747
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
2748
                                $extraFieldInfo['id'],
2749
                                $value
2750
                            );
2751
2752
                            if ($optionInfo && isset($optionInfo[0])) {
2753
                                $optionInfo = $optionInfo[0];
2754
                                $extraFieldItem = [
2755
                                    'variable' => $extraFieldInfo['variable'],
2756
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2757
                                    'value' => $optionInfo['display_text'],
2758
                                ];
2759
                            } else {
2760
                                $extraFieldItem = [
2761
                                    'variable' => $extraFieldInfo['variable'],
2762
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2763
                                    'value' => implode(',', $data),
2764
                                ];
2765
                            }
2766
                            break;
2767
                        default:
2768
                            $extra_information_value .=
2769
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
2770
                                .' '.implode(',', $data).'</li>';
2771
                            $extraFieldItem = [
2772
                                'variable' => $extraFieldInfo['variable'],
2773
                                'label' => ucfirst($extraFieldInfo['display_text']),
2774
                                'value' => implode(',', $data),
2775
                            ];
2776
                            break;
2777
                    }
2778
                } else {
2779
                    switch ($extraFieldInfo['field_type']) {
2780
                        case ExtraField::FIELD_TYPE_RADIO:
2781
                            $objEfOption = new ExtraFieldOption('user');
2782
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
2783
                            break;
2784
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
2785
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
2786
                            $data = explode('::', $data);
2787
                            $data = $data[0];
2788
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2789
                            $extraFieldItem = [
2790
                                'variable' => $extraFieldInfo['variable'],
2791
                                'label' => ucfirst($extraFieldInfo['display_text']),
2792
                                'value' => $data,
2793
                            ];
2794
                            break;
2795
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
2796
                            $id_options = explode('::', $data);
2797
                            $value_options = [];
2798
                            // get option display text from user_field_options table
2799
                            foreach ($id_options as $id_option) {
2800
                                $sql = "SELECT display_text
2801
                                    FROM $t_ufo
2802
                                    WHERE id = '$id_option'";
2803
                                $res_options = Database::query($sql);
2804
                                $row_options = Database::fetch_row($res_options);
2805
                                $value_options[] = $row_options[0];
2806
                            }
2807
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2808
                                .' '.implode(' ', $value_options).'</li>';
2809
                            $extraFieldItem = [
2810
                                'variable' => $extraFieldInfo['variable'],
2811
                                'label' => ucfirst($extraFieldInfo['display_text']),
2812
                                'value' => $value_options,
2813
                            ];
2814
                            break;
2815
                        case ExtraField::FIELD_TYPE_TAG:
2816
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
2817
2818
                            $tag_tmp = '';
2819
                            foreach ($user_tags as $tags) {
2820
                                $tag_tmp .= '<a class="label label_tag"'
2821
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
2822
                                    .$tags['tag']
2823
                                    .'</a>';
2824
                            }
2825
                            if (is_array($user_tags) && count($user_tags) > 0) {
2826
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2827
                                    .' '.$tag_tmp.'</li>';
2828
                            }
2829
                            $extraFieldItem = [
2830
                                'variable' => $extraFieldInfo['variable'],
2831
                                'label' => ucfirst($extraFieldInfo['display_text']),
2832
                                'value' => $tag_tmp,
2833
                            ];
2834
                            break;
2835
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
2836
                            $icon_path = UserManager::get_favicon_from_url($data);
2837
                            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...
2838
                                break;
2839
                            }
2840
                            $bottom = '0.2';
2841
                            //quick hack for hi5
2842
                            $domain = parse_url($icon_path, PHP_URL_HOST);
2843
                            if ($domain == 'www.hi5.com' || $domain == 'hi5.com') {
2844
                                $bottom = '-0.8';
2845
                            }
2846
                            $data = '<a href="'.$data.'">'
2847
                                .'<img src="'.$icon_path.'" alt="icon"'
2848
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
2849
                                .$extraFieldInfo['display_text']
2850
                                .'</a>';
2851
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
2852
                            $extraFieldItem = [
2853
                                'variable' => $extraFieldInfo['variable'],
2854
                                'label' => ucfirst($extraFieldInfo['display_text']),
2855
                                'value' => $data,
2856
                            ];
2857
                            break;
2858
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
2859
                            $parsedData = explode('::', $data);
2860
2861
                            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...
2862
                                break;
2863
                            }
2864
2865
                            $objEfOption = new ExtraFieldOption('user');
2866
                            $optionInfo = $objEfOption->get($parsedData[0]);
2867
2868
                            $extra_information_value .= '<li class="list-group-item">'
2869
                                .$optionInfo['display_text'].': '
2870
                                .$parsedData[1].'</li>';
2871
                            $extraFieldItem = [
2872
                                'variable' => $extraFieldInfo['variable'],
2873
                                'label' => ucfirst($extraFieldInfo['display_text']),
2874
                                'value' => $parsedData[1],
2875
                            ];
2876
                            break;
2877
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
2878
                            $optionIds = explode(';', $data);
2879
                            $optionValues = [];
2880
2881
                            foreach ($optionIds as $optionId) {
2882
                                $objEfOption = new ExtraFieldOption('user');
2883
                                $optionInfo = $objEfOption->get($optionId);
2884
2885
                                $optionValues[] = $optionInfo['display_text'];
2886
                            }
2887
                            $extra_information_value .= '<li class="list-group-item">'
2888
                                .ucfirst($extraFieldInfo['display_text']).': '
2889
                                .implode(' ', $optionValues).'</li>';
2890
                            $extraFieldItem = [
2891
                                'variable' => $extraFieldInfo['variable'],
2892
                                'label' => ucfirst($extraFieldInfo['display_text']),
2893
                                'value' => implode(' ', $optionValues),
2894
                            ];
2895
                            break;
2896
                        default:
2897
                            // Ofaj
2898
                            // Converts "Date of birth" into "age"
2899
                            if ($key === 'terms_datedenaissance') {
2900
                                $dataArray = date_to_str_ago($data, 'UTC', true);
2901
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
2902
                                if (!empty($dataToString)) {
2903
                                    $data = $dataToString;
2904
                                    $extraFieldInfo['display_text'] = get_lang('Age');
2905
                                }
2906
                            }
2907
2908
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2909
                            $extraFieldItem = [
2910
                                'variable' => $extraFieldInfo['variable'],
2911
                                'label' => ucfirst($extraFieldInfo['display_text']),
2912
                                'value' => $data,
2913
                            ];
2914
                            break;
2915
                    }
2916
                }
2917
2918
                $listType[] = $extraFieldItem;
2919
            }
2920
2921
            if ($isArray) {
2922
                return $listType;
2923
            } else {
2924
                // if there are information to show
2925
                if (!empty($extra_information_value)) {
2926
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
2927
                    $extra_information .= Display::panelCollapse(
2928
                        get_lang('ExtraInformation'),
2929
                        $extra_information_value,
2930
                        'sn-extra-information',
2931
                        null,
2932
                        'sn-extra-accordion',
2933
                        'sn-extra-collapse'
2934
                    );
2935
                }
2936
            }
2937
        }
2938
2939
        return $extra_information;
2940
    }
2941
2942
    /**
2943
     * @param string $url
2944
     */
2945
    public static function handlePosts($url)
2946
    {
2947
        $friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
2948
        $url = Security::remove_XSS($url);
2949
        $wallSocialAddPost = SocialManager::getWallForm(api_get_self());
2950
2951
        if (!$wallSocialAddPost->validate()) {
2952
            return;
2953
        }
2954
2955
        $values = $wallSocialAddPost->exportValues();
2956
2957
        // Main post
2958
        if (!empty($values['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
2959
            $messageContent = $values['social_wall_new_msg_main'];
2960
            if (!empty($_POST['url_content'])) {
2961
                $messageContent = $values['social_wall_new_msg_main'].'<br /><br />'.$values['url_content'];
2962
            }
2963
2964
            $messageId = self::sendWallMessage(
2965
                api_get_user_id(),
2966
                $friendId,
2967
                $messageContent,
2968
                0,
2969
                MESSAGE_STATUS_WALL_POST
2970
            );
2971
2972
            if ($messageId && !empty($_FILES['picture']['tmp_name'])) {
2973
                self::sendWallMessageAttachmentFile(
2974
                    api_get_user_id(),
2975
                    $_FILES['picture'],
2976
                    $messageId
2977
                );
2978
            }
2979
2980
            Display::addFlash(Display::return_message(get_lang('MessageSent')));
2981
            header('Location: '.$url);
2982
            exit;
2983
        }
2984
    }
2985
2986
    /**
2987
     * @param int   $countPost
2988
     * @param array $htmlHeadXtra
2989
     */
2990
    public static function getScrollJs($countPost, &$htmlHeadXtra)
2991
    {
2992
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
2993
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
2994
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
2995
        $locale = api_get_language_isocode();
2996
2997
        // Add Jquery scroll pagination plugin
2998
        $htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
2999
        // Add Jquery Time ago plugin
3000
        $htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
3001
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
3002
        if (file_exists($timeAgoLocaleDir)) {
3003
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
3004
        }
3005
3006
        if ($countPost > self::DEFAULT_WALL_POSTS) {
3007
            $htmlHeadXtra[] = '<script>
3008
            $(function() {
3009
                var container = $("#wallMessages");
3010
                container.jscroll({
3011
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
3012
                    nextSelector: "a.nextPage:last",
3013
                    contentSelector: "",
3014
                    callback: timeAgo
3015
                });
3016
            });
3017
            </script>';
3018
        }
3019
3020
        $htmlHeadXtra[] = '<script>
3021
            function deleteMessage(id)
3022
            {
3023
                $.ajax({
3024
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3025
                    success: function (result) {
3026
                        if (result) {
3027
                            $("#message_" + id).parent().parent().parent().parent().html(result);
3028
                        }
3029
                    }
3030
                });
3031
            }
3032
3033
            function deleteComment(id)
3034
            {
3035
                $.ajax({
3036
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3037
                    success: function (result) {
3038
                        if (result) {
3039
                            $("#message_" + id).parent().parent().parent().html(result);
3040
                        }
3041
                    }
3042
                });
3043
            }
3044
3045
            function submitComment(messageId)
3046
            {
3047
                var data = $("#form_comment_"+messageId).serializeArray();
3048
                $.ajax({
3049
                    type : "POST",
3050
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
3051
                    data: data,
3052
                    success: function (result) {
3053
                        if (result) {
3054
                            $("#post_" + messageId + " textarea").val("");
3055
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
3056
                            $("#post_" + messageId + " .sub-mediapost").append(
3057
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved')).'</div>\')
3058
                            );
3059
3060
                            $("#result_" + messageId + "").fadeIn("fast", function() {
3061
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
3062
                                    $(this).remove();
3063
                                });
3064
                            });
3065
                        }
3066
                    }
3067
                });
3068
            }
3069
3070
            $(function() {
3071
                timeAgo();
3072
3073
                /*$(".delete_message").on("click", function() {
3074
                    var id = $(this).attr("id");
3075
                    id = id.split("_")[1];
3076
                    $.ajax({
3077
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3078
                        success: function (result) {
3079
                            if (result) {
3080
                                $("#message_" + id).parent().parent().parent().parent().html(result);
3081
                            }
3082
                        }
3083
                    });
3084
                });
3085
3086
3087
                $(".delete_comment").on("click", function() {
3088
                    var id = $(this).attr("id");
3089
                    id = id.split("_")[1];
3090
                    $.ajax({
3091
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3092
                        success: function (result) {
3093
                            if (result) {
3094
                                $("#message_" + id).parent().parent().parent().html(result);
3095
                            }
3096
                        }
3097
                    });
3098
                });
3099
                */
3100
            });
3101
3102
            function timeAgo() {
3103
                $(".timeago").timeago();
3104
            }
3105
            </script>';
3106
    }
3107
3108
    /**
3109
     * @param int $userId
3110
     * @param int $countPost
3111
     *
3112
     * @return string
3113
     */
3114
    public static function getAutoExtendLink($userId, $countPost)
3115
    {
3116
        $userId = (int) $userId;
3117
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
3118
        $socialAutoExtendLink = '';
3119
        if ($countPost > self::DEFAULT_WALL_POSTS) {
3120
            $socialAutoExtendLink = Display::url(
3121
                get_lang('SeeMore'),
3122
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
3123
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
3124
                [
3125
                    'class' => 'nextPage next',
3126
                ]
3127
            );
3128
        }
3129
3130
        return $socialAutoExtendLink;
3131
    }
3132
3133
    /**
3134
     * @param int $userId
3135
     *
3136
     * @return array
3137
     */
3138
    public static function getThreadList($userId)
3139
    {
3140
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3141
3142
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
3143
3144
        $threads = [];
3145
        if (!empty($forumCourseId)) {
3146
            $courseInfo = api_get_course_info_by_id($forumCourseId);
3147
            getNotificationsPerUser($userId, true, $forumCourseId);
3148
            $notification = Session::read('forum_notification');
3149
            Session::erase('forum_notification');
3150
3151
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
3152
                'cidReq' => $courseInfo['code'],
3153
            ]).'&';
3154
            if (isset($notification['thread']) && !empty($notification['thread'])) {
3155
                $threadList = array_filter(array_unique($notification['thread']));
3156
                $em = Database::getManager();
3157
                $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
3158
                foreach ($threadList as $threadId) {
3159
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
3160
                    $thread = $repo->find($threadId);
3161
                    if ($thread) {
3162
                        $threadUrl = $threadUrlBase.http_build_query([
3163
                            'forum' => $thread->getForumId(),
3164
                            'thread' => $thread->getIid(),
3165
                        ]);
3166
                        $threads[] = [
3167
                            'id' => $threadId,
3168
                            'url' => Display::url(
3169
                                $thread->getThreadTitle(),
3170
                                $threadUrl
3171
                            ),
3172
                            'name' => Display::url(
3173
                                $thread->getThreadTitle(),
3174
                                $threadUrl
3175
                            ),
3176
                            'description' => '',
3177
                        ];
3178
                    }
3179
                }
3180
            }
3181
        }
3182
3183
        return $threads;
3184
    }
3185
3186
    /**
3187
     * @param int $userId
3188
     *
3189
     * @return string
3190
     */
3191
    public static function getGroupBlock($userId)
3192
    {
3193
        $threadList = self::getThreadList($userId);
3194
        $userGroup = new UserGroup();
3195
3196
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3197
        $courseInfo = null;
3198
        if (!empty($forumCourseId)) {
3199
            $courseInfo = api_get_course_info_by_id($forumCourseId);
3200
        }
3201
3202
        $social_group_block = '';
3203
        if (!empty($courseInfo)) {
3204
            if (!empty($threadList)) {
3205
                $social_group_block .= '<div class="list-group">';
3206
                foreach ($threadList as $group) {
3207
                    $social_group_block .= ' <li class="list-group-item">';
3208
                    $social_group_block .= $group['name'];
3209
                    $social_group_block .= '</li>';
3210
                }
3211
                $social_group_block .= '</div>';
3212
            }
3213
3214
            $social_group_block .= Display::url(
3215
                get_lang('SeeAllCommunities'),
3216
                api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code']
3217
            );
3218
3219
            if (!empty($social_group_block)) {
3220
                $social_group_block = Display::panelCollapse(
3221
                    get_lang('MyCommunities'),
3222
                    $social_group_block,
3223
                    'sm-groups',
3224
                    null,
3225
                    'grups-acordion',
3226
                    'groups-collapse'
3227
                );
3228
            }
3229
        } else {
3230
            // Load my groups
3231
            $results = $userGroup->get_groups_by_user(
3232
                $userId,
3233
                [
3234
                    GROUP_USER_PERMISSION_ADMIN,
3235
                    GROUP_USER_PERMISSION_READER,
3236
                    GROUP_USER_PERMISSION_MODERATOR,
3237
                    GROUP_USER_PERMISSION_HRM,
3238
                ]
3239
            );
3240
3241
            $myGroups = [];
3242
            if (!empty($results)) {
3243
                foreach ($results as $result) {
3244
                    $id = $result['id'];
3245
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
3246
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
3247
3248
                    $group_url = "group_view.php?id=$id";
3249
3250
                    $link = Display::url(
3251
                        api_ucwords(cut($result['name'], 40, true)),
3252
                        $group_url
3253
                    );
3254
3255
                    $result['name'] = $link;
3256
3257
                    $picture = $userGroup->get_picture_group(
3258
                        $id,
3259
                        $result['picture'],
3260
                        null,
3261
                        GROUP_IMAGE_SIZE_BIG
3262
                    );
3263
3264
                    $result['picture'] = '<img class="img-responsive" src="'.$picture['file'].'" />';
3265
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
3266
                        get_lang('SeeMore').'</a></div>';
3267
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
3268
                    $myGroups[] = [
3269
                        'url' => Display::url(
3270
                            $result['picture'],
3271
                            $group_url
3272
                        ),
3273
                        'name' => $result['name'],
3274
                        'description' => $group_info.$group_actions,
3275
                    ];
3276
                }
3277
3278
                $social_group_block .= '<div class="list-group">';
3279
                foreach ($myGroups as $group) {
3280
                    $social_group_block .= ' <li class="list-group-item">';
3281
                    $social_group_block .= $group['name'];
3282
                    $social_group_block .= '</li>';
3283
                }
3284
                $social_group_block .= '</div>';
3285
3286
                $form = new FormValidator(
3287
                    'find_groups_form',
3288
                    'get',
3289
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
3290
                    null,
3291
                    null,
3292
                    FormValidator::LAYOUT_BOX_NO_LABEL
3293
                );
3294
                $form->addHidden('search_type', 2);
3295
3296
                $form->addText(
3297
                    'q',
3298
                    get_lang('Search'),
3299
                    false,
3300
                    [
3301
                        'aria-label' => get_lang('Search'),
3302
                        'custom' => true,
3303
                        'placeholder' => get_lang('Search'),
3304
                    ]
3305
                );
3306
3307
                $social_group_block .= $form->returnForm();
3308
3309
                if (!empty($social_group_block)) {
3310
                    $social_group_block = Display::panelCollapse(
3311
                        get_lang('MyGroups'),
3312
                        $social_group_block,
3313
                        'sm-groups',
3314
                        null,
3315
                        'grups-acordion',
3316
                        'groups-collapse'
3317
                    );
3318
                }
3319
            }
3320
        }
3321
3322
        return $social_group_block;
3323
    }
3324
3325
    /**
3326
     * @param string $selected
3327
     *
3328
     * @return string
3329
     */
3330
    public static function getHomeProfileTabs($selected = 'home')
3331
    {
3332
        $headers = [
3333
            [
3334
                'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
3335
                'content' => get_lang('Profile'),
3336
            ],
3337
        ];
3338
        $allowJustification = api_get_plugin_setting('justification', 'tool_enable') === 'true';
3339
        if ($allowJustification) {
3340
            $plugin = Justification::create();
3341
            $headers[] = [
3342
                'url' => api_get_path(WEB_CODE_PATH).'auth/justification.php',
3343
                'content' => $plugin->get_lang('Justification'),
3344
            ];
3345
        }
3346
3347
        $allowPauseTraining = api_get_plugin_setting('pausetraining', 'tool_enable') === 'true';
3348
        $allowEdit = api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation') === 'true';
3349
        if ($allowPauseTraining && $allowEdit) {
3350
            $plugin = PauseTraining::create();
3351
            $headers[] = [
3352
                'url' => api_get_path(WEB_CODE_PATH).'auth/pausetraining.php',
3353
                'content' => $plugin->get_lang('PauseTraining'),
3354
            ];
3355
        }
3356
3357
        $selectedItem = 1;
3358
        foreach ($headers as $header) {
3359
            $info = pathinfo($header['url']);
3360
            if ($selected === $info['filename']) {
3361
                break;
3362
            }
3363
            $selectedItem++;
3364
        }
3365
3366
        $tabs = '';
3367
        if (count($headers) > 1) {
3368
            $tabs = Display::tabsOnlyLink($headers, $selectedItem);
3369
        }
3370
3371
        return $tabs;
3372
    }
3373
3374
    private static function getWallForm(string $urlForm): FormValidator
3375
    {
3376
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
3377
        $form = new FormValidator(
3378
            'social_wall_main',
3379
            'post',
3380
            $urlForm.$userId,
3381
            null,
3382
            ['enctype' => 'multipart/form-data'],
3383
            FormValidator::LAYOUT_HORIZONTAL
3384
        );
3385
3386
        $socialWallPlaceholder = isset($_GET['u'])
3387
            ? get_lang('SocialWallWriteNewPostToFriend')
3388
            : get_lang('SocialWallWhatAreYouThinkingAbout');
3389
3390
        $form->addTextarea(
3391
            'social_wall_new_msg_main',
3392
            null,
3393
            [
3394
                'placeholder' => $socialWallPlaceholder,
3395
                'cols-size' => [1, 12, 1],
3396
                'aria-label' => $socialWallPlaceholder,
3397
            ]
3398
        );
3399
        $form->addHtml('<div class="form-group">');
3400
        $form->addHtml('<div class="col-sm-6">');
3401
        $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
3402
        $form->addHtml('</div>');
3403
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
3404
        $form->addButtonSend(
3405
            get_lang('Post'),
3406
            'wall_post_button',
3407
            false,
3408
            [
3409
                'cols-size' => [1, 10, 1],
3410
                'custom' => true,
3411
            ]
3412
        );
3413
        $form->addHtml('</div></div>');
3414
        $form->addHtml('</div>');
3415
        $form->addHidden('url_content', '');
3416
3417
        return $form;
3418
    }
3419
3420
    /**
3421
     * Returns the formatted header message post.
3422
     *
3423
     * @param int   $authorInfo
3424
     * @param int   $receiverInfo
3425
     * @param array $message      Message data
3426
     *
3427
     * @return string $html       The formatted header message post
3428
     */
3429
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
3430
    {
3431
        $currentUserId = api_get_user_id();
3432
        $authorId = (int) $authorInfo['user_id'];
3433
        $receiverId = (int) $receiverInfo['user_id'];
3434
        $iconStatus = $authorInfo['icon_status'];
3435
3436
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
3437
        $avatarAuthor = $authorInfo['avatar'];
3438
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
3439
        $nameCompleteAuthor = $authorInfo['complete_name'];
3440
3441
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
3442
        $nameCompleteReceiver = $receiverInfo['complete_name'];
3443
3444
        $htmlReceiver = '';
3445
        if ($authorId !== $receiverId) {
3446
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
3447
        }
3448
3449
        if (!empty($message['group_info'])) {
3450
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
3451
        }
3452
        $canEdit = ($currentUserId == $authorInfo['user_id'] || $currentUserId == $receiverInfo['user_id']) && empty($message['group_info']);
3453
3454
        if (!empty($message['thread_id'])) {
3455
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
3456
            $canEdit = false;
3457
        }
3458
3459
        $postAttachment = self::getPostAttachment($message);
3460
3461
        $html = '<div class="top-mediapost" >';
3462
        $html .= '<div class="pull-right btn-group btn-group-sm">';
3463
3464
        $html .= MessageManager::getLikesButton(
3465
            $message['id'],
3466
            $currentUserId,
3467
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
3468
        );
3469
3470
        if ($canEdit) {
3471
            $htmlDelete = Display::url(
3472
                Display::returnFontAwesomeIcon('trash', '', true),
3473
                'javascript:void(0)',
3474
                [
3475
                    'id' => 'message_'.$message['id'],
3476
                    'title' => get_lang('SocialMessageDelete'),
3477
                    'onclick' => 'deleteMessage('.$message['id'].')',
3478
                    'class' => 'btn btn-default',
3479
                ]
3480
            );
3481
3482
            $html .= $htmlDelete;
3483
        }
3484
        $html .= '</div>';
3485
3486
        $html .= '<div class="user-image" >';
3487
        $html .= '<a href="'.$urlAuthor.'">
3488
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
3489
        $html .= '</div>';
3490
        $html .= '<div class="user-data">';
3491
        $html .= $iconStatus;
3492
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
3493
        $html .= '<div class="post-date">'.$date.'</div>';
3494
        $html .= '</div>';
3495
        $html .= '<div class="msg-content">';
3496
        if (!empty($postAttachment)) {
3497
            $html .= '<div class="post-attachment thumbnail">';
3498
            $html .= $postAttachment;
3499
            $html .= '</div>';
3500
        }
3501
        $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
3502
        $html .= '</div>';
3503
        $html .= '</div>'; // end mediaPost
3504
3505
        // Popularity post functionality
3506
        $html .= '<div class="popularity-mediapost"></div>';
3507
3508
        return $html;
3509
    }
3510
}
3511