Passed
Pull Request — 1.11.x (#3931)
by Angel Fernando Quiroz
13:58
created

SocialManager::get_friends()   B

Complexity

Conditions 7
Paths 18

Size

Total Lines 49
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 32
c 0
b 0
f 0
nc 18
nop 4
dl 0
loc 49
rs 8.4746
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 getWallForm(string $urlForm): FormValidator
2408
    {
2409
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
2410
        $form = new FormValidator(
2411
            'social_wall_main',
2412
            'post',
2413
            $urlForm.$userId,
2414
            null,
2415
            ['enctype' => 'multipart/form-data'],
2416
            FormValidator::LAYOUT_HORIZONTAL
2417
        );
2418
2419
        $socialWallPlaceholder = isset($_GET['u'])
2420
            ? get_lang('SocialWallWriteNewPostToFriend')
2421
            : get_lang('SocialWallWhatAreYouThinkingAbout');
2422
2423
        $form->addTextarea(
2424
            'social_wall_new_msg_main',
2425
            null,
2426
            [
2427
                'placeholder' => $socialWallPlaceholder,
2428
                'cols-size' => [1, 12, 1],
2429
                'aria-label' => $socialWallPlaceholder,
2430
            ]
2431
        );
2432
        $form->addHtml('<div class="form-group">');
2433
        $form->addHtml('<div class="col-sm-6">');
2434
        $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
2435
        $form->addHtml('</div>');
2436
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
2437
        $form->addButtonSend(
2438
            get_lang('Post'),
2439
            'wall_post_button',
2440
            false,
2441
            [
2442
                'cols-size' => [1, 10, 1],
2443
                'custom' => true,
2444
            ]
2445
        );
2446
        $form->addHtml('</div></div>');
2447
        $form->addHtml('</div>');
2448
        $form->addHidden('url_content', '');
2449
2450
        return $form;
2451
    }
2452
2453
    public static function displayWallForm(string $urlForm): string
2454
    {
2455
        $form = self::getWallForm($urlForm);
2456
        $form->protect();
2457
2458
        return Display::panel($form->returnForm(), get_lang('SocialWall'));
2459
    }
2460
2461
    /**
2462
     * Show middle section for Portfolio extended.
2463
     * Must be active on main/admin/settings.php?category=User into extended_profile.
2464
     *
2465
     * @param string $urlForm
2466
     *
2467
     * @return string
2468
     */
2469
    public static function getWallFormPortfolio($urlForm)
2470
    {
2471
        $userId = isset($_GET['u']) ? (int) $_GET['u'] : 0;
2472
        $userId = $userId !== 0 ? $userId : api_get_user_id();
2473
        $user_info = api_get_user_info($userId);
2474
        $friend = true;
2475
        $editPorfolioLink = '';
2476
        if ($userId != api_get_user_id()) {
2477
            $friend = self::get_relation_between_contacts(api_get_user_id(), $userId);
2478
        } else {
2479
            $editPorfolioLink .= "<div class=\"pull-right\" style='margin-top: -5px'>".
2480
                '<a href="/main/auth/profile.php?type=extended#openarea" class="btn btn-default btn-sm btn-social-edit">'.
2481
                "<i class=\"fa fa-pencil\" aria-hidden=\"true\"></i>".
2482
                '</a>'.
2483
                "</div>";
2484
        }
2485
        if ($friend == 0) {
2486
            /* if has not relation, get current user */
2487
            $userId = api_get_user_id();
2488
            $user_info = api_get_user_info($userId);
2489
        }
2490
        // Images uploaded by course
2491
        $more_info = '';
2492
2493
        // Productions
2494
        $production_list = UserManager::build_production_list($userId);
2495
2496
        $form = new FormValidator(
2497
            'social_wall_main',
2498
            'post',
2499
            $urlForm.$userId,
2500
            null,
2501
            ['enctype' => 'multipart/form-data'],
2502
            FormValidator::LAYOUT_HORIZONTAL
2503
        );
2504
2505
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
2506
            'SocialWallWhatAreYouThinkingAbout'
2507
        );
2508
2509
        if (!empty($user_info['competences']) || !empty($user_info['diplomas'])
2510
            || !empty($user_info['openarea']) || !empty($user_info['teach'])) {
2511
            // $more_info .= '<div><h3>'.get_lang('MoreInformation').'</h3></div>';
2512
            //    MY PERSONAL OPEN AREA
2513
            if (!empty($user_info['openarea'])) {
2514
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyPersonalOpenArea').'</strong></div>';
2515
                $more_info .= '<div class="social-profile-extended">'.$user_info['openarea'].'</div>';
2516
                $more_info .= '<br />';
2517
            }
2518
            //    MY COMPETENCES
2519
            if (!empty($user_info['competences'])) {
2520
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyCompetences').'</strong></div>';
2521
                $more_info .= '<div class="social-profile-extended">'.$user_info['competences'].'</div>';
2522
                $more_info .= '<br />';
2523
            }
2524
            //    MY DIPLOMAS
2525
            if (!empty($user_info['diplomas'])) {
2526
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyDiplomas').'</strong></div>';
2527
                $more_info .= '<div class="social-profile-extended">'.$user_info['diplomas'].'</div>';
2528
                $more_info .= '<br />';
2529
            }
2530
            //    MY PRODUCTIONS
2531
            if (!empty($production_list)) {
2532
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyProductions').'</strong></div>';
2533
                $more_info .= '<div class="social-profile-extended">'.$production_list.'</div>';
2534
                $more_info .= '<br />';
2535
            }
2536
            // WHAT I AM ABLE TO TEACH
2537
            if (!empty($user_info['teach'])) {
2538
                $more_info .= '<div class="social-actions-message"><strong>'.get_lang('MyTeach').'</strong></div>';
2539
                $more_info .= '<div class="social-profile-extended">'.$user_info['teach'].'</div>';
2540
                $more_info .= '<br />';
2541
            }
2542
        }
2543
2544
        $form->addTextarea(
2545
            'social_wall_new_msg_main',
2546
            null,
2547
            [
2548
                'placeholder' => $socialWallPlaceholder,
2549
                'cols-size' => [1, 12, 1],
2550
                'aria-label' => $socialWallPlaceholder,
2551
            ]
2552
        );
2553
        $form->addHtml('<div class="form-group">');
2554
        $form->addHtml('<div class="col-sm-6">');
2555
        $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
2556
        $form->addHtml('</div>');
2557
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
2558
        $form->addButtonSend(
2559
            get_lang('Post'),
2560
            'wall_post_button',
2561
            false,
2562
            [
2563
                'cols-size' => [1, 10, 1],
2564
                'custom' => true,
2565
            ]
2566
        );
2567
        $form->addHtml('</div></div>');
2568
        $form->addHtml('</div>');
2569
        $form->addHidden('url_content', '');
2570
2571
        return Display::panel($more_info, get_lang('Portfolio').$editPorfolioLink);
2572
    }
2573
2574
    /**
2575
     * @param int   $userId
2576
     * @param int   $start
2577
     * @param int   $length
2578
     * @param array $threadList
2579
     *
2580
     * @return array
2581
     */
2582
    public static function getMyWallMessages($userId, $start = 0, $length = 10, $threadList = [])
2583
    {
2584
        $userGroup = new UserGroup();
2585
        $groups = $userGroup->get_groups_by_user($userId, [GROUP_USER_PERMISSION_READER, GROUP_USER_PERMISSION_ADMIN]);
2586
        $groupList = [];
2587
        if (!empty($groups)) {
2588
            $groupList = array_column($groups, 'id');
2589
        }
2590
2591
        $friends = self::get_friends($userId, USER_RELATION_TYPE_FRIEND);
2592
        $friendList = [];
2593
        if (!empty($friends)) {
2594
            $friendList = array_column($friends, 'friend_user_id');
2595
        }
2596
2597
        $messages = self::getWallMessages(
2598
            $userId,
2599
            0,
2600
            $groupList,
2601
            $friendList,
2602
            '',
2603
            $start,
2604
            $length,
2605
            false,
2606
            $threadList
2607
        );
2608
2609
        $countPost = self::getCountWallMessagesByUser($userId, $groupList, $friendList, $threadList);
2610
        $messages = self::formatWallMessages($messages);
2611
2612
        $html = '';
2613
        foreach ($messages as $message) {
2614
            $post = $message['html'];
2615
            $comments = '';
2616
            if (in_array($message['msg_status'], [MESSAGE_STATUS_WALL_POST, MESSAGE_STATUS_PROMOTED])) {
2617
                $comments = self::getWallPostComments($userId, $message);
2618
            }
2619
2620
            $html .= self::wrapPost($message, $post.$comments);
2621
        }
2622
2623
        return [
2624
            'posts' => $html,
2625
            'count' => $countPost,
2626
        ];
2627
    }
2628
2629
    /**
2630
     * @param string $message
2631
     * @param string $content
2632
     *
2633
     * @return string
2634
     */
2635
    public static function wrapPost($message, $content)
2636
    {
2637
        $class = '';
2638
        if ($message['msg_status'] === MESSAGE_STATUS_PROMOTED) {
2639
            $class = 'promoted_post';
2640
        }
2641
2642
        return Display::panel($content, '',
2643
            '',
2644
            'default',
2645
            '',
2646
            'post_'.$message['id'],
2647
            null,
2648
            $class
2649
        );
2650
    }
2651
2652
    /**
2653
     * @param int   $userId
2654
     * @param array $groupList
2655
     * @param array $friendList
2656
     * @param array $threadList
2657
     *
2658
     * @return int
2659
     */
2660
    public static function getCountWallMessagesByUser($userId, $groupList = [], $friendList = [], $threadList = [])
2661
    {
2662
        return self::getWallMessages(
2663
            $userId,
2664
            0,
2665
            $groupList,
2666
            $friendList,
2667
            '',
2668
            0,
2669
            0,
2670
            true,
2671
            $threadList
2672
        );
2673
    }
2674
2675
    /**
2676
     * @param int $userId
2677
     *
2678
     * @return string
2679
     */
2680
    public static function getWallMessagesByUser($userId)
2681
    {
2682
        $messages = self::getWallMessages($userId);
2683
        $messages = self::formatWallMessages($messages);
2684
2685
        $html = '';
2686
        foreach ($messages as $message) {
2687
            $post = $message['html'];
2688
            $comments = self::getWallPostComments($userId, $message);
2689
            $html .= self::wrapPost($message, $post.$comments);
2690
        }
2691
2692
        return $html;
2693
    }
2694
2695
    /**
2696
     * Get HTML code block for user skills.
2697
     *
2698
     * @param int    $userId      The user ID
2699
     * @param string $orientation
2700
     *
2701
     * @return string
2702
     */
2703
    public static function getSkillBlock($userId, $orientation = 'horizontal')
2704
    {
2705
        if (Skill::isAllowed($userId, false) === false) {
2706
            return '';
2707
        }
2708
2709
        $skill = new Skill();
2710
        $ranking = $skill->getUserSkillRanking($userId);
2711
2712
        $template = new Template(null, false, false, false, false, false);
2713
        $template->assign('ranking', $ranking);
2714
        $template->assign('orientation', $orientation);
2715
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
2716
        $template->assign('user_id', $userId);
2717
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
2718
2719
        $skillBlock = $template->get_template('social/skills_block.tpl');
2720
2721
        return $template->fetch($skillBlock);
2722
    }
2723
2724
    /**
2725
     * @param int  $user_id
2726
     * @param bool $isArray
2727
     *
2728
     * @return string|array
2729
     */
2730
    public static function getExtraFieldBlock($user_id, $isArray = false)
2731
    {
2732
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
2733
        $fieldVisibilityKeys = [];
2734
        if (isset($fieldVisibility['options'])) {
2735
            $fieldVisibility = $fieldVisibility['options'];
2736
            $fieldVisibilityKeys = array_keys($fieldVisibility);
2737
        }
2738
2739
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
2740
        $extra_user_data = UserManager::get_extra_user_data($user_id);
2741
2742
        $extra_information = '';
2743
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
2744
            $extra_information_value = '';
2745
            $extraField = new ExtraField('user');
2746
            $listType = [];
2747
            $extraFieldItem = [];
2748
            foreach ($extra_user_data as $key => $data) {
2749
                if (empty($data)) {
2750
                    continue;
2751
                }
2752
                if (in_array($key, $fieldVisibilityKeys) && $fieldVisibility[$key] === false) {
2753
                    continue;
2754
                }
2755
2756
                // Avoiding parameters
2757
                if (in_array(
2758
                    $key,
2759
                    [
2760
                        'mail_notify_invitation',
2761
                        'mail_notify_message',
2762
                        'mail_notify_group_message',
2763
                    ]
2764
                )) {
2765
                    continue;
2766
                }
2767
                // get display text, visibility and type from user_field table
2768
                $field_variable = str_replace('extra_', '', $key);
2769
2770
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2771
                    $field_variable
2772
                );
2773
2774
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
2775
                    continue;
2776
                }
2777
2778
                // if is not visible skip
2779
                if ($extraFieldInfo['visible_to_self'] != 1) {
2780
                    continue;
2781
                }
2782
2783
                // if is not visible to others skip also
2784
                if ($extraFieldInfo['visible_to_others'] != 1) {
2785
                    continue;
2786
                }
2787
2788
                if (is_array($data)) {
2789
                    switch ($extraFieldInfo['field_type']) {
2790
                        case ExtraField::FIELD_TYPE_RADIO:
2791
                            $objEfOption = new ExtraFieldOption('user');
2792
                            $value = $data['extra_'.$extraFieldInfo['variable']];
2793
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
2794
                                $extraFieldInfo['id'],
2795
                                $value
2796
                            );
2797
2798
                            if ($optionInfo && isset($optionInfo[0])) {
2799
                                $optionInfo = $optionInfo[0];
2800
                                $extraFieldItem = [
2801
                                    'variable' => $extraFieldInfo['variable'],
2802
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2803
                                    'value' => $optionInfo['display_text'],
2804
                                ];
2805
                            } else {
2806
                                $extraFieldItem = [
2807
                                    'variable' => $extraFieldInfo['variable'],
2808
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2809
                                    'value' => implode(',', $data),
2810
                                ];
2811
                            }
2812
                            break;
2813
                        default:
2814
                            $extra_information_value .=
2815
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
2816
                                .' '.implode(',', $data).'</li>';
2817
                            $extraFieldItem = [
2818
                                'variable' => $extraFieldInfo['variable'],
2819
                                'label' => ucfirst($extraFieldInfo['display_text']),
2820
                                'value' => implode(',', $data),
2821
                            ];
2822
                            break;
2823
                    }
2824
                } else {
2825
                    switch ($extraFieldInfo['field_type']) {
2826
                        case ExtraField::FIELD_TYPE_RADIO:
2827
                            $objEfOption = new ExtraFieldOption('user');
2828
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
2829
                            break;
2830
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
2831
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
2832
                            $data = explode('::', $data);
2833
                            $data = $data[0];
2834
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2835
                            $extraFieldItem = [
2836
                                'variable' => $extraFieldInfo['variable'],
2837
                                'label' => ucfirst($extraFieldInfo['display_text']),
2838
                                'value' => $data,
2839
                            ];
2840
                            break;
2841
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
2842
                            $id_options = explode('::', $data);
2843
                            $value_options = [];
2844
                            // get option display text from user_field_options table
2845
                            foreach ($id_options as $id_option) {
2846
                                $sql = "SELECT display_text
2847
                                    FROM $t_ufo
2848
                                    WHERE id = '$id_option'";
2849
                                $res_options = Database::query($sql);
2850
                                $row_options = Database::fetch_row($res_options);
2851
                                $value_options[] = $row_options[0];
2852
                            }
2853
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2854
                                .' '.implode(' ', $value_options).'</li>';
2855
                            $extraFieldItem = [
2856
                                'variable' => $extraFieldInfo['variable'],
2857
                                'label' => ucfirst($extraFieldInfo['display_text']),
2858
                                'value' => $value_options,
2859
                            ];
2860
                            break;
2861
                        case ExtraField::FIELD_TYPE_TAG:
2862
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
2863
2864
                            $tag_tmp = '';
2865
                            foreach ($user_tags as $tags) {
2866
                                $tag_tmp .= '<a class="label label_tag"'
2867
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
2868
                                    .$tags['tag']
2869
                                    .'</a>';
2870
                            }
2871
                            if (is_array($user_tags) && count($user_tags) > 0) {
2872
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2873
                                    .' '.$tag_tmp.'</li>';
2874
                            }
2875
                            $extraFieldItem = [
2876
                                'variable' => $extraFieldInfo['variable'],
2877
                                'label' => ucfirst($extraFieldInfo['display_text']),
2878
                                'value' => $tag_tmp,
2879
                            ];
2880
                            break;
2881
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
2882
                            $icon_path = UserManager::get_favicon_from_url($data);
2883
                            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...
2884
                                break;
2885
                            }
2886
                            $bottom = '0.2';
2887
                            //quick hack for hi5
2888
                            $domain = parse_url($icon_path, PHP_URL_HOST);
2889
                            if ($domain == 'www.hi5.com' || $domain == 'hi5.com') {
2890
                                $bottom = '-0.8';
2891
                            }
2892
                            $data = '<a href="'.$data.'">'
2893
                                .'<img src="'.$icon_path.'" alt="icon"'
2894
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
2895
                                .$extraFieldInfo['display_text']
2896
                                .'</a>';
2897
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
2898
                            $extraFieldItem = [
2899
                                'variable' => $extraFieldInfo['variable'],
2900
                                'label' => ucfirst($extraFieldInfo['display_text']),
2901
                                'value' => $data,
2902
                            ];
2903
                            break;
2904
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
2905
                            $parsedData = explode('::', $data);
2906
2907
                            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...
2908
                                break;
2909
                            }
2910
2911
                            $objEfOption = new ExtraFieldOption('user');
2912
                            $optionInfo = $objEfOption->get($parsedData[0]);
2913
2914
                            $extra_information_value .= '<li class="list-group-item">'
2915
                                .$optionInfo['display_text'].': '
2916
                                .$parsedData[1].'</li>';
2917
                            $extraFieldItem = [
2918
                                'variable' => $extraFieldInfo['variable'],
2919
                                'label' => ucfirst($extraFieldInfo['display_text']),
2920
                                'value' => $parsedData[1],
2921
                            ];
2922
                            break;
2923
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
2924
                            $optionIds = explode(';', $data);
2925
                            $optionValues = [];
2926
2927
                            foreach ($optionIds as $optionId) {
2928
                                $objEfOption = new ExtraFieldOption('user');
2929
                                $optionInfo = $objEfOption->get($optionId);
2930
2931
                                $optionValues[] = $optionInfo['display_text'];
2932
                            }
2933
                            $extra_information_value .= '<li class="list-group-item">'
2934
                                .ucfirst($extraFieldInfo['display_text']).': '
2935
                                .implode(' ', $optionValues).'</li>';
2936
                            $extraFieldItem = [
2937
                                'variable' => $extraFieldInfo['variable'],
2938
                                'label' => ucfirst($extraFieldInfo['display_text']),
2939
                                'value' => implode(' ', $optionValues),
2940
                            ];
2941
                            break;
2942
                        default:
2943
                            // Ofaj
2944
                            // Converts "Date of birth" into "age"
2945
                            if ($key === 'terms_datedenaissance') {
2946
                                $dataArray = date_to_str_ago($data, 'UTC', true);
2947
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
2948
                                if (!empty($dataToString)) {
2949
                                    $data = $dataToString;
2950
                                    $extraFieldInfo['display_text'] = get_lang('Age');
2951
                                }
2952
                            }
2953
2954
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2955
                            $extraFieldItem = [
2956
                                'variable' => $extraFieldInfo['variable'],
2957
                                'label' => ucfirst($extraFieldInfo['display_text']),
2958
                                'value' => $data,
2959
                            ];
2960
                            break;
2961
                    }
2962
                }
2963
2964
                $listType[] = $extraFieldItem;
2965
            }
2966
2967
            if ($isArray) {
2968
                return $listType;
2969
            } else {
2970
                // if there are information to show
2971
                if (!empty($extra_information_value)) {
2972
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
2973
                    $extra_information .= Display::panelCollapse(
2974
                        get_lang('ExtraInformation'),
2975
                        $extra_information_value,
2976
                        'sn-extra-information',
2977
                        null,
2978
                        'sn-extra-accordion',
2979
                        'sn-extra-collapse'
2980
                    );
2981
                }
2982
            }
2983
        }
2984
2985
        return $extra_information;
2986
    }
2987
2988
    /**
2989
     * @param string $url
2990
     */
2991
    public static function handlePosts($url)
2992
    {
2993
        $friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
2994
        $url = Security::remove_XSS($url);
2995
        $wallSocialAddPost = SocialManager::getWallForm(api_get_self());
2996
2997
        if (!$wallSocialAddPost->validate()) {
2998
            return;
2999
        }
3000
3001
        $values = $wallSocialAddPost->exportValues();
3002
3003
        // Main post
3004
        if (!empty($values['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
3005
            $messageContent = $values['social_wall_new_msg_main'];
3006
            if (!empty($_POST['url_content'])) {
3007
                $messageContent = $values['social_wall_new_msg_main'].'<br /><br />'.$values['url_content'];
3008
            }
3009
3010
            $messageId = self::sendWallMessage(
3011
                api_get_user_id(),
3012
                $friendId,
3013
                $messageContent,
3014
                0,
3015
                MESSAGE_STATUS_WALL_POST
3016
            );
3017
3018
            if ($messageId && !empty($_FILES['picture']['tmp_name'])) {
3019
                self::sendWallMessageAttachmentFile(
3020
                    api_get_user_id(),
3021
                    $_FILES['picture'],
3022
                    $messageId
3023
                );
3024
            }
3025
3026
            Display::addFlash(Display::return_message(get_lang('MessageSent')));
3027
            header('Location: '.$url);
3028
            exit;
3029
        }
3030
    }
3031
3032
    /**
3033
     * @param int   $countPost
3034
     * @param array $htmlHeadXtra
3035
     */
3036
    public static function getScrollJs($countPost, &$htmlHeadXtra)
3037
    {
3038
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
3039
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
3040
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
3041
        $locale = api_get_language_isocode();
3042
3043
        // Add Jquery scroll pagination plugin
3044
        $htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
3045
        // Add Jquery Time ago plugin
3046
        $htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
3047
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
3048
        if (file_exists($timeAgoLocaleDir)) {
3049
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
3050
        }
3051
3052
        if ($countPost > self::DEFAULT_WALL_POSTS) {
3053
            $htmlHeadXtra[] = '<script>
3054
            $(function() {
3055
                var container = $("#wallMessages");
3056
                container.jscroll({
3057
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
3058
                    nextSelector: "a.nextPage:last",
3059
                    contentSelector: "",
3060
                    callback: timeAgo
3061
                });
3062
            });
3063
            </script>';
3064
        }
3065
3066
        $htmlHeadXtra[] = '<script>
3067
            function deleteMessage(id)
3068
            {
3069
                $.ajax({
3070
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3071
                    success: function (result) {
3072
                        if (result) {
3073
                            $("#message_" + id).parent().parent().parent().parent().html(result);
3074
                        }
3075
                    }
3076
                });
3077
            }
3078
3079
            function deleteComment(id)
3080
            {
3081
                $.ajax({
3082
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3083
                    success: function (result) {
3084
                        if (result) {
3085
                            $("#message_" + id).parent().parent().parent().html(result);
3086
                        }
3087
                    }
3088
                });
3089
            }
3090
3091
            function submitComment(messageId)
3092
            {
3093
                var data = $("#form_comment_"+messageId).serializeArray();
3094
                $.ajax({
3095
                    type : "POST",
3096
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
3097
                    data: data,
3098
                    success: function (result) {
3099
                        if (result) {
3100
                            $("#post_" + messageId + " textarea").val("");
3101
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
3102
                            $("#post_" + messageId + " .sub-mediapost").append(
3103
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved')).'</div>\')
3104
                            );
3105
3106
                            $("#result_" + messageId + "").fadeIn("fast", function() {
3107
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
3108
                                    $(this).remove();
3109
                                });
3110
                            });
3111
                        }
3112
                    }
3113
                });
3114
            }
3115
3116
            $(function() {
3117
                timeAgo();
3118
3119
                /*$(".delete_message").on("click", function() {
3120
                    var id = $(this).attr("id");
3121
                    id = id.split("_")[1];
3122
                    $.ajax({
3123
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3124
                        success: function (result) {
3125
                            if (result) {
3126
                                $("#message_" + id).parent().parent().parent().parent().html(result);
3127
                            }
3128
                        }
3129
                    });
3130
                });
3131
3132
3133
                $(".delete_comment").on("click", function() {
3134
                    var id = $(this).attr("id");
3135
                    id = id.split("_")[1];
3136
                    $.ajax({
3137
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3138
                        success: function (result) {
3139
                            if (result) {
3140
                                $("#message_" + id).parent().parent().parent().html(result);
3141
                            }
3142
                        }
3143
                    });
3144
                });
3145
                */
3146
            });
3147
3148
            function timeAgo() {
3149
                $(".timeago").timeago();
3150
            }
3151
            </script>';
3152
    }
3153
3154
    /**
3155
     * @param int $userId
3156
     * @param int $countPost
3157
     *
3158
     * @return string
3159
     */
3160
    public static function getAutoExtendLink($userId, $countPost)
3161
    {
3162
        $userId = (int) $userId;
3163
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
3164
        $socialAutoExtendLink = '';
3165
        if ($countPost > self::DEFAULT_WALL_POSTS) {
3166
            $socialAutoExtendLink = Display::url(
3167
                get_lang('SeeMore'),
3168
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
3169
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
3170
                [
3171
                    'class' => 'nextPage next',
3172
                ]
3173
            );
3174
        }
3175
3176
        return $socialAutoExtendLink;
3177
    }
3178
3179
    /**
3180
     * @param int $userId
3181
     *
3182
     * @return array
3183
     */
3184
    public static function getThreadList($userId)
3185
    {
3186
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3187
3188
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
3189
3190
        $threads = [];
3191
        if (!empty($forumCourseId)) {
3192
            $courseInfo = api_get_course_info_by_id($forumCourseId);
3193
            getNotificationsPerUser($userId, true, $forumCourseId);
3194
            $notification = Session::read('forum_notification');
3195
            Session::erase('forum_notification');
3196
3197
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
3198
                'cidReq' => $courseInfo['code'],
3199
            ]).'&';
3200
            if (isset($notification['thread']) && !empty($notification['thread'])) {
3201
                $threadList = array_filter(array_unique($notification['thread']));
3202
                $em = Database::getManager();
3203
                $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
3204
                foreach ($threadList as $threadId) {
3205
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
3206
                    $thread = $repo->find($threadId);
3207
                    if ($thread) {
3208
                        $threadUrl = $threadUrlBase.http_build_query([
3209
                            'forum' => $thread->getForumId(),
3210
                            'thread' => $thread->getIid(),
3211
                        ]);
3212
                        $threads[] = [
3213
                            'id' => $threadId,
3214
                            'url' => Display::url(
3215
                                $thread->getThreadTitle(),
3216
                                $threadUrl
3217
                            ),
3218
                            'name' => Display::url(
3219
                                $thread->getThreadTitle(),
3220
                                $threadUrl
3221
                            ),
3222
                            'description' => '',
3223
                        ];
3224
                    }
3225
                }
3226
            }
3227
        }
3228
3229
        return $threads;
3230
    }
3231
3232
    /**
3233
     * @param int $userId
3234
     *
3235
     * @return string
3236
     */
3237
    public static function getGroupBlock($userId)
3238
    {
3239
        $threadList = self::getThreadList($userId);
3240
        $userGroup = new UserGroup();
3241
3242
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3243
        $courseInfo = null;
3244
        if (!empty($forumCourseId)) {
3245
            $courseInfo = api_get_course_info_by_id($forumCourseId);
3246
        }
3247
3248
        $social_group_block = '';
3249
        if (!empty($courseInfo)) {
3250
            if (!empty($threadList)) {
3251
                $social_group_block .= '<div class="list-group">';
3252
                foreach ($threadList as $group) {
3253
                    $social_group_block .= ' <li class="list-group-item">';
3254
                    $social_group_block .= $group['name'];
3255
                    $social_group_block .= '</li>';
3256
                }
3257
                $social_group_block .= '</div>';
3258
            }
3259
3260
            $social_group_block .= Display::url(
3261
                get_lang('SeeAllCommunities'),
3262
                api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code']
3263
            );
3264
3265
            if (!empty($social_group_block)) {
3266
                $social_group_block = Display::panelCollapse(
3267
                    get_lang('MyCommunities'),
3268
                    $social_group_block,
3269
                    'sm-groups',
3270
                    null,
3271
                    'grups-acordion',
3272
                    'groups-collapse'
3273
                );
3274
            }
3275
        } else {
3276
            // Load my groups
3277
            $results = $userGroup->get_groups_by_user(
3278
                $userId,
3279
                [
3280
                    GROUP_USER_PERMISSION_ADMIN,
3281
                    GROUP_USER_PERMISSION_READER,
3282
                    GROUP_USER_PERMISSION_MODERATOR,
3283
                    GROUP_USER_PERMISSION_HRM,
3284
                ]
3285
            );
3286
3287
            $myGroups = [];
3288
            if (!empty($results)) {
3289
                foreach ($results as $result) {
3290
                    $id = $result['id'];
3291
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
3292
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
3293
3294
                    $group_url = "group_view.php?id=$id";
3295
3296
                    $link = Display::url(
3297
                        api_ucwords(cut($result['name'], 40, true)),
3298
                        $group_url
3299
                    );
3300
3301
                    $result['name'] = $link;
3302
3303
                    $picture = $userGroup->get_picture_group(
3304
                        $id,
3305
                        $result['picture'],
3306
                        null,
3307
                        GROUP_IMAGE_SIZE_BIG
3308
                    );
3309
3310
                    $result['picture'] = '<img class="img-responsive" src="'.$picture['file'].'" />';
3311
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
3312
                        get_lang('SeeMore').'</a></div>';
3313
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
3314
                    $myGroups[] = [
3315
                        'url' => Display::url(
3316
                            $result['picture'],
3317
                            $group_url
3318
                        ),
3319
                        'name' => $result['name'],
3320
                        'description' => $group_info.$group_actions,
3321
                    ];
3322
                }
3323
3324
                $social_group_block .= '<div class="list-group">';
3325
                foreach ($myGroups as $group) {
3326
                    $social_group_block .= ' <li class="list-group-item">';
3327
                    $social_group_block .= $group['name'];
3328
                    $social_group_block .= '</li>';
3329
                }
3330
                $social_group_block .= '</div>';
3331
3332
                $form = new FormValidator(
3333
                    'find_groups_form',
3334
                    'get',
3335
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
3336
                    null,
3337
                    null,
3338
                    FormValidator::LAYOUT_BOX_NO_LABEL
3339
                );
3340
                $form->addHidden('search_type', 2);
3341
3342
                $form->addText(
3343
                    'q',
3344
                    get_lang('Search'),
3345
                    false,
3346
                    [
3347
                        'aria-label' => get_lang('Search'),
3348
                        'custom' => true,
3349
                        'placeholder' => get_lang('Search'),
3350
                    ]
3351
                );
3352
3353
                $social_group_block .= $form->returnForm();
3354
3355
                if (!empty($social_group_block)) {
3356
                    $social_group_block = Display::panelCollapse(
3357
                        get_lang('MyGroups'),
3358
                        $social_group_block,
3359
                        'sm-groups',
3360
                        null,
3361
                        'grups-acordion',
3362
                        'groups-collapse'
3363
                    );
3364
                }
3365
            }
3366
        }
3367
3368
        return $social_group_block;
3369
    }
3370
3371
    /**
3372
     * @param string $selected
3373
     *
3374
     * @return string
3375
     */
3376
    public static function getHomeProfileTabs($selected = 'home')
3377
    {
3378
        $headers = [
3379
            [
3380
                'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
3381
                'content' => get_lang('Profile'),
3382
            ],
3383
        ];
3384
        $allowJustification = api_get_plugin_setting('justification', 'tool_enable') === 'true';
3385
        if ($allowJustification) {
3386
            $plugin = Justification::create();
3387
            $headers[] = [
3388
                'url' => api_get_path(WEB_CODE_PATH).'auth/justification.php',
3389
                'content' => $plugin->get_lang('Justification'),
3390
            ];
3391
        }
3392
3393
        $allowPauseTraining = api_get_plugin_setting('pausetraining', 'tool_enable') === 'true';
3394
        $allowEdit = api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation') === 'true';
3395
        if ($allowPauseTraining && $allowEdit) {
3396
            $plugin = PauseTraining::create();
3397
            $headers[] = [
3398
                'url' => api_get_path(WEB_CODE_PATH).'auth/pausetraining.php',
3399
                'content' => $plugin->get_lang('PauseTraining'),
3400
            ];
3401
        }
3402
3403
        $selectedItem = 1;
3404
        foreach ($headers as $header) {
3405
            $info = pathinfo($header['url']);
3406
            if ($selected === $info['filename']) {
3407
                break;
3408
            }
3409
            $selectedItem++;
3410
        }
3411
3412
        $tabs = '';
3413
        if (count($headers) > 1) {
3414
            $tabs = Display::tabsOnlyLink($headers, $selectedItem);
3415
        }
3416
3417
        return $tabs;
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