Passed
Push — master ( 2a697d...2fc9bb )
by Julito
11:49 queued 02:46
created

SocialManager::getThreadList()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 46
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 31
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 46
rs 8.8017
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
use Zend\Feed\Reader\Entry\Rss;
6
use Zend\Feed\Reader\Reader;
7
8
/**
9
 * Class SocialManager.
10
 *
11
 * This class provides methods for the social network management.
12
 * Include/require it in your code to use its features.
13
 *
14
 * @package chamilo.social
15
 */
16
class SocialManager extends UserManager
17
{
18
    const DEFAULT_WALL_POSTS = 10;
19
    const DEFAULT_SCROLL_NEW_POST = 5;
20
21
    /**
22
     * Constructor.
23
     */
24
    public function __construct()
25
    {
26
    }
27
28
    /**
29
     * Allow to see contacts list.
30
     *
31
     * @author isaac flores paz
32
     *
33
     * @return array
34
     */
35
    public static function show_list_type_friends()
36
    {
37
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
38
        $sql = 'SELECT id, title FROM '.$table.'
39
                WHERE id<>6 
40
                ORDER BY id ASC';
41
        $result = Database::query($sql);
42
        $friend_relation_list = [];
43
        while ($row = Database::fetch_array($result, 'ASSOC')) {
44
            $friend_relation_list[] = $row;
45
        }
46
        $count_list = count($friend_relation_list);
47
        if ($count_list == 0) {
48
            $friend_relation_list[] = get_lang('Unknown');
49
        } else {
50
            return $friend_relation_list;
51
        }
52
    }
53
54
    /**
55
     * Get relation type contact by name.
56
     *
57
     * @param string names of the kind of relation
58
     *
59
     * @return int
60
     *
61
     * @author isaac flores paz
62
     */
63
    public static function get_relation_type_by_name($relation_type_name)
64
    {
65
        $list_type_friend = self::show_list_type_friends();
66
        foreach ($list_type_friend as $value_type_friend) {
67
            if (strtolower($value_type_friend['title']) == $relation_type_name) {
68
                return $value_type_friend['id'];
69
            }
70
        }
71
    }
72
73
    /**
74
     * Get the kind of relation between contacts.
75
     *
76
     * @param int user id
77
     * @param int user friend id
78
     * @param string
79
     *
80
     * @return int
81
     *
82
     * @author isaac flores paz
83
     */
84
    public static function get_relation_between_contacts($user_id, $user_friend)
85
    {
86
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
87
        $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
88
        $sql = 'SELECT rt.id as id 
89
                FROM '.$table.' rt
90
                WHERE rt.id = (
91
                    SELECT uf.relation_type 
92
                    FROM '.$userRelUserTable.' uf
93
                    WHERE
94
                        user_id='.((int) $user_id).' AND
95
                        friend_user_id='.((int) $user_friend).' AND
96
                        uf.relation_type <> '.USER_RELATION_TYPE_RRHH.'
97
                    LIMIT 1
98
                )';
99
        $res = Database::query($sql);
100
        if (Database::num_rows($res) > 0) {
101
            $row = Database::fetch_array($res, 'ASSOC');
102
103
            return $row['id'];
104
        } else {
105
            return USER_UNKNOWN;
106
        }
107
    }
108
109
    /**
110
     * Get count of friends from user.
111
     *
112
     * @param int $userId
113
     *
114
     * @return int
115
     */
116
    public static function getCountFriends($userId)
117
    {
118
        $table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
119
        $userId = (int) $userId;
120
        if (empty($userId)) {
121
            return 0;
122
        }
123
124
        $sql = 'SELECT count(friend_user_id) count
125
                FROM '.$table.'
126
                WHERE
127
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
128
                    friend_user_id<>'.$userId.' AND
129
                    user_id='.$userId;
130
        $res = Database::query($sql);
131
        if (Database::num_rows($res)) {
132
            $row = Database::fetch_array($res, 'ASSOC');
133
134
            return (int) $row['count'];
135
        }
136
137
        return 0;
138
    }
139
140
    /**
141
     * Gets friends id list.
142
     *
143
     * @param int  user id
144
     * @param int group id
145
     * @param string name to search
146
     * @param bool true will load firstname, lastname, and image name
147
     *
148
     * @return array
149
     *
150
     * @author Julio Montoya <[email protected]> Cleaning code, function renamed, $load_extra_info option added
151
     * @author isaac flores paz
152
     */
153
    public static function get_friends(
154
        $user_id,
155
        $id_group = null,
156
        $search_name = null,
157
        $load_extra_info = true
158
    ) {
159
        $user_id = (int) $user_id;
160
161
        $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
162
        $tbl_my_user = Database::get_main_table(TABLE_MAIN_USER);
163
        $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
164
                WHERE
165
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
166
                    friend_user_id<>'.$user_id.' AND
167
                    user_id='.$user_id;
168
        if (isset($id_group) && $id_group > 0) {
169
            $sql .= ' AND relation_type='.$id_group;
170
        }
171
        if (isset($search_name)) {
172
            $search_name = trim($search_name);
173
            $search_name = str_replace(' ', '', $search_name);
174
            $sql .= ' AND friend_user_id IN (
175
                SELECT user_id FROM '.$tbl_my_user.'
176
                WHERE
177
                    firstName LIKE "%'.Database::escape_string($search_name).'%" OR
178
                    lastName LIKE "%'.Database::escape_string($search_name).'%" OR
179
                    '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
180
                ) ';
181
        }
182
183
        $res = Database::query($sql);
184
        $list = [];
185
        while ($row = Database::fetch_array($res, 'ASSOC')) {
186
            if ($load_extra_info) {
187
                $userInfo = api_get_user_info($row['friend_user_id']);
188
                $list[] = [
189
                    'friend_user_id' => $row['friend_user_id'],
190
                    'firstName' => $userInfo['firstName'],
191
                    'lastName' => $userInfo['lastName'],
192
                    'username' => $userInfo['username'],
193
                    'image' => $userInfo['avatar'],
194
                    'user_info' => $userInfo,
195
                ];
196
            } else {
197
                $list[] = $row;
198
            }
199
        }
200
201
        return $list;
202
    }
203
204
    /**
205
     * get web path of user invitate.
206
     *
207
     * @author isaac flores paz
208
     * @author Julio Montoya setting variable array
209
     *
210
     * @param int user id
211
     *
212
     * @return array
213
     */
214
    public static function get_list_web_path_user_invitation_by_user_id($user_id)
215
    {
216
        $list_ids = self::get_list_invitation_of_friends_by_user_id($user_id);
217
        $list = [];
218
        foreach ($list_ids as $values_ids) {
219
            $list[] = UserManager::get_user_picture_path_by_id(
220
                $values_ids['user_sender_id'],
221
                'web'
222
            );
223
        }
224
225
        return $list;
226
    }
227
228
    /**
229
     * Sends an invitation to contacts.
230
     *
231
     * @param int user id
232
     * @param int user friend id
233
     * @param string title of the message
234
     * @param string content of the message
235
     *
236
     * @return bool
237
     *
238
     * @author isaac flores paz
239
     * @author Julio Montoya <[email protected]> Cleaning code
240
     */
241
    public static function send_invitation_friend(
242
        $user_id,
243
        $friend_id,
244
        $message_title,
245
        $message_content
246
    ) {
247
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
248
        $user_id = (int) $user_id;
249
        $friend_id = (int) $friend_id;
250
251
        //Just in case we replace the and \n and \n\r while saving in the DB
252
        $message_content = str_replace(["\n", "\n\r"], '<br />', $message_content);
253
254
        $clean_message_content = Database::escape_string($message_content);
255
        $now = api_get_utc_datetime();
256
        $sql = 'SELECT COUNT(*) AS count FROM '.$tbl_message.'
257
                WHERE
258
                    user_sender_id='.$user_id.' AND
259
                    user_receiver_id='.$friend_id.' AND
260
                    msg_status IN('.MESSAGE_STATUS_INVITATION_PENDING.', '.MESSAGE_STATUS_INVITATION_ACCEPTED.', '.MESSAGE_STATUS_INVITATION_DENIED.');
261
                ';
262
        $res_exist = Database::query($sql);
263
        $row_exist = Database::fetch_array($res_exist, 'ASSOC');
264
265
        if ($row_exist['count'] == 0) {
266
            $params = [
267
                'user_sender_id' => $user_id,
268
                'user_receiver_id' => $friend_id,
269
                'msg_status' => MESSAGE_STATUS_INVITATION_PENDING,
270
                'send_date' => $now,
271
                'title' => $message_title,
272
                'content' => $message_content,
273
                'group_id' => 0,
274
                'parent_id' => 0,
275
                'update_date' => $now,
276
            ];
277
            $messageId = Database::insert($tbl_message, $params);
278
279
            $senderInfo = api_get_user_info($user_id);
280
            $notification = new Notification();
281
            $notification->saveNotification(
282
                $messageId,
0 ignored issues
show
Bug introduced by
It seems like $messageId can also be of type false; however, parameter $messageId of Notification::saveNotification() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

282
                /** @scrutinizer ignore-type */ $messageId,
Loading history...
283
                Notification::NOTIFICATION_TYPE_INVITATION,
284
                [$friend_id],
285
                $message_title,
286
                $message_content,
287
                $senderInfo
288
            );
289
290
            return true;
291
        } else {
292
            // invitation already exist
293
            $sql = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
294
                    WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7';
295
            $res_if_exist = Database::query($sql);
296
            $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
297
            if ($row_if_exist['count'] == 1) {
298
                $sql = 'UPDATE '.$tbl_message.' SET
299
                        msg_status=5, content = "'.$clean_message_content.'"
300
                        WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7 ';
301
                Database::query($sql);
302
303
                return true;
304
            } else {
305
                return false;
306
            }
307
        }
308
    }
309
310
    /**
311
     * Get number messages of the inbox.
312
     *
313
     * @author isaac flores paz
314
     *
315
     * @param int $userId user receiver id
316
     *
317
     * @return int
318
     */
319
    public static function get_message_number_invitation_by_user_id($userId)
320
    {
321
        $table = Database::get_main_table(TABLE_MESSAGE);
322
        $userId = (int) $userId;
323
        $sql = 'SELECT COUNT(*) as count_message_in_box FROM '.$table.'
324
                WHERE
325
                    user_receiver_id='.$userId.' AND
326
                    msg_status='.MESSAGE_STATUS_INVITATION_PENDING;
327
        $res = Database::query($sql);
328
        $row = Database::fetch_array($res, 'ASSOC');
329
        if ($row) {
330
            return (int) $row['count_message_in_box'];
331
        }
332
333
        return 0;
334
    }
335
336
    /**
337
     * Get number of messages sent to other users.
338
     *
339
     * @param int $userId
340
     *
341
     * @return int
342
     */
343
    public static function getCountMessagesSent($userId)
344
    {
345
        $userId = (int) $userId;
346
        $table = Database::get_main_table(TABLE_MESSAGE);
347
        $sql = 'SELECT COUNT(*) FROM '.$table.'
348
                WHERE
349
                    user_sender_id='.$userId.' AND
350
                    msg_status < 5';
351
        $res = Database::query($sql);
352
        $row = Database::fetch_row($res);
353
354
        return $row[0];
355
    }
356
357
    /**
358
     * Get number of messages received from other users.
359
     *
360
     * @param int $receiver_id
361
     *
362
     * @return int
363
     */
364
    public static function getCountMessagesReceived($receiver_id)
365
    {
366
        $table = Database::get_main_table(TABLE_MESSAGE);
367
        $sql = 'SELECT COUNT(*) FROM '.$table.'
368
                WHERE
369
                    user_receiver_id='.intval($receiver_id).' AND
370
                    msg_status < 4';
371
        $res = Database::query($sql);
372
        $row = Database::fetch_row($res);
373
374
        return $row[0];
375
    }
376
377
    /**
378
     * Get number of messages posted on own wall.
379
     *
380
     * @param int $userId
381
     *
382
     * @return int
383
     */
384
    public static function getCountWallPostedMessages($userId)
385
    {
386
        $userId = (int) $userId;
387
388
        if (empty($userId)) {
389
            return 0;
390
        }
391
392
        $table = Database::get_main_table(TABLE_MESSAGE);
393
        $sql = 'SELECT COUNT(*) 
394
                FROM '.$table.'
395
                WHERE
396
                    user_sender_id='.$userId.' AND
397
                    (msg_status = '.MESSAGE_STATUS_WALL.' OR 
398
                    msg_status = '.MESSAGE_STATUS_WALL_POST.') AND 
399
                    parent_id = 0';
400
        $res = Database::query($sql);
401
        $row = Database::fetch_row($res);
402
403
        return $row[0];
404
    }
405
406
    /**
407
     * Get invitation list received by user.
408
     *
409
     * @author isaac flores paz
410
     *
411
     * @param int $userId
412
     * @param int $limit
413
     *
414
     * @return array
415
     */
416
    public static function get_list_invitation_of_friends_by_user_id($userId, $limit = 0)
417
    {
418
        $userId = (int) $userId;
419
        $limit = (int) $limit;
420
421
        if (empty($userId)) {
422
            return [];
423
        }
424
425
        $table = Database::get_main_table(TABLE_MESSAGE);
426
        $sql = 'SELECT user_sender_id, send_date, title, content
427
                FROM '.$table.'
428
                WHERE
429
                    user_receiver_id = '.$userId.' AND
430
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
431
        if ($limit != null && $limit > 0) {
432
            $sql .= ' LIMIT '.$limit;
433
        }
434
        $res = Database::query($sql);
435
        $list = [];
436
        while ($row = Database::fetch_array($res, 'ASSOC')) {
437
            $list[] = $row;
438
        }
439
440
        return $list;
441
    }
442
443
    /**
444
     * Get invitation list sent by user.
445
     *
446
     * @author Julio Montoya <[email protected]>
447
     *
448
     * @param int $userId
449
     *
450
     * @return array
451
     */
452
    public static function get_list_invitation_sent_by_user_id($userId)
453
    {
454
        $userId = (int) $userId;
455
456
        if (empty($userId)) {
457
            return [];
458
        }
459
460
        $table = Database::get_main_table(TABLE_MESSAGE);
461
        $sql = 'SELECT user_receiver_id, send_date,title,content
462
                FROM '.$table.'
463
                WHERE
464
                    user_sender_id = '.$userId.' AND
465
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
466
        $res = Database::query($sql);
467
        $list = [];
468
        while ($row = Database::fetch_array($res, 'ASSOC')) {
469
            $list[$row['user_receiver_id']] = $row;
470
        }
471
472
        return $list;
473
    }
474
475
    /**
476
     * Get count invitation sent by user.
477
     *
478
     * @author Julio Montoya <[email protected]>
479
     *
480
     * @param int $userId
481
     *
482
     * @return int
483
     */
484
    public static function getCountInvitationSent($userId)
485
    {
486
        $userId = (int) $userId;
487
488
        if (empty($userId)) {
489
            return 0;
490
        }
491
492
        $table = Database::get_main_table(TABLE_MESSAGE);
493
        $sql = 'SELECT count(user_receiver_id) count
494
                FROM '.$table.'
495
                WHERE
496
                    user_sender_id = '.$userId.' AND
497
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
498
        $res = Database::query($sql);
499
        if (Database::num_rows($res)) {
500
            $row = Database::fetch_array($res, 'ASSOC');
501
502
            return (int) $row['count'];
503
        }
504
505
        return 0;
506
    }
507
508
    /**
509
     * Accepts invitation.
510
     *
511
     * @param int $user_send_id
512
     * @param int $user_receiver_id
513
     *
514
     * @return bool
515
     *
516
     * @author isaac flores paz
517
     * @author Julio Montoya <[email protected]> Cleaning code
518
     */
519
    public static function invitation_accepted($user_send_id, $user_receiver_id)
520
    {
521
        if (empty($user_send_id) || empty($user_receiver_id)) {
522
            return false;
523
        }
524
525
        $table = Database::get_main_table(TABLE_MESSAGE);
526
        $sql = "UPDATE $table
527
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
528
                WHERE
529
                    user_sender_id = ".((int) $user_send_id)." AND
530
                    user_receiver_id=".((int) $user_receiver_id)." AND
531
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
532
        Database::query($sql);
533
534
        return true;
535
    }
536
537
    /**
538
     * Denies invitation.
539
     *
540
     * @param int user sender id
541
     * @param int user receiver id
542
     *
543
     * @return bool
544
     *
545
     * @author isaac flores paz
546
     * @author Julio Montoya <[email protected]> Cleaning code
547
     */
548
    public static function invitation_denied($user_send_id, $user_receiver_id)
549
    {
550
        if (empty($user_send_id) || empty($user_receiver_id)) {
551
            return false;
552
        }
553
        $table = Database::get_main_table(TABLE_MESSAGE);
554
        $sql = 'DELETE FROM '.$table.'
555
                WHERE
556
                    user_sender_id =  '.((int) $user_send_id).' AND
557
                    user_receiver_id='.((int) $user_receiver_id).' AND
558
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
559
        Database::query($sql);
560
561
        return true;
562
    }
563
564
    /**
565
     * Allow attaching to group.
566
     *
567
     * @author Isaac Flores Paz
568
     *
569
     * @param int $id_friend_qualify User to qualify
570
     * @param int $type_qualify      Kind of rating
571
     *
572
     * @deprecated 2017-03
573
     */
574
    public static function qualify_friend($id_friend_qualify, $type_qualify)
575
    {
576
        $table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
577
        $user_id = api_get_user_id();
578
        $sql = 'UPDATE '.$table.' SET relation_type='.((int) $type_qualify).'
579
                WHERE user_id = '.$user_id.' AND friend_user_id='.(int) $id_friend_qualify;
580
        Database::query($sql);
581
    }
582
583
    /**
584
     * Get user's feeds.
585
     *
586
     * @param int $user  User ID
587
     * @param int $limit Limit of posts per feed
588
     *
589
     * @return string HTML section with all feeds included
590
     *
591
     * @author  Yannick Warnier
592
     *
593
     * @since   Dokeos 1.8.6.1
594
     */
595
    public static function getUserRssFeed($user, $limit = 5)
596
    {
597
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
598
599
        if (empty($feed)) {
600
            return '';
601
        }
602
        $feeds = explode(';', $feed['rssfeeds']);
603
        if (count($feeds) == 0) {
604
            return '';
605
        }
606
        $res = '';
607
        foreach ($feeds as $url) {
608
            if (empty($url)) {
609
                continue;
610
            }
611
            try {
612
                $channel = Reader::import($url);
613
                $i = 1;
614
                if (!empty($channel)) {
615
                    $iconRss = '';
616
                    if (!empty($feed)) {
617
                        $iconRss = Display::url(
618
                            Display::return_icon('social_rss.png', '', [], 22),
619
                            Security::remove_XSS($feed['rssfeeds']),
620
                            ['target' => '_blank']
621
                        );
622
                    }
623
624
                    $res .= '<h3 class="title-rss">'.$iconRss.' '.$channel->getTitle().'</h3>';
625
                    $res .= '<div class="rss-items">';
626
                    /** @var Rss $item */
627
                    foreach ($channel as $item) {
628
                        if ($limit >= 0 and $i > $limit) {
629
                            break;
630
                        }
631
                        $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
632
                        $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
633
                        $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
634
                        $i++;
635
                    }
636
                    $res .= '</div>';
637
                }
638
            } catch (Exception $e) {
639
                error_log($e->getMessage());
640
            }
641
        }
642
643
        return $res;
644
    }
645
646
    /**
647
     * Sends invitations to friends.
648
     *
649
     * @param int    $userId
650
     * @param string $subject
651
     * @param string $content
652
     *
653
     * @return bool
654
     */
655
    public static function sendInvitationToUser($userId, $subject = '', $content = '')
656
    {
657
        $user_info = api_get_user_info($userId);
658
        $success = get_lang('MessageSentTo');
659
        $success .= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
660
661
        if (isset($subject) && isset($content) && isset($userId)) {
662
            $result = MessageManager::send_message($userId, $subject, $content);
663
664
            if ($result) {
665
                Display::addFlash(
666
                    Display::return_message($success, 'normal', false)
667
                );
668
            } else {
669
                Display::addFlash(
670
                    Display::return_message(get_lang('ErrorSendingMessage'), 'error', false)
671
                );
672
            }
673
674
            return false;
675
        } elseif (isset($userId) && !isset($subject)) {
676
            if (isset($userId) && $userId > 0) {
677
                $count = self::send_invitation_friend(
678
                    api_get_user_id(),
679
                    $userId,
680
                    get_lang('Invitation'),
681
                    $content
682
                );
683
684
                if ($count) {
685
                    Display::addFlash(
686
                        Display::return_message(
687
                            api_htmlentities(get_lang('InvitationHasBeenSent')),
688
                            'normal',
689
                            false
690
                        )
691
                    );
692
                } else {
693
                    Display::addFlash(
694
                        Display::return_message(
695
                            api_htmlentities(get_lang('YouAlreadySentAnInvitation')),
696
                            'warning',
697
                            false
698
                        )
699
                    );
700
                }
701
            }
702
        }
703
    }
704
705
    /**
706
     * Helper functions definition.
707
     */
708
    public static function get_logged_user_course_html($my_course, $count)
709
    {
710
        $result = '';
711
        $count = (int) $count;
712
713
        // Table definitions
714
        $main_user_table = Database::get_main_table(TABLE_MAIN_USER);
715
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
716
        $course_directory = $my_course['course_info']['directory'];
717
        $course_title = $my_course['course_info']['title'];
718
        $course_visibility = $my_course['course_info']['visibility'];
719
720
        $user_in_course_status = CourseManager::getUserInCourseStatus(
721
            api_get_user_id(),
722
            $my_course['course_info']['real_id']
723
        );
724
725
        $course_path = api_get_path(SYS_COURSE_PATH).$course_directory; // course path
726
        if (api_get_setting('course_images_in_courses_list') === 'true') {
727
            if (file_exists($course_path.'/course-pic85x85.png')) {
728
                $image = $my_course['course_info']['course_image'];
729
                $imageCourse = Display::img($image, $course_title, ['class' => 'img-course']);
730
            } else {
731
                $imageCourse = Display::return_icon(
732
                    'session_default_small.png',
733
                    $course_title,
734
                    ['class' => 'img-course']
735
                );
736
            }
737
        } else {
738
            $imageCourse = Display::return_icon(
739
                'course.png',
740
                get_lang('Course'),
741
                ['class' => 'img-default']
742
            );
743
        }
744
745
        //display course entry
746
        if (api_get_setting('course_images_in_courses_list') === 'true') {
747
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:65px;">';
748
        } else {
749
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:44px;">';
750
        }
751
        $result .= $imageCourse;
752
753
        //show a hyperlink to the course, unless the course is closed and user is not course admin
754
        if ($course_visibility != COURSE_VISIBILITY_HIDDEN &&
755
            ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER)
756
        ) {
757
            $result .= '<span class="title">'.$course_title.'<span>';
758
        } else {
759
            $result .= $course_title.' '.get_lang('CourseClosed');
760
        }
761
762
        $result .= '</li>';
763
        $session = '';
764
        if (!empty($my_course['session_name']) && !empty($my_course['id_session'])) {
765
            // Request for the name of the general coach
766
            $sql = 'SELECT lastname, firstname
767
                    FROM '.$tbl_session.' ts
768
                    LEFT JOIN '.$main_user_table.' tu
769
                    ON ts.id_coach = tu.user_id
770
                    WHERE ts.id='.(int) $my_course['id_session'].' LIMIT 1';
771
            $rs = Database::query($sql);
772
            $sessioncoach = Database::store_result($rs);
773
            $sessioncoach = $sessioncoach[0];
774
775
            $session = [];
776
            $session['title'] = $my_course['session_name'];
777
            if ($my_course['access_start_date'] == '0000-00-00') {
778
                $session['dates'] = get_lang('WithoutTimeLimits');
779
                if (api_get_setting('show_session_coach') === 'true') {
780
                    $session['coach'] = get_lang('GeneralCoach').': '.
781
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
782
                }
783
            } else {
784
                $session['dates'] = ' - '.get_lang('From').' '.$my_course['access_start_date'].' '.get_lang('To').' '.$my_course['access_end_date'];
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
            }
790
        }
791
792
        $my_course['id_session'] = isset($my_course['id_session']) ? $my_course['id_session'] : 0;
793
        $output = [
794
            $my_course['user_course_cat'],
795
            $result,
796
            $my_course['id_session'],
797
            $session,
798
        ];
799
800
        return $output;
801
    }
802
803
    /**
804
     * Shows the avatar block in social pages.
805
     *
806
     * @param string $show     highlight link possible values:
807
     *                         group_add,
808
     *                         home,
809
     *                         messages,
810
     *                         messages_inbox,
811
     *                         messages_compose,
812
     *                         messages_outbox,
813
     *                         invitations,
814
     *                         shared_profile,
815
     *                         friends,
816
     *                         groups search
817
     * @param int    $group_id
818
     * @param int    $user_id
819
     */
820
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
821
    {
822
        $user_id = (int) $user_id;
823
        $group_id = (int) $group_id;
824
825
        if (empty($user_id)) {
826
            $user_id = api_get_user_id();
827
        }
828
829
        $show_groups = [
830
            'groups',
831
            'group_messages',
832
            'messages_list',
833
            'group_add',
834
            'mygroups',
835
            'group_edit',
836
            'member_list',
837
            'invite_friends',
838
            'waiting_list',
839
            'browse_groups',
840
        ];
841
842
        $template = new Template(null, false, false, false, false, false);
843
844
        if (in_array($show, $show_groups) && !empty($group_id)) {
845
            // Group image
846
            $userGroup = new UserGroup();
847
            $group_info = $userGroup->get($group_id);
848
849
            $userGroupImage = $userGroup->get_picture_group(
850
                    $group_id,
851
                $group_info['picture'],
852
                    128,
853
                    GROUP_IMAGE_SIZE_BIG
854
            );
855
856
            $template->assign('show_group', true);
857
            $template->assign('group_id', $group_id);
858
            $template->assign('user_group_image', $userGroupImage);
859
            $template->assign(
860
                'user_is_group_admin',
861
                $userGroup->is_group_admin(
862
                    $group_id,
863
                    api_get_user_id()
864
                )
865
            );
866
        } else {
867
            $template->assign('show_group', false);
868
            $template->assign('show_user', true);
869
            $template->assign(
870
                'user_image',
871
                [
872
                    'big' => UserManager::getUserPicture(
873
                        $user_id,
874
                        USER_IMAGE_SIZE_BIG
875
                    ),
876
                    'normal' => UserManager::getUserPicture(
877
                        $user_id,
878
                        USER_IMAGE_SIZE_MEDIUM
879
                    ),
880
                ]
881
            );
882
        }
883
884
        $skillBlock = $template->get_template('social/avatar_block.tpl');
885
886
        return $template->fetch($skillBlock);
887
    }
888
889
    /**
890
     * Shows the right menu of the Social Network tool.
891
     *
892
     * @param string $show                       highlight link possible values:
893
     *                                           group_add,
894
     *                                           home,
895
     *                                           messages,
896
     *                                           messages_inbox,
897
     *                                           messages_compose ,
898
     *                                           messages_outbox,
899
     *                                           invitations,
900
     *                                           shared_profile,
901
     *                                           friends,
902
     *                                           groups search
903
     * @param int    $group_id                   group id
904
     * @param int    $user_id                    user id
905
     * @param bool   $show_full_profile          show profile or not (show or hide the user image/information)
906
     * @param bool   $show_delete_account_button
907
     */
908
    public static function show_social_menu(
909
        $show = '',
910
        $group_id = 0,
911
        $user_id = 0,
912
        $show_full_profile = false,
913
        $show_delete_account_button = false
914
    ) {
915
        $user_id = (int) $user_id;
916
        $group_id = (int) $group_id;
917
918
        if (empty($user_id)) {
919
            $user_id = api_get_user_id();
920
        }
921
922
        $usergroup = new UserGroup();
923
        $show_groups = [
924
            'groups',
925
            'group_messages',
926
            'messages_list',
927
            'group_add',
928
            'mygroups',
929
            'group_edit',
930
            'member_list',
931
            'invite_friends',
932
            'waiting_list',
933
            'browse_groups',
934
        ];
935
936
        // get count unread message and total invitations
937
        $count_unread_message = MessageManager::getNumberOfMessages(true);
938
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
939
940
        $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
941
        $group_pending_invitations = $usergroup->get_groups_by_user(
942
            api_get_user_id(),
943
            GROUP_USER_PERMISSION_PENDING_INVITATION,
944
            false
945
        );
946
        $group_pending_invitations = count($group_pending_invitations);
947
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
948
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
949
950
        $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), null, ICON_SIZE_SMALL);
951
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), null, ICON_SIZE_SMALL);
952
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), null, ICON_SIZE_SMALL);
953
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), null, ICON_SIZE_SMALL);
954
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), null, ICON_SIZE_SMALL);
955
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), null, ICON_SIZE_SMALL);
956
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
957
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), null, ICON_SIZE_SMALL);
958
        $portfolioIcon = Display::return_icon('wiki_task.png', get_lang('Portfolio'));
959
        $personalDataIcon = Display::return_icon('database.png', get_lang('PersonalDataReport'));
960
961
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
962
        $groupUrl = api_get_path(WEB_CODE_PATH).'social/groups.php';
963
        if (!empty($forumCourseId)) {
964
            $courseInfo = api_get_course_info_by_id($forumCourseId);
0 ignored issues
show
Bug introduced by
It seems like $forumCourseId can also be of type boolean; however, parameter $id of api_get_course_info_by_id() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

964
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
965
            if (!empty($courseInfo)) {
966
                $groupUrl = api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code'];
967
            }
968
        }
969
970
        $html = '';
971
        $active = null;
972
        if (!in_array(
973
            $show,
974
            ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
975
        )) {
976
            $links = '<ul class="nav nav-pills nav-stacked">';
977
            $active = $show === 'home' ? 'active' : null;
978
            $links .= '
979
                <li class="home-icon '.$active.'">
980
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
981
                        '.$homeIcon.' '.get_lang('Home').'
982
                    </a>
983
                </li>';
984
            $active = $show == 'messages' ? 'active' : null;
985
            $links .= '
986
                <li class="messages-icon '.$active.'">
987
                    <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
988
                        '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
989
                    </a>
990
                </li>';
991
992
            // Invitations
993
            $active = $show == 'invitations' ? 'active' : null;
994
            $links .= '
995
                <li class="invitations-icon '.$active.'">
996
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
997
                        '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
998
                    </a>
999
                </li>';
1000
1001
            // Shared profile and groups
1002
            $active = $show == 'shared_profile' ? 'active' : null;
1003
            $links .= '
1004
                <li class="shared-profile-icon'.$active.'">
1005
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1006
                        '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1007
                    </a>
1008
                </li>';
1009
            $active = $show == 'friends' ? 'active' : null;
1010
            $links .= '
1011
                <li class="friends-icon '.$active.'">
1012
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1013
                        '.$friendsIcon.' '.get_lang('Friends').'
1014
                    </a>
1015
                </li>';
1016
            $active = $show === 'browse_groups' ? 'active' : null;
1017
            $links .= '
1018
                <li class="browse-groups-icon '.$active.'">
1019
                    <a href="'.$groupUrl.'">
1020
                        '.$groupsIcon.' '.get_lang('SocialGroups').'
1021
                    </a>
1022
                </li>';
1023
1024
            // Search users
1025
            $active = $show == 'search' ? 'active' : null;
1026
            $links .= '
1027
                <li class="search-icon '.$active.'">
1028
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1029
                        '.$searchIcon.' '.get_lang('Search').'
1030
                    </a>
1031
                </li>';
1032
1033
            // My files
1034
            $active = $show == 'myfiles' ? 'active' : null;
1035
1036
            $myFiles = '
1037
                <li class="myfiles-icon '.$active.'">
1038
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1039
                        '.$filesIcon.' '.get_lang('MyFiles').'
1040
                    </a>
1041
                </li>';
1042
1043
            if (api_get_setting('allow_my_files') === 'false') {
1044
                $myFiles = '';
1045
            }
1046
            $links .= $myFiles;
1047
            if (api_get_configuration_value('allow_portfolio_tool')) {
1048
                $links .= '
1049
                    <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1050
                        <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1051
                            '.$portfolioIcon.' '.get_lang('Portfolio').'
1052
                        </a>
1053
                    </li>
1054
                ';
1055
            }
1056
1057
            if (!api_get_configuration_value('disable_gdpr')) {
1058
                $active = $show == 'personal-data' ? 'active' : null;
1059
                $personalData = '
1060
                    <li class="personal-data-icon '.$active.'">
1061
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1062
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1063
                        </a>
1064
                    </li>';
1065
                $links .= $personalData;
1066
                $links .= '</ul>';
1067
            }
1068
1069
            $html .= Display::panelCollapse(
1070
                get_lang('SocialNetwork'),
1071
                $links,
1072
                'social-network-menu',
1073
                null,
1074
                'sn-sidebar',
1075
                'sn-sidebar-collapse'
1076
            );
1077
        }
1078
1079
        if (in_array($show, $show_groups) && !empty($group_id)) {
1080
            $html .= $usergroup->show_group_column_information(
1081
                $group_id,
1082
                api_get_user_id(),
1083
                $show
1084
            );
1085
        }
1086
1087
        if ($show === 'shared_profile') {
1088
            $links = '<ul class="nav nav-pills nav-stacked">';
1089
            // My own profile
1090
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
1091
                $links .= '
1092
                    <li class="home-icon '.$active.'">
1093
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
1094
                            '.$homeIcon.' '.get_lang('Home').'
1095
                        </a>
1096
                    </li>
1097
                    <li class="messages-icon '.$active.'">
1098
                        <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
1099
                            '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
1100
                        </a>
1101
                    </li>';
1102
                $active = $show === 'invitations' ? 'active' : null;
1103
                $links .= '
1104
                    <li class="invitations-icon'.$active.'">
1105
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
1106
                            '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
1107
                        </a>
1108
                    </li>';
1109
1110
                $links .= '
1111
                    <li class="shared-profile-icon active">
1112
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1113
                            '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1114
                        </a>
1115
                    </li>
1116
                    <li class="friends-icon">
1117
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1118
                            '.$friendsIcon.' '.get_lang('Friends').'
1119
                        </a>
1120
                    </li>';
1121
1122
                $links .= '<li class="browse-groups-icon">
1123
                        <a href="'.$groupUrl.'">
1124
                            '.$groupsIcon.' '.get_lang('SocialGroups').'
1125
                        </a>
1126
                        </li>';
1127
1128
                $active = $show == 'search' ? 'active' : null;
1129
                $links .= '
1130
                    <li class="search-icon '.$active.'">
1131
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1132
                            '.$searchIcon.' '.get_lang('Search').'
1133
                        </a>
1134
                    </li>';
1135
                $active = $show == 'myfiles' ? 'active' : null;
1136
1137
                $myFiles = '
1138
                    <li class="myfiles-icon '.$active.'">
1139
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1140
                            '.$filesIcon.' '.get_lang('MyFiles').'
1141
                        </a>
1142
                    </li>';
1143
1144
                if (api_get_setting('allow_my_files') === 'false') {
1145
                    $myFiles = '';
1146
                }
1147
                $links .= $myFiles;
1148
1149
                if (api_get_configuration_value('allow_portfolio_tool')) {
1150
                    $links .= '
1151
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1152
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1153
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1154
                            </a>
1155
                        </li>
1156
                    ';
1157
                }
1158
            }
1159
1160
            // My friend profile.
1161
            if ($user_id != api_get_user_id()) {
1162
                $sendMessageText = get_lang('SendMessage');
1163
                $sendMessageIcon = Display::return_icon(
1164
                    'new-message.png',
1165
                    $sendMessageText
1166
                );
1167
                $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
1168
                        'a' => 'get_user_popup',
1169
                        'user_id' => $user_id,
1170
                    ]);
1171
1172
                $links .= '<li>';
1173
                $links .= Display::url(
1174
                    "$sendMessageIcon $sendMessageText",
1175
                    $sendMessageUrl,
1176
                    [
1177
                        'class' => 'ajax',
1178
                        'title' => $sendMessageText,
1179
                        'data-title' => $sendMessageText,
1180
                    ]
1181
                );
1182
                $links .= '</li>';
1183
1184
                if (api_get_configuration_value('allow_portfolio_tool')) {
1185
                    $links .= '
1186
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1187
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id.'">
1188
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1189
                            </a>
1190
                        </li>
1191
                    ';
1192
                }
1193
            }
1194
1195
            // Check if I already sent an invitation message
1196
            $invitation_sent_list = self::get_list_invitation_sent_by_user_id(api_get_user_id());
1197
1198
            if (isset($invitation_sent_list[$user_id]) && is_array($invitation_sent_list[$user_id]) &&
1199
                count($invitation_sent_list[$user_id]) > 0
1200
            ) {
1201
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
1202
                    Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
1203
                    .'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
1204
            } else {
1205
                if (!$show_full_profile) {
1206
                    $links .= '<li>
1207
                        <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('SendInvitation').'">'.
1208
                        Display::return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').
1209
                        '</a></li>';
1210
                }
1211
            }
1212
1213
            $links .= '</ul>';
1214
            $html .= Display::panelCollapse(
1215
                get_lang('SocialNetwork'),
1216
                $links,
1217
                'social-network-menu',
1218
                null,
1219
                'sn-sidebar',
1220
                'sn-sidebar-collapse'
1221
            );
1222
1223
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
1224
                $personal_course_list = UserManager::get_personal_session_course_list($user_id);
1225
                $course_list_code = [];
1226
                $i = 1;
1227
                if (is_array($personal_course_list)) {
1228
                    foreach ($personal_course_list as $my_course) {
1229
                        if ($i <= 10) {
1230
                            $course_list_code[] = ['code' => $my_course['code']];
1231
                        } else {
1232
                            break;
1233
                        }
1234
                        $i++;
1235
                    }
1236
                    // To avoid repeated courses
1237
                    $course_list_code = array_unique_dimensional($course_list_code);
1238
                }
1239
1240
                // Announcements
1241
                $my_announcement_by_user_id = intval($user_id);
1242
                $announcements = [];
1243
                foreach ($course_list_code as $course) {
1244
                    $course_info = api_get_course_info($course['code']);
1245
                    if (!empty($course_info)) {
1246
                        $content = AnnouncementManager::get_all_annoucement_by_user_course(
1247
                            $course_info['code'],
1248
                            $my_announcement_by_user_id
1249
                        );
1250
1251
                        if (!empty($content)) {
1252
                            $url = Display::url(
1253
                                Display::return_icon(
1254
                                    'announcement.png',
1255
                                    get_lang('Announcements')
1256
                                ).$course_info['name'].' ('.$content['count'].')',
1257
                                api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']
1258
                            );
1259
                            $announcements[] = Display::tag('li', $url);
1260
                        }
1261
                    }
1262
                }
1263
                if (!empty($announcements)) {
1264
                    $html .= '<div class="social_menu_items">';
1265
                    $html .= '<ul>';
1266
                    foreach ($announcements as $announcement) {
1267
                        $html .= $announcement;
1268
                    }
1269
                    $html .= '</ul>';
1270
                    $html .= '</div>';
1271
                }
1272
            }
1273
        }
1274
1275
        if ($show_delete_account_button) {
1276
            $html .= '<div class="panel panel-default"><div class="panel-body">';
1277
            $html .= '<ul class="nav nav-pills nav-stacked"><li>';
1278
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
1279
            $html .= Display::url(
1280
                Display::return_icon(
1281
                    'delete.png',
1282
                    get_lang('Unsubscribe'),
1283
                    [],
1284
                    ICON_SIZE_TINY
1285
                ).get_lang('Unsubscribe'),
1286
                $url
1287
            );
1288
            $html .= '</li></ul>';
1289
            $html .= '</div></div>';
1290
        }
1291
        $html .= '';
1292
1293
        return $html;
1294
    }
1295
1296
    /**
1297
     * Displays a sortable table with the list of online users.
1298
     *
1299
     * @param array $user_list The list of users to be shown
1300
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
1301
     *
1302
     * @return string HTML block or null if and ID was defined
1303
     * @assert (null) === false
1304
     */
1305
    public static function display_user_list($user_list, $wrap = true)
1306
    {
1307
        $html = '';
1308
1309
        if (isset($_GET['id']) || count($user_list) < 1) {
1310
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
1311
        }
1312
1313
        $course_url = '';
1314
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1315
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
1316
        }
1317
1318
        $hide = api_get_configuration_value('hide_complete_name_in_whoisonline');
1319
        foreach ($user_list as $uid) {
1320
            $user_info = api_get_user_info($uid, true);
1321
            $lastname = $user_info['lastname'];
1322
            $firstname = $user_info['firstname'];
1323
            $completeName = $firstname.', '.$lastname;
1324
            $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);
1325
            $status_icon_chat = null;
1326
            if (isset($user_info['user_is_online_in_chat']) && $user_info['user_is_online_in_chat'] == 1) {
1327
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1328
            } else {
1329
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1330
            }
1331
1332
            $userPicture = $user_info['avatar'];
1333
            $officialCode = '';
1334
            if (api_get_setting('show_official_code_whoisonline') == 'true') {
1335
                $officialCode .= '<div class="items-user-official-code"><p style="min-height: 30px;" title="'.get_lang('OfficialCode').'">'.$user_info['official_code'].'</p></div>';
1336
            }
1337
1338
            if ($hide === true) {
1339
                $completeName = '';
1340
                $firstname = '';
1341
                $lastname = '';
1342
            }
1343
1344
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1345
1346
            $url = null;
1347
            // Anonymous users can't have access to the profile
1348
            if (!api_is_anonymous()) {
1349
                if (api_get_setting('allow_social_tool') === 'true') {
1350
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1351
                } else {
1352
                    $url = '?id='.$uid.$course_url;
1353
                }
1354
            } else {
1355
                $url = null;
1356
            }
1357
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1358
1359
            $html .= '<div class="col-xs-6 col-md-2">
1360
                        <div class="items-user">
1361
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1362
                            <div class="items-user-name">
1363
                            '.$name.'
1364
                            </div>
1365
                            '.$officialCode.'
1366
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1367
                        </div>
1368
                      </div>';
1369
        }
1370
1371
        return $html;
1372
    }
1373
1374
    /**
1375
     * Displays the information of an individual user.
1376
     *
1377
     * @param int $user_id
1378
     *
1379
     * @return string
1380
     */
1381
    public static function display_individual_user($user_id)
1382
    {
1383
        global $interbreadcrumb;
1384
        $safe_user_id = (int) $user_id;
1385
        $currentUserId = api_get_user_id();
1386
1387
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1388
        $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
1389
        $result = Database::query($sql);
1390
        $html = null;
1391
        if (Database::num_rows($result) == 1) {
1392
            $user_object = Database::fetch_object($result);
1393
            $userInfo = api_get_user_info($user_id);
1394
            $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
1395
            $status = get_status_from_code($user_object->status);
1396
            $interbreadcrumb[] = ['url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList')];
1397
1398
            $html .= '<div class ="thumbnail">';
1399
            $fullurl = $userInfo['avatar'];
1400
1401
            $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
1402
1403
            if (!empty($status)) {
1404
                $html .= '<div class="caption">'.$status.'</div>';
1405
            }
1406
            $html .= '</div>';
1407
1408
            if (api_get_setting('show_email_addresses') == 'true') {
1409
                $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
1410
            }
1411
1412
            if ($user_object->competences) {
1413
                $html .= Display::page_subheader(get_lang('MyCompetences'));
1414
                $html .= '<p>'.$user_object->competences.'</p>';
1415
            }
1416
            if ($user_object->diplomas) {
1417
                $html .= Display::page_subheader(get_lang('MyDiplomas'));
1418
                $html .= '<p>'.$user_object->diplomas.'</p>';
1419
            }
1420
            if ($user_object->teach) {
1421
                $html .= Display::page_subheader(get_lang('MyTeach'));
1422
                $html .= '<p>'.$user_object->teach.'</p>';
1423
            }
1424
            self::display_productions($user_object->user_id);
1425
            if ($user_object->openarea) {
1426
                $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
1427
                $html .= '<p>'.$user_object->openarea.'</p>';
1428
            }
1429
        } else {
1430
            $html .= '<div class="actions-title">';
1431
            $html .= get_lang('UsersOnLineList');
1432
            $html .= '</div>';
1433
        }
1434
1435
        return $html;
1436
    }
1437
1438
    /**
1439
     * Display productions in who is online.
1440
     *
1441
     * @param int $user_id User id
1442
     */
1443
    public static function display_productions($user_id)
1444
    {
1445
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1446
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1447
        $webdir = UserManager::getUserPathById($user_id, 'web');
1448
1449
        if (!is_dir($sysdir)) {
1450
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1451
        }
1452
1453
        $productions = UserManager::get_user_productions($user_id);
1454
1455
        if (count($productions) > 0) {
1456
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1457
            echo '<dd><ul>';
1458
            foreach ($productions as $file) {
1459
                // Only display direct file links to avoid browsing an empty directory
1460
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1461
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1462
                }
1463
                // Real productions are under a subdirectory by the User's id
1464
                if (is_dir($sysdir.$file)) {
1465
                    $subs = scandir($sysdir.$file);
1466
                    foreach ($subs as $my => $sub) {
1467
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1468
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1469
                        }
1470
                    }
1471
                }
1472
            }
1473
            echo '</ul></dd>';
1474
        }
1475
    }
1476
1477
    /**
1478
     * @param string $content
1479
     * @param string $span_count
1480
     *
1481
     * @return string
1482
     */
1483
    public static function social_wrapper_div($content, $span_count)
1484
    {
1485
        $span_count = (int) $span_count;
1486
        $html = '<div class="span'.$span_count.'">';
1487
        $html .= '<div class="well_border">';
1488
        $html .= $content;
1489
        $html .= '</div></div>';
1490
1491
        return $html;
1492
    }
1493
1494
    /**
1495
     * Dummy function.
1496
     */
1497
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1498
    {
1499
        $content = '';
1500
        switch ($place) {
1501
            case SOCIAL_CENTER_PLUGIN:
1502
                $social_plugins = [1, 2];
1503
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1504
                    $content .= '<div id="social-plugins">';
1505
                    foreach ($social_plugins as $plugin) {
1506
                        $content .= '<div class="social-plugin-item">';
1507
                        $content .= $plugin;
1508
                        $content .= '</div>';
1509
                    }
1510
                    $content .= '</div>';
1511
                }
1512
                break;
1513
            case SOCIAL_LEFT_PLUGIN:
1514
                break;
1515
            case SOCIAL_RIGHT_PLUGIN:
1516
                break;
1517
        }
1518
1519
        return $content;
1520
    }
1521
1522
    /**
1523
     * Sends a message to someone's wall.
1524
     *
1525
     * @param int    $userId         id of author
1526
     * @param int    $friendId       id where we send the message
1527
     * @param string $messageContent of the message
1528
     * @param int    $messageId      id parent
1529
     * @param string $messageStatus  status type of message
1530
     *
1531
     * @return int
1532
     *
1533
     * @author Yannick Warnier
1534
     */
1535
    public static function sendWallMessage(
1536
        $userId,
1537
        $friendId,
1538
        $messageContent,
1539
        $messageId = 0,
1540
        $messageStatus = ''
1541
    ) {
1542
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1543
        $userId = (int) $userId;
1544
        $friendId = (int) $friendId;
1545
        $messageId = (int) $messageId;
1546
1547
        if (empty($userId) || empty($friendId)) {
1548
            return 0;
1549
        }
1550
1551
        // Just in case we replace the and \n and \n\r while saving in the DB
1552
        $messageContent = str_replace(["\n", "\n\r"], '<br />', $messageContent);
1553
        $now = api_get_utc_datetime();
1554
1555
        $attributes = [
1556
            'user_sender_id' => $userId,
1557
            'user_receiver_id' => $friendId,
1558
            'msg_status' => $messageStatus,
1559
            'send_date' => $now,
1560
            'title' => '',
1561
            'content' => $messageContent,
1562
            'parent_id' => $messageId,
1563
            'group_id' => 0,
1564
            'update_date' => $now,
1565
        ];
1566
1567
        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...
1568
    }
1569
1570
    /**
1571
     * Send File attachment (jpg,png).
1572
     *
1573
     * @author Anibal Copitan
1574
     *
1575
     * @param int    $userId      id user
1576
     * @param array  $fileAttach
1577
     * @param int    $messageId   id message (relation with main message)
1578
     * @param string $fileComment description attachment file
1579
     *
1580
     * @return bool|int
1581
     */
1582
    public static function sendWallMessageAttachmentFile(
1583
        $userId,
1584
        $fileAttach,
1585
        $messageId,
1586
        $fileComment = ''
1587
    ) {
1588
        $safeFileName = Database::escape_string($fileAttach['name']);
1589
1590
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1591
        $allowedTypes = api_get_supported_image_extensions();
1592
1593
        $allowedTypes[] = 'mp4';
1594
        $allowedTypes[] = 'webm';
1595
        $allowedTypes[] = 'ogg';
1596
1597
        if (in_array($extension, $allowedTypes)) {
1598
            return MessageManager::saveMessageAttachmentFile($fileAttach, $fileComment, $messageId, $userId);
1599
        }
1600
1601
        return false;
1602
    }
1603
1604
    /**
1605
     * Gets all messages from someone's wall (within specific limits).
1606
     *
1607
     * @param int        $userId     id of wall shown
1608
     * @param int|string $parentId   id message (Post main)
1609
     * @param int|array  $groupId
1610
     * @param int|array  $friendId
1611
     * @param string     $startDate  Date from which we want to show the messages, in UTC time
1612
     * @param int        $start      Limit for the number of parent messages we want to show
1613
     * @param int        $length     Wall message query offset
1614
     * @param bool       $getCount
1615
     * @param array      $threadList
1616
     *
1617
     * @return array|int
1618
     *
1619
     * @author Yannick Warnier
1620
     */
1621
    public static function getWallMessages(
1622
        $userId,
1623
        $parentId = 0,
1624
        $groupId = 0,
1625
        $friendId = 0,
1626
        $startDate = '',
1627
        $start = 0,
1628
        $length = 10,
1629
        $getCount = false,
1630
        $threadList = []
1631
    ) {
1632
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1633
1634
        $parentId = (int) $parentId;
1635
        $userId = (int) $userId;
1636
        $start = (int) $start;
1637
        $length = (int) $length;
1638
        $startDate = Database::escape_string($startDate);
1639
1640
        $select = " SELECT
1641
                    id,
1642
                    user_sender_id,
1643
                    user_receiver_id,
1644
                    send_date,
1645
                    content,
1646
                    parent_id,
1647
                    msg_status,
1648
                    group_id,
1649
                    '' as forum_id,
1650
                    '' as thread_id,
1651
                    '' as c_id
1652
                  ";
1653
1654
        if ($getCount) {
1655
            $select = ' SELECT count(id) count ';
1656
        }
1657
1658
        $sql = "$select                    
1659
                    FROM $tblMessage tm
1660
                WHERE
1661
                    msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
1662
1663
        // My own posts
1664
        $userReceiverCondition = ' (
1665
            user_receiver_id = '.$userId.' AND 
1666
            msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
1667
            parent_id = '.$parentId.'
1668
        )';
1669
1670
        // User condition
1671
        $sql .= $userReceiverCondition;
1672
1673
        // Get my group posts
1674
        $groupCondition = '';
1675
        if (!empty($groupId)) {
1676
            if (is_array($groupId)) {
1677
                $groupId = array_map('intval', $groupId);
1678
                $groupId = implode("','", $groupId);
1679
                $groupCondition = " OR ( group_id IN ('$groupId') ";
1680
            } else {
1681
                $groupId = (int) $groupId;
1682
                $groupCondition = " OR ( group_id = '$groupId' ";
1683
            }
1684
            $groupCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_NEW.', '.MESSAGE_STATUS_UNREAD.')) ';
1685
        }
1686
1687
        $friendCondition = '';
1688
        // Get my friend posts
1689
        if (!empty($friendId)) {
1690
            if (is_array($friendId)) {
1691
                $friendId = array_map('intval', $friendId);
1692
                $friendId = implode("','", $friendId);
1693
                $friendCondition = " OR ( user_receiver_id IN ('$friendId') ";
1694
            } else {
1695
                $friendId = (int) $friendId;
1696
                $friendCondition = " OR ( user_receiver_id = '$friendId' ";
1697
            }
1698
            $friendCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_WALL_POST.') AND parent_id = 0) ';
1699
        }
1700
1701
        if (!empty($groupCondition) || !empty($friendCondition)) {
1702
            $sql .= " $groupCondition $friendCondition ";
1703
        }
1704
1705
        if (!empty($threadList)) {
1706
            if ($getCount) {
1707
                $select = ' SELECT count(iid) count ';
1708
            } else {
1709
                $select = " SELECT 
1710
                                iid,
1711
                                poster_id,
1712
                                '' as user_receiver_id,
1713
                                post_date,
1714
                                post_text,
1715
                                '' as parent_id,
1716
                                ".MESSAGE_STATUS_FORUM.",
1717
                                '' as group_id,
1718
                                forum_id,
1719
                                thread_id,
1720
                                c_id                            
1721
        ";
1722
            }
1723
1724
            $threadList = array_map('intval', $threadList);
1725
            $threadList = implode("','", $threadList);
1726
            $condition = " thread_id IN ('$threadList') ";
1727
            $sql .= "                
1728
                UNION (
1729
                    $select
1730
                    FROM c_forum_post  
1731
                    WHERE $condition                                         
1732
                )
1733
                ";
1734
        }
1735
1736
        if ($getCount) {
1737
            $res = Database::query($sql);
1738
            $row = Database::fetch_array($res);
1739
1740
            return (int) $row['count'];
1741
        }
1742
1743
        $sql .= ' ORDER BY send_date DESC ';
1744
        $sql .= " LIMIT $start, $length ";
1745
1746
        $messages = [];
1747
        $res = Database::query($sql);
1748
        $em = Database::getManager();
1749
        if (Database::num_rows($res) > 0) {
1750
            $repo = $em->getRepository('ChamiloCourseBundle:CForumPost');
1751
            $repoThread = $em->getRepository('ChamiloCourseBundle:CForumThread');
1752
            $groups = [];
1753
            $forums = [];
1754
            $userGroup = new UserGroup();
1755
            $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
1756
            while ($row = Database::fetch_array($res, 'ASSOC')) {
1757
                $row['group_info'] = [];
1758
                if (!empty($row['group_id'])) {
1759
                    if (!in_array($row['group_id'], $groups)) {
1760
                        $group = $userGroup->get($row['group_id']);
1761
                        $group['url'] = $urlGroup.$group['id'];
1762
                        $groups[$row['group_id']] = $group;
1763
                        $row['group_info'] = $group;
1764
                    } else {
1765
                        $row['group_info'] = $groups[$row['group_id']];
1766
                    }
1767
                }
1768
1769
                // forums
1770
                $row['post_title'] = '';
1771
                $row['forum_title'] = '';
1772
                $row['thread_url'] = '';
1773
                if ($row['msg_status'] == MESSAGE_STATUS_FORUM) {
1774
                    /** @var \Chamilo\CourseBundle\Entity\CForumPost $post */
1775
                    $post = $repo->find($row['id']);
1776
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
1777
                    $thread = $repoThread->find($row['thread_id']);
1778
                    if ($post && $thread) {
1779
                        $courseInfo = api_get_course_info_by_id($post->getCId());
1780
                        $row['post_title'] = $post->getForumId();
1781
                        $row['forum_title'] = $thread->getThreadTitle();
1782
                        $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
1783
                            'cidReq' => $courseInfo['code'],
1784
                            'forum' => $post->getForumId(),
1785
                            'thread' => $post->getThreadId(),
0 ignored issues
show
Bug introduced by
The method getThreadId() does not exist on Chamilo\CourseBundle\Entity\CForumPost. Did you maybe mean getThread()? ( Ignorable by Annotation )

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

1785
                            'thread' => $post->/** @scrutinizer ignore-call */ getThreadId(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1786
                            'post_id' => $post->getIid(),
1787
                        ]).'#post_id_'.$post->getIid();
1788
                    }
1789
                }
1790
1791
                $messages[] = $row;
1792
            }
1793
        }
1794
1795
        return $messages;
1796
    }
1797
1798
    /**
1799
     * Gets all messages from someone's wall (within specific limits), formatted.
1800
     *
1801
     * @param int    $userId      USER ID of the person's wall
1802
     * @param array  $messageInfo
1803
     * @param string $start       Start date (from when we want the messages until today)
1804
     * @param int    $limit       Limit to the number of messages we want
1805
     * @param int    $offset      Wall messages offset
1806
     *
1807
     * @return string HTML formatted string to show messages
1808
     */
1809
    public static function getWallPostComments(
1810
        $userId,
1811
        $messageInfo,
1812
        $start = null,
1813
        $limit = 10,
1814
        $offset = 0
1815
    ) {
1816
        $messageId = $messageInfo['id'];
1817
        $messages = MessageManager::getMessagesByParent($messageInfo['id'], 0, $offset, $limit);
1818
        $formattedList = '<div class="sub-mediapost row">';
1819
        $users = [];
1820
1821
        // The messages are ordered by date descendant, for comments we need ascendant
1822
        krsort($messages);
1823
        foreach ($messages as $message) {
1824
            $userIdLoop = $message['user_sender_id'];
1825
            if (!isset($users[$userIdLoop])) {
1826
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1827
            }
1828
            $media = self::processPostComment($message, $users);
1829
            $formattedList .= $media;
1830
        }
1831
1832
        $formattedList .= '</div>';
1833
        $formattedList .= '<div class="mediapost-form">';
1834
        $formattedList .= '<form class="form-horizontal" id="form_comment_'.$messageId.'" name="post_comment" method="POST">
1835
                <div class="col-sm-9">
1836
                <label for="comment" class="hide">'.get_lang('SocialWriteNewComment').'</label>
1837
                <input type="hidden" name = "messageId" value="'.$messageId.'" />
1838
                <textarea rows="3" class="form-control" placeholder="'.get_lang('SocialWriteNewComment').'" name="comment" rows="1" ></textarea>
1839
                </div>
1840
                <div class="col-sm-3">
1841
                <a onclick="submitComment('.$messageId.');" href="javascript:void(0);" name="social_wall_new_msg_submit" class="btn btn-default btn-post">
1842
                    <em class="fa fa-pencil"></em> '.get_lang('Post').'
1843
                </a>
1844
                </div>
1845
                </form>';
1846
        $formattedList .= '</div>';
1847
1848
        return $formattedList;
1849
    }
1850
1851
    /**
1852
     * @param array $message
1853
     * @param array $users
1854
     *
1855
     * @return string
1856
     */
1857
    public static function processPostComment($message, $users = [])
1858
    {
1859
        if (empty($message)) {
1860
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
1861
        }
1862
1863
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
1864
        $currentUserId = api_get_user_id();
1865
        $userIdLoop = $message['user_sender_id'];
1866
        $receiverId = $message['user_receiver_id'];
1867
        $urlImg = api_get_path(WEB_IMG_PATH);
1868
1869
        if (!isset($users[$userIdLoop])) {
1870
            $users[$userIdLoop] = api_get_user_info($userIdLoop);
1871
        }
1872
1873
        $iconStatus = '';
1874
        $userStatus = (int) $users[$userIdLoop]['status'];
1875
        $isAdmin = self::is_admin($users[$userIdLoop]['id']);
1876
        if ($userStatus === 5) {
1877
            if ($users[$userIdLoop]['has_certificates']) {
1878
                $iconStatus = '<img src="'.$urlImg.'icons/svg/identifier_graduated.svg" width="22px" height="22px">';
1879
            } else {
1880
                $iconStatus = '<img src="'.$urlImg.'icons/svg/identifier_student.svg" width="22px" height="22px">';
1881
            }
1882
        } else {
1883
            if ($userStatus === 1) {
1884
                if ($isAdmin) {
1885
                    $iconStatus = '<img src="'.$urlImg.'icons/svg/identifier_admin.svg" width="22px" height="22px">';
1886
                } else {
1887
                    $iconStatus = '<img src="'.$urlImg.'icons/svg/identifier_teacher.svg" width="22px" height="22px">';
1888
                }
1889
            }
1890
        }
1891
1892
        $nameComplete = $users[$userIdLoop]['complete_name'];
1893
        $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$userIdLoop;
1894
1895
        $comment = '<div class="rep-post col-md-12">';
1896
        $comment .= '<div class="col-md-2 col-xs-2 social-post-answers">';
1897
        $comment .= '<div class="user-image pull-right">';
1898
        $comment .= '<a href="'.$url.'">
1899
                        <img src="'.$users[$userIdLoop]['avatar'].'" 
1900
                        alt="'.$users[$userIdLoop]['complete_name'].'" 
1901
                        class="avatar-thumb">
1902
                     </a>';
1903
        $comment .= '</div>';
1904
        $comment .= '</div>';
1905
        $comment .= '<div class="col-md-7 col-xs-7 social-post-answers">';
1906
        $comment .= '<div class="user-data">';
1907
        $comment .= $iconStatus;
1908
        $comment .= '<div class="username"><a href="'.$url.'">'.$nameComplete.'</a> 
1909
                        <span>'.Security::remove_XSS($message['content']).'</span>
1910
                       </div>';
1911
        $comment .= '<div>'.$date.'</div>';
1912
        $comment .= '<br />';
1913
        $comment .= '</div>';
1914
        $comment .= '</div>';
1915
1916
        $comment .= '<div class="col-md-3 col-xs-3 social-post-answers">';
1917
        $comment .= '<div class="pull-right btn-group btn-group-sm">';
1918
1919
        $comment .= MessageManager::getLikesButton(
1920
            $message['id'],
1921
            $currentUserId
1922
        );
1923
1924
        $isOwnWall = $currentUserId == $userIdLoop || $currentUserId == $receiverId;
1925
        if ($isOwnWall) {
1926
            $comment .= Display::url(
1927
                    Display::returnFontAwesomeIcon('trash', '', true),
1928
                'javascript:void(0)',
1929
                [
1930
                    'id' => 'message_'.$message['id'],
1931
                    'title' => get_lang('SocialMessageDelete'),
1932
                    'onclick' => 'deleteComment('.$message['id'].')',
1933
                    'class' => 'btn btn-default',
1934
                ]
1935
            );
1936
        }
1937
        $comment .= '</div>';
1938
        $comment .= '</div>';
1939
        $comment .= '</div>';
1940
1941
        return $comment;
1942
    }
1943
1944
    /**
1945
     * @param array $message
1946
     *
1947
     * @return array
1948
     */
1949
    public static function getAttachmentPreviewList($message)
1950
    {
1951
        $messageId = $message['id'];
1952
1953
        $list = [];
1954
1955
        if (empty($message['group_id'])) {
1956
            $files = MessageManager::getAttachmentList($messageId);
1957
            if ($files) {
1958
                $downloadUrl = api_get_path(WEB_CODE_PATH).'social/download.php?message_id='.$messageId;
1959
                foreach ($files as $row_file) {
1960
                    $url = $downloadUrl.'&attachment_id='.$row_file['id'];
1961
                    $display = Display::fileHtmlGuesser($row_file['filename'], $url);
1962
                    $list[] = $display;
1963
                }
1964
            }
1965
        } else {
1966
            $list = MessageManager::getAttachmentLinkList($messageId);
1967
        }
1968
1969
        return $list;
1970
    }
1971
1972
    /**
1973
     * @param array $message
1974
     *
1975
     * @return string
1976
     */
1977
    public static function getPostAttachment($message)
1978
    {
1979
        $previews = self::getAttachmentPreviewList($message);
1980
1981
        if (empty($previews)) {
1982
            return '';
1983
        }
1984
1985
        return implode('', $previews);
1986
    }
1987
1988
    /**
1989
     * @param array $messages
1990
     *
1991
     * @return array
1992
     */
1993
    public static function formatWallMessages($messages)
1994
    {
1995
        $data = [];
1996
        $users = [];
1997
        foreach ($messages as $key => $message) {
1998
            $userIdLoop = $message['user_sender_id'];
1999
            $userFriendIdLoop = $message['user_receiver_id'];
2000
            if (!isset($users[$userIdLoop])) {
2001
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
2002
            }
2003
2004
            if (!isset($users[$userFriendIdLoop])) {
2005
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
2006
            }
2007
2008
            $html = self::headerMessagePost(
2009
                $users[$userIdLoop],
2010
                $users[$userFriendIdLoop],
2011
                $message
2012
            );
2013
2014
            $data[$key] = $message;
2015
            $data[$key]['html'] = $html;
2016
        }
2017
2018
        return $data;
2019
    }
2020
2021
    /**
2022
     * get html data with OpenGrap passing the URL.
2023
     *
2024
     * @param $link url
2025
     *
2026
     * @return string data html
2027
     */
2028
    public static function readContentWithOpenGraph($link)
2029
    {
2030
        if (strpos($link, "://") === false && substr($link, 0, 1) != "/") {
2031
            $link = "http://".$link;
2032
        }
2033
        $graph = OpenGraph::fetch($link);
2034
        $link = parse_url($link);
2035
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
2036
        if (!$graph) {
2037
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
2038
        }
2039
        $url = $graph->url;
2040
        $image = $graph->image;
2041
        $description = $graph->description;
2042
        $title = $graph->title;
2043
        $html = '<div class="thumbnail social-thumbnail">';
2044
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
2045
                <img class="img-responsive social-image" src="'.$image.'" /></a>';
2046
        $html .= '<div class="social-description">';
2047
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
2048
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
2049
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
2050
        $html .= '</div>';
2051
        $html .= '</div>';
2052
2053
        return $html;
2054
    }
2055
2056
    /**
2057
     * verify if Url Exist - Using Curl.
2058
     *
2059
     * @param $uri url
2060
     *
2061
     * @return bool
2062
     */
2063
    public static function verifyUrl($uri)
2064
    {
2065
        $curl = curl_init($uri);
2066
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_setopt() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

2066
        curl_setopt(/** @scrutinizer ignore-type */ $curl, CURLOPT_FAILONERROR, true);
Loading history...
2067
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
2068
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2069
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
2070
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
2071
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
2072
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
2073
        $response = curl_exec($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_exec() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

2073
        $response = curl_exec(/** @scrutinizer ignore-type */ $curl);
Loading history...
2074
        curl_close($curl);
0 ignored issues
show
Bug introduced by
It seems like $curl can also be of type false; however, parameter $ch of curl_close() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

2074
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
2075
        if (!empty($response)) {
2076
            return true;
2077
        }
2078
2079
        return false;
2080
    }
2081
2082
    /**
2083
     * Soft delete a message and his chidren.
2084
     *
2085
     * @param int $id id message to delete
2086
     *
2087
     * @return bool status query
2088
     */
2089
    public static function deleteMessage($id)
2090
    {
2091
        $id = (int) $id;
2092
        $messageInfo = MessageManager::get_message_by_id($id);
2093
        if (!empty($messageInfo)) {
2094
            // Delete comments too
2095
            $messages = MessageManager::getMessagesByParent($id);
2096
            if (!empty($messages)) {
2097
                foreach ($messages as $message) {
2098
                    self::deleteMessage($message['id']);
2099
                }
2100
            }
2101
2102
            // Soft delete message
2103
            $tblMessage = Database::get_main_table(TABLE_MESSAGE);
2104
            $statusMessage = MESSAGE_STATUS_WALL_DELETE;
2105
            $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
2106
            Database::query($sql);
2107
2108
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_sender_id']);
2109
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_receiver_id']);
2110
2111
            return true;
2112
        }
2113
2114
        return false;
2115
    }
2116
2117
    /**
2118
     * Generate the social block for a user.
2119
     *
2120
     * @param Template $template
2121
     * @param int      $userId            The user id
2122
     * @param string   $groupBlock        Optional. Highlight link possible values:
2123
     *                                    group_add, home, messages, messages_inbox, messages_compose,
2124
     *                                    messages_outbox, invitations, shared_profile, friends, groups, search
2125
     * @param int      $groupId           Optional. Group ID
2126
     * @param bool     $show_full_profile
2127
     *
2128
     * @return string The HTML code with the social block
2129
     */
2130
    public static function setSocialUserBlock(
2131
        Template $template,
2132
        $userId,
2133
        $groupBlock = '',
2134
        $groupId = 0,
2135
        $show_full_profile = true
2136
    ) {
2137
        if (api_get_setting('allow_social_tool') != 'true') {
2138
            return '';
2139
        }
2140
2141
        $currentUserId = api_get_user_id();
2142
        $userId = (int) $userId;
2143
        $userRelationType = 0;
2144
2145
        $socialAvatarBlock = self::show_social_avatar_block(
2146
            $groupBlock,
2147
            $groupId,
2148
            $userId
2149
        );
2150
2151
        $profileEditionLink = null;
2152
        if ($currentUserId === $userId) {
2153
            $profileEditionLink = Display::getProfileEditionLink($userId);
2154
        } else {
2155
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
2156
        }
2157
2158
        $options = api_get_configuration_value('profile_fields_visibility');
2159
        if (isset($options['options'])) {
2160
            $options = $options['options'];
2161
        }
2162
2163
        $vCardUserLink = Display::getVCardUserLink($userId);
2164
        if (isset($options['vcard']) && $options['vcard'] === false) {
2165
            $vCardUserLink = '';
2166
        }
2167
2168
        $userInfo = api_get_user_info($userId, true, false, true, true);
2169
2170
        if (isset($options['firstname']) && $options['firstname'] === false) {
2171
            $userInfo['firstname'] = '';
2172
        }
2173
        if (isset($options['lastname']) && $options['lastname'] === false) {
2174
            $userInfo['lastname'] = '';
2175
        }
2176
2177
        if (isset($options['email']) && $options['email'] === false) {
2178
            $userInfo['email'] = '';
2179
        }
2180
2181
        // Ofaj
2182
        $hasCertificates = Certificate::getCertificateByUser($userId);
2183
        $userInfo['has_certificates'] = 0;
2184
        if (!empty($hasCertificates)) {
2185
            $userInfo['has_certificates'] = 1;
2186
        }
2187
2188
        $userInfo['is_admin'] = Usermanager::is_admin($userId);
2189
2190
        $languageId = api_get_language_id($userInfo['language']);
2191
        $languageInfo = api_get_language_info($languageId);
2192
        if ($languageInfo) {
2193
            $userInfo['language'] = [
2194
                'label' => $languageInfo['original_name'],
2195
                'value' => $languageInfo['english_name'],
2196
                'code' => $languageInfo['isocode'],
2197
            ];
2198
        }
2199
2200
        if (isset($options['language']) && $options['language'] === false) {
2201
            $userInfo['language'] = '';
2202
        }
2203
2204
        if (isset($options['photo']) && $options['photo'] === false) {
2205
            $socialAvatarBlock = '';
2206
        }
2207
2208
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
2209
2210
        $template->assign('user', $userInfo);
2211
        $template->assign('extra_info', $extraFieldBlock);
2212
        $template->assign('social_avatar_block', $socialAvatarBlock);
2213
        $template->assign('profile_edition_link', $profileEditionLink);
2214
        //Added the link to export the vCard to the Template
2215
2216
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
2217
        if ($show_full_profile) {
2218
            $template->assign('vcard_user_link', $vCardUserLink);
2219
        }
2220
2221
        if (api_get_setting('gamification_mode') === '1') {
2222
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
2223
                $userId,
2224
                $userInfo['status']
2225
            );
2226
2227
            $template->assign('gamification_points', $gamificationPoints);
2228
        }
2229
        $chatEnabled = api_is_global_chat_enabled();
2230
2231
        if (isset($options['chat']) && $options['chat'] === false) {
2232
            $chatEnabled = '';
2233
        }
2234
2235
        $template->assign('chat_enabled', $chatEnabled);
2236
        $template->assign('user_relation', $userRelationType);
2237
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
2238
        $template->assign('show_full_profile', $show_full_profile);
2239
2240
        $templateName = $template->get_template('social/user_block.tpl');
2241
2242
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
2243
            $templateName = $template->get_template('social/group_block.tpl');
2244
        }
2245
2246
        $template->assign('social_avatar_block', $template->fetch($templateName));
2247
    }
2248
2249
    /**
2250
     * @param int $user_id
2251
     * @param $link_shared
2252
     * @param $show_full_profile
2253
     *
2254
     * @return string
2255
     */
2256
    public static function listMyFriends($user_id, $link_shared, $show_full_profile)
2257
    {
2258
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
2259
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
2260
        $number_of_images = 30;
2261
        $number_friends = count($friends);
2262
        $friendHtml = '';
2263
        if ($number_friends != 0) {
2264
            if ($number_friends > $number_of_images) {
2265
                if (api_get_user_id() == $user_id) {
2266
                    $friendHtml .= ' <span><a href="friends.php">'.get_lang('SeeAll').'</a></span>';
2267
                } else {
2268
                    $friendHtml .= ' <span>'
2269
                        .'<a href="'.api_get_path(WEB_CODE_PATH).'social/profile_friends_and_groups.inc.php'
2270
                        .'?view=friends&height=390&width=610&user_id='.$user_id.'"'
2271
                        .'class="ajax" data-title="'.get_lang('SeeAll').'" title="'.get_lang('SeeAll').'" >'.get_lang('SeeAll').'</a></span>';
2272
                }
2273
            }
2274
2275
            $friendHtml .= '<ul class="nav nav-list">';
2276
            $j = 1;
2277
            for ($k = 0; $k < $number_friends; $k++) {
2278
                if ($j > $number_of_images) {
2279
                    break;
2280
                }
2281
                if (isset($friends[$k])) {
2282
                    $friend = $friends[$k];
2283
                    $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2284
                    $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2285
2286
                    if ($user_info_friend['user_is_online']) {
2287
                        $statusIcon = Display::span('', ['class' => 'online_user_in_text']);
2288
                    } else {
2289
                        $statusIcon = Display::span('', ['class' => 'offline_user_in_text']);
2290
                    }
2291
2292
                    $friendHtml .= '<li>';
2293
                    $friendHtml .= '<div>';
2294
2295
                    // the height = 92 must be the same in the image_friend_network span style in default.css
2296
                    $friends_profile = UserManager::getUserPicture(
2297
                        $friend['friend_user_id'],
2298
                        USER_IMAGE_SIZE_SMALL
2299
                    );
2300
                    $friendHtml .= '<img src="'.$friends_profile.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'"/>';
2301
                    $link_shared = (empty($link_shared)) ? '' : '&'.$link_shared;
2302
                    $friendHtml .= $statusIcon.'<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'">'.$name_user.'</a>';
2303
                    $friendHtml .= '</div>';
2304
                    $friendHtml .= '</li>';
2305
                }
2306
                $j++;
2307
            }
2308
            $friendHtml .= '</ul>';
2309
        } else {
2310
            $friendHtml .= '<div class="">'.get_lang('NoFriendsInYourContactList').'<br />
2311
                <a class="btn btn-primary" href="'.api_get_path(WEB_PATH).'whoisonline.php">
2312
                <em class="fa fa-search"></em> '.get_lang('TryAndFindSomeFriends').'</a></div>';
2313
        }
2314
2315
        $friendHtml = Display::panel($friendHtml, get_lang('SocialFriend').' ('.$number_friends.')');
2316
2317
        return $friendHtml;
2318
    }
2319
2320
    /**
2321
     * @param int $user_id
2322
     * @param $link_shared
2323
     * @param bool $showLinkToChat
2324
     *
2325
     * @return string
2326
     */
2327
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
2328
    {
2329
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
2330
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
2331
        $numberFriends = count($friends);
2332
        $friendHtml = '';
2333
2334
        if (!empty($numberFriends)) {
2335
            $friendHtml .= '<div class="list-group contact-list">';
2336
            $j = 1;
2337
2338
            usort(
2339
                $friends,
2340
                function ($a, $b) {
2341
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
2342
                }
2343
            );
2344
2345
            foreach ($friends as $friend) {
2346
                if ($j > $numberFriends) {
2347
                    break;
2348
                }
2349
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2350
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2351
2352
                $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
2353
                $status = 0;
2354
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
2355
                    $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
2356
                    $status = 1;
2357
                }
2358
2359
                $friendAvatarMedium = UserManager::getUserPicture(
2360
                    $friend['friend_user_id'],
2361
                    USER_IMAGE_SIZE_MEDIUM
2362
                );
2363
                $friendAvatarSmall = UserManager::getUserPicture(
2364
                    $friend['friend_user_id'],
2365
                    USER_IMAGE_SIZE_SMALL
2366
                );
2367
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
2368
2369
                $relation = self::get_relation_between_contacts(
2370
                    $friend['friend_user_id'],
2371
                    api_get_user_id()
2372
                );
2373
2374
                if ($showLinkToChat) {
2375
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
2376
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2377
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2378
                } else {
2379
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
2380
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
2381
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2382
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2383
                }
2384
2385
                $friendHtml .= '</a>';
2386
2387
                $j++;
2388
            }
2389
            $friendHtml .= '</div>';
2390
        }
2391
2392
        return $friendHtml;
2393
    }
2394
2395
    /**
2396
     * @param string $urlForm
2397
     *
2398
     * @return string
2399
     */
2400
    public static function getWallForm($urlForm)
2401
    {
2402
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
2403
        $form = new FormValidator(
2404
            'social_wall_main',
2405
            'post',
2406
            $urlForm.$userId,
2407
            null,
2408
            ['enctype' => 'multipart/form-data'],
2409
            FormValidator::LAYOUT_HORIZONTAL
2410
        );
2411
2412
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
2413
            'SocialWallWhatAreYouThinkingAbout'
2414
        );
2415
2416
        $form->addTextarea(
2417
            'social_wall_new_msg_main',
2418
            null,
2419
            [
2420
                'placeholder' => $socialWallPlaceholder,
2421
                'cols-size' => [1, 10, 1],
2422
                'aria-label' => $socialWallPlaceholder,
2423
            ]
2424
        );
2425
        $form->addHtml('<div class="form-group">');
2426
        $form->addHtml('<div class="col-sm-4 col-md-offset-1">');
2427
        $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
2428
        $form->addHtml('</div>');
2429
        $form->addHtml('<div class="col-sm-6">');
2430
        $form->addButtonSend(
2431
            get_lang('Post'),
2432
            'wall_post_button',
2433
            false,
2434
            [
2435
                'cols-size' => [1, 10, 1],
2436
                'custom' => true,
2437
            ]
2438
        );
2439
        $form->addHtml('</div>');
2440
        $form->addHtml('</div>');
2441
2442
        $form->addHidden('url_content', '');
2443
        $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
2444
2445
        return $html;
2446
    }
2447
2448
    /**
2449
     * @param int   $userId
2450
     * @param int   $start
2451
     * @param int   $length
2452
     * @param array $threadList
2453
     *
2454
     * @return array
2455
     */
2456
    public static function getMyWallMessages($userId, $start = 0, $length = 10, $threadList = [])
2457
    {
2458
        $userGroup = new UserGroup();
2459
        $groups = $userGroup->get_groups_by_user($userId, [GROUP_USER_PERMISSION_READER, GROUP_USER_PERMISSION_ADMIN]);
2460
        $groupList = [];
2461
        if (!empty($groups)) {
2462
            $groupList = array_column($groups, 'id');
2463
        }
2464
2465
        $friends = self::get_friends($userId, USER_RELATION_TYPE_FRIEND);
2466
        $friendList = [];
2467
        if (!empty($friends)) {
2468
            $friendList = array_column($friends, 'friend_user_id');
2469
        }
2470
2471
        $messages = self::getWallMessages(
2472
            $userId,
2473
            0,
2474
            $groupList,
2475
            $friendList,
2476
            '',
2477
            $start,
2478
            $length,
2479
            false,
2480
            $threadList
2481
        );
2482
2483
        $countPost = self::getCountWallMessagesByUser($userId, $groupList, $friendList, $threadList);
2484
        $messages = self::formatWallMessages($messages);
2485
2486
        $html = '';
2487
        foreach ($messages as $message) {
2488
            $post = $message['html'];
2489
            $comments = '';
2490
            if ($message['msg_status'] == MESSAGE_STATUS_WALL_POST) {
2491
                $comments = self::getWallPostComments($userId, $message);
2492
            }
2493
2494
            $html .= self::wrapPost($message, $post.$comments);
2495
        }
2496
2497
        return [
2498
            'posts' => $html,
2499
            'count' => $countPost,
2500
        ];
2501
    }
2502
2503
    /**
2504
     * @param string $message
2505
     * @param string $content
2506
     *
2507
     * @return string
2508
     */
2509
    public static function wrapPost($message, $content)
2510
    {
2511
        return Display::panel($content, '',
2512
            '',
2513
            'default',
2514
            '',
2515
            'post_'.$message['id']
2516
        );
2517
    }
2518
2519
    /**
2520
     * @param int $userId
2521
     *
2522
     * @return int
2523
     */
2524
    public static function getCountWallMessagesByUser($userId, $groupList = [], $friendList = [], $threadList = [])
2525
    {
2526
        $count = self::getWallMessages(
2527
            $userId,
2528
            0,
2529
            $groupList,
2530
            $friendList,
2531
            '',
2532
            0,
2533
            0,
2534
            true,
2535
            $threadList
2536
        );
2537
2538
        return $count;
2539
    }
2540
2541
    /**
2542
     * @param int $userId
2543
     *
2544
     * @return string
2545
     */
2546
    public static function getWallMessagesByUser($userId)
2547
    {
2548
        $messages = self::getWallMessages($userId);
2549
        $messages = self::formatWallMessages($messages);
2550
2551
        $html = '';
2552
        foreach ($messages as $message) {
2553
            $post = $message['html'];
2554
            $comments = self::getWallPostComments($userId, $message);
2555
            $html .= self::wrapPost($message, $post.$comments);
2556
        }
2557
2558
        return $html;
2559
    }
2560
2561
    /**
2562
     * Get HTML code block for user skills.
2563
     *
2564
     * @param int    $userId      The user ID
2565
     * @param string $orientation
2566
     *
2567
     * @return string
2568
     */
2569
    public static function getSkillBlock($userId, $orientation = 'horizontal')
2570
    {
2571
        if (Skill::isAllowed($userId, false) === false) {
2572
            return '';
2573
        }
2574
2575
        $skill = new Skill();
2576
        $ranking = $skill->getUserSkillRanking($userId);
2577
2578
        $template = new Template(null, false, false, false, false, false);
2579
        $template->assign('ranking', $ranking);
2580
        $template->assign('orientation', $orientation);
2581
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
2582
        $template->assign('user_id', $userId);
2583
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
2584
2585
        $skillBlock = $template->get_template('social/skills_block.tpl');
2586
2587
        return $template->fetch($skillBlock);
2588
    }
2589
2590
    /**
2591
     * @param int $user_id
2592
     *
2593
     * @return string|array
2594
     */
2595
    public static function getExtraFieldBlock($user_id, $isArray = false)
2596
    {
2597
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
2598
        $fieldVisibilityKeys = [];
2599
        if (isset($fieldVisibility['options'])) {
2600
            $fieldVisibility = $fieldVisibility['options'];
2601
            $fieldVisibilityKeys = array_keys($fieldVisibility);
2602
        }
2603
2604
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
2605
        $extra_user_data = UserManager::get_extra_user_data($user_id);
2606
2607
        $extra_information = '';
2608
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
2609
            $extra_information_value = '';
2610
            $extraField = new ExtraField('user');
2611
            $listType = [];
2612
            $extraFieldItem = [];
2613
            foreach ($extra_user_data as $key => $data) {
2614
                if (empty($data)) {
2615
                    continue;
2616
                }
2617
                if (in_array($key, $fieldVisibilityKeys) && $fieldVisibility[$key] === false) {
2618
                    continue;
2619
                }
2620
2621
                // Avoiding parameters
2622
                if (in_array(
2623
                    $key,
2624
                    [
2625
                        'mail_notify_invitation',
2626
                        'mail_notify_message',
2627
                        'mail_notify_group_message',
2628
                    ]
2629
                )) {
2630
                    continue;
2631
                }
2632
                // get display text, visibility and type from user_field table
2633
                $field_variable = str_replace('extra_', '', $key);
2634
2635
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2636
                    $field_variable
2637
                );
2638
2639
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
2640
                    continue;
2641
                }
2642
2643
                // if is not visible skip
2644
                if ($extraFieldInfo['visible_to_self'] != 1) {
2645
                    continue;
2646
                }
2647
2648
                // if is not visible to others skip also
2649
                if ($extraFieldInfo['visible_to_others'] != 1) {
2650
                    continue;
2651
                }
2652
2653
                if (is_array($data)) {
2654
                    switch ($extraFieldInfo['field_type']) {
2655
                        case ExtraField::FIELD_TYPE_RADIO:
2656
                            $objEfOption = new ExtraFieldOption('user');
2657
                            $value = $data['extra_'.$extraFieldInfo['variable']];
2658
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
2659
                                $extraFieldInfo['id'],
2660
                                $value
2661
                            );
2662
2663
                            if ($optionInfo && isset($optionInfo[0])) {
2664
                                $optionInfo = $optionInfo[0];
2665
                                $extraFieldItem = [
2666
                                    'variable' => $extraFieldInfo['variable'],
2667
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2668
                                    'value' => $optionInfo['display_text'],
2669
                                ];
2670
                            } else {
2671
                                $extraFieldItem = [
2672
                                    'variable' => $extraFieldInfo['variable'],
2673
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2674
                                    'value' => implode(',', $data),
2675
                                ];
2676
                            }
2677
                            break;
2678
                        default:
2679
                            $extra_information_value .=
2680
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
2681
                                .' '.implode(',', $data).'</li>';
2682
                            $extraFieldItem = [
2683
                                'variable' => $extraFieldInfo['variable'],
2684
                                'label' => ucfirst($extraFieldInfo['display_text']),
2685
                                'value' => implode(',', $data),
2686
                            ];
2687
                            break;
2688
                    }
2689
                } else {
2690
                    switch ($extraFieldInfo['field_type']) {
2691
                        case ExtraField::FIELD_TYPE_RADIO:
2692
                            $objEfOption = new ExtraFieldOption('user');
2693
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
2694
                            break;
2695
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
2696
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
2697
                            $data = explode('::', $data);
2698
                            $data = $data[0];
2699
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2700
                            $extraFieldItem = [
2701
                                'variable' => $extraFieldInfo['variable'],
2702
                                'label' => ucfirst($extraFieldInfo['display_text']),
2703
                                'value' => $data,
2704
                            ];
2705
                            break;
2706
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
2707
                            $id_options = explode('::', $data);
2708
                            $value_options = [];
2709
                            // get option display text from user_field_options table
2710
                            foreach ($id_options as $id_option) {
2711
                                $sql = "SELECT display_text 
2712
                                    FROM $t_ufo 
2713
                                    WHERE id = '$id_option'";
2714
                                $res_options = Database::query($sql);
2715
                                $row_options = Database::fetch_row($res_options);
2716
                                $value_options[] = $row_options[0];
2717
                            }
2718
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2719
                                .' '.implode(' ', $value_options).'</li>';
2720
                            $extraFieldItem = [
2721
                                'variable' => $extraFieldInfo['variable'],
2722
                                'label' => ucfirst($extraFieldInfo['display_text']),
2723
                                'value' => $value_options,
2724
                            ];
2725
                            break;
2726
                        case ExtraField::FIELD_TYPE_TAG:
2727
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
2728
2729
                            $tag_tmp = '';
2730
                            foreach ($user_tags as $tags) {
2731
                                $tag_tmp .= '<a class="label label_tag"'
2732
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
2733
                                    .$tags['tag']
2734
                                    .'</a>';
2735
                            }
2736
                            if (is_array($user_tags) && count($user_tags) > 0) {
2737
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2738
                                    .' '.$tag_tmp.'</li>';
2739
                            }
2740
                            $extraFieldItem = [
2741
                                'variable' => $extraFieldInfo['variable'],
2742
                                'label' => ucfirst($extraFieldInfo['display_text']),
2743
                                'value' => $tag_tmp,
2744
                            ];
2745
                            break;
2746
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
2747
                            $icon_path = UserManager::get_favicon_from_url($data);
2748
                            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...
2749
                                break;
2750
                            }
2751
                            $bottom = '0.2';
2752
                            //quick hack for hi5
2753
                            $domain = parse_url($icon_path, PHP_URL_HOST);
2754
                            if ($domain == 'www.hi5.com' || $domain == 'hi5.com') {
2755
                                $bottom = '-0.8';
2756
                            }
2757
                            $data = '<a href="'.$data.'">'
2758
                                .'<img src="'.$icon_path.'" alt="icon"'
2759
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
2760
                                .$extraFieldInfo['display_text']
2761
                                .'</a>';
2762
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
2763
                            $extraFieldItem = [
2764
                                'variable' => $extraFieldInfo['variable'],
2765
                                'label' => ucfirst($extraFieldInfo['display_text']),
2766
                                'value' => $data,
2767
                            ];
2768
                            break;
2769
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
2770
                            $parsedData = explode('::', $data);
2771
2772
                            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...
2773
                                break;
2774
                            }
2775
2776
                            $objEfOption = new ExtraFieldOption('user');
2777
                            $optionInfo = $objEfOption->get($parsedData[0]);
2778
2779
                            $extra_information_value .= '<li class="list-group-item">'
2780
                                .$optionInfo['display_text'].': '
2781
                                .$parsedData[1].'</li>';
2782
                            $extraFieldItem = [
2783
                                'variable' => $extraFieldInfo['variable'],
2784
                                'label' => ucfirst($extraFieldInfo['display_text']),
2785
                                'value' => $parsedData[1],
2786
                            ];
2787
                            break;
2788
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
2789
                            $optionIds = explode(';', $data);
2790
                            $optionValues = [];
2791
2792
                            foreach ($optionIds as $optionId) {
2793
                                $objEfOption = new ExtraFieldOption('user');
2794
                                $optionInfo = $objEfOption->get($optionId);
2795
2796
                                $optionValues[] = $optionInfo['display_text'];
2797
                            }
2798
                            $extra_information_value .= '<li class="list-group-item">'
2799
                                .ucfirst($extraFieldInfo['display_text']).': '
2800
                                .implode(' ', $optionValues).'</li>';
2801
                            $extraFieldItem = [
2802
                                'variable' => $extraFieldInfo['variable'],
2803
                                'label' => ucfirst($extraFieldInfo['display_text']),
2804
                                'value' => implode(' ', $optionValues),
2805
                            ];
2806
                            break;
2807
                        default:
2808
                            // Ofaj
2809
                            // Converts "Date of birth" into "age"
2810
                            if ($key === 'terms_datedenaissance') {
2811
                                $dataArray = date_to_str_ago($data, 'UTC', true);
2812
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
2813
                                if (!empty($dataToString)) {
2814
                                    $data = $dataToString;
2815
                                    $extraFieldInfo['display_text'] = get_lang('Age');
2816
                                }
2817
                            }
2818
2819
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2820
                            $extraFieldItem = [
2821
                                'variable' => $extraFieldInfo['variable'],
2822
                                'label' => ucfirst($extraFieldInfo['display_text']),
2823
                                'value' => $data,
2824
                            ];
2825
                            break;
2826
                    }
2827
                }
2828
2829
                $listType[] = $extraFieldItem;
2830
            }
2831
2832
            if ($isArray) {
2833
                return $listType;
2834
            } else {
2835
                // if there are information to show
2836
                if (!empty($extra_information_value)) {
2837
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
2838
                    $extra_information .= Display::panelCollapse(
2839
                        get_lang('ExtraInformation'),
2840
                        $extra_information_value,
2841
                        'sn-extra-information',
2842
                        null,
2843
                        'sn-extra-accordion',
2844
                        'sn-extra-collapse'
2845
                    );
2846
                }
2847
            }
2848
        }
2849
2850
        return $extra_information;
2851
    }
2852
2853
    /**
2854
     * @param string $url
2855
     */
2856
    public static function handlePosts($url)
2857
    {
2858
        $friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
2859
        $url = Security::remove_XSS($url);
2860
2861
        // Main post
2862
        if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
2863
            $messageContent = $_POST['social_wall_new_msg_main'];
2864
            if (!empty($_POST['url_content'])) {
2865
                $messageContent = $_POST['social_wall_new_msg_main'].'<br /><br />'.$_POST['url_content'];
2866
            }
2867
2868
            $messageId = self::sendWallMessage(
2869
                api_get_user_id(),
2870
                $friendId,
2871
                $messageContent,
2872
                0,
2873
                MESSAGE_STATUS_WALL_POST
2874
            );
2875
2876
            if ($messageId && !empty($_FILES['picture']['tmp_name'])) {
2877
                self::sendWallMessageAttachmentFile(
2878
                    api_get_user_id(),
2879
                    $_FILES['picture'],
2880
                    $messageId
2881
                );
2882
            }
2883
2884
            Display::addFlash(Display::return_message(get_lang('MessageSent')));
2885
            header('Location: '.$url);
2886
            exit;
2887
        }
2888
    }
2889
2890
    /**
2891
     * @param int   $countPost
2892
     * @param array $htmlHeadXtra
2893
     */
2894
    public static function getScrollJs($countPost, &$htmlHeadXtra)
2895
    {
2896
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
2897
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
2898
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
2899
        $locale = api_get_language_isocode();
2900
2901
        // Add Jquery scroll pagination plugin
2902
        //$htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
2903
        // Add Jquery Time ago plugin
2904
        //$htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
2905
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
2906
        if (file_exists($timeAgoLocaleDir)) {
2907
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
2908
        }
2909
2910
        if ($countPost > self::DEFAULT_WALL_POSTS) {
2911
            $htmlHeadXtra[] = '<script>
2912
            $(function() {
2913
                var container = $("#wallMessages");
2914
                container.jscroll({
2915
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
2916
                    nextSelector: "a.nextPage:last",
2917
                    contentSelector: "",
2918
                    callback: timeAgo                    
2919
                });
2920
            });
2921
            </script>';
2922
        }
2923
2924
        $htmlHeadXtra[] = '<script>
2925
            function deleteMessage(id) 
2926
            {                      
2927
                $.ajax({
2928
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2929
                    success: function (result) {
2930
                        if (result) {
2931
                            $("#message_" + id).parent().parent().parent().parent().html(result);
2932
                        }
2933
                    }
2934
                });                        
2935
            }
2936
            
2937
            function deleteComment(id) 
2938
            {                      
2939
                $.ajax({
2940
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2941
                    success: function (result) {
2942
                        if (result) {
2943
                            $("#message_" + id).parent().parent().parent().html(result);
2944
                        }
2945
                    }
2946
                });                     
2947
            }           
2948
            
2949
            function submitComment(messageId) 
2950
            {
2951
                var data = $("#form_comment_"+messageId).serializeArray();                                
2952
                $.ajax({
2953
                    type : "POST",
2954
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
2955
                    data: data,
2956
                    success: function (result) {                        
2957
                        if (result) {
2958
                            $("#post_" + messageId + " textarea").val("");
2959
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
2960
                            $("#post_" + messageId + " .sub-mediapost").append(
2961
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved')).'</div>\')
2962
                            ); 
2963
                                                        
2964
                            $("#result_" + messageId + "").fadeIn("fast", function() {
2965
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
2966
                                    $(this).remove();
2967
                                }); 
2968
                            });
2969
                        }
2970
                    }
2971
                });  
2972
            } 
2973
            
2974
            $(function() {
2975
                timeAgo();
2976
                
2977
                /*$(".delete_message").on("click", function() {
2978
                    var id = $(this).attr("id");
2979
                    id = id.split("_")[1];          
2980
                    $.ajax({
2981
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2982
                        success: function (result) {
2983
                            if (result) {
2984
                                $("#message_" + id).parent().parent().parent().parent().html(result);
2985
                            }
2986
                        }
2987
                    });        
2988
                });                  
2989
                
2990
                
2991
                $(".delete_comment").on("click", function() {
2992
                    var id = $(this).attr("id");
2993
                    id = id.split("_")[1];                    
2994
                    $.ajax({
2995
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2996
                        success: function (result) {
2997
                            if (result) {
2998
                                $("#message_" + id).parent().parent().parent().html(result);
2999
                            }
3000
                        }
3001
                    });
3002
                });          
3003
                */
3004
            });
3005
            
3006
            function timeAgo() {
3007
                $(".timeago").timeago();
3008
            }
3009
            </script>';
3010
    }
3011
3012
    /**
3013
     * @param int $userId
3014
     * @param int $countPost
3015
     *
3016
     * @return string
3017
     */
3018
    public static function getAutoExtendLink($userId, $countPost)
3019
    {
3020
        $userId = (int) $userId;
3021
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
3022
        $socialAutoExtendLink = '';
3023
        if ($countPost > self::DEFAULT_WALL_POSTS) {
3024
            $socialAutoExtendLink = Display::url(
3025
                get_lang('SeeMore'),
3026
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
3027
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
3028
                [
3029
                    'class' => 'nextPage next',
3030
                ]
3031
            );
3032
        }
3033
3034
        return $socialAutoExtendLink;
3035
    }
3036
3037
    /**
3038
     * @param int $userId
3039
     *
3040
     * @return array
3041
     */
3042
    public static function getThreadList($userId)
3043
    {
3044
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3045
3046
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
3047
3048
        $threads = [];
3049
        if (!empty($forumCourseId)) {
3050
            $courseInfo = api_get_course_info_by_id($forumCourseId);
0 ignored issues
show
Bug introduced by
It seems like $forumCourseId can also be of type boolean; however, parameter $id of api_get_course_info_by_id() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

3050
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
3051
            getNotificationsPerUser($userId, true, $forumCourseId);
3052
            $notification = Session::read('forum_notification');
3053
            Session::erase('forum_notification');
3054
3055
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
3056
                'cidReq' => $courseInfo['code'],
3057
            ]).'&';
3058
            if (isset($notification['thread']) && !empty($notification['thread'])) {
3059
                $threadList = array_filter(array_unique($notification['thread']));
3060
                $em = Database::getManager();
3061
                $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
3062
                foreach ($threadList as $threadId) {
3063
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
3064
                    $thread = $repo->find($threadId);
3065
                    if ($thread) {
3066
                        $threadUrl = $threadUrlBase.http_build_query([
3067
                            'forum' => $thread->getForumId(),
0 ignored issues
show
Bug introduced by
The method getForumId() does not exist on Chamilo\CourseBundle\Entity\CForumThread. Did you maybe mean getForum()? ( Ignorable by Annotation )

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

3067
                            'forum' => $thread->/** @scrutinizer ignore-call */ getForumId(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3068
                            'thread' => $thread->getIid(),
3069
                        ]);
3070
                        $threads[] = [
3071
                            'id' => $threadId,
3072
                            'url' => Display::url(
3073
                                $thread->getThreadTitle(),
3074
                                $threadUrl
3075
                            ),
3076
                            'name' => Display::url(
3077
                                $thread->getThreadTitle(),
3078
                                $threadUrl
3079
                            ),
3080
                            'description' => '',
3081
                        ];
3082
                    }
3083
                }
3084
            }
3085
        }
3086
3087
        return $threads;
3088
    }
3089
3090
    /**
3091
     * @param int $userId
3092
     *
3093
     * @return string
3094
     */
3095
    public static function getGroupBlock($userId)
3096
    {
3097
        $threadList = self::getThreadList($userId);
3098
        $userGroup = new UserGroup();
3099
3100
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3101
        $courseInfo = null;
3102
        if (!empty($forumCourseId)) {
3103
            $courseInfo = api_get_course_info_by_id($forumCourseId);
0 ignored issues
show
Bug introduced by
It seems like $forumCourseId can also be of type boolean; however, parameter $id of api_get_course_info_by_id() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

3103
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
3104
        }
3105
3106
        $social_group_block = '';
3107
        if (!empty($courseInfo)) {
3108
            if (!empty($threadList)) {
3109
                $social_group_block .= '<div class="list-group">';
3110
                foreach ($threadList as $group) {
3111
                    $social_group_block .= ' <li class="list-group-item">';
3112
                    $social_group_block .= $group['name'];
3113
                    $social_group_block .= '</li>';
3114
                }
3115
                $social_group_block .= '</div>';
3116
            }
3117
3118
            $social_group_block .= Display::url(
3119
                get_lang('SeeAllCommunities'),
3120
                api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code']
3121
            );
3122
3123
            if (!empty($social_group_block)) {
3124
                $social_group_block = Display::panelCollapse(
3125
                    get_lang('MyCommunities'),
3126
                    $social_group_block,
3127
                    'sm-groups',
3128
                    null,
3129
                    'grups-acordion',
3130
                    'groups-collapse'
3131
                );
3132
            }
3133
        } else {
3134
            // Load my groups
3135
            $results = $userGroup->get_groups_by_user($userId,
3136
                [
3137
                    GROUP_USER_PERMISSION_ADMIN,
3138
                    GROUP_USER_PERMISSION_READER,
3139
                    GROUP_USER_PERMISSION_MODERATOR,
3140
                    GROUP_USER_PERMISSION_HRM,
3141
                ]
3142
            );
3143
3144
            $myGroups = [];
3145
            if (!empty($results)) {
3146
                foreach ($results as $result) {
3147
                    $id = $result['id'];
3148
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
3149
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
3150
3151
                    $group_url = "group_view.php?id=$id";
3152
3153
                    $link = Display::url(
3154
                        api_ucwords(cut($result['name'], 40, true)),
3155
                        $group_url
3156
                    );
3157
3158
                    $result['name'] = $link;
3159
3160
                    $picture = $userGroup->get_picture_group(
3161
                        $id,
3162
                        $result['picture'],
3163
                        null,
3164
                        GROUP_IMAGE_SIZE_BIG
3165
                    );
3166
3167
                    $result['picture'] = '<img class="img-responsive" src="'.$picture['file'].'" />';
3168
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
3169
                        get_lang('SeeMore').'</a></div>';
3170
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
3171
                    $myGroups[] = [
3172
                        'url' => Display::url(
3173
                            $result['picture'],
3174
                            $group_url
3175
                        ),
3176
                        'name' => $result['name'],
3177
                        'description' => $group_info.$group_actions,
3178
                    ];
3179
                }
3180
3181
                $social_group_block .= '<div class="list-group">';
3182
                foreach ($myGroups as $group) {
3183
                    $social_group_block .= ' <li class="list-group-item">';
3184
                    $social_group_block .= $group['name'];
3185
                    $social_group_block .= '</li>';
3186
                }
3187
                $social_group_block .= '</div>';
3188
3189
                $form = new FormValidator(
3190
                    'find_groups_form',
3191
                    'get',
3192
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
3193
                    null,
3194
                    null,
3195
                    FormValidator::LAYOUT_BOX_NO_LABEL
3196
                );
3197
                $form->addHidden('search_type', 2);
3198
3199
                $form->addText(
3200
                    'q',
3201
                    get_lang('Search'),
3202
                    false,
3203
                    [
3204
                        'aria-label' => get_lang('Search'),
3205
                        'custom' => true,
3206
                        'placeholder' => get_lang('Search'),
3207
                    ]
3208
                );
3209
3210
                $social_group_block .= $form->returnForm();
3211
3212
                if (!empty($social_group_block)) {
3213
                    $social_group_block = Display::panelCollapse(
3214
                        get_lang('MyGroups'),
3215
                        $social_group_block,
3216
                        'sm-groups',
3217
                        null,
3218
                        'grups-acordion',
3219
                        'groups-collapse'
3220
                    );
3221
                }
3222
            }
3223
        }
3224
3225
        return $social_group_block;
3226
    }
3227
3228
    /**
3229
     * Returns the formatted header message post.
3230
     *
3231
     * @param int   $authorInfo
3232
     * @param int   $receiverInfo
3233
     * @param array $message      Message data
3234
     *
3235
     * @return string $html       The formatted header message post
3236
     */
3237
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
3238
    {
3239
        $currentUserId = api_get_user_id();
3240
        $iconStatus = null;
3241
        $authorId = (int) $authorInfo['user_id'];
3242
        $receiverId = (int) $receiverInfo['user_id'];
3243
        $userStatus = (int) $authorInfo['status'];
3244
        $urlImg = api_get_path(WEB_IMG_PATH);
3245
        $isAdmin = self::is_admin($authorId);
3246
3247
        if ($userStatus === 5) {
3248
            if ($authorInfo['has_certificates']) {
3249
                $iconStatus = Display::return_icon('identifier_graduated.png', get_lang('User status'), ['class' => 'float-left'], ICON_SIZE_SMALL);
3250
            } else {
3251
                $iconStatus = Display::return_icon('identifier_student.png', get_lang('User status'), ['class' => 'float-left'], ICON_SIZE_SMALL);
3252
            }
3253
        } else {
3254
            if ($userStatus === 1) {
3255
                if ($isAdmin) {
3256
                    $iconStatus = Display::return_icon('identifier_admin.png', get_lang('User status'), ['class' => 'float-left'], ICON_SIZE_SMALL);
3257
                } else {
3258
                    $iconStatus = Display::return_icon('identifier_teacher.png', get_lang('User status'), ['class' => 'float-left'], ICON_SIZE_SMALL);
3259
                }
3260
            }
3261
        }
3262
3263
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
3264
        $avatarAuthor = $authorInfo['avatar'];
3265
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
3266
        $nameCompleteAuthor = $authorInfo['complete_name'];
3267
3268
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
3269
        $nameCompleteReceiver = $receiverInfo['complete_name'];
3270
3271
        $htmlReceiver = '';
3272
        if ($authorId !== $receiverId) {
3273
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
3274
        }
3275
3276
        if (!empty($message['group_info'])) {
3277
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
3278
        }
3279
        $canEdit = ($currentUserId == $authorInfo['user_id'] || $currentUserId == $receiverInfo['user_id']) && empty($message['group_info']);
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: $canEdit = ($currentUser...message['group_info'])), Probably Intended Meaning: $canEdit = $currentUserI...message['group_info']))
Loading history...
3280
3281
        if (!empty($message['thread_id'])) {
3282
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
3283
            $canEdit = false;
3284
        }
3285
3286
        $postAttachment = self::getPostAttachment($message);
3287
3288
        $html = '';
3289
        $html .= '<div class="top-mediapost" >';
3290
        $html .= '<div class="pull-right btn-group btn-group-sm">';
3291
3292
        $html .= MessageManager::getLikesButton(
3293
            $message['id'],
3294
            $currentUserId,
3295
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
3296
        );
3297
3298
        if ($canEdit) {
3299
            $htmlDelete = Display::url(
3300
                Display::returnFontAwesomeIcon('trash', '', true),
3301
                'javascript:void(0)',
3302
                [
3303
                    'id' => 'message_'.$message['id'],
3304
                    'title' => get_lang('SocialMessageDelete'),
3305
                    'onclick' => 'deleteMessage('.$message['id'].')',
3306
                    'class' => 'btn btn-default',
3307
                ]
3308
            );
3309
3310
            $html .= $htmlDelete;
3311
        }
3312
        $html .= '</div>';
3313
3314
        $html .= '<div class="user-image" >';
3315
        $html .= '<a href="'.$urlAuthor.'">
3316
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
3317
        $html .= '</div>';
3318
        $html .= '<div class="user-data">';
3319
        $html .= $iconStatus;
3320
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
3321
        $html .= '<div class="post-date">'.$date.'</div>';
3322
        $html .= '</div>';
3323
        $html .= '<div class="msg-content">';
3324
        if (!empty($postAttachment)) {
3325
            $html .= '<div class="post-attachment thumbnail">';
3326
            $html .= $postAttachment;
3327
            $html .= '</div>';
3328
        }
3329
        $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
3330
        $html .= '</div>';
3331
        $html .= '</div>'; // end mediaPost
3332
3333
        // Popularity post functionality
3334
        $html .= '<div class="popularity-mediapost"></div>';
3335
3336
        return $html;
3337
    }
3338
}
3339