Completed
Push — master ( 8b2aa0...562606 )
by Julito
09:06
created

SocialManager::getWallMessages()   F

Complexity

Conditions 22
Paths 5616

Size

Total Lines 189
Code Lines 105

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 105
nc 5616
nop 9
dl 0
loc 189
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

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

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

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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

265
                /** @scrutinizer ignore-type */ $messageId,
Loading history...
266
                Notification::NOTIFICATION_TYPE_INVITATION,
267
                [$friend_id],
268
                $message_title,
269
                $message_content,
270
                $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

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

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

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

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

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

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

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

2031
        curl_setopt(/** @scrutinizer ignore-type */ $curl, CURLOPT_FAILONERROR, true);
Loading history...
2032
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
2033
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2034
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
2035
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
2036
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
2037
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
2038
        $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

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

2039
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
2040
        if (!empty($response)) {
2041
            return true;
2042
        }
2043
2044
        return false;
2045
    }
2046
2047
    /**
2048
     * Soft delete a message and his chidren.
2049
     *
2050
     * @param int $id id message to delete
2051
     *
2052
     * @return bool status query
2053
     */
2054
    public static function deleteMessage($id)
2055
    {
2056
        $id = (int) $id;
2057
        $messageInfo = MessageManager::get_message_by_id($id);
2058
        if (!empty($messageInfo)) {
2059
            // Delete comments too
2060
            $messages = MessageManager::getMessagesByParent($id);
2061
            if (!empty($messages)) {
2062
                foreach ($messages as $message) {
2063
                    self::deleteMessage($message['id']);
2064
                }
2065
            }
2066
2067
            // Soft delete message
2068
            $tblMessage = Database::get_main_table(TABLE_MESSAGE);
2069
            $statusMessage = MESSAGE_STATUS_WALL_DELETE;
2070
            $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
2071
            Database::query($sql);
2072
2073
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_sender_id']);
2074
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_receiver_id']);
2075
2076
            return true;
2077
        }
2078
2079
        return false;
2080
    }
2081
2082
    /**
2083
     * Generate the social block for a user.
2084
     *
2085
     * @param Template $template
2086
     * @param int      $userId            The user id
2087
     * @param string   $groupBlock        Optional. Highlight link possible values:
2088
     *                                    group_add, home, messages, messages_inbox, messages_compose,
2089
     *                                    messages_outbox, invitations, shared_profile, friends, groups, search
2090
     * @param int      $groupId           Optional. Group ID
2091
     * @param bool     $show_full_profile
2092
     *
2093
     * @return string The HTML code with the social block
2094
     */
2095
    public static function setSocialUserBlock(
2096
        Template $template,
2097
        $userId,
2098
        $groupBlock = '',
2099
        $groupId = 0,
2100
        $show_full_profile = true
2101
    ) {
2102
        if (api_get_setting('allow_social_tool') != 'true') {
2103
            return '';
2104
        }
2105
2106
        $currentUserId = api_get_user_id();
2107
        $userId = (int) $userId;
2108
        $userRelationType = 0;
2109
2110
        $socialAvatarBlock = self::show_social_avatar_block(
2111
            $groupBlock,
2112
            $groupId,
2113
            $userId
2114
        );
2115
2116
        $profileEditionLink = null;
2117
        if ($currentUserId === $userId) {
2118
            $profileEditionLink = Display::getProfileEditionLink($userId);
2119
        } else {
2120
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
2121
        }
2122
2123
        $options = api_get_configuration_value('profile_fields_visibility');
2124
        if (isset($options['options'])) {
2125
            $options = $options['options'];
2126
        }
2127
2128
        $vCardUserLink = Display::getVCardUserLink($userId);
2129
        if (isset($options['vcard']) && $options['vcard'] === false) {
2130
            $vCardUserLink = '';
2131
        }
2132
2133
        $userInfo = api_get_user_info($userId, true, false, true, true);
2134
2135
        if (isset($options['firstname']) && $options['firstname'] === false) {
2136
            $userInfo['firstname'] = '';
2137
        }
2138
        if (isset($options['lastname']) && $options['lastname'] === false) {
2139
            $userInfo['lastname'] = '';
2140
        }
2141
2142
        if (isset($options['email']) && $options['email'] === false) {
2143
            $userInfo['email'] = '';
2144
        }
2145
2146
        // Ofaj
2147
        $hasCertificates = Certificate::getCertificateByUser($userId);
2148
        $userInfo['has_certificates'] = 0;
2149
        if (!empty($hasCertificates)) {
2150
            $userInfo['has_certificates'] = 1;
2151
        }
2152
2153
        $userInfo['is_admin'] = UserManager::is_admin($userId);
2154
2155
        $languageId = api_get_language_id($userInfo['language']);
2156
        $languageInfo = api_get_language_info($languageId);
2157
        if ($languageInfo) {
2158
            $userInfo['language'] = [
2159
                'label' => $languageInfo['original_name'],
2160
                'value' => $languageInfo['english_name'],
2161
                'code' => $languageInfo['isocode'],
2162
            ];
2163
        }
2164
2165
        if (isset($options['language']) && $options['language'] === false) {
2166
            $userInfo['language'] = '';
2167
        }
2168
2169
        if (isset($options['photo']) && $options['photo'] === false) {
2170
            $socialAvatarBlock = '';
2171
        }
2172
2173
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
2174
        $showLanguageFlag = api_get_configuration_value('social_show_language_flag_in_profile');
2175
2176
        $template->assign('user', $userInfo);
2177
        $template->assign('show_language_flag', $showLanguageFlag);
2178
        $template->assign('extra_info', $extraFieldBlock);
2179
        $template->assign('social_avatar_block', $socialAvatarBlock);
2180
        $template->assign('profile_edition_link', $profileEditionLink);
2181
        //Added the link to export the vCard to the Template
2182
2183
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
2184
        if ($show_full_profile) {
2185
            $template->assign('vcard_user_link', $vCardUserLink);
2186
        }
2187
2188
        if (api_get_setting('gamification_mode') === '1') {
2189
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
2190
                $userId,
2191
                $userInfo['status']
2192
            );
2193
2194
            $template->assign('gamification_points', $gamificationPoints);
2195
        }
2196
        $chatEnabled = api_is_global_chat_enabled();
2197
2198
        if (isset($options['chat']) && $options['chat'] === false) {
2199
            $chatEnabled = '';
2200
        }
2201
2202
        $template->assign('chat_enabled', $chatEnabled);
2203
        $template->assign('user_relation', $userRelationType);
2204
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
2205
        $template->assign('show_full_profile', $show_full_profile);
2206
2207
        $templateName = $template->get_template('social/user_block.tpl');
2208
2209
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
2210
            $templateName = $template->get_template('social/group_block.tpl');
2211
        }
2212
2213
        $template->assign('social_avatar_block', $template->fetch($templateName));
2214
    }
2215
2216
    /**
2217
     * @param int $user_id
2218
     * @param $link_shared
2219
     * @param bool $showLinkToChat
2220
     *
2221
     * @return string
2222
     */
2223
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
2224
    {
2225
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
2226
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
2227
        $numberFriends = count($friends);
2228
        $friendHtml = '';
2229
2230
        if (!empty($numberFriends)) {
2231
            $friendHtml .= '<div class="list-group contact-list">';
2232
            $j = 1;
2233
2234
            usort(
2235
                $friends,
2236
                function ($a, $b) {
2237
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
2238
                }
2239
            );
2240
2241
            foreach ($friends as $friend) {
2242
                if ($j > $numberFriends) {
2243
                    break;
2244
                }
2245
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2246
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2247
2248
                $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
2249
                $status = 0;
2250
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
2251
                    $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
2252
                    $status = 1;
2253
                }
2254
2255
                $friendAvatarMedium = UserManager::getUserPicture(
2256
                    $friend['friend_user_id'],
2257
                    USER_IMAGE_SIZE_MEDIUM
2258
                );
2259
                $friendAvatarSmall = UserManager::getUserPicture(
2260
                    $friend['friend_user_id'],
2261
                    USER_IMAGE_SIZE_SMALL
2262
                );
2263
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
2264
2265
                $relation = self::get_relation_between_contacts(
2266
                    $friend['friend_user_id'],
2267
                    api_get_user_id()
2268
                );
2269
2270
                if ($showLinkToChat) {
2271
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
2272
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2273
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2274
                } else {
2275
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
2276
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
2277
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2278
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2279
                }
2280
2281
                $friendHtml .= '</a>';
2282
2283
                $j++;
2284
            }
2285
            $friendHtml .= '</div>';
2286
        } else {
2287
            $friendHtml = Display::return_message(get_lang('NoFriendsInYourContactList'), 'warning');
2288
        }
2289
2290
        return $friendHtml;
2291
    }
2292
2293
    /**
2294
     * @return string Get the JS code necessary for social wall to load open graph from URLs.
2295
     */
2296
    public static function getScriptToGetOpenGraph()
2297
    {
2298
        return '<script>
2299
            $(function() {
2300
                $("[name=\'social_wall_new_msg_main\']").on("paste", function(e) {
2301
                    $.ajax({
2302
                        contentType: "application/x-www-form-urlencoded",
2303
                        beforeSend: function() {
2304
                            $("[name=\'wall_post_button\']").prop( "disabled", true );
2305
                            $(".panel-preview").hide();
2306
                            $(".spinner").html("'
2307
                                .'<div class=\'text-center\'>'
2308
                                .'<em class=\'fa fa-spinner fa-pulse fa-1x\'></em>'
2309
                                .'<p>'.get_lang('Loading').' '.get_lang('Preview').'</p>'
2310
                                .'</div>'
2311
                            .'");
2312
                        },
2313
                        type: "POST",
2314
                        url: "'.api_get_path(WEB_AJAX_PATH).'social.ajax.php?a=read_url_with_open_graph",
2315
                        data: "social_wall_new_msg_main=" + e.originalEvent.clipboardData.getData("text"),
2316
                        success: function(response) {
2317
                            $("[name=\'wall_post_button\']").prop("disabled", false);
2318
                            if (!response == false) {
2319
                                $(".spinner").html("");
2320
                                $(".panel-preview").show();
2321
                                $(".url_preview").html(response);
2322
                                $("[name=\'url_content\']").val(response);
2323
                                $(".url_preview img").addClass("img-responsive");
2324
                            } else {
2325
                                $(".spinner").html("");
2326
                            }
2327
                        }
2328
                    });
2329
                });
2330
            });
2331
        </script>';
2332
    }
2333
2334
    /**
2335
     * @param string $urlForm
2336
     *
2337
     * @return string
2338
     */
2339
    public static function getWallForm($urlForm)
2340
    {
2341
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
2342
        $form = new FormValidator(
2343
            'social_wall_main',
2344
            'post',
2345
            $urlForm.$userId,
2346
            null,
2347
            ['enctype' => 'multipart/form-data'],
2348
            FormValidator::LAYOUT_HORIZONTAL
2349
        );
2350
2351
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
2352
            'SocialWallWhatAreYouThinkingAbout'
2353
        );
2354
2355
        $form->addTextarea(
2356
            'social_wall_new_msg_main',
2357
            null,
2358
            [
2359
                'placeholder' => $socialWallPlaceholder,
2360
                'cols-size' => [1, 12, 1],
2361
                'aria-label' => $socialWallPlaceholder,
2362
            ]
2363
        );
2364
        $form->addHtml('<div class="form-group">');
2365
        $form->addHtml('<div class="col-sm-6">');
2366
        $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
2367
        $form->addHtml('</div>');
2368
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
2369
        $form->addButtonSend(
2370
            get_lang('Post'),
2371
            'wall_post_button',
2372
            false,
2373
            [
2374
                'cols-size' => [1, 10, 1],
2375
                'custom' => true,
2376
            ]
2377
        );
2378
        $form->addHtml('</div></div>');
2379
        $form->addHtml('</div>');
2380
        $form->addHidden('url_content', '');
2381
        $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
2382
2383
        return $html;
2384
    }
2385
2386
    /**
2387
     * @param int   $userId
2388
     * @param int   $start
2389
     * @param int   $length
2390
     * @param array $threadList
2391
     *
2392
     * @return array
2393
     */
2394
    public static function getMyWallMessages($userId, $start = 0, $length = 10, $threadList = [])
2395
    {
2396
        $userGroup = new UserGroup();
2397
        $groups = $userGroup->get_groups_by_user($userId, [GROUP_USER_PERMISSION_READER, GROUP_USER_PERMISSION_ADMIN]);
2398
        $groupList = [];
2399
        if (!empty($groups)) {
2400
            $groupList = array_column($groups, 'id');
2401
        }
2402
2403
        $friends = self::get_friends($userId, USER_RELATION_TYPE_FRIEND);
2404
        $friendList = [];
2405
        if (!empty($friends)) {
2406
            $friendList = array_column($friends, 'friend_user_id');
2407
        }
2408
2409
        $messages = self::getWallMessages(
2410
            $userId,
2411
            0,
2412
            $groupList,
2413
            $friendList,
2414
            '',
2415
            $start,
2416
            $length,
2417
            false,
2418
            $threadList
2419
        );
2420
2421
        $countPost = self::getCountWallMessagesByUser($userId, $groupList, $friendList, $threadList);
2422
        $messages = self::formatWallMessages($messages);
0 ignored issues
show
Bug introduced by
It seems like $messages can also be of type integer; however, parameter $messages of SocialManager::formatWallMessages() 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

2422
        $messages = self::formatWallMessages(/** @scrutinizer ignore-type */ $messages);
Loading history...
2423
2424
        $html = '';
2425
        foreach ($messages as $message) {
2426
            $post = $message['html'];
2427
            $comments = '';
2428
            if (in_array($message['msg_status'], [MESSAGE_STATUS_WALL_POST, MESSAGE_STATUS_PROMOTED])) {
2429
                $comments = self::getWallPostComments($userId, $message);
2430
            }
2431
2432
            $html .= self::wrapPost($message, $post.$comments);
2433
        }
2434
2435
        return [
2436
            'posts' => $html,
2437
            'count' => $countPost,
2438
        ];
2439
    }
2440
2441
    /**
2442
     * @param string $message
2443
     * @param string $content
2444
     *
2445
     * @return string
2446
     */
2447
    public static function wrapPost($message, $content)
2448
    {
2449
        $class = '';
2450
        if ($message['msg_status'] === MESSAGE_STATUS_PROMOTED) {
2451
            $class = 'promoted_post';
2452
        }
2453
2454
        return Display::panel($content, '',
2455
            '',
2456
            'default',
2457
            '',
2458
            'post_'.$message['id'],
2459
            null,
2460
            $class
2461
        );
2462
    }
2463
2464
    /**
2465
     * @param int   $userId
2466
     * @param array $groupList
2467
     * @param array $friendList
2468
     * @param array $threadList
2469
     *
2470
     * @return int
2471
     */
2472
    public static function getCountWallMessagesByUser($userId, $groupList = [], $friendList = [], $threadList = [])
2473
    {
2474
        $count = self::getWallMessages(
2475
            $userId,
2476
            0,
2477
            $groupList,
2478
            $friendList,
2479
            '',
2480
            0,
2481
            0,
2482
            true,
2483
            $threadList
2484
        );
2485
2486
        return $count;
2487
    }
2488
2489
    /**
2490
     * @param int $userId
2491
     *
2492
     * @return string
2493
     */
2494
    public static function getWallMessagesByUser($userId)
2495
    {
2496
        $messages = self::getWallMessages($userId);
2497
        $messages = self::formatWallMessages($messages);
0 ignored issues
show
Bug introduced by
It seems like $messages can also be of type integer; however, parameter $messages of SocialManager::formatWallMessages() 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

2497
        $messages = self::formatWallMessages(/** @scrutinizer ignore-type */ $messages);
Loading history...
2498
2499
        $html = '';
2500
        foreach ($messages as $message) {
2501
            $post = $message['html'];
2502
            $comments = self::getWallPostComments($userId, $message);
2503
            $html .= self::wrapPost($message, $post.$comments);
2504
        }
2505
2506
        return $html;
2507
    }
2508
2509
    /**
2510
     * Get HTML code block for user skills.
2511
     *
2512
     * @param int    $userId      The user ID
2513
     * @param string $orientation
2514
     *
2515
     * @return string
2516
     */
2517
    public static function getSkillBlock($userId, $orientation = 'horizontal')
2518
    {
2519
        if (Skill::isAllowed($userId, false) === false) {
2520
            return '';
2521
        }
2522
2523
        $skill = new Skill();
2524
        $ranking = $skill->getUserSkillRanking($userId);
2525
2526
        $template = new Template(null, false, false, false, false, false);
2527
        $template->assign('ranking', $ranking);
2528
        $template->assign('orientation', $orientation);
2529
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
2530
        $template->assign('user_id', $userId);
2531
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
2532
2533
        $skillBlock = $template->get_template('social/skills_block.tpl');
2534
2535
        return $template->fetch($skillBlock);
2536
    }
2537
2538
    /**
2539
     * @param int  $user_id
2540
     * @param bool $isArray
2541
     *
2542
     * @return string|array
2543
     */
2544
    public static function getExtraFieldBlock($user_id, $isArray = false)
2545
    {
2546
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
2547
        $fieldVisibilityKeys = [];
2548
        if (isset($fieldVisibility['options'])) {
2549
            $fieldVisibility = $fieldVisibility['options'];
2550
            $fieldVisibilityKeys = array_keys($fieldVisibility);
2551
        }
2552
2553
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
2554
        $extra_user_data = UserManager::get_extra_user_data($user_id);
2555
2556
        $extra_information = '';
2557
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
2558
            $extra_information_value = '';
2559
            $extraField = new ExtraField('user');
2560
            $listType = [];
2561
            $extraFieldItem = [];
2562
            foreach ($extra_user_data as $key => $data) {
2563
                if (empty($data)) {
2564
                    continue;
2565
                }
2566
                if (in_array($key, $fieldVisibilityKeys) && $fieldVisibility[$key] === false) {
2567
                    continue;
2568
                }
2569
2570
                // Avoiding parameters
2571
                if (in_array(
2572
                    $key,
2573
                    [
2574
                        'mail_notify_invitation',
2575
                        'mail_notify_message',
2576
                        'mail_notify_group_message',
2577
                    ]
2578
                )) {
2579
                    continue;
2580
                }
2581
                // get display text, visibility and type from user_field table
2582
                $field_variable = str_replace('extra_', '', $key);
2583
2584
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
2585
                    $field_variable
2586
                );
2587
2588
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
2589
                    continue;
2590
                }
2591
2592
                // if is not visible skip
2593
                if ($extraFieldInfo['visible_to_self'] != 1) {
2594
                    continue;
2595
                }
2596
2597
                // if is not visible to others skip also
2598
                if ($extraFieldInfo['visible_to_others'] != 1) {
2599
                    continue;
2600
                }
2601
2602
                if (is_array($data)) {
2603
                    switch ($extraFieldInfo['field_type']) {
2604
                        case ExtraField::FIELD_TYPE_RADIO:
2605
                            $objEfOption = new ExtraFieldOption('user');
2606
                            $value = $data['extra_'.$extraFieldInfo['variable']];
2607
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
2608
                                $extraFieldInfo['id'],
2609
                                $value
2610
                            );
2611
2612
                            if ($optionInfo && isset($optionInfo[0])) {
2613
                                $optionInfo = $optionInfo[0];
2614
                                $extraFieldItem = [
2615
                                    'variable' => $extraFieldInfo['variable'],
2616
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2617
                                    'value' => $optionInfo['display_text'],
2618
                                ];
2619
                            } else {
2620
                                $extraFieldItem = [
2621
                                    'variable' => $extraFieldInfo['variable'],
2622
                                    'label' => ucfirst($extraFieldInfo['display_text']),
2623
                                    'value' => implode(',', $data),
2624
                                ];
2625
                            }
2626
                            break;
2627
                        default:
2628
                            $extra_information_value .=
2629
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
2630
                                .' '.implode(',', $data).'</li>';
2631
                            $extraFieldItem = [
2632
                                'variable' => $extraFieldInfo['variable'],
2633
                                'label' => ucfirst($extraFieldInfo['display_text']),
2634
                                'value' => implode(',', $data),
2635
                            ];
2636
                            break;
2637
                    }
2638
                } else {
2639
                    switch ($extraFieldInfo['field_type']) {
2640
                        case ExtraField::FIELD_TYPE_RADIO:
2641
                            $objEfOption = new ExtraFieldOption('user');
2642
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
2643
                            break;
2644
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
2645
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
2646
                            $data = explode('::', $data);
2647
                            $data = $data[0];
2648
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2649
                            $extraFieldItem = [
2650
                                'variable' => $extraFieldInfo['variable'],
2651
                                'label' => ucfirst($extraFieldInfo['display_text']),
2652
                                'value' => $data,
2653
                            ];
2654
                            break;
2655
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
2656
                            $id_options = explode('::', $data);
2657
                            $value_options = [];
2658
                            // get option display text from user_field_options table
2659
                            foreach ($id_options as $id_option) {
2660
                                $sql = "SELECT display_text 
2661
                                    FROM $t_ufo 
2662
                                    WHERE id = '$id_option'";
2663
                                $res_options = Database::query($sql);
2664
                                $row_options = Database::fetch_row($res_options);
2665
                                $value_options[] = $row_options[0];
2666
                            }
2667
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2668
                                .' '.implode(' ', $value_options).'</li>';
2669
                            $extraFieldItem = [
2670
                                'variable' => $extraFieldInfo['variable'],
2671
                                'label' => ucfirst($extraFieldInfo['display_text']),
2672
                                'value' => $value_options,
2673
                            ];
2674
                            break;
2675
                        case ExtraField::FIELD_TYPE_TAG:
2676
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
2677
2678
                            $tag_tmp = '';
2679
                            foreach ($user_tags as $tags) {
2680
                                $tag_tmp .= '<a class="label label_tag"'
2681
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
2682
                                    .$tags['tag']
2683
                                    .'</a>';
2684
                            }
2685
                            if (is_array($user_tags) && count($user_tags) > 0) {
2686
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
2687
                                    .' '.$tag_tmp.'</li>';
2688
                            }
2689
                            $extraFieldItem = [
2690
                                'variable' => $extraFieldInfo['variable'],
2691
                                'label' => ucfirst($extraFieldInfo['display_text']),
2692
                                'value' => $tag_tmp,
2693
                            ];
2694
                            break;
2695
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
2696
                            $icon_path = UserManager::get_favicon_from_url($data);
2697
                            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...
2698
                                break;
2699
                            }
2700
                            $bottom = '0.2';
2701
                            //quick hack for hi5
2702
                            $domain = parse_url($icon_path, PHP_URL_HOST);
2703
                            if ($domain == 'www.hi5.com' || $domain == 'hi5.com') {
2704
                                $bottom = '-0.8';
2705
                            }
2706
                            $data = '<a href="'.$data.'">'
2707
                                .'<img src="'.$icon_path.'" alt="icon"'
2708
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
2709
                                .$extraFieldInfo['display_text']
2710
                                .'</a>';
2711
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
2712
                            $extraFieldItem = [
2713
                                'variable' => $extraFieldInfo['variable'],
2714
                                'label' => ucfirst($extraFieldInfo['display_text']),
2715
                                'value' => $data,
2716
                            ];
2717
                            break;
2718
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
2719
                            $parsedData = explode('::', $data);
2720
2721
                            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...
2722
                                break;
2723
                            }
2724
2725
                            $objEfOption = new ExtraFieldOption('user');
2726
                            $optionInfo = $objEfOption->get($parsedData[0]);
2727
2728
                            $extra_information_value .= '<li class="list-group-item">'
2729
                                .$optionInfo['display_text'].': '
2730
                                .$parsedData[1].'</li>';
2731
                            $extraFieldItem = [
2732
                                'variable' => $extraFieldInfo['variable'],
2733
                                'label' => ucfirst($extraFieldInfo['display_text']),
2734
                                'value' => $parsedData[1],
2735
                            ];
2736
                            break;
2737
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
2738
                            $optionIds = explode(';', $data);
2739
                            $optionValues = [];
2740
2741
                            foreach ($optionIds as $optionId) {
2742
                                $objEfOption = new ExtraFieldOption('user');
2743
                                $optionInfo = $objEfOption->get($optionId);
2744
2745
                                $optionValues[] = $optionInfo['display_text'];
2746
                            }
2747
                            $extra_information_value .= '<li class="list-group-item">'
2748
                                .ucfirst($extraFieldInfo['display_text']).': '
2749
                                .implode(' ', $optionValues).'</li>';
2750
                            $extraFieldItem = [
2751
                                'variable' => $extraFieldInfo['variable'],
2752
                                'label' => ucfirst($extraFieldInfo['display_text']),
2753
                                'value' => implode(' ', $optionValues),
2754
                            ];
2755
                            break;
2756
                        default:
2757
                            // Ofaj
2758
                            // Converts "Date of birth" into "age"
2759
                            if ($key === 'terms_datedenaissance') {
2760
                                $dataArray = date_to_str_ago($data, 'UTC', true);
2761
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
2762
                                if (!empty($dataToString)) {
2763
                                    $data = $dataToString;
2764
                                    $extraFieldInfo['display_text'] = get_lang('Age');
2765
                                }
2766
                            }
2767
2768
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
2769
                            $extraFieldItem = [
2770
                                'variable' => $extraFieldInfo['variable'],
2771
                                'label' => ucfirst($extraFieldInfo['display_text']),
2772
                                'value' => $data,
2773
                            ];
2774
                            break;
2775
                    }
2776
                }
2777
2778
                $listType[] = $extraFieldItem;
2779
            }
2780
2781
            if ($isArray) {
2782
                return $listType;
2783
            } else {
2784
                // if there are information to show
2785
                if (!empty($extra_information_value)) {
2786
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
2787
                    $extra_information .= Display::panelCollapse(
2788
                        get_lang('ExtraInformation'),
2789
                        $extra_information_value,
2790
                        'sn-extra-information',
2791
                        null,
2792
                        'sn-extra-accordion',
2793
                        'sn-extra-collapse'
2794
                    );
2795
                }
2796
            }
2797
        }
2798
2799
        return $extra_information;
2800
    }
2801
2802
    /**
2803
     * @param string $url
2804
     */
2805
    public static function handlePosts($url)
2806
    {
2807
        $friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
2808
        $url = Security::remove_XSS($url);
2809
2810
        // Main post
2811
        if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
2812
            $messageContent = $_POST['social_wall_new_msg_main'];
2813
            if (!empty($_POST['url_content'])) {
2814
                $messageContent = $_POST['social_wall_new_msg_main'].'<br /><br />'.$_POST['url_content'];
2815
            }
2816
2817
            $messageId = self::sendWallMessage(
2818
                api_get_user_id(),
2819
                $friendId,
2820
                $messageContent,
2821
                0,
2822
                MESSAGE_STATUS_WALL_POST
2823
            );
2824
2825
            if ($messageId && !empty($_FILES['picture']['tmp_name'])) {
2826
                self::sendWallMessageAttachmentFile(
2827
                    api_get_user_id(),
2828
                    $_FILES['picture'],
2829
                    $messageId
2830
                );
2831
            }
2832
2833
            Display::addFlash(Display::return_message(get_lang('MessageSent')));
2834
            header('Location: '.$url);
2835
            exit;
2836
        }
2837
    }
2838
2839
    /**
2840
     * @param int   $countPost
2841
     * @param array $htmlHeadXtra
2842
     */
2843
    public static function getScrollJs($countPost, &$htmlHeadXtra)
2844
    {
2845
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
2846
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
2847
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
2848
        $locale = api_get_language_isocode();
2849
2850
        // Add Jquery scroll pagination plugin
2851
        //$htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
2852
        // Add Jquery Time ago plugin
2853
        //$htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
2854
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
2855
        if (file_exists($timeAgoLocaleDir)) {
2856
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
2857
        }
2858
2859
        if ($countPost > self::DEFAULT_WALL_POSTS) {
2860
            $htmlHeadXtra[] = '<script>
2861
            $(function() {
2862
                var container = $("#wallMessages");
2863
                container.jscroll({
2864
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
2865
                    nextSelector: "a.nextPage:last",
2866
                    contentSelector: "",
2867
                    callback: timeAgo                    
2868
                });
2869
            });
2870
            </script>';
2871
        }
2872
2873
        $htmlHeadXtra[] = '<script>
2874
            function deleteMessage(id) 
2875
            {                      
2876
                $.ajax({
2877
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2878
                    success: function (result) {
2879
                        if (result) {
2880
                            $("#message_" + id).parent().parent().parent().parent().html(result);
2881
                        }
2882
                    }
2883
                });                        
2884
            }
2885
            
2886
            function deleteComment(id) 
2887
            {                      
2888
                $.ajax({
2889
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2890
                    success: function (result) {
2891
                        if (result) {
2892
                            $("#message_" + id).parent().parent().parent().html(result);
2893
                        }
2894
                    }
2895
                });                     
2896
            }           
2897
            
2898
            function submitComment(messageId) 
2899
            {
2900
                var data = $("#form_comment_"+messageId).serializeArray();                                
2901
                $.ajax({
2902
                    type : "POST",
2903
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
2904
                    data: data,
2905
                    success: function (result) {                        
2906
                        if (result) {
2907
                            $("#post_" + messageId + " textarea").val("");
2908
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
2909
                            $("#post_" + messageId + " .sub-mediapost").append(
2910
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved')).'</div>\')
2911
                            ); 
2912
                                                        
2913
                            $("#result_" + messageId + "").fadeIn("fast", function() {
2914
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
2915
                                    $(this).remove();
2916
                                }); 
2917
                            });
2918
                        }
2919
                    }
2920
                });  
2921
            } 
2922
            
2923
            $(function() {
2924
                timeAgo();
2925
                
2926
                /*$(".delete_message").on("click", function() {
2927
                    var id = $(this).attr("id");
2928
                    id = id.split("_")[1];          
2929
                    $.ajax({
2930
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2931
                        success: function (result) {
2932
                            if (result) {
2933
                                $("#message_" + id).parent().parent().parent().parent().html(result);
2934
                            }
2935
                        }
2936
                    });        
2937
                });                  
2938
                
2939
                
2940
                $(".delete_comment").on("click", function() {
2941
                    var id = $(this).attr("id");
2942
                    id = id.split("_")[1];                    
2943
                    $.ajax({
2944
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
2945
                        success: function (result) {
2946
                            if (result) {
2947
                                $("#message_" + id).parent().parent().parent().html(result);
2948
                            }
2949
                        }
2950
                    });
2951
                });          
2952
                */
2953
            });
2954
            
2955
            function timeAgo() {
2956
                $(".timeago").timeago();
2957
            }
2958
            </script>';
2959
    }
2960
2961
    /**
2962
     * @param int $userId
2963
     * @param int $countPost
2964
     *
2965
     * @return string
2966
     */
2967
    public static function getAutoExtendLink($userId, $countPost)
2968
    {
2969
        $userId = (int) $userId;
2970
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
2971
        $socialAutoExtendLink = '';
2972
        if ($countPost > self::DEFAULT_WALL_POSTS) {
2973
            $socialAutoExtendLink = Display::url(
2974
                get_lang('SeeMore'),
2975
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
2976
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
2977
                [
2978
                    'class' => 'nextPage next',
2979
                ]
2980
            );
2981
        }
2982
2983
        return $socialAutoExtendLink;
2984
    }
2985
2986
    /**
2987
     * @param int $userId
2988
     *
2989
     * @return array
2990
     */
2991
    public static function getThreadList($userId)
2992
    {
2993
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
2994
2995
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
2996
2997
        $threads = [];
2998
        if (!empty($forumCourseId)) {
2999
            $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

2999
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
3000
            getNotificationsPerUser($userId, true, $forumCourseId);
3001
            $notification = Session::read('forum_notification');
3002
            Session::erase('forum_notification');
3003
3004
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
3005
                'cidReq' => $courseInfo['code'],
3006
            ]).'&';
3007
            if (isset($notification['thread']) && !empty($notification['thread'])) {
3008
                $threadList = array_filter(array_unique($notification['thread']));
3009
                $em = Database::getManager();
3010
                $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
3011
                foreach ($threadList as $threadId) {
3012
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
3013
                    $thread = $repo->find($threadId);
3014
                    if ($thread) {
3015
                        $threadUrl = $threadUrlBase.http_build_query([
3016
                            '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

3016
                            '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...
3017
                            'thread' => $thread->getIid(),
3018
                        ]);
3019
                        $threads[] = [
3020
                            'id' => $threadId,
3021
                            'url' => Display::url(
3022
                                $thread->getThreadTitle(),
3023
                                $threadUrl
3024
                            ),
3025
                            'name' => Display::url(
3026
                                $thread->getThreadTitle(),
3027
                                $threadUrl
3028
                            ),
3029
                            'description' => '',
3030
                        ];
3031
                    }
3032
                }
3033
            }
3034
        }
3035
3036
        return $threads;
3037
    }
3038
3039
    /**
3040
     * @param int $userId
3041
     *
3042
     * @return string
3043
     */
3044
    public static function getGroupBlock($userId)
3045
    {
3046
        $threadList = self::getThreadList($userId);
3047
        $userGroup = new UserGroup();
3048
3049
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3050
        $courseInfo = null;
3051
        if (!empty($forumCourseId)) {
3052
            $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

3052
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
3053
        }
3054
3055
        $social_group_block = '';
3056
        if (!empty($courseInfo)) {
3057
            if (!empty($threadList)) {
3058
                $social_group_block .= '<div class="list-group">';
3059
                foreach ($threadList as $group) {
3060
                    $social_group_block .= ' <li class="list-group-item">';
3061
                    $social_group_block .= $group['name'];
3062
                    $social_group_block .= '</li>';
3063
                }
3064
                $social_group_block .= '</div>';
3065
            }
3066
3067
            $social_group_block .= Display::url(
3068
                get_lang('SeeAllCommunities'),
3069
                api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code']
3070
            );
3071
3072
            if (!empty($social_group_block)) {
3073
                $social_group_block = Display::panelCollapse(
3074
                    get_lang('MyCommunities'),
3075
                    $social_group_block,
3076
                    'sm-groups',
3077
                    null,
3078
                    'grups-acordion',
3079
                    'groups-collapse'
3080
                );
3081
            }
3082
        } else {
3083
            // Load my groups
3084
            $results = $userGroup->get_groups_by_user(
3085
                $userId,
3086
                [
3087
                    GROUP_USER_PERMISSION_ADMIN,
3088
                    GROUP_USER_PERMISSION_READER,
3089
                    GROUP_USER_PERMISSION_MODERATOR,
3090
                    GROUP_USER_PERMISSION_HRM,
3091
                ]
3092
            );
3093
3094
            $myGroups = [];
3095
            if (!empty($results)) {
3096
                foreach ($results as $result) {
3097
                    $id = $result['id'];
3098
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
3099
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
3100
3101
                    $group_url = "group_view.php?id=$id";
3102
3103
                    $link = Display::url(
3104
                        api_ucwords(cut($result['name'], 40, true)),
3105
                        $group_url
3106
                    );
3107
3108
                    $result['name'] = $link;
3109
3110
                    $picture = $userGroup->get_picture_group(
3111
                        $id,
3112
                        $result['picture'],
3113
                        null,
3114
                        GROUP_IMAGE_SIZE_BIG
3115
                    );
3116
3117
                    $result['picture'] = '<img class="img-responsive" src="'.$picture['file'].'" />';
3118
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
3119
                        get_lang('SeeMore').'</a></div>';
3120
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
3121
                    $myGroups[] = [
3122
                        'url' => Display::url(
3123
                            $result['picture'],
3124
                            $group_url
3125
                        ),
3126
                        'name' => $result['name'],
3127
                        'description' => $group_info.$group_actions,
3128
                    ];
3129
                }
3130
3131
                $social_group_block .= '<div class="list-group">';
3132
                foreach ($myGroups as $group) {
3133
                    $social_group_block .= ' <li class="list-group-item">';
3134
                    $social_group_block .= $group['name'];
3135
                    $social_group_block .= '</li>';
3136
                }
3137
                $social_group_block .= '</div>';
3138
3139
                $form = new FormValidator(
3140
                    'find_groups_form',
3141
                    'get',
3142
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
3143
                    null,
3144
                    null,
3145
                    FormValidator::LAYOUT_BOX_NO_LABEL
3146
                );
3147
                $form->addHidden('search_type', 2);
3148
3149
                $form->addText(
3150
                    'q',
3151
                    get_lang('Search'),
3152
                    false,
3153
                    [
3154
                        'aria-label' => get_lang('Search'),
3155
                        'custom' => true,
3156
                        'placeholder' => get_lang('Search'),
3157
                    ]
3158
                );
3159
3160
                $social_group_block .= $form->returnForm();
3161
3162
                if (!empty($social_group_block)) {
3163
                    $social_group_block = Display::panelCollapse(
3164
                        get_lang('MyGroups'),
3165
                        $social_group_block,
3166
                        'sm-groups',
3167
                        null,
3168
                        'grups-acordion',
3169
                        'groups-collapse'
3170
                    );
3171
                }
3172
            }
3173
        }
3174
3175
        return $social_group_block;
3176
    }
3177
3178
    /**
3179
     * Returns the formatted header message post.
3180
     *
3181
     * @param int   $authorInfo
3182
     * @param int   $receiverInfo
3183
     * @param array $message      Message data
3184
     *
3185
     * @return string $html       The formatted header message post
3186
     */
3187
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
3188
    {
3189
        $currentUserId = api_get_user_id();
3190
        $authorId = (int) $authorInfo['user_id'];
3191
        $receiverId = (int) $receiverInfo['user_id'];
3192
        $iconStatus = $authorInfo['icon_status'];
3193
3194
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
3195
        $avatarAuthor = $authorInfo['avatar'];
3196
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
3197
        $nameCompleteAuthor = $authorInfo['complete_name'];
3198
3199
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
3200
        $nameCompleteReceiver = $receiverInfo['complete_name'];
3201
3202
        $htmlReceiver = '';
3203
        if ($authorId !== $receiverId) {
3204
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
3205
        }
3206
3207
        if (!empty($message['group_info'])) {
3208
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
3209
        }
3210
        $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...
3211
3212
        if (!empty($message['thread_id'])) {
3213
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
3214
            $canEdit = false;
3215
        }
3216
3217
        $postAttachment = self::getPostAttachment($message);
3218
3219
        $html = '<div class="top-mediapost" >';
3220
        $html .= '<div class="pull-right btn-group btn-group-sm">';
3221
3222
        $html .= MessageManager::getLikesButton(
3223
            $message['id'],
3224
            $currentUserId,
3225
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
3226
        );
3227
3228
        if ($canEdit) {
3229
            $htmlDelete = Display::url(
3230
                Display::returnFontAwesomeIcon('trash', '', true),
3231
                'javascript:void(0)',
3232
                [
3233
                    'id' => 'message_'.$message['id'],
3234
                    'title' => get_lang('SocialMessageDelete'),
3235
                    'onclick' => 'deleteMessage('.$message['id'].')',
3236
                    'class' => 'btn btn-default',
3237
                ]
3238
            );
3239
3240
            $html .= $htmlDelete;
3241
        }
3242
        $html .= '</div>';
3243
3244
        $html .= '<div class="user-image" >';
3245
        $html .= '<a href="'.$urlAuthor.'">
3246
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
3247
        $html .= '</div>';
3248
        $html .= '<div class="user-data">';
3249
        $html .= $iconStatus;
3250
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
3251
        $html .= '<div class="post-date">'.$date.'</div>';
3252
        $html .= '</div>';
3253
        $html .= '<div class="msg-content">';
3254
        if (!empty($postAttachment)) {
3255
            $html .= '<div class="post-attachment thumbnail">';
3256
            $html .= $postAttachment;
3257
            $html .= '</div>';
3258
        }
3259
        $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
3260
        $html .= '</div>';
3261
        $html .= '</div>'; // end mediaPost
3262
3263
        // Popularity post functionality
3264
        $html .= '<div class="popularity-mediapost"></div>';
3265
3266
        return $html;
3267
    }
3268
}
3269