Passed
Push — master ( 15378b...a2dd4f )
by Julito
09:24
created

SocialManager::social_wrapper_div()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
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
0 ignored issues
show
Bug introduced by
It seems like $senderInfo can also be of type false and mixed; however, parameter $senderInfo of Notification::saveNotification() does only seem to accept array, 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

287
                /** @scrutinizer ignore-type */ $senderInfo
Loading history...
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
     * Get user's feeds.
566
     *
567
     * @param int $user  User ID
568
     * @param int $limit Limit of posts per feed
569
     *
570
     * @return string HTML section with all feeds included
571
     *
572
     * @author  Yannick Warnier
573
     *
574
     * @since   Dokeos 1.8.6.1
575
     */
576
    public static function getUserRssFeed($user, $limit = 5)
577
    {
578
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
579
580
        if (empty($feed)) {
581
            return '';
582
        }
583
        $feeds = explode(';', $feed['rssfeeds']);
584
        if (count($feeds) == 0) {
585
            return '';
586
        }
587
        $res = '';
588
        foreach ($feeds as $url) {
589
            if (empty($url)) {
590
                continue;
591
            }
592
            try {
593
                $channel = Reader::import($url);
594
                $i = 1;
595
                if (!empty($channel)) {
596
                    $iconRss = '';
597
                    if (!empty($feed)) {
598
                        $iconRss = Display::url(
599
                            Display::return_icon('social_rss.png', '', [], 22),
600
                            Security::remove_XSS($feed['rssfeeds']),
601
                            ['target' => '_blank']
602
                        );
603
                    }
604
605
                    $res .= '<h3 class="title-rss">'.$iconRss.' '.$channel->getTitle().'</h3>';
606
                    $res .= '<div class="rss-items">';
607
                    /** @var Rss $item */
608
                    foreach ($channel as $item) {
609
                        if ($limit >= 0 and $i > $limit) {
610
                            break;
611
                        }
612
                        $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
613
                        $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
614
                        $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
615
                        $i++;
616
                    }
617
                    $res .= '</div>';
618
                }
619
            } catch (Exception $e) {
620
                error_log($e->getMessage());
621
            }
622
        }
623
624
        return $res;
625
    }
626
627
    /**
628
     * Sends invitations to friends.
629
     *
630
     * @param int    $userId
631
     * @param string $subject
632
     * @param string $content
633
     *
634
     * @return bool
635
     */
636
    public static function sendInvitationToUser($userId, $subject = '', $content = '')
637
    {
638
        $user_info = api_get_user_info($userId);
639
        $success = get_lang('MessageSentTo');
640
        $success .= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
641
642
        if (isset($subject) && isset($content) && isset($userId)) {
643
            $result = MessageManager::send_message($userId, $subject, $content);
644
645
            if ($result) {
646
                Display::addFlash(
647
                    Display::return_message($success, 'normal', false)
648
                );
649
            } else {
650
                Display::addFlash(
651
                    Display::return_message(get_lang('ErrorSendingMessage'), 'error', false)
652
                );
653
            }
654
655
            return false;
656
        } elseif (isset($userId) && !isset($subject)) {
657
            if (isset($userId) && $userId > 0) {
658
                $count = self::send_invitation_friend(
659
                    api_get_user_id(),
660
                    $userId,
661
                    get_lang('Invitation'),
662
                    $content
663
                );
664
665
                if ($count) {
666
                    Display::addFlash(
667
                        Display::return_message(
668
                            api_htmlentities(get_lang('InvitationHasBeenSent')),
669
                            'normal',
670
                            false
671
                        )
672
                    );
673
                } else {
674
                    Display::addFlash(
675
                        Display::return_message(
676
                            api_htmlentities(get_lang('YouAlreadySentAnInvitation')),
677
                            'warning',
678
                            false
679
                        )
680
                    );
681
                }
682
            }
683
        }
684
    }
685
686
    /**
687
     * Helper functions definition.
688
     */
689
    public static function get_logged_user_course_html($my_course, $count)
690
    {
691
        $result = '';
692
        $count = (int) $count;
693
694
        // Table definitions
695
        $main_user_table = Database::get_main_table(TABLE_MAIN_USER);
696
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
697
        $course_directory = $my_course['course_info']['directory'];
698
        $course_title = $my_course['course_info']['title'];
699
        $course_visibility = $my_course['course_info']['visibility'];
700
701
        $user_in_course_status = CourseManager::getUserInCourseStatus(
702
            api_get_user_id(),
703
            $my_course['course_info']['real_id']
704
        );
705
706
        $course_path = api_get_path(SYS_COURSE_PATH).$course_directory; // course path
707
        if (api_get_setting('course_images_in_courses_list') === 'true') {
708
            if (file_exists($course_path.'/course-pic85x85.png')) {
709
                $image = $my_course['course_info']['course_image'];
710
                $imageCourse = Display::img($image, $course_title, ['class' => 'img-course']);
711
            } else {
712
                $imageCourse = Display::return_icon(
713
                    'session_default_small.png',
714
                    $course_title,
715
                    ['class' => 'img-course']
716
                );
717
            }
718
        } else {
719
            $imageCourse = Display::return_icon(
720
                'course.png',
721
                get_lang('Course'),
722
                ['class' => 'img-default']
723
            );
724
        }
725
726
        //display course entry
727
        if (api_get_setting('course_images_in_courses_list') === 'true') {
728
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:65px;">';
729
        } else {
730
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:44px;">';
731
        }
732
        $result .= $imageCourse;
733
734
        //show a hyperlink to the course, unless the course is closed and user is not course admin
735
        if ($course_visibility != COURSE_VISIBILITY_HIDDEN &&
736
            ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER)
737
        ) {
738
            $result .= '<span class="title">'.$course_title.'<span>';
739
        } else {
740
            $result .= $course_title.' '.get_lang('CourseClosed');
741
        }
742
743
        $result .= '</li>';
744
        $session = '';
745
        if (!empty($my_course['session_name']) && !empty($my_course['id_session'])) {
746
            // Request for the name of the general coach
747
            $sql = 'SELECT lastname, firstname
748
                    FROM '.$tbl_session.' ts
749
                    LEFT JOIN '.$main_user_table.' tu
750
                    ON ts.id_coach = tu.user_id
751
                    WHERE ts.id='.(int) $my_course['id_session'].' LIMIT 1';
752
            $rs = Database::query($sql);
753
            $sessioncoach = Database::store_result($rs);
754
            $sessioncoach = $sessioncoach[0];
755
756
            $session = [];
757
            $session['title'] = $my_course['session_name'];
758
            if ($my_course['access_start_date'] == '0000-00-00') {
759
                $session['dates'] = get_lang('WithoutTimeLimits');
760
                if (api_get_setting('show_session_coach') === 'true') {
761
                    $session['coach'] = get_lang('GeneralCoach').': '.
762
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
763
                }
764
            } else {
765
                $session['dates'] = ' - '.get_lang('From').' '.$my_course['access_start_date'].' '.get_lang('To').' '.$my_course['access_end_date'];
766
                if (api_get_setting('show_session_coach') === 'true') {
767
                    $session['coach'] = get_lang('GeneralCoach').': '.
768
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
769
                }
770
            }
771
        }
772
773
        $my_course['id_session'] = isset($my_course['id_session']) ? $my_course['id_session'] : 0;
774
        $output = [
775
            $my_course['user_course_cat'],
776
            $result,
777
            $my_course['id_session'],
778
            $session,
779
        ];
780
781
        return $output;
782
    }
783
784
    /**
785
     * Shows the avatar block in social pages.
786
     *
787
     * @param string $show     highlight link possible values:
788
     *                         group_add,
789
     *                         home,
790
     *                         messages,
791
     *                         messages_inbox,
792
     *                         messages_compose,
793
     *                         messages_outbox,
794
     *                         invitations,
795
     *                         shared_profile,
796
     *                         friends,
797
     *                         groups search
798
     * @param int    $group_id
799
     * @param int    $user_id
800
     */
801
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
802
    {
803
        $user_id = (int) $user_id;
804
        $group_id = (int) $group_id;
805
806
        if (empty($user_id)) {
807
            $user_id = api_get_user_id();
808
        }
809
810
        $show_groups = [
811
            'groups',
812
            'group_messages',
813
            'messages_list',
814
            'group_add',
815
            'mygroups',
816
            'group_edit',
817
            'member_list',
818
            'invite_friends',
819
            'waiting_list',
820
            'browse_groups',
821
        ];
822
823
        $template = new Template(null, false, false, false, false, false);
824
825
        if (in_array($show, $show_groups) && !empty($group_id)) {
826
            // Group image
827
            $userGroup = new UserGroup();
828
            $group_info = $userGroup->get($group_id);
829
830
            $userGroupImage = $userGroup->get_picture_group(
831
                $group_id,
832
                $group_info['picture'],
833
                128,
834
                GROUP_IMAGE_SIZE_BIG
835
            );
836
837
            $template->assign('show_group', true);
838
            $template->assign('group_id', $group_id);
839
            $template->assign('user_group_image', $userGroupImage);
840
            $template->assign(
841
                'user_is_group_admin',
842
                $userGroup->is_group_admin(
843
                    $group_id,
844
                    api_get_user_id()
845
                )
846
            );
847
        } else {
848
            $template->assign('show_group', false);
849
            $template->assign('show_user', true);
850
            $template->assign(
851
                'user_image',
852
                [
853
                    'big' => UserManager::getUserPicture(
854
                        $user_id,
855
                        USER_IMAGE_SIZE_BIG
856
                    ),
857
                    'normal' => UserManager::getUserPicture(
858
                        $user_id,
859
                        USER_IMAGE_SIZE_MEDIUM
860
                    ),
861
                ]
862
            );
863
        }
864
865
        $skillBlock = $template->get_template('social/avatar_block.tpl');
866
867
        return $template->fetch($skillBlock);
868
    }
869
870
    /**
871
     * Shows the right menu of the Social Network tool.
872
     *
873
     * @param string $show                       highlight link possible values:
874
     *                                           group_add,
875
     *                                           home,
876
     *                                           messages,
877
     *                                           messages_inbox,
878
     *                                           messages_compose ,
879
     *                                           messages_outbox,
880
     *                                           invitations,
881
     *                                           shared_profile,
882
     *                                           friends,
883
     *                                           groups search
884
     * @param int    $group_id                   group id
885
     * @param int    $user_id                    user id
886
     * @param bool   $show_full_profile          show profile or not (show or hide the user image/information)
887
     * @param bool   $show_delete_account_button
888
     */
889
    public static function show_social_menu(
890
        $show = '',
891
        $group_id = 0,
892
        $user_id = 0,
893
        $show_full_profile = false,
894
        $show_delete_account_button = false
895
    ) {
896
        $user_id = (int) $user_id;
897
        $group_id = (int) $group_id;
898
899
        if (empty($user_id)) {
900
            $user_id = api_get_user_id();
901
        }
902
903
        $usergroup = new UserGroup();
904
        $show_groups = [
905
            'groups',
906
            'group_messages',
907
            'messages_list',
908
            'group_add',
909
            'mygroups',
910
            'group_edit',
911
            'member_list',
912
            'invite_friends',
913
            'waiting_list',
914
            'browse_groups',
915
        ];
916
917
        // get count unread message and total invitations
918
        $count_unread_message = MessageManager::getNumberOfMessages(['message_status' => [MESSAGE_STATUS_UNREAD]]);
919
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
920
921
        $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
922
        $group_pending_invitations = $usergroup->get_groups_by_user(
923
            api_get_user_id(),
924
            GROUP_USER_PERMISSION_PENDING_INVITATION,
925
            false
926
        );
927
        $group_pending_invitations = count($group_pending_invitations);
928
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
929
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
930
931
        $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), null, ICON_SIZE_SMALL);
932
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), null, ICON_SIZE_SMALL);
933
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), null, ICON_SIZE_SMALL);
934
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), null, ICON_SIZE_SMALL);
935
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), null, ICON_SIZE_SMALL);
936
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), null, ICON_SIZE_SMALL);
937
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
938
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), null, ICON_SIZE_SMALL);
939
        $portfolioIcon = Display::return_icon('wiki_task.png', get_lang('Portfolio'));
940
        $personalDataIcon = Display::return_icon('database.png', get_lang('PersonalDataReport'));
941
942
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
943
        $groupUrl = api_get_path(WEB_CODE_PATH).'social/groups.php';
944
        if (!empty($forumCourseId)) {
945
            $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

945
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
946
            if (!empty($courseInfo)) {
947
                $groupUrl = api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code'];
948
            }
949
        }
950
951
        $html = '';
952
        $active = null;
953
        if (!in_array(
954
            $show,
955
            ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
956
        )) {
957
            $links = '<ul class="nav nav-pills nav-stacked">';
958
            $active = $show === 'home' ? 'active' : null;
959
            $links .= '
960
                <li class="home-icon '.$active.'">
961
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
962
                        '.$homeIcon.' '.get_lang('Home').'
963
                    </a>
964
                </li>';
965
            $active = $show === 'messages' ? 'active' : null;
966
            $links .= '
967
                <li class="messages-icon '.$active.'">
968
                    <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
969
                        '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
970
                    </a>
971
                </li>';
972
973
            // Invitations
974
            $active = $show === 'invitations' ? 'active' : null;
975
            $links .= '
976
                <li class="invitations-icon '.$active.'">
977
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
978
                        '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
979
                    </a>
980
                </li>';
981
982
            // Shared profile and groups
983
            $active = $show === 'shared_profile' ? 'active' : null;
984
            $links .= '
985
                <li class="shared-profile-icon'.$active.'">
986
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
987
                        '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
988
                    </a>
989
                </li>';
990
            $active = $show === 'friends' ? 'active' : null;
991
            $links .= '
992
                <li class="friends-icon '.$active.'">
993
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
994
                        '.$friendsIcon.' '.get_lang('Friends').'
995
                    </a>
996
                </li>';
997
            $active = $show === 'browse_groups' ? 'active' : null;
998
            $links .= '
999
                <li class="browse-groups-icon '.$active.'">
1000
                    <a href="'.$groupUrl.'">
1001
                        '.$groupsIcon.' '.get_lang('SocialGroups').'
1002
                    </a>
1003
                </li>';
1004
1005
            // Search users
1006
            $active = $show === 'search' ? 'active' : null;
1007
            $links .= '
1008
                <li class="search-icon '.$active.'">
1009
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1010
                        '.$searchIcon.' '.get_lang('Search').'
1011
                    </a>
1012
                </li>';
1013
1014
            // My files
1015
            $active = $show === 'myfiles' ? 'active' : null;
1016
1017
            $myFiles = '
1018
                <li class="myfiles-icon '.$active.'">
1019
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1020
                        '.$filesIcon.' '.get_lang('MyFiles').'
1021
                    </a>
1022
                </li>';
1023
1024
            if (api_get_setting('allow_my_files') === 'false') {
1025
                $myFiles = '';
1026
            }
1027
            $links .= $myFiles;
1028
            if (api_get_configuration_value('allow_portfolio_tool')) {
1029
                $links .= '
1030
                    <li class="portoflio-icon '.($show === 'portfolio' ? 'active' : '').'">
1031
                        <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1032
                            '.$portfolioIcon.' '.get_lang('Portfolio').'
1033
                        </a>
1034
                    </li>
1035
                ';
1036
            }
1037
1038
            if (!api_get_configuration_value('disable_gdpr')) {
1039
                $active = $show === 'personal-data' ? 'active' : null;
1040
                $personalData = '
1041
                    <li class="personal-data-icon '.$active.'">
1042
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1043
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1044
                        </a>
1045
                    </li>';
1046
                $links .= $personalData;
1047
            }
1048
1049
            if (api_is_platform_admin()) {
1050
                $active = $show === 'promoted_messages' ? 'active' : null;
1051
                $personalData = '
1052
                    <li class="personal-data-icon '.$active.'">
1053
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/promoted_messages.php">
1054
                            '.$personalDataIcon.' '.get_lang('PromotedMessages').'
1055
                        </a>
1056
                    </li>';
1057
                $links .= $personalData;
1058
            }
1059
            $links .= '</ul>';
1060
            $html .= Display::panelCollapse(
1061
                get_lang('SocialNetwork'),
1062
                $links,
1063
                'social-network-menu',
1064
                null,
1065
                'sn-sidebar',
1066
                'sn-sidebar-collapse'
1067
            );
1068
        }
1069
1070
        if (!empty($group_id) && in_array($show, $show_groups)) {
1071
            $html .= $usergroup->show_group_column_information(
1072
                $group_id,
1073
                api_get_user_id(),
1074
                $show
1075
            );
1076
        }
1077
1078
        if ($show === 'shared_profile') {
1079
            $links = '<ul class="nav nav-pills nav-stacked">';
1080
            // My own profile
1081
            if ($show_full_profile && $user_id == api_get_user_id()) {
1082
                $links .= '
1083
                    <li class="home-icon '.$active.'">
1084
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
1085
                            '.$homeIcon.' '.get_lang('Home').'
1086
                        </a>
1087
                    </li>
1088
                    <li class="messages-icon '.$active.'">
1089
                        <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
1090
                            '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
1091
                        </a>
1092
                    </li>';
1093
                $active = $show === 'invitations' ? 'active' : null;
1094
                $links .= '
1095
                    <li class="invitations-icon'.$active.'">
1096
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
1097
                            '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
1098
                        </a>
1099
                    </li>';
1100
1101
                $links .= '
1102
                    <li class="shared-profile-icon active">
1103
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1104
                            '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1105
                        </a>
1106
                    </li>
1107
                    <li class="friends-icon">
1108
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1109
                            '.$friendsIcon.' '.get_lang('Friends').'
1110
                        </a>
1111
                    </li>';
1112
1113
                $links .= '<li class="browse-groups-icon">
1114
                        <a href="'.$groupUrl.'">
1115
                            '.$groupsIcon.' '.get_lang('SocialGroups').'
1116
                        </a>
1117
                        </li>';
1118
1119
                $active = $show == 'search' ? 'active' : null;
1120
                $links .= '
1121
                    <li class="search-icon '.$active.'">
1122
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1123
                            '.$searchIcon.' '.get_lang('Search').'
1124
                        </a>
1125
                    </li>';
1126
                $active = $show == 'myfiles' ? 'active' : null;
1127
1128
                $myFiles = '
1129
                    <li class="myfiles-icon '.$active.'">
1130
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1131
                            '.$filesIcon.' '.get_lang('MyFiles').'
1132
                        </a>
1133
                    </li>';
1134
1135
                if (api_get_setting('allow_my_files') === 'false') {
1136
                    $myFiles = '';
1137
                }
1138
                $links .= $myFiles;
1139
1140
                if (api_get_configuration_value('allow_portfolio_tool')) {
1141
                    $links .= '
1142
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1143
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1144
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1145
                            </a>
1146
                        </li>
1147
                    ';
1148
                }
1149
1150
                if (!api_get_configuration_value('disable_gdpr')) {
1151
                    $active = $show == 'personal-data' ? 'active' : null;
1152
                    $personalData = '
1153
                    <li class="personal-data-icon '.$active.'">
1154
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1155
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1156
                        </a>
1157
                    </li>';
1158
                    $links .= $personalData;
1159
                    $links .= '</ul>';
1160
                }
1161
            }
1162
1163
            // My friend profile.
1164
            if ($user_id != api_get_user_id()) {
1165
                $sendMessageText = get_lang('SendMessage');
1166
                $sendMessageIcon = Display::return_icon(
1167
                    'new-message.png',
1168
                    $sendMessageText
1169
                );
1170
                $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
1171
                    'a' => 'get_user_popup',
1172
                    'user_id' => $user_id,
1173
                ]);
1174
1175
                $links .= '<li>';
1176
                $links .= Display::url(
1177
                    "$sendMessageIcon $sendMessageText",
1178
                    $sendMessageUrl,
1179
                    [
1180
                        'class' => 'ajax',
1181
                        'title' => $sendMessageText,
1182
                        'data-title' => $sendMessageText,
1183
                    ]
1184
                );
1185
                $links .= '</li>';
1186
1187
                if (api_get_configuration_value('allow_portfolio_tool')) {
1188
                    $links .= '
1189
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1190
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id.'">
1191
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1192
                            </a>
1193
                        </li>
1194
                    ';
1195
                }
1196
            }
1197
1198
            // Check if I already sent an invitation message
1199
            $invitationSentList = self::get_list_invitation_sent_by_user_id(api_get_user_id());
1200
1201
            if (isset($invitationSentList[$user_id]) && is_array($invitationSentList[$user_id]) &&
1202
                count($invitationSentList[$user_id]) > 0
1203
            ) {
1204
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
1205
                    Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
1206
                    .'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
1207
            } else {
1208
                if (!$show_full_profile) {
1209
                    $links .= '<li>
1210
                        <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('SendInvitation').'">'.
1211
                        Display::return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').
1212
                        '</a></li>';
1213
                }
1214
            }
1215
1216
            $links .= '</ul>';
1217
            $html .= Display::panelCollapse(
1218
                get_lang('SocialNetwork'),
1219
                $links,
1220
                'social-network-menu',
1221
                null,
1222
                'sn-sidebar',
1223
                'sn-sidebar-collapse'
1224
            );
1225
1226
            if ($show_full_profile && $user_id == api_get_user_id()) {
1227
                $personal_course_list = UserManager::get_personal_session_course_list($user_id);
1228
                $course_list_code = [];
1229
                $i = 1;
1230
                if (is_array($personal_course_list)) {
1231
                    foreach ($personal_course_list as $my_course) {
1232
                        if ($i <= 10) {
1233
                            $course_list_code[] = ['code' => $my_course['code']];
1234
                        } else {
1235
                            break;
1236
                        }
1237
                        $i++;
1238
                    }
1239
                    // To avoid repeated courses
1240
                    $course_list_code = array_unique_dimensional($course_list_code);
1241
                }
1242
1243
                // Announcements
1244
                $announcements = [];
1245
                foreach ($course_list_code as $course) {
1246
                    $course_info = api_get_course_info($course['code']);
1247
                    if (!empty($course_info)) {
1248
                        $content = AnnouncementManager::get_all_annoucement_by_user_course(
1249
                            $course_info['code'],
1250
                            $user_id
1251
                        );
1252
1253
                        if (!empty($content)) {
1254
                            $url = Display::url(
1255
                                Display::return_icon(
1256
                                    'announcement.png',
1257
                                    get_lang('Announcements')
1258
                                ).$course_info['name'].' ('.$content['count'].')',
1259
                                api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']
1260
                            );
1261
                            $announcements[] = Display::tag('li', $url);
1262
                        }
1263
                    }
1264
                }
1265
                if (!empty($announcements)) {
1266
                    $html .= '<div class="social_menu_items">';
1267
                    $html .= '<ul>';
1268
                    foreach ($announcements as $announcement) {
1269
                        $html .= $announcement;
1270
                    }
1271
                    $html .= '</ul>';
1272
                    $html .= '</div>';
1273
                }
1274
            }
1275
        }
1276
1277
        if ($show_delete_account_button) {
1278
            $html .= '<div class="panel panel-default"><div class="panel-body">';
1279
            $html .= '<ul class="nav nav-pills nav-stacked"><li>';
1280
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
1281
            $html .= Display::url(
1282
                Display::return_icon(
1283
                    'delete.png',
1284
                    get_lang('Unsubscribe'),
1285
                    [],
1286
                    ICON_SIZE_TINY
1287
                ).get_lang('Unsubscribe'),
1288
                $url
1289
            );
1290
            $html .= '</li></ul>';
1291
            $html .= '</div></div>';
1292
        }
1293
        $html .= '';
1294
1295
        return $html;
1296
    }
1297
1298
    /**
1299
     * Displays a sortable table with the list of online users.
1300
     *
1301
     * @param array $user_list The list of users to be shown
1302
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
1303
     *
1304
     * @return string HTML block or null if and ID was defined
1305
     * @assert (null) === false
1306
     */
1307
    public static function display_user_list($user_list, $wrap = true)
1308
    {
1309
        $html = '';
1310
1311
        if (isset($_GET['id']) || count($user_list) < 1) {
1312
            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...
1313
        }
1314
1315
        $course_url = '';
1316
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1317
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
1318
        }
1319
1320
        $hide = api_get_configuration_value('hide_complete_name_in_whoisonline');
1321
        foreach ($user_list as $uid) {
1322
            $user_info = api_get_user_info($uid, true);
1323
            $lastname = $user_info['lastname'];
1324
            $firstname = $user_info['firstname'];
1325
            $completeName = $firstname.', '.$lastname;
1326
            $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);
1327
            $status_icon_chat = null;
1328
            if (isset($user_info['user_is_online_in_chat']) && $user_info['user_is_online_in_chat'] == 1) {
1329
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1330
            } else {
1331
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1332
            }
1333
1334
            $userPicture = $user_info['avatar'];
1335
            $officialCode = '';
1336
            if (api_get_setting('show_official_code_whoisonline') == 'true') {
1337
                $officialCode .= '<div class="items-user-official-code"><p style="min-height: 30px;" title="'.get_lang('OfficialCode').'">'.$user_info['official_code'].'</p></div>';
1338
            }
1339
1340
            if ($hide === true) {
1341
                $completeName = '';
1342
                $firstname = '';
1343
                $lastname = '';
1344
            }
1345
1346
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1347
1348
            $url = null;
1349
            // Anonymous users can't have access to the profile
1350
            if (!api_is_anonymous()) {
1351
                if (api_get_setting('allow_social_tool') === 'true') {
1352
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1353
                } else {
1354
                    $url = '?id='.$uid.$course_url;
1355
                }
1356
            } else {
1357
                $url = null;
1358
            }
1359
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1360
1361
            $html .= '<div class="col-xs-6 col-md-2">
1362
                        <div class="items-user">
1363
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1364
                            <div class="items-user-name">
1365
                            '.$name.'
1366
                            </div>
1367
                            '.$officialCode.'
1368
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1369
                        </div>
1370
                      </div>';
1371
        }
1372
1373
        return $html;
1374
    }
1375
1376
    /**
1377
     * Displays the information of an individual user.
1378
     *
1379
     * @param int $user_id
1380
     *
1381
     * @return string
1382
     */
1383
    public static function display_individual_user($user_id)
1384
    {
1385
        global $interbreadcrumb;
1386
        $safe_user_id = (int) $user_id;
1387
        $currentUserId = api_get_user_id();
1388
1389
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1390
        $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
1391
        $result = Database::query($sql);
1392
        $html = null;
1393
        if (Database::num_rows($result) == 1) {
1394
            $user_object = Database::fetch_object($result);
1395
            $userInfo = api_get_user_info($user_id);
1396
            $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
1397
            $status = get_status_from_code($user_object->status);
1398
            $interbreadcrumb[] = ['url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList')];
1399
1400
            $html .= '<div class ="thumbnail">';
1401
            $fullurl = $userInfo['avatar'];
1402
1403
            $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
1404
1405
            if (!empty($status)) {
1406
                $html .= '<div class="caption">'.$status.'</div>';
1407
            }
1408
            $html .= '</div>';
1409
1410
            if (api_get_setting('show_email_addresses') == 'true') {
1411
                $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
1412
            }
1413
1414
            if ($user_object->competences) {
1415
                $html .= Display::page_subheader(get_lang('MyCompetences'));
1416
                $html .= '<p>'.$user_object->competences.'</p>';
1417
            }
1418
            if ($user_object->diplomas) {
1419
                $html .= Display::page_subheader(get_lang('MyDiplomas'));
1420
                $html .= '<p>'.$user_object->diplomas.'</p>';
1421
            }
1422
            if ($user_object->teach) {
1423
                $html .= Display::page_subheader(get_lang('MyTeach'));
1424
                $html .= '<p>'.$user_object->teach.'</p>';
1425
            }
1426
            self::display_productions($user_object->user_id);
1427
            if ($user_object->openarea) {
1428
                $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
1429
                $html .= '<p>'.$user_object->openarea.'</p>';
1430
            }
1431
        } else {
1432
            $html .= '<div class="actions-title">';
1433
            $html .= get_lang('UsersOnLineList');
1434
            $html .= '</div>';
1435
        }
1436
1437
        return $html;
1438
    }
1439
1440
    /**
1441
     * Display productions in who is online.
1442
     *
1443
     * @param int $user_id User id
1444
     */
1445
    public static function display_productions($user_id)
1446
    {
1447
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1448
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1449
        $webdir = UserManager::getUserPathById($user_id, 'web');
1450
1451
        if (!is_dir($sysdir)) {
1452
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1453
        }
1454
1455
        $productions = UserManager::get_user_productions($user_id);
1456
1457
        if (count($productions) > 0) {
1458
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1459
            echo '<dd><ul>';
1460
            foreach ($productions as $file) {
1461
                // Only display direct file links to avoid browsing an empty directory
1462
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1463
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1464
                }
1465
                // Real productions are under a subdirectory by the User's id
1466
                if (is_dir($sysdir.$file)) {
1467
                    $subs = scandir($sysdir.$file);
1468
                    foreach ($subs as $my => $sub) {
1469
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1470
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1471
                        }
1472
                    }
1473
                }
1474
            }
1475
            echo '</ul></dd>';
1476
        }
1477
    }
1478
1479
    /**
1480
     * @param string $content
1481
     * @param string $span_count
1482
     *
1483
     * @return string
1484
     */
1485
    public static function social_wrapper_div($content, $span_count)
1486
    {
1487
        $span_count = (int) $span_count;
1488
        $html = '<div class="span'.$span_count.'">';
1489
        $html .= '<div class="well_border">';
1490
        $html .= $content;
1491
        $html .= '</div></div>';
1492
1493
        return $html;
1494
    }
1495
1496
    /**
1497
     * Dummy function.
1498
     */
1499
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1500
    {
1501
        $content = '';
1502
        switch ($place) {
1503
            case SOCIAL_CENTER_PLUGIN:
1504
                $social_plugins = [1, 2];
1505
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1506
                    $content .= '<div id="social-plugins">';
1507
                    foreach ($social_plugins as $plugin) {
1508
                        $content .= '<div class="social-plugin-item">';
1509
                        $content .= $plugin;
1510
                        $content .= '</div>';
1511
                    }
1512
                    $content .= '</div>';
1513
                }
1514
                break;
1515
            case SOCIAL_LEFT_PLUGIN:
1516
                break;
1517
            case SOCIAL_RIGHT_PLUGIN:
1518
                break;
1519
        }
1520
1521
        return $content;
1522
    }
1523
1524
    /**
1525
     * Sends a message to someone's wall.
1526
     *
1527
     * @param int    $userId         id of author
1528
     * @param int    $friendId       id where we send the message
1529
     * @param string $messageContent of the message
1530
     * @param int    $messageId      id parent
1531
     * @param string $messageStatus  status type of message
1532
     *
1533
     * @return int
1534
     *
1535
     * @author Yannick Warnier
1536
     */
1537
    public static function sendWallMessage(
1538
        $userId,
1539
        $friendId,
1540
        $messageContent,
1541
        $messageId = 0,
1542
        $messageStatus = ''
1543
    ) {
1544
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1545
        $userId = (int) $userId;
1546
        $friendId = (int) $friendId;
1547
        $messageId = (int) $messageId;
1548
1549
        if (empty($userId) || empty($friendId)) {
1550
            return 0;
1551
        }
1552
1553
        // Just in case we replace the and \n and \n\r while saving in the DB
1554
        $messageContent = str_replace(["\n", "\n\r"], '<br />', $messageContent);
1555
        $now = api_get_utc_datetime();
1556
1557
        $attributes = [
1558
            'user_sender_id' => $userId,
1559
            'user_receiver_id' => $friendId,
1560
            'msg_status' => $messageStatus,
1561
            'send_date' => $now,
1562
            'title' => '',
1563
            'content' => $messageContent,
1564
            'parent_id' => $messageId,
1565
            'group_id' => 0,
1566
            'update_date' => $now,
1567
        ];
1568
1569
        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...
1570
    }
1571
1572
    /**
1573
     * Send File attachment (jpg,png).
1574
     *
1575
     * @author Anibal Copitan
1576
     *
1577
     * @param int    $userId      id user
1578
     * @param array  $fileAttach
1579
     * @param int    $messageId   id message (relation with main message)
1580
     * @param string $fileComment description attachment file
1581
     *
1582
     * @return bool|int
1583
     */
1584
    public static function sendWallMessageAttachmentFile(
1585
        $userId,
1586
        $fileAttach,
1587
        $messageId,
1588
        $fileComment = ''
1589
    ) {
1590
        $safeFileName = Database::escape_string($fileAttach['name']);
1591
1592
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1593
        $allowedTypes = api_get_supported_image_extensions();
1594
1595
        $allowedTypes[] = 'mp4';
1596
        $allowedTypes[] = 'webm';
1597
        $allowedTypes[] = 'ogg';
1598
1599
        if (in_array($extension, $allowedTypes)) {
1600
            return MessageManager::saveMessageAttachmentFile($fileAttach, $fileComment, $messageId, $userId);
1601
        }
1602
1603
        return false;
1604
    }
1605
1606
    /**
1607
     * Gets all messages from someone's wall (within specific limits).
1608
     *
1609
     * @param int        $userId     id of wall shown
1610
     * @param int|string $parentId   id message (Post main)
1611
     * @param int|array  $groupId
1612
     * @param int|array  $friendId
1613
     * @param string     $startDate  Date from which we want to show the messages, in UTC time
1614
     * @param int        $start      Limit for the number of parent messages we want to show
1615
     * @param int        $length     Wall message query offset
1616
     * @param bool       $getCount
1617
     * @param array      $threadList
1618
     *
1619
     * @return array|int
1620
     *
1621
     * @author Yannick Warnier
1622
     */
1623
    public static function getWallMessages(
1624
        $userId,
1625
        $parentId = 0,
1626
        $groupId = 0,
1627
        $friendId = 0,
1628
        $startDate = '',
1629
        $start = 0,
1630
        $length = 10,
1631
        $getCount = false,
1632
        $threadList = []
1633
    ) {
1634
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1635
1636
        $parentId = (int) $parentId;
1637
        $userId = (int) $userId;
1638
        $start = (int) $start;
1639
        $length = (int) $length;
1640
1641
        $select = " SELECT
1642
                    id,
1643
                    user_sender_id,
1644
                    user_receiver_id,
1645
                    send_date,
1646
                    content,
1647
                    parent_id,
1648
                    msg_status,
1649
                    group_id,
1650
                    '' as forum_id,
1651
                    '' as thread_id,
1652
                    '' as c_id
1653
                  ";
1654
1655
        if ($getCount) {
1656
            $select = ' SELECT count(id) count ';
1657
        }
1658
1659
        $sql = "$select                    
1660
                    FROM $tblMessage m
1661
                WHERE
1662
                    msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
1663
1664
        // Get my own posts
1665
        $userReceiverCondition = ' (
1666
            user_receiver_id = '.$userId.' AND 
1667
            msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
1668
            parent_id = '.$parentId.'
1669
        )';
1670
1671
        $sql .= $userReceiverCondition;
1672
1673
        $sql .= ' OR (
1674
            msg_status IN ('.MESSAGE_STATUS_PROMOTED.')             
1675
        ) ';
1676
1677
        // Get my group posts
1678
        $groupCondition = '';
1679
        if (!empty($groupId)) {
1680
            if (is_array($groupId)) {
1681
                $groupId = array_map('intval', $groupId);
1682
                $groupId = implode("','", $groupId);
1683
                $groupCondition = " OR ( group_id IN ('$groupId') ";
1684
            } else {
1685
                $groupId = (int) $groupId;
1686
                $groupCondition = " OR ( group_id = '$groupId' ";
1687
            }
1688
            $groupCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_NEW.', '.MESSAGE_STATUS_UNREAD.')) ';
1689
        }
1690
1691
        // Get my friend posts
1692
        $friendCondition = '';
1693
        if (!empty($friendId)) {
1694
            if (is_array($friendId)) {
1695
                $friendId = array_map('intval', $friendId);
1696
                $friendId = implode("','", $friendId);
1697
                $friendCondition = " OR ( user_receiver_id IN ('$friendId') ";
1698
            } else {
1699
                $friendId = (int) $friendId;
1700
                $friendCondition = " OR ( user_receiver_id = '$friendId' ";
1701
            }
1702
            $friendCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_WALL_POST.') AND parent_id = 0) ';
1703
        }
1704
1705
        if (!empty($groupCondition) || !empty($friendCondition)) {
1706
            $sql .= " $groupCondition $friendCondition ";
1707
        }
1708
1709
        if (!empty($threadList)) {
1710
            if ($getCount) {
1711
                $select = ' SELECT count(iid) count ';
1712
            } else {
1713
                $select = " SELECT 
1714
                                iid,
1715
                                poster_id,
1716
                                '' as user_receiver_id,
1717
                                post_date,
1718
                                post_text,
1719
                                '' as parent_id,
1720
                                ".MESSAGE_STATUS_FORUM.",
1721
                                '' as group_id,
1722
                                forum_id,
1723
                                thread_id,
1724
                                c_id                            
1725
                            ";
1726
            }
1727
1728
            $threadList = array_map('intval', $threadList);
1729
            $threadList = implode("','", $threadList);
1730
            $condition = " thread_id IN ('$threadList') ";
1731
            $sql .= "                
1732
                UNION (
1733
                    $select
1734
                    FROM c_forum_post  
1735
                    WHERE $condition                                         
1736
                )
1737
                ";
1738
        }
1739
1740
        if ($getCount) {
1741
            $res = Database::query($sql);
1742
            $row = Database::fetch_array($res);
1743
1744
            return (int) $row['count'];
1745
        }
1746
1747
        $sql .= ' ORDER BY send_date DESC ';
1748
        $sql .= " LIMIT $start, $length ";
1749
1750
        $messages = [];
1751
        $res = Database::query($sql);
1752
        $em = Database::getManager();
1753
        if (Database::num_rows($res) > 0) {
1754
            $repo = $em->getRepository('ChamiloCourseBundle:CForumPost');
1755
            $repoThread = $em->getRepository('ChamiloCourseBundle:CForumThread');
1756
            $groups = [];
1757
            $userGroup = new UserGroup();
1758
            $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
1759
            while ($row = Database::fetch_array($res, 'ASSOC')) {
1760
                $row['group_info'] = [];
1761
                if (!empty($row['group_id'])) {
1762
                    if (!in_array($row['group_id'], $groups)) {
1763
                        $group = $userGroup->get($row['group_id']);
1764
                        $group['url'] = $urlGroup.$group['id'];
1765
                        $groups[$row['group_id']] = $group;
1766
                        $row['group_info'] = $group;
1767
                    } else {
1768
                        $row['group_info'] = $groups[$row['group_id']];
1769
                    }
1770
                }
1771
1772
                // Forums
1773
                $row['post_title'] = '';
1774
                $row['forum_title'] = '';
1775
                $row['thread_url'] = '';
1776
                if ($row['msg_status'] == MESSAGE_STATUS_FORUM) {
1777
                    /** @var CForumPost $post */
1778
                    $post = $repo->find($row['id']);
1779
                    /** @var CForumThread $thread */
1780
                    $thread = $repoThread->find($row['thread_id']);
1781
                    if ($post && $thread) {
1782
                        $courseInfo = api_get_course_info_by_id($post->getCId());
1783
                        $row['post_title'] = $post->getForumId();
1784
                        $row['forum_title'] = $thread->getThreadTitle();
1785
                        $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
1786
                            'cidReq' => $courseInfo['code'],
1787
                            'forum' => $post->getForumId(),
1788
                            'thread' => $post->getThreadId(),
1789
                            'post_id' => $post->getIid(),
1790
                        ]).'#post_id_'.$post->getIid();
1791
                    }
1792
                }
1793
1794
                $messages[] = $row;
1795
            }
1796
        }
1797
1798
        return $messages;
1799
    }
1800
1801
    /**
1802
     * Gets all messages from someone's wall (within specific limits), formatted.
1803
     *
1804
     * @param int    $userId      USER ID of the person's wall
1805
     * @param array  $messageInfo
1806
     * @param string $start       Start date (from when we want the messages until today)
1807
     * @param int    $limit       Limit to the number of messages we want
1808
     * @param int    $offset      Wall messages offset
1809
     *
1810
     * @return string HTML formatted string to show messages
1811
     */
1812
    public static function getWallPostComments(
1813
        $userId,
1814
        $messageInfo,
1815
        $start = null,
1816
        $limit = 10,
1817
        $offset = 0
1818
    ) {
1819
        $messageId = $messageInfo['id'];
1820
        $messages = MessageManager::getMessagesByParent($messageInfo['id'], 0, $offset, $limit);
1821
        $formattedList = '<div class="sub-mediapost row">';
1822
        $users = [];
1823
1824
        // The messages are ordered by date descendant, for comments we need ascendant
1825
        krsort($messages);
1826
        foreach ($messages as $message) {
1827
            $userIdLoop = $message['user_sender_id'];
1828
            if (!isset($users[$userIdLoop])) {
1829
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1830
            }
1831
            $media = self::processPostComment($message, $users);
1832
            $formattedList .= $media;
1833
        }
1834
1835
        $formattedList .= '</div>';
1836
        $formattedList .= '<div class="mediapost-form">';
1837
        $formattedList .= '<form class="form-horizontal" id="form_comment_'.$messageId.'" name="post_comment" method="POST">
1838
                <div class="col-sm-9">
1839
                <label for="comment" class="hide">'.get_lang('SocialWriteNewComment').'</label>
1840
                <input type="hidden" name = "messageId" value="'.$messageId.'" />
1841
                <textarea rows="3" class="form-control" placeholder="'.get_lang('SocialWriteNewComment').'" name="comment" rows="1" ></textarea>
1842
                </div>
1843
                <div class="col-sm-3">
1844
                <a onclick="submitComment('.$messageId.');" href="javascript:void(0);" name="social_wall_new_msg_submit" class="btn btn-default btn-post">
1845
                    <em class="fa fa-pencil"></em> '.get_lang('Post').'
1846
                </a>
1847
                </div>
1848
                </form>';
1849
        $formattedList .= '</div>';
1850
1851
        return $formattedList;
1852
    }
1853
1854
    /**
1855
     * @param array $message
1856
     * @param array $users
1857
     *
1858
     * @return string
1859
     */
1860
    public static function processPostComment($message, $users = [])
1861
    {
1862
        if (empty($message)) {
1863
            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...
1864
        }
1865
1866
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
1867
        $currentUserId = api_get_user_id();
1868
        $userIdLoop = $message['user_sender_id'];
1869
        $receiverId = $message['user_receiver_id'];
1870
1871
        if (!isset($users[$userIdLoop])) {
1872
            $users[$userIdLoop] = api_get_user_info($userIdLoop);
1873
        }
1874
1875
        $iconStatus = $users[$userIdLoop]['icon_status'];
1876
        $nameComplete = $users[$userIdLoop]['complete_name'];
1877
        $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$userIdLoop;
1878
1879
        $comment = '<div class="rep-post col-md-12">';
1880
        $comment .= '<div class="col-md-2 col-xs-2 social-post-answers">';
1881
        $comment .= '<div class="user-image pull-right">';
1882
        $comment .= '<a href="'.$url.'">
1883
                        <img src="'.$users[$userIdLoop]['avatar'].'" 
1884
                        alt="'.$users[$userIdLoop]['complete_name'].'" 
1885
                        class="avatar-thumb">
1886
                     </a>';
1887
        $comment .= '</div>';
1888
        $comment .= '</div>';
1889
        $comment .= '<div class="col-md-7 col-xs-7 social-post-answers">';
1890
        $comment .= '<div class="user-data">';
1891
        $comment .= $iconStatus;
1892
        $comment .= '<div class="username"><a href="'.$url.'">'.$nameComplete.'</a> 
1893
                        <span>'.Security::remove_XSS($message['content']).'</span>
1894
                       </div>';
1895
        $comment .= '<div>'.$date.'</div>';
1896
        $comment .= '<br />';
1897
        $comment .= '</div>';
1898
        $comment .= '</div>';
1899
1900
        $comment .= '<div class="col-md-3 col-xs-3 social-post-answers">';
1901
        $comment .= '<div class="pull-right btn-group btn-group-sm">';
1902
1903
        $comment .= MessageManager::getLikesButton(
1904
            $message['id'],
1905
            $currentUserId
1906
        );
1907
1908
        $isOwnWall = $currentUserId == $userIdLoop || $currentUserId == $receiverId;
1909
        if ($isOwnWall) {
1910
            $comment .= Display::url(
1911
                    Display::returnFontAwesomeIcon('trash', '', true),
1912
                'javascript:void(0)',
1913
                [
1914
                    'id' => 'message_'.$message['id'],
1915
                    'title' => get_lang('SocialMessageDelete'),
1916
                    'onclick' => 'deleteComment('.$message['id'].')',
1917
                    'class' => 'btn btn-default',
1918
                ]
1919
            );
1920
        }
1921
        $comment .= '</div>';
1922
        $comment .= '</div>';
1923
        $comment .= '</div>';
1924
1925
        return $comment;
1926
    }
1927
1928
    /**
1929
     * @param array $message
1930
     *
1931
     * @return array
1932
     */
1933
    public static function getAttachmentPreviewList($message)
1934
    {
1935
        $messageId = $message['id'];
1936
1937
        $list = [];
1938
1939
        if (empty($message['group_id'])) {
1940
            $files = MessageManager::getAttachmentList($messageId);
1941
            if ($files) {
1942
                $downloadUrl = api_get_path(WEB_CODE_PATH).'social/download.php?message_id='.$messageId;
1943
                foreach ($files as $row_file) {
1944
                    $url = $downloadUrl.'&attachment_id='.$row_file['id'];
1945
                    $display = Display::fileHtmlGuesser($row_file['filename'], $url);
1946
                    $list[] = $display;
1947
                }
1948
            }
1949
        } else {
1950
            $list = MessageManager::getAttachmentLinkList($messageId);
1951
        }
1952
1953
        return $list;
1954
    }
1955
1956
    /**
1957
     * @param array $message
1958
     *
1959
     * @return string
1960
     */
1961
    public static function getPostAttachment($message)
1962
    {
1963
        $previews = self::getAttachmentPreviewList($message);
1964
1965
        if (empty($previews)) {
1966
            return '';
1967
        }
1968
1969
        return implode('', $previews);
1970
    }
1971
1972
    /**
1973
     * @param array $messages
1974
     *
1975
     * @return array
1976
     */
1977
    public static function formatWallMessages($messages)
1978
    {
1979
        $data = [];
1980
        $users = [];
1981
        foreach ($messages as $key => $message) {
1982
            $userIdLoop = $message['user_sender_id'];
1983
            $userFriendIdLoop = $message['user_receiver_id'];
1984
            if (!isset($users[$userIdLoop])) {
1985
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1986
            }
1987
1988
            if (!isset($users[$userFriendIdLoop])) {
1989
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
1990
            }
1991
1992
            $html = self::headerMessagePost(
1993
                $users[$userIdLoop],
1994
                $users[$userFriendIdLoop],
1995
                $message
1996
            );
1997
1998
            $data[$key] = $message;
1999
            $data[$key]['html'] = $html;
2000
        }
2001
2002
        return $data;
2003
    }
2004
2005
    /**
2006
     * get html data with OpenGrap passing the URL.
2007
     *
2008
     * @param $link url
2009
     *
2010
     * @return string data html
2011
     */
2012
    public static function readContentWithOpenGraph($link)
2013
    {
2014
        if (strpos($link, "://") === false && substr($link, 0, 1) != "/") {
2015
            $link = "http://".$link;
2016
        }
2017
        $graph = OpenGraph::fetch($link);
2018
        $link = parse_url($link);
2019
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
2020
        if (!$graph) {
2021
            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...
2022
        }
2023
        $url = $graph->url;
2024
        $image = $graph->image;
2025
        $description = $graph->description;
2026
        $title = $graph->title;
2027
        $html = '<div class="thumbnail social-thumbnail">';
2028
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
2029
                <img class="img-responsive social-image" src="'.$image.'" /></a>';
2030
        $html .= '<div class="social-description">';
2031
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
2032
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
2033
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
2034
        $html .= '</div>';
2035
        $html .= '</div>';
2036
2037
        return $html;
2038
    }
2039
2040
    /**
2041
     * verify if Url Exist - Using Curl.
2042
     *
2043
     * @param $uri url
2044
     *
2045
     * @return bool
2046
     */
2047
    public static function verifyUrl($uri)
2048
    {
2049
        $curl = curl_init($uri);
2050
        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

2050
        curl_setopt(/** @scrutinizer ignore-type */ $curl, CURLOPT_FAILONERROR, true);
Loading history...
2051
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
2052
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2053
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
2054
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
2055
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
2056
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
2057
        $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

2057
        $response = curl_exec(/** @scrutinizer ignore-type */ $curl);
Loading history...
2058
        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

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

3083
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
3084
            getNotificationsPerUser($userId, true, $forumCourseId);
3085
            $notification = Session::read('forum_notification');
3086
            Session::erase('forum_notification');
3087
3088
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
3089
                'cidReq' => $courseInfo['code'],
3090
            ]).'&';
3091
            if (isset($notification['thread']) && !empty($notification['thread'])) {
3092
                $threadList = array_filter(array_unique($notification['thread']));
3093
                $em = Database::getManager();
3094
                $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
3095
                foreach ($threadList as $threadId) {
3096
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
3097
                    $thread = $repo->find($threadId);
3098
                    if ($thread) {
3099
                        $threadUrl = $threadUrlBase.http_build_query([
3100
                            '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

3100
                            '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...
3101
                            'thread' => $thread->getIid(),
3102
                        ]);
3103
                        $threads[] = [
3104
                            'id' => $threadId,
3105
                            'url' => Display::url(
3106
                                $thread->getThreadTitle(),
3107
                                $threadUrl
3108
                            ),
3109
                            'name' => Display::url(
3110
                                $thread->getThreadTitle(),
3111
                                $threadUrl
3112
                            ),
3113
                            'description' => '',
3114
                        ];
3115
                    }
3116
                }
3117
            }
3118
        }
3119
3120
        return $threads;
3121
    }
3122
3123
    /**
3124
     * @param int $userId
3125
     *
3126
     * @return string
3127
     */
3128
    public static function getGroupBlock($userId)
3129
    {
3130
        $threadList = self::getThreadList($userId);
3131
        $userGroup = new UserGroup();
3132
3133
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3134
        $courseInfo = null;
3135
        if (!empty($forumCourseId)) {
3136
            $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

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