Passed
Push — master ( d0b226...f5358a )
by Julito
10:41
created

SocialManager   F

Complexity

Total Complexity 406

Size/Duplication

Total Lines 3689
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 1910
dl 0
loc 3689
rs 0.8
c 0
b 0
f 0
wmc 406

56 Methods

Rating   Name   Duplication   Size   Complexity  
A getCountFriends() 0 22 3
A getCountMessagesReceived() 0 11 1
A send_invitation_friend() 0 65 3
A get_relation_type_by_name() 0 6 3
A show_list_type_friends() 0 16 3
A get_relation_between_contacts() 0 22 2
A getCountWallPostedMessages() 0 20 2
A get_list_web_path_user_invitation_by_user_id() 0 12 2
A __construct() 0 2 1
A get_message_number_invitation_by_user_id() 0 15 2
B get_friends() 0 49 7
A getCountMessagesSent() 0 12 1
B getUserRssFeed() 0 49 11
A qualify_friend() 0 7 1
A get_list_invitation_sent_by_user_id() 0 21 3
B sendInvitationToUser() 0 43 10
C get_logged_user_course_html() 0 93 13
A invitation_accepted() 0 16 3
A get_list_invitation_of_friends_by_user_id() 0 25 5
A getCountInvitationSent() 0 22 3
A invitation_denied() 0 14 3
B readContentWithOpenGraph() 0 26 8
A show_social_avatar_block() 0 67 4
B get_plugins() 0 23 7
F show_social_menu() 0 386 49
F setSocialUserBlock() 0 117 23
B handlePosts() 0 31 7
A getWallForm() 0 46 3
A getWallPostComments() 0 40 3
F getExtraFieldBlock() 0 256 39
F getWallMessages() 0 175 18
B display_productions() 0 31 10
B listMyFriendsBlock() 0 66 7
A getCountWallMessagesByUser() 0 15 1
A wrapPost() 0 7 1
B display_individual_user() 0 55 9
A formatWallMessages() 0 26 4
A getWallMessagesByUser() 0 13 2
C getGroupBlock() 0 131 10
A getAttachmentPreviewList() 0 21 4
A social_wrapper_div() 0 9 1
A verifyUrl() 0 17 2
B listMyFriends() 0 62 9
A getSkillBlock() 0 19 4
A sendWallMessageAttachmentFile() 0 20 2
F headerMessagePost() 0 100 13
B getThreadList() 0 46 6
A getPostAttachment() 0 9 2
B processPostComment() 0 85 9
A sendWallMessage() 0 33 3
A getScrollJs() 0 102 3
F getMenuSocial() 0 347 37
A getAutoExtendLink() 0 17 2
A getMyWallMessages() 0 44 5
C display_user_list() 0 67 13
A deleteMessage() 0 26 4

How to fix   Complexity   

Complex Class

Complex classes like SocialManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SocialManager, and based on these observations, apply Extract Interface, too.

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

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

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

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

964
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
965
            if (!empty($courseInfo)) {
966
                $groupUrl = api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code'];
967
            }
968
        }
969
970
        $html = '';
971
        $active = null;
972
        $links = null;
973
974
        $itemMenu = [];
975
976
        if (!in_array(
977
            $show,
978
            ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
979
        )) {
980
            $itemMenu[0] = [
981
                'item' => get_lang('Home'),
982
                'url' => api_get_path(WEB_CODE_PATH).'social/home.php',
983
                'icon' => $homeIcon,
984
                'active' => ($show == 'home' ? 'active' : null),
985
            ];
986
987
            $itemMenu[1] = [
988
                'item' => get_lang('Messages').$count_unread_message,
989
                'url' => api_get_path(WEB_CODE_PATH).'messages/inbox.php',
990
                'icon' => $messagesIcon,
991
                'active' => ($show == 'messages' ? 'active' : null),
992
            ];
993
994
            $itemMenu[2] = [
995
                'item' => get_lang('Invitations').$total_invitations,
996
                'url' => api_get_path(WEB_CODE_PATH).'social/invitations.php',
997
                'icon' => $invitationsIcon,
998
                'active' => ($show == 'invitations' ? 'active' : null),
999
            ];
1000
1001
            $itemMenu[3] = [
1002
                'item' => get_lang('ViewMySharedProfile'),
1003
                'url' => api_get_path(WEB_CODE_PATH).'social/profile.php',
1004
                'icon' => $sharedProfileIcon,
1005
                'active' => ($show == 'shared_profile' ? 'active' : null),
1006
            ];
1007
1008
            $itemMenu[4] = [
1009
                'item' => get_lang('Friends'),
1010
                'url' => api_get_path(WEB_CODE_PATH).'social/friends.php',
1011
                'icon' => $friendsIcon,
1012
                'active' => ($show == 'friends' ? 'active' : null),
1013
            ];
1014
1015
            $itemMenu[5] = [
1016
                'item' => get_lang('SocialGroups'),
1017
                'url' => api_get_path(WEB_CODE_PATH).'social/groups.php',
1018
                'icon' => $groupsIcon,
1019
                'active' => ($show == 'browse_groups' ? 'active' : null),
1020
            ];
1021
1022
            $itemMenu[6] = [
1023
                'item' => get_lang('Search'),
1024
                'url' => api_get_path(WEB_CODE_PATH).'social/search.php',
1025
                'icon' => $searchIcon,
1026
                'active' => ($show == 'search' ? 'active' : null),
1027
            ];
1028
1029
            if (api_get_setting('allow_my_files') === 'false') {
1030
                $itemMenu[7] = [
1031
                    'item' => get_lang('MyFiles'),
1032
                    'url' => api_get_path(WEB_CODE_PATH).'social/myfiles.php',
1033
                    'icon' => $filesIcon,
1034
                    'active' => ($show == 'myfiles' ? 'active' : null),
1035
                ];
1036
            }
1037
1038
            if (api_get_configuration_value('allow_portfolio_tool')) {
1039
                $itemMenu[8] = [
1040
                    'item' => get_lang('Portfolio'),
1041
                    'url' => api_get_path(WEB_CODE_PATH).'portfolio/index.php',
1042
                    'icon' => $portfolioIcon,
1043
                    'active' => ($show == 'portfolio' ? 'active' : null),
1044
                ];
1045
            }
1046
1047
            if (!api_get_configuration_value('disable_gdpr')) {
1048
                $itemMenu[9] = [
1049
                    'item' => get_lang('PersonalDataReport'),
1050
                    'url' => api_get_path(WEB_CODE_PATH).'social/personal_data.php',
1051
                    'icon' => $personalDataIcon,
1052
                    'active' => ($show == 'personal-data' ? 'active' : null),
1053
                ];
1054
            }
1055
        }
1056
        //Move group menu to another function
1057
1058
        /*if (in_array($show, $show_groups) && !empty($group_id)) {
1059
            $html .= $usergroup->show_group_column_information(
1060
                $group_id,
1061
                api_get_user_id(),
1062
                $show
1063
            );
1064
        }*/
1065
1066
        if ($show == 'shared_profile') {
1067
            // My own profile
1068
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
1069
                $itemMenu[0] = [
1070
                    'item' => get_lang('Home'),
1071
                    'url' => api_get_path(WEB_CODE_PATH).'social/home.php',
1072
                    'icon' => $homeIcon,
1073
                    'active' => ($show == 'home' ? 'active' : null),
1074
                ];
1075
1076
                $itemMenu[1] = [
1077
                    'item' => get_lang('Messages').$count_unread_message,
1078
                    'url' => api_get_path(WEB_CODE_PATH).'messages/inbox.php',
1079
                    'icon' => $messagesIcon,
1080
                    'active' => ($show == 'messages' ? 'active' : null),
1081
                ];
1082
1083
                $itemMenu[2] = [
1084
                    'item' => get_lang('Invitations').$total_invitations,
1085
                    'url' => api_get_path(WEB_CODE_PATH).'social/invitations.php',
1086
                    'icon' => $invitationsIcon,
1087
                    'active' => ($show == 'invitations' ? 'active' : null),
1088
                ];
1089
1090
                $itemMenu[3] = [
1091
                    'item' => get_lang('ViewMySharedProfile'),
1092
                    'url' => api_get_path(WEB_CODE_PATH).'social/profile.php',
1093
                    'icon' => $sharedProfileIcon,
1094
                    'active' => ($show == 'shared_profile' ? 'active' : null),
1095
                ];
1096
1097
                $itemMenu[4] = [
1098
                    'item' => get_lang('Friends'),
1099
                    'url' => api_get_path(WEB_CODE_PATH).'social/friends.php',
1100
                    'icon' => $friendsIcon,
1101
                    'active' => ($show == 'friends' ? 'active' : null),
1102
                ];
1103
1104
                $itemMenu[5] = [
1105
                    'item' => get_lang('SocialGroups'),
1106
                    'url' => api_get_path(WEB_CODE_PATH).'social/groups.php',
1107
                    'icon' => $groupsIcon,
1108
                    'active' => ($show == 'browse_groups' ? 'active' : null),
1109
                ];
1110
1111
                $itemMenu[6] = [
1112
                    'item' => get_lang('Search'),
1113
                    'url' => api_get_path(WEB_CODE_PATH).'social/search.php',
1114
                    'icon' => $searchIcon,
1115
                    'active' => ($show == 'search' ? 'active' : null),
1116
                ];
1117
1118
                if (api_get_setting('allow_my_files') === 'false') {
1119
                    $itemMenu[7] = [
1120
                        'item' => get_lang('MyFiles'),
1121
                        'url' => api_get_path(WEB_CODE_PATH).'social/myfiles.php',
1122
                        'icon' => $filesIcon,
1123
                        'active' => ($show == 'myfiles' ? 'active' : null),
1124
                    ];
1125
                }
1126
1127
                if (api_get_configuration_value('allow_portfolio_tool')) {
1128
                    $itemMenu[8] = [
1129
                        'item' => get_lang('Portfolio'),
1130
                        'url' => api_get_path(WEB_CODE_PATH).'portfolio/index.php',
1131
                        'icon' => $portfolioIcon,
1132
                        'active' => ($show == 'portfolio' ? 'active' : null),
1133
                    ];
1134
                }
1135
            }
1136
1137
            // My friend profile.
1138
            if ($user_id != api_get_user_id()) {
1139
                $sendMessageIcon = Display::return_icon(
1140
                    'new-message.png',
1141
                    get_lang('SendMessage')
1142
                );
1143
                $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
1144
                    'a' => 'get_user_popup',
1145
                    'user_id' => $user_id,
1146
                ]);
1147
1148
                $itemMenu[1] = [
1149
                    'item' => get_lang('SendMessage'),
1150
                    'url' => $sendMessageUrl,
1151
                    'icon' => $sendMessageIcon,
1152
                    'class' => 'ajax',
1153
                ];
1154
                if (api_get_configuration_value('allow_portfolio_tool')) {
1155
                    $itemMenu[8] = [
1156
                        'item' => get_lang('Portfolio'),
1157
                        'url' => api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id,
1158
                        'icon' => $portfolioIcon,
1159
                        'active' => ($show == 'portfolio' ? 'active' : null),
1160
                    ];
1161
                }
1162
            }
1163
1164
            // Check if I already sent an invitation message
1165
            /*$invitation_sent_list = self::get_list_invitation_sent_by_user_id(
1166
                api_get_user_id()
1167
            );
1168
1169
            if (isset($invitation_sent_list[$user_id]) && is_array($invitation_sent_list[$user_id]) &&
1170
                count($invitation_sent_list[$user_id]) > 0
1171
            ) {
1172
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
1173
                    Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
1174
                    .'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
1175
            } else {
1176
                if (!$show_full_profile) {
1177
                    $links .= '<li>
1178
                        <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('SendInvitation').'">'.
1179
                        Display::return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').
1180
                        '</a></li>';
1181
                }
1182
            }*/
1183
1184
            // Announcements in Courses
1185
1186
            /*if ($show_full_profile && $user_id == intval(api_get_user_id())) {
1187
                $personal_course_list = UserManager::get_personal_session_course_list($user_id);
1188
                $course_list_code = [];
1189
                $i = 1;
1190
                if (is_array($personal_course_list)) {
1191
                    foreach ($personal_course_list as $my_course) {
1192
                        if ($i <= 10) {
1193
                            $course_list_code[] = ['code' => $my_course['code']];
1194
                        } else {
1195
                            break;
1196
                        }
1197
                        $i++;
1198
                    }
1199
                    // To avoid repeated courses
1200
                    $course_list_code = array_unique_dimensional($course_list_code);
1201
                }
1202
1203
                // Announcements
1204
                $my_announcement_by_user_id = intval($user_id);
1205
                $announcements = [];
1206
                foreach ($course_list_code as $course) {
1207
                    $course_info = api_get_course_info($course['code']);
1208
                    if (!empty($course_info)) {
1209
                        $content = AnnouncementManager::get_all_annoucement_by_user_course(
1210
                            $course_info['code'],
1211
                            $my_announcement_by_user_id
1212
                        );
1213
1214
                        if (!empty($content)) {
1215
                            $url = Display::url(
1216
                                Display::return_icon(
1217
                                    'announcement.png',
1218
                                    get_lang('Announcements')
1219
                                ).$course_info['name'].' ('.$content['count'].')',
1220
                                api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']
1221
                            );
1222
                            $announcements[] = Display::tag('li', $url);
1223
                        }
1224
                    }
1225
                }
1226
                if (!empty($announcements)) {
1227
                    $html .= '<div class="social_menu_items">';
1228
                    $html .= '<ul>';
1229
                    foreach ($announcements as $announcement) {
1230
                        $html .= $announcement;
1231
                    }
1232
                    $html .= '</ul>';
1233
                    $html .= '</div>';
1234
                }
1235
            }*/
1236
        }
1237
1238
//        if ($show_delete_account_button) {
1239
        $deleteIcon = Display::return_icon(
1240
                'delete.png',
1241
                get_lang('Unsubscribe'),
1242
                [],
1243
                ICON_SIZE_TINY
1244
            );
1245
        $itemMenu[9] = [
1246
                'item' => get_lang('Unsubscribe'),
1247
                'url' => api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php',
1248
                'icon' => $deleteIcon,
1249
                'active' => null,
1250
            ];
1251
1252
//        }
1253
1254
        return Display::dropdownMenu($itemMenu);
1255
    }
1256
1257
    /**
1258
     * Shows the right menu of the Social Network tool.
1259
     *
1260
     * @param string $show                       highlight link possible values:
1261
     *                                           group_add,
1262
     *                                           home,
1263
     *                                           messages,
1264
     *                                           messages_inbox,
1265
     *                                           messages_compose ,
1266
     *                                           messages_outbox,
1267
     *                                           invitations,
1268
     *                                           shared_profile,
1269
     *                                           friends,
1270
     *                                           groups search
1271
     * @param int    $group_id                   group id
1272
     * @param int    $user_id                    user id
1273
     * @param bool   $show_full_profile          show profile or not (show or hide the user image/information)
1274
     * @param bool   $show_delete_account_button
1275
     */
1276
    public static function show_social_menu(
1277
        $show = '',
1278
        $group_id = 0,
1279
        $user_id = 0,
1280
        $show_full_profile = false,
1281
        $show_delete_account_button = false
1282
    ) {
1283
        $user_id = (int) $user_id;
1284
        $group_id = (int) $group_id;
1285
1286
        if (empty($user_id)) {
1287
            $user_id = api_get_user_id();
1288
        }
1289
1290
        $usergroup = new UserGroup();
1291
        $show_groups = [
1292
            'groups',
1293
            'group_messages',
1294
            'messages_list',
1295
            'group_add',
1296
            'mygroups',
1297
            'group_edit',
1298
            'member_list',
1299
            'invite_friends',
1300
            'waiting_list',
1301
            'browse_groups',
1302
        ];
1303
1304
        // get count unread message and total invitations
1305
        $count_unread_message = MessageManager::getNumberOfMessages(true);
1306
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
1307
1308
        $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
1309
        $group_pending_invitations = $usergroup->get_groups_by_user(
1310
            api_get_user_id(),
1311
            GROUP_USER_PERMISSION_PENDING_INVITATION,
1312
            false
1313
        );
1314
        $group_pending_invitations = count($group_pending_invitations);
1315
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
1316
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
1317
1318
        $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), null, ICON_SIZE_SMALL);
1319
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), null, ICON_SIZE_SMALL);
1320
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), null, ICON_SIZE_SMALL);
1321
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), null, ICON_SIZE_SMALL);
1322
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), null, ICON_SIZE_SMALL);
1323
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), null, ICON_SIZE_SMALL);
1324
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
1325
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), null, ICON_SIZE_SMALL);
1326
        $portfolioIcon = Display::return_icon('wiki_task.png', get_lang('Portfolio'));
1327
        $personalDataIcon = Display::return_icon('database.png', get_lang('PersonalDataReport'));
1328
1329
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
1330
        $groupUrl = api_get_path(WEB_CODE_PATH).'social/groups.php';
1331
        if (!empty($forumCourseId)) {
1332
            $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

1332
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
1333
            if (!empty($courseInfo)) {
1334
                $groupUrl = api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code'];
1335
            }
1336
        }
1337
1338
        $html = '';
1339
        $active = null;
1340
        if (!in_array(
1341
            $show,
1342
            ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
1343
        )) {
1344
            $links = '<ul class="nav nav-pills nav-stacked">';
1345
            $active = $show === 'home' ? 'active' : null;
1346
            $links .= '
1347
                <li class="home-icon '.$active.'">
1348
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
1349
                        '.$homeIcon.' '.get_lang('Home').'
1350
                    </a>
1351
                </li>';
1352
            $active = $show == 'messages' ? 'active' : null;
1353
            $links .= '
1354
                <li class="messages-icon '.$active.'">
1355
                    <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
1356
                        '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
1357
                    </a>
1358
                </li>';
1359
1360
            // Invitations
1361
            $active = $show == 'invitations' ? 'active' : null;
1362
            $links .= '
1363
                <li class="invitations-icon '.$active.'">
1364
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
1365
                        '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
1366
                    </a>
1367
                </li>';
1368
1369
            // Shared profile and groups
1370
            $active = $show == 'shared_profile' ? 'active' : null;
1371
            $links .= '
1372
                <li class="shared-profile-icon'.$active.'">
1373
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1374
                        '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1375
                    </a>
1376
                </li>';
1377
            $active = $show == 'friends' ? 'active' : null;
1378
            $links .= '
1379
                <li class="friends-icon '.$active.'">
1380
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1381
                        '.$friendsIcon.' '.get_lang('Friends').'
1382
                    </a>
1383
                </li>';
1384
            $active = $show === 'browse_groups' ? 'active' : null;
1385
            $links .= '
1386
                <li class="browse-groups-icon '.$active.'">
1387
                    <a href="'.$groupUrl.'">
1388
                        '.$groupsIcon.' '.get_lang('SocialGroups').'
1389
                    </a>
1390
                </li>';
1391
1392
            // Search users
1393
            $active = $show == 'search' ? 'active' : null;
1394
            $links .= '
1395
                <li class="search-icon '.$active.'">
1396
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1397
                        '.$searchIcon.' '.get_lang('Search').'
1398
                    </a>
1399
                </li>';
1400
1401
            // My files
1402
            $active = $show == 'myfiles' ? 'active' : null;
1403
1404
            $myFiles = '
1405
                <li class="myfiles-icon '.$active.'">
1406
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1407
                        '.$filesIcon.' '.get_lang('MyFiles').'
1408
                    </a>
1409
                </li>';
1410
1411
            if (api_get_setting('allow_my_files') === 'false') {
1412
                $myFiles = '';
1413
            }
1414
            $links .= $myFiles;
1415
            if (api_get_configuration_value('allow_portfolio_tool')) {
1416
                $links .= '
1417
                    <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1418
                        <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1419
                            '.$portfolioIcon.' '.get_lang('Portfolio').'
1420
                        </a>
1421
                    </li>
1422
                ';
1423
            }
1424
1425
            if (!api_get_configuration_value('disable_gdpr')) {
1426
                $active = $show == 'personal-data' ? 'active' : null;
1427
                $personalData = '
1428
                    <li class="personal-data-icon '.$active.'">
1429
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1430
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1431
                        </a>
1432
                    </li>';
1433
                $links .= $personalData;
1434
                $links .= '</ul>';
1435
            }
1436
1437
            $html .= Display::panelCollapse(
1438
                get_lang('SocialNetwork'),
1439
                $links,
1440
                'social-network-menu',
1441
                null,
1442
                'sn-sidebar',
1443
                'sn-sidebar-collapse'
1444
            );
1445
        }
1446
1447
        if (in_array($show, $show_groups) && !empty($group_id)) {
1448
            $html .= $usergroup->show_group_column_information(
1449
                $group_id,
1450
                api_get_user_id(),
1451
                $show
1452
            );
1453
        }
1454
1455
        if ($show === 'shared_profile') {
1456
            $links = '<ul class="nav nav-pills nav-stacked">';
1457
            // My own profile
1458
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
1459
                $links .= '
1460
                    <li class="home-icon '.$active.'">
1461
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
1462
                            '.$homeIcon.' '.get_lang('Home').'
1463
                        </a>
1464
                    </li>
1465
                    <li class="messages-icon '.$active.'">
1466
                        <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
1467
                            '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
1468
                        </a>
1469
                    </li>';
1470
                $active = $show === 'invitations' ? 'active' : null;
1471
                $links .= '
1472
                    <li class="invitations-icon'.$active.'">
1473
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
1474
                            '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
1475
                        </a>
1476
                    </li>';
1477
1478
                $links .= '
1479
                    <li class="shared-profile-icon active">
1480
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1481
                            '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1482
                        </a>
1483
                    </li>
1484
                    <li class="friends-icon">
1485
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1486
                            '.$friendsIcon.' '.get_lang('Friends').'
1487
                        </a>
1488
                    </li>';
1489
1490
                $links .= '<li class="browse-groups-icon">
1491
                        <a href="'.$groupUrl.'">
1492
                            '.$groupsIcon.' '.get_lang('SocialGroups').'
1493
                        </a>
1494
                        </li>';
1495
1496
                $active = $show == 'search' ? 'active' : null;
1497
                $links .= '
1498
                    <li class="search-icon '.$active.'">
1499
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1500
                            '.$searchIcon.' '.get_lang('Search').'
1501
                        </a>
1502
                    </li>';
1503
                $active = $show == 'myfiles' ? 'active' : null;
1504
1505
                $myFiles = '
1506
                    <li class="myfiles-icon '.$active.'">
1507
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1508
                            '.$filesIcon.' '.get_lang('MyFiles').'
1509
                        </a>
1510
                    </li>';
1511
1512
                if (api_get_setting('allow_my_files') === 'false') {
1513
                    $myFiles = '';
1514
                }
1515
                $links .= $myFiles;
1516
1517
                if (api_get_configuration_value('allow_portfolio_tool')) {
1518
                    $links .= '
1519
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1520
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1521
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1522
                            </a>
1523
                        </li>
1524
                    ';
1525
                }
1526
            }
1527
1528
            // My friend profile.
1529
            if ($user_id != api_get_user_id()) {
1530
                $sendMessageText = get_lang('SendMessage');
1531
                $sendMessageIcon = Display::return_icon(
1532
                    'new-message.png',
1533
                    $sendMessageText
1534
                );
1535
                $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
1536
                        'a' => 'get_user_popup',
1537
                        'user_id' => $user_id,
1538
                    ]);
1539
1540
                $links .= '<li>';
1541
                $links .= Display::url(
1542
                    "$sendMessageIcon $sendMessageText",
1543
                    $sendMessageUrl,
1544
                    [
1545
                        'class' => 'ajax',
1546
                        'title' => $sendMessageText,
1547
                        'data-title' => $sendMessageText,
1548
                    ]
1549
                );
1550
                $links .= '</li>';
1551
1552
                if (api_get_configuration_value('allow_portfolio_tool')) {
1553
                    $links .= '
1554
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1555
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id.'">
1556
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1557
                            </a>
1558
                        </li>
1559
                    ';
1560
                }
1561
            }
1562
1563
            // Check if I already sent an invitation message
1564
            $invitation_sent_list = self::get_list_invitation_sent_by_user_id(api_get_user_id());
1565
1566
            if (isset($invitation_sent_list[$user_id]) && is_array($invitation_sent_list[$user_id]) &&
1567
                count($invitation_sent_list[$user_id]) > 0
1568
            ) {
1569
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
1570
                    Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
1571
                    .'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
1572
            } else {
1573
                if (!$show_full_profile) {
1574
                    $links .= '<li>
1575
                        <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('SendInvitation').'">'.
1576
                        Display::return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').
1577
                        '</a></li>';
1578
                }
1579
            }
1580
1581
            $links .= '</ul>';
1582
            $html .= Display::panelCollapse(
1583
                get_lang('SocialNetwork'),
1584
                $links,
1585
                'social-network-menu',
1586
                null,
1587
                'sn-sidebar',
1588
                'sn-sidebar-collapse'
1589
            );
1590
1591
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
1592
                $personal_course_list = UserManager::get_personal_session_course_list($user_id);
1593
                $course_list_code = [];
1594
                $i = 1;
1595
                if (is_array($personal_course_list)) {
1596
                    foreach ($personal_course_list as $my_course) {
1597
                        if ($i <= 10) {
1598
                            $course_list_code[] = ['code' => $my_course['code']];
1599
                        } else {
1600
                            break;
1601
                        }
1602
                        $i++;
1603
                    }
1604
                    // To avoid repeated courses
1605
                    $course_list_code = array_unique_dimensional($course_list_code);
1606
                }
1607
1608
                // Announcements
1609
                $my_announcement_by_user_id = intval($user_id);
1610
                $announcements = [];
1611
                foreach ($course_list_code as $course) {
1612
                    $course_info = api_get_course_info($course['code']);
1613
                    if (!empty($course_info)) {
1614
                        $content = AnnouncementManager::get_all_annoucement_by_user_course(
1615
                            $course_info['code'],
1616
                            $my_announcement_by_user_id
1617
                        );
1618
1619
                        if (!empty($content)) {
1620
                            $url = Display::url(
1621
                                Display::return_icon(
1622
                                    'announcement.png',
1623
                                    get_lang('Announcements')
1624
                                ).$course_info['name'].' ('.$content['count'].')',
1625
                                api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']
1626
                            );
1627
                            $announcements[] = Display::tag('li', $url);
1628
                        }
1629
                    }
1630
                }
1631
                if (!empty($announcements)) {
1632
                    $html .= '<div class="social_menu_items">';
1633
                    $html .= '<ul>';
1634
                    foreach ($announcements as $announcement) {
1635
                        $html .= $announcement;
1636
                    }
1637
                    $html .= '</ul>';
1638
                    $html .= '</div>';
1639
                }
1640
            }
1641
        }
1642
1643
        if ($show_delete_account_button) {
1644
            $html .= '<div class="panel panel-default"><div class="panel-body">';
1645
            $html .= '<ul class="nav nav-pills nav-stacked"><li>';
1646
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
1647
            $html .= Display::url(
1648
                Display::return_icon(
1649
                    'delete.png',
1650
                    get_lang('Unsubscribe'),
1651
                    [],
1652
                    ICON_SIZE_TINY
1653
                ).get_lang('Unsubscribe'),
1654
                $url
1655
            );
1656
            $html .= '</li></ul>';
1657
            $html .= '</div></div>';
1658
        }
1659
        $html .= '';
1660
1661
        return $html;
1662
    }
1663
1664
    /**
1665
     * Displays a sortable table with the list of online users.
1666
     *
1667
     * @param array $user_list The list of users to be shown
1668
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
1669
     *
1670
     * @return string HTML block or null if and ID was defined
1671
     * @assert (null) === false
1672
     */
1673
    public static function display_user_list($user_list, $wrap = true)
1674
    {
1675
        $html = '';
1676
1677
        if (isset($_GET['id']) || count($user_list) < 1) {
1678
            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...
1679
        }
1680
1681
        $course_url = '';
1682
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1683
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
1684
        }
1685
1686
        $hide = api_get_configuration_value('hide_complete_name_in_whoisonline');
1687
        foreach ($user_list as $uid) {
1688
            $user_info = api_get_user_info($uid, true);
1689
            $lastname = $user_info['lastname'];
1690
            $firstname = $user_info['firstname'];
1691
            $completeName = $firstname.', '.$lastname;
1692
            $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);
1693
            $status_icon_chat = null;
1694
            if (isset($user_info['user_is_online_in_chat']) && $user_info['user_is_online_in_chat'] == 1) {
1695
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1696
            } else {
1697
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1698
            }
1699
1700
            $userPicture = $user_info['avatar'];
1701
            $officialCode = '';
1702
            if (api_get_setting('show_official_code_whoisonline') == 'true') {
1703
                $officialCode .= '<div class="items-user-official-code"><p style="min-height: 30px;" title="'.get_lang('OfficialCode').'">'.$user_info['official_code'].'</p></div>';
1704
            }
1705
1706
            if ($hide === true) {
1707
                $completeName = '';
1708
                $firstname = '';
1709
                $lastname = '';
1710
            }
1711
1712
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1713
1714
            $url = null;
1715
            // Anonymous users can't have access to the profile
1716
            if (!api_is_anonymous()) {
1717
                if (api_get_setting('allow_social_tool') === 'true') {
1718
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1719
                } else {
1720
                    $url = '?id='.$uid.$course_url;
1721
                }
1722
            } else {
1723
                $url = null;
1724
            }
1725
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1726
1727
            $html .= '<div class="col-xs-6 col-md-2">
1728
                        <div class="items-user">
1729
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1730
                            <div class="items-user-name">
1731
                            '.$name.'
1732
                            </div>
1733
                            '.$officialCode.'
1734
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1735
                        </div>
1736
                      </div>';
1737
        }
1738
1739
        return $html;
1740
    }
1741
1742
    /**
1743
     * Displays the information of an individual user.
1744
     *
1745
     * @param int $user_id
1746
     *
1747
     * @return string
1748
     */
1749
    public static function display_individual_user($user_id)
1750
    {
1751
        global $interbreadcrumb;
1752
        $safe_user_id = (int) $user_id;
1753
        $currentUserId = api_get_user_id();
1754
1755
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1756
        $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
1757
        $result = Database::query($sql);
1758
        $html = null;
1759
        if (Database::num_rows($result) == 1) {
1760
            $user_object = Database::fetch_object($result);
1761
            $userInfo = api_get_user_info($user_id);
1762
            $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
1763
            $status = get_status_from_code($user_object->status);
1764
            $interbreadcrumb[] = ['url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList')];
1765
1766
            $html .= '<div class ="thumbnail">';
1767
            $fullurl = $userInfo['avatar'];
1768
1769
            $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
1770
1771
            if (!empty($status)) {
1772
                $html .= '<div class="caption">'.$status.'</div>';
1773
            }
1774
            $html .= '</div>';
1775
1776
            if (api_get_setting('show_email_addresses') == 'true') {
1777
                $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
1778
            }
1779
1780
            if ($user_object->competences) {
1781
                $html .= Display::page_subheader(get_lang('MyCompetences'));
1782
                $html .= '<p>'.$user_object->competences.'</p>';
1783
            }
1784
            if ($user_object->diplomas) {
1785
                $html .= Display::page_subheader(get_lang('MyDiplomas'));
1786
                $html .= '<p>'.$user_object->diplomas.'</p>';
1787
            }
1788
            if ($user_object->teach) {
1789
                $html .= Display::page_subheader(get_lang('MyTeach'));
1790
                $html .= '<p>'.$user_object->teach.'</p>';
1791
            }
1792
            self::display_productions($user_object->user_id);
1793
            if ($user_object->openarea) {
1794
                $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
1795
                $html .= '<p>'.$user_object->openarea.'</p>';
1796
            }
1797
        } else {
1798
            $html .= '<div class="actions-title">';
1799
            $html .= get_lang('UsersOnLineList');
1800
            $html .= '</div>';
1801
        }
1802
1803
        return $html;
1804
    }
1805
1806
    /**
1807
     * Display productions in who is online.
1808
     *
1809
     * @param int $user_id User id
1810
     */
1811
    public static function display_productions($user_id)
1812
    {
1813
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1814
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1815
        $webdir = UserManager::getUserPathById($user_id, 'web');
1816
1817
        if (!is_dir($sysdir)) {
1818
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1819
        }
1820
1821
        $productions = UserManager::get_user_productions($user_id);
1822
1823
        if (count($productions) > 0) {
1824
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1825
            echo '<dd><ul>';
1826
            foreach ($productions as $file) {
1827
                // Only display direct file links to avoid browsing an empty directory
1828
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1829
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1830
                }
1831
                // Real productions are under a subdirectory by the User's id
1832
                if (is_dir($sysdir.$file)) {
1833
                    $subs = scandir($sysdir.$file);
1834
                    foreach ($subs as $my => $sub) {
1835
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1836
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1837
                        }
1838
                    }
1839
                }
1840
            }
1841
            echo '</ul></dd>';
1842
        }
1843
    }
1844
1845
    /**
1846
     * @param string $content
1847
     * @param string $span_count
1848
     *
1849
     * @return string
1850
     */
1851
    public static function social_wrapper_div($content, $span_count)
1852
    {
1853
        $span_count = (int) $span_count;
1854
        $html = '<div class="span'.$span_count.'">';
1855
        $html .= '<div class="well_border">';
1856
        $html .= $content;
1857
        $html .= '</div></div>';
1858
1859
        return $html;
1860
    }
1861
1862
    /**
1863
     * Dummy function.
1864
     */
1865
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1866
    {
1867
        $content = '';
1868
        switch ($place) {
1869
            case SOCIAL_CENTER_PLUGIN:
1870
                $social_plugins = [1, 2];
1871
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1872
                    $content .= '<div id="social-plugins">';
1873
                    foreach ($social_plugins as $plugin) {
1874
                        $content .= '<div class="social-plugin-item">';
1875
                        $content .= $plugin;
1876
                        $content .= '</div>';
1877
                    }
1878
                    $content .= '</div>';
1879
                }
1880
                break;
1881
            case SOCIAL_LEFT_PLUGIN:
1882
                break;
1883
            case SOCIAL_RIGHT_PLUGIN:
1884
                break;
1885
        }
1886
1887
        return $content;
1888
    }
1889
1890
    /**
1891
     * Sends a message to someone's wall.
1892
     *
1893
     * @param int    $userId         id of author
1894
     * @param int    $friendId       id where we send the message
1895
     * @param string $messageContent of the message
1896
     * @param int    $messageId      id parent
1897
     * @param string $messageStatus  status type of message
1898
     *
1899
     * @return int
1900
     *
1901
     * @author Yannick Warnier
1902
     */
1903
    public static function sendWallMessage(
1904
        $userId,
1905
        $friendId,
1906
        $messageContent,
1907
        $messageId = 0,
1908
        $messageStatus = ''
1909
    ) {
1910
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1911
        $userId = (int) $userId;
1912
        $friendId = (int) $friendId;
1913
        $messageId = (int) $messageId;
1914
1915
        if (empty($userId) || empty($friendId)) {
1916
            return 0;
1917
        }
1918
1919
        // Just in case we replace the and \n and \n\r while saving in the DB
1920
        $messageContent = str_replace(["\n", "\n\r"], '<br />', $messageContent);
1921
        $now = api_get_utc_datetime();
1922
1923
        $attributes = [
1924
            'user_sender_id' => $userId,
1925
            'user_receiver_id' => $friendId,
1926
            'msg_status' => $messageStatus,
1927
            'send_date' => $now,
1928
            'title' => '',
1929
            'content' => $messageContent,
1930
            'parent_id' => $messageId,
1931
            'group_id' => 0,
1932
            'update_date' => $now,
1933
        ];
1934
1935
        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...
1936
    }
1937
1938
    /**
1939
     * Send File attachment (jpg,png).
1940
     *
1941
     * @author Anibal Copitan
1942
     *
1943
     * @param int    $userId      id user
1944
     * @param array  $fileAttach
1945
     * @param int    $messageId   id message (relation with main message)
1946
     * @param string $fileComment description attachment file
1947
     *
1948
     * @return bool|int
1949
     */
1950
    public static function sendWallMessageAttachmentFile(
1951
        $userId,
1952
        $fileAttach,
1953
        $messageId,
1954
        $fileComment = ''
1955
    ) {
1956
        $safeFileName = Database::escape_string($fileAttach['name']);
1957
1958
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1959
        $allowedTypes = api_get_supported_image_extensions();
1960
1961
        $allowedTypes[] = 'mp4';
1962
        $allowedTypes[] = 'webm';
1963
        $allowedTypes[] = 'ogg';
1964
1965
        if (in_array($extension, $allowedTypes)) {
1966
            return MessageManager::saveMessageAttachmentFile($fileAttach, $fileComment, $messageId, $userId);
1967
        }
1968
1969
        return false;
1970
    }
1971
1972
    /**
1973
     * Gets all messages from someone's wall (within specific limits).
1974
     *
1975
     * @param int        $userId     id of wall shown
1976
     * @param int|string $parentId   id message (Post main)
1977
     * @param int|array  $groupId
1978
     * @param int|array  $friendId
1979
     * @param string     $startDate  Date from which we want to show the messages, in UTC time
1980
     * @param int        $start      Limit for the number of parent messages we want to show
1981
     * @param int        $length     Wall message query offset
1982
     * @param bool       $getCount
1983
     * @param array      $threadList
1984
     *
1985
     * @return array|int
1986
     *
1987
     * @author Yannick Warnier
1988
     */
1989
    public static function getWallMessages(
1990
        $userId,
1991
        $parentId = 0,
1992
        $groupId = 0,
1993
        $friendId = 0,
1994
        $startDate = '',
1995
        $start = 0,
1996
        $length = 10,
1997
        $getCount = false,
1998
        $threadList = []
1999
    ) {
2000
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
2001
2002
        $parentId = (int) $parentId;
2003
        $userId = (int) $userId;
2004
        $start = (int) $start;
2005
        $length = (int) $length;
2006
        $startDate = Database::escape_string($startDate);
2007
2008
        $select = " SELECT
2009
                    id,
2010
                    user_sender_id,
2011
                    user_receiver_id,
2012
                    send_date,
2013
                    content,
2014
                    parent_id,
2015
                    msg_status,
2016
                    group_id,
2017
                    '' as forum_id,
2018
                    '' as thread_id,
2019
                    '' as c_id
2020
                  ";
2021
2022
        if ($getCount) {
2023
            $select = ' SELECT count(id) count ';
2024
        }
2025
2026
        $sql = "$select                    
2027
                    FROM $tblMessage tm
2028
                WHERE
2029
                    msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
2030
2031
        // My own posts
2032
        $userReceiverCondition = ' (
2033
            user_receiver_id = '.$userId.' AND 
2034
            msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
2035
            parent_id = '.$parentId.'
2036
        )';
2037
2038
        // User condition
2039
        $sql .= $userReceiverCondition;
2040
2041
        // Get my group posts
2042
        $groupCondition = '';
2043
        if (!empty($groupId)) {
2044
            if (is_array($groupId)) {
2045
                $groupId = array_map('intval', $groupId);
2046
                $groupId = implode("','", $groupId);
2047
                $groupCondition = " OR ( group_id IN ('$groupId') ";
2048
            } else {
2049
                $groupId = (int) $groupId;
2050
                $groupCondition = " OR ( group_id = '$groupId' ";
2051
            }
2052
            $groupCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_NEW.', '.MESSAGE_STATUS_UNREAD.')) ';
2053
        }
2054
2055
        $friendCondition = '';
2056
        // Get my friend posts
2057
        if (!empty($friendId)) {
2058
            if (is_array($friendId)) {
2059
                $friendId = array_map('intval', $friendId);
2060
                $friendId = implode("','", $friendId);
2061
                $friendCondition = " OR ( user_receiver_id IN ('$friendId') ";
2062
            } else {
2063
                $friendId = (int) $friendId;
2064
                $friendCondition = " OR ( user_receiver_id = '$friendId' ";
2065
            }
2066
            $friendCondition .= ' AND msg_status IN ('.MESSAGE_STATUS_WALL_POST.') AND parent_id = 0) ';
2067
        }
2068
2069
        if (!empty($groupCondition) || !empty($friendCondition)) {
2070
            $sql .= " $groupCondition $friendCondition ";
2071
        }
2072
2073
        if (!empty($threadList)) {
2074
            if ($getCount) {
2075
                $select = ' SELECT count(iid) count ';
2076
            } else {
2077
                $select = " SELECT 
2078
                                iid,
2079
                                poster_id,
2080
                                '' as user_receiver_id,
2081
                                post_date,
2082
                                post_text,
2083
                                '' as parent_id,
2084
                                ".MESSAGE_STATUS_FORUM.",
2085
                                '' as group_id,
2086
                                forum_id,
2087
                                thread_id,
2088
                                c_id                            
2089
        ";
2090
            }
2091
2092
            $threadList = array_map('intval', $threadList);
2093
            $threadList = implode("','", $threadList);
2094
            $condition = " thread_id IN ('$threadList') ";
2095
            $sql .= "                
2096
                UNION (
2097
                    $select
2098
                    FROM c_forum_post  
2099
                    WHERE $condition                                         
2100
                )
2101
                ";
2102
        }
2103
2104
        if ($getCount) {
2105
            $res = Database::query($sql);
2106
            $row = Database::fetch_array($res);
2107
2108
            return (int) $row['count'];
2109
        }
2110
2111
        $sql .= ' ORDER BY send_date DESC ';
2112
        $sql .= " LIMIT $start, $length ";
2113
2114
        $messages = [];
2115
        $res = Database::query($sql);
2116
        $em = Database::getManager();
2117
        if (Database::num_rows($res) > 0) {
2118
            $repo = $em->getRepository('ChamiloCourseBundle:CForumPost');
2119
            $repoThread = $em->getRepository('ChamiloCourseBundle:CForumThread');
2120
            $groups = [];
2121
            $forums = [];
2122
            $userGroup = new UserGroup();
2123
            $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
2124
            while ($row = Database::fetch_array($res, 'ASSOC')) {
2125
                $row['group_info'] = [];
2126
                if (!empty($row['group_id'])) {
2127
                    if (!in_array($row['group_id'], $groups)) {
2128
                        $group = $userGroup->get($row['group_id']);
2129
                        $group['url'] = $urlGroup.$group['id'];
2130
                        $groups[$row['group_id']] = $group;
2131
                        $row['group_info'] = $group;
2132
                    } else {
2133
                        $row['group_info'] = $groups[$row['group_id']];
2134
                    }
2135
                }
2136
2137
                // forums
2138
                $row['post_title'] = '';
2139
                $row['forum_title'] = '';
2140
                $row['thread_url'] = '';
2141
                if ($row['msg_status'] == MESSAGE_STATUS_FORUM) {
2142
                    /** @var \Chamilo\CourseBundle\Entity\CForumPost $post */
2143
                    $post = $repo->find($row['id']);
2144
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
2145
                    $thread = $repoThread->find($row['thread_id']);
2146
                    if ($post && $thread) {
2147
                        $courseInfo = api_get_course_info_by_id($post->getCId());
2148
                        $row['post_title'] = $post->getForumId();
2149
                        $row['forum_title'] = $thread->getThreadTitle();
2150
                        $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
2151
                            'cidReq' => $courseInfo['code'],
2152
                            'forum' => $post->getForumId(),
2153
                            '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

2153
                            '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...
2154
                            'post_id' => $post->getIid(),
2155
                        ]).'#post_id_'.$post->getIid();
2156
                    }
2157
                }
2158
2159
                $messages[] = $row;
2160
            }
2161
        }
2162
2163
        return $messages;
2164
    }
2165
2166
    /**
2167
     * Gets all messages from someone's wall (within specific limits), formatted.
2168
     *
2169
     * @param int    $userId      USER ID of the person's wall
2170
     * @param array  $messageInfo
2171
     * @param string $start       Start date (from when we want the messages until today)
2172
     * @param int    $limit       Limit to the number of messages we want
2173
     * @param int    $offset      Wall messages offset
2174
     *
2175
     * @return string HTML formatted string to show messages
2176
     */
2177
    public static function getWallPostComments(
2178
        $userId,
2179
        $messageInfo,
2180
        $start = null,
2181
        $limit = 10,
2182
        $offset = 0
2183
    ) {
2184
        $messageId = $messageInfo['id'];
2185
        $messages = MessageManager::getMessagesByParent($messageInfo['id'], 0, $offset, $limit);
2186
        $formattedList = '<div class="sub-mediapost row">';
2187
        $users = [];
2188
2189
        // The messages are ordered by date descendant, for comments we need ascendant
2190
        krsort($messages);
2191
        foreach ($messages as $message) {
2192
            $userIdLoop = $message['user_sender_id'];
2193
            if (!isset($users[$userIdLoop])) {
2194
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
2195
            }
2196
            $media = self::processPostComment($message, $users);
2197
            $formattedList .= $media;
2198
        }
2199
2200
        $formattedList .= '</div>';
2201
        $formattedList .= '<div class="mediapost-form">';
2202
        $formattedList .= '<form class="form-horizontal" id="form_comment_'.$messageId.'" name="post_comment" method="POST">
2203
                <div class="col-sm-9">
2204
                <label for="comment" class="hide">'.get_lang('SocialWriteNewComment').'</label>
2205
                <input type="hidden" name = "messageId" value="'.$messageId.'" />
2206
                <textarea rows="3" class="form-control" placeholder="'.get_lang('SocialWriteNewComment').'" name="comment" rows="1" ></textarea>
2207
                </div>
2208
                <div class="col-sm-3">
2209
                <a onclick="submitComment('.$messageId.');" href="javascript:void(0);" name="social_wall_new_msg_submit" class="btn btn-default btn-post">
2210
                    <em class="fa fa-pencil"></em> '.get_lang('Post').'
2211
                </a>
2212
                </div>
2213
                </form>';
2214
        $formattedList .= '</div>';
2215
2216
        return $formattedList;
2217
    }
2218
2219
    /**
2220
     * @param array $message
2221
     * @param array $users
2222
     *
2223
     * @return string
2224
     */
2225
    public static function processPostComment($message, $users = [])
2226
    {
2227
        if (empty($message)) {
2228
            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...
2229
        }
2230
2231
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
2232
        $currentUserId = api_get_user_id();
2233
        $userIdLoop = $message['user_sender_id'];
2234
        $receiverId = $message['user_receiver_id'];
2235
        $urlImg = api_get_path(WEB_IMG_PATH);
2236
2237
        if (!isset($users[$userIdLoop])) {
2238
            $users[$userIdLoop] = api_get_user_info($userIdLoop);
2239
        }
2240
2241
        $iconStatus = '';
2242
        $userStatus = (int) $users[$userIdLoop]['status'];
2243
        $isAdmin = self::is_admin($users[$userIdLoop]['id']);
2244
        if ($userStatus === 5) {
2245
            if ($users[$userIdLoop]['has_certificates']) {
2246
                $iconStatus = '<img src="'.$urlImg.'icons/svg/identifier_graduated.svg" width="22px" height="22px">';
2247
            } else {
2248
                $iconStatus = '<img src="'.$urlImg.'icons/svg/identifier_student.svg" width="22px" height="22px">';
2249
            }
2250
        } else {
2251
            if ($userStatus === 1) {
2252
                if ($isAdmin) {
2253
                    $iconStatus = '<img src="'.$urlImg.'icons/svg/identifier_admin.svg" width="22px" height="22px">';
2254
                } else {
2255
                    $iconStatus = '<img src="'.$urlImg.'icons/svg/identifier_teacher.svg" width="22px" height="22px">';
2256
                }
2257
            }
2258
        }
2259
2260
        $nameComplete = $users[$userIdLoop]['complete_name'];
2261
        $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$userIdLoop;
2262
2263
        $comment = '<div class="rep-post col-md-12">';
2264
        $comment .= '<div class="col-md-2 col-xs-2 social-post-answers">';
2265
        $comment .= '<div class="user-image pull-right">';
2266
        $comment .= '<a href="'.$url.'">
2267
                        <img src="'.$users[$userIdLoop]['avatar'].'" 
2268
                        alt="'.$users[$userIdLoop]['complete_name'].'" 
2269
                        class="avatar-thumb">
2270
                     </a>';
2271
        $comment .= '</div>';
2272
        $comment .= '</div>';
2273
        $comment .= '<div class="col-md-7 col-xs-7 social-post-answers">';
2274
        $comment .= '<div class="user-data">';
2275
        $comment .= $iconStatus;
2276
        $comment .= '<div class="username"><a href="'.$url.'">'.$nameComplete.'</a> 
2277
                        <span>'.Security::remove_XSS($message['content']).'</span>
2278
                       </div>';
2279
        $comment .= '<div>'.$date.'</div>';
2280
        $comment .= '<br />';
2281
        $comment .= '</div>';
2282
        $comment .= '</div>';
2283
2284
        $comment .= '<div class="col-md-3 col-xs-3 social-post-answers">';
2285
        $comment .= '<div class="pull-right btn-group btn-group-sm">';
2286
2287
        $comment .= MessageManager::getLikesButton(
2288
            $message['id'],
2289
            $currentUserId
2290
        );
2291
2292
        $isOwnWall = $currentUserId == $userIdLoop || $currentUserId == $receiverId;
2293
        if ($isOwnWall) {
2294
            $comment .= Display::url(
2295
                    Display::returnFontAwesomeIcon('trash', '', true),
2296
                'javascript:void(0)',
2297
                [
2298
                    'id' => 'message_'.$message['id'],
2299
                    'title' => get_lang('SocialMessageDelete'),
2300
                    'onclick' => 'deleteComment('.$message['id'].')',
2301
                    'class' => 'btn btn-default',
2302
                ]
2303
            );
2304
        }
2305
        $comment .= '</div>';
2306
        $comment .= '</div>';
2307
        $comment .= '</div>';
2308
2309
        return $comment;
2310
    }
2311
2312
    /**
2313
     * @param array $message
2314
     *
2315
     * @return array
2316
     */
2317
    public static function getAttachmentPreviewList($message)
2318
    {
2319
        $messageId = $message['id'];
2320
2321
        $list = [];
2322
2323
        if (empty($message['group_id'])) {
2324
            $files = MessageManager::getAttachmentList($messageId);
2325
            if ($files) {
2326
                $downloadUrl = api_get_path(WEB_CODE_PATH).'social/download.php?message_id='.$messageId;
2327
                foreach ($files as $row_file) {
2328
                    $url = $downloadUrl.'&attachment_id='.$row_file['id'];
2329
                    $display = Display::fileHtmlGuesser($row_file['filename'], $url);
2330
                    $list[] = $display;
2331
                }
2332
            }
2333
        } else {
2334
            $list = MessageManager::getAttachmentLinkList($messageId);
2335
        }
2336
2337
        return $list;
2338
    }
2339
2340
    /**
2341
     * @param array $message
2342
     *
2343
     * @return string
2344
     */
2345
    public static function getPostAttachment($message)
2346
    {
2347
        $previews = self::getAttachmentPreviewList($message);
2348
2349
        if (empty($previews)) {
2350
            return '';
2351
        }
2352
2353
        return implode('', $previews);
2354
    }
2355
2356
    /**
2357
     * @param array $messages
2358
     *
2359
     * @return array
2360
     */
2361
    public static function formatWallMessages($messages)
2362
    {
2363
        $data = [];
2364
        $users = [];
2365
        foreach ($messages as $key => $message) {
2366
            $userIdLoop = $message['user_sender_id'];
2367
            $userFriendIdLoop = $message['user_receiver_id'];
2368
            if (!isset($users[$userIdLoop])) {
2369
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
2370
            }
2371
2372
            if (!isset($users[$userFriendIdLoop])) {
2373
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
2374
            }
2375
2376
            $html = self::headerMessagePost(
2377
                $users[$userIdLoop],
2378
                $users[$userFriendIdLoop],
2379
                $message
2380
            );
2381
2382
            $data[$key] = $message;
2383
            $data[$key]['html'] = $html;
2384
        }
2385
2386
        return $data;
2387
    }
2388
2389
    /**
2390
     * get html data with OpenGrap passing the URL.
2391
     *
2392
     * @param $link url
2393
     *
2394
     * @return string data html
2395
     */
2396
    public static function readContentWithOpenGraph($link)
2397
    {
2398
        if (strpos($link, "://") === false && substr($link, 0, 1) != "/") {
2399
            $link = "http://".$link;
2400
        }
2401
        $graph = OpenGraph::fetch($link);
2402
        $link = parse_url($link);
2403
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
2404
        if (!$graph) {
2405
            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...
2406
        }
2407
        $url = $graph->url;
2408
        $image = $graph->image;
2409
        $description = $graph->description;
2410
        $title = $graph->title;
2411
        $html = '<div class="thumbnail social-thumbnail">';
2412
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
2413
                <img class="img-responsive social-image" src="'.$image.'" /></a>';
2414
        $html .= '<div class="social-description">';
2415
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
2416
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
2417
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
2418
        $html .= '</div>';
2419
        $html .= '</div>';
2420
2421
        return $html;
2422
    }
2423
2424
    /**
2425
     * verify if Url Exist - Using Curl.
2426
     *
2427
     * @param $uri url
2428
     *
2429
     * @return bool
2430
     */
2431
    public static function verifyUrl($uri)
2432
    {
2433
        $curl = curl_init($uri);
2434
        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

2434
        curl_setopt(/** @scrutinizer ignore-type */ $curl, CURLOPT_FAILONERROR, true);
Loading history...
2435
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
2436
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
2437
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
2438
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
2439
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
2440
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
2441
        $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

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

2442
        curl_close(/** @scrutinizer ignore-type */ $curl);
Loading history...
2443
        if (!empty($response)) {
2444
            return true;
2445
        }
2446
2447
        return false;
2448
    }
2449
2450
    /**
2451
     * Soft delete a message and his chidren.
2452
     *
2453
     * @param int $id id message to delete
2454
     *
2455
     * @return bool status query
2456
     */
2457
    public static function deleteMessage($id)
2458
    {
2459
        $id = (int) $id;
2460
        $messageInfo = MessageManager::get_message_by_id($id);
2461
        if (!empty($messageInfo)) {
2462
            // Delete comments too
2463
            $messages = MessageManager::getMessagesByParent($id);
2464
            if (!empty($messages)) {
2465
                foreach ($messages as $message) {
2466
                    self::deleteMessage($message['id']);
2467
                }
2468
            }
2469
2470
            // Soft delete message
2471
            $tblMessage = Database::get_main_table(TABLE_MESSAGE);
2472
            $statusMessage = MESSAGE_STATUS_WALL_DELETE;
2473
            $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
2474
            Database::query($sql);
2475
2476
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_sender_id']);
2477
            MessageManager::delete_message_attachment_file($id, $messageInfo['user_receiver_id']);
2478
2479
            return true;
2480
        }
2481
2482
        return false;
2483
    }
2484
2485
    /**
2486
     * Generate the social block for a user.
2487
     *
2488
     * @param Template $template
2489
     * @param int      $userId            The user id
2490
     * @param string   $groupBlock        Optional. Highlight link possible values:
2491
     *                                    group_add, home, messages, messages_inbox, messages_compose,
2492
     *                                    messages_outbox, invitations, shared_profile, friends, groups, search
2493
     * @param int      $groupId           Optional. Group ID
2494
     * @param bool     $show_full_profile
2495
     *
2496
     * @return string The HTML code with the social block
2497
     */
2498
    public static function setSocialUserBlock(
2499
        Template $template,
2500
        $userId,
2501
        $groupBlock = '',
2502
        $groupId = 0,
2503
        $show_full_profile = true
2504
    ) {
2505
        if (api_get_setting('allow_social_tool') != 'true') {
2506
            return '';
2507
        }
2508
2509
        $currentUserId = api_get_user_id();
2510
        $userId = (int) $userId;
2511
        $userRelationType = 0;
2512
2513
        $socialAvatarBlock = self::show_social_avatar_block(
2514
            $groupBlock,
2515
            $groupId,
2516
            $userId
2517
        );
2518
2519
        $profileEditionLink = null;
2520
        if ($currentUserId === $userId) {
2521
            $profileEditionLink = Display::getProfileEditionLink($userId);
2522
        } else {
2523
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
2524
        }
2525
2526
        $options = api_get_configuration_value('profile_fields_visibility');
2527
        if (isset($options['options'])) {
2528
            $options = $options['options'];
2529
        }
2530
2531
        $vCardUserLink = Display::getVCardUserLink($userId);
2532
        if (isset($options['vcard']) && $options['vcard'] === false) {
2533
            $vCardUserLink = '';
2534
        }
2535
2536
        $userInfo = api_get_user_info($userId, true, false, true, true);
2537
2538
        if (isset($options['firstname']) && $options['firstname'] === false) {
2539
            $userInfo['firstname'] = '';
2540
        }
2541
        if (isset($options['lastname']) && $options['lastname'] === false) {
2542
            $userInfo['lastname'] = '';
2543
        }
2544
2545
        if (isset($options['email']) && $options['email'] === false) {
2546
            $userInfo['email'] = '';
2547
        }
2548
2549
        // Ofaj
2550
        $hasCertificates = Certificate::getCertificateByUser($userId);
2551
        $userInfo['has_certificates'] = 0;
2552
        if (!empty($hasCertificates)) {
2553
            $userInfo['has_certificates'] = 1;
2554
        }
2555
2556
        $userInfo['is_admin'] = Usermanager::is_admin($userId);
2557
2558
        $languageId = api_get_language_id($userInfo['language']);
2559
        $languageInfo = api_get_language_info($languageId);
2560
        if ($languageInfo) {
2561
            $userInfo['language'] = [
2562
                'label' => $languageInfo['original_name'],
2563
                'value' => $languageInfo['english_name'],
2564
                'code' => $languageInfo['isocode'],
2565
            ];
2566
        }
2567
2568
        if (isset($options['language']) && $options['language'] === false) {
2569
            $userInfo['language'] = '';
2570
        }
2571
2572
        if (isset($options['photo']) && $options['photo'] === false) {
2573
            $socialAvatarBlock = '';
2574
        }
2575
2576
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
2577
2578
        $template->assign('user', $userInfo);
2579
        $template->assign('extra_info', $extraFieldBlock);
2580
        $template->assign('social_avatar_block', $socialAvatarBlock);
2581
        $template->assign('profile_edition_link', $profileEditionLink);
2582
        //Added the link to export the vCard to the Template
2583
2584
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
2585
        if ($show_full_profile) {
2586
            $template->assign('vcard_user_link', $vCardUserLink);
2587
        }
2588
2589
        if (api_get_setting('gamification_mode') === '1') {
2590
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
2591
                $userId,
2592
                $userInfo['status']
2593
            );
2594
2595
            $template->assign('gamification_points', $gamificationPoints);
2596
        }
2597
        $chatEnabled = api_is_global_chat_enabled();
2598
2599
        if (isset($options['chat']) && $options['chat'] === false) {
2600
            $chatEnabled = '';
2601
        }
2602
2603
        $template->assign('chat_enabled', $chatEnabled);
2604
        $template->assign('user_relation', $userRelationType);
2605
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
2606
        $template->assign('show_full_profile', $show_full_profile);
2607
2608
        $templateName = $template->get_template('social/user_block.tpl');
2609
2610
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
2611
            $templateName = $template->get_template('social/group_block.tpl');
2612
        }
2613
2614
        $template->assign('social_avatar_block', $template->fetch($templateName));
2615
    }
2616
2617
    /**
2618
     * @param int $user_id
2619
     * @param $link_shared
2620
     * @param $show_full_profile
2621
     *
2622
     * @return string
2623
     */
2624
    public static function listMyFriends($user_id, $link_shared, $show_full_profile)
2625
    {
2626
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
2627
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
2628
        $number_of_images = 30;
2629
        $number_friends = count($friends);
2630
        $friendHtml = '';
2631
        if ($number_friends != 0) {
2632
            if ($number_friends > $number_of_images) {
2633
                if (api_get_user_id() == $user_id) {
2634
                    $friendHtml .= ' <span><a href="friends.php">'.get_lang('SeeAll').'</a></span>';
2635
                } else {
2636
                    $friendHtml .= ' <span>'
2637
                        .'<a href="'.api_get_path(WEB_CODE_PATH).'social/profile_friends_and_groups.inc.php'
2638
                        .'?view=friends&height=390&width=610&user_id='.$user_id.'"'
2639
                        .'class="ajax" data-title="'.get_lang('SeeAll').'" title="'.get_lang('SeeAll').'" >'.get_lang('SeeAll').'</a></span>';
2640
                }
2641
            }
2642
2643
            $friendHtml .= '<ul class="nav nav-list">';
2644
            $j = 1;
2645
            for ($k = 0; $k < $number_friends; $k++) {
2646
                if ($j > $number_of_images) {
2647
                    break;
2648
                }
2649
                if (isset($friends[$k])) {
2650
                    $friend = $friends[$k];
2651
                    $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2652
                    $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2653
2654
                    if ($user_info_friend['user_is_online']) {
2655
                        $statusIcon = Display::span('', ['class' => 'online_user_in_text']);
2656
                    } else {
2657
                        $statusIcon = Display::span('', ['class' => 'offline_user_in_text']);
2658
                    }
2659
2660
                    $friendHtml .= '<li>';
2661
                    $friendHtml .= '<div>';
2662
2663
                    // the height = 92 must be the same in the image_friend_network span style in default.css
2664
                    $friends_profile = UserManager::getUserPicture(
2665
                        $friend['friend_user_id'],
2666
                        USER_IMAGE_SIZE_SMALL
2667
                    );
2668
                    $friendHtml .= '<img src="'.$friends_profile.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'"/>';
2669
                    $link_shared = (empty($link_shared)) ? '' : '&'.$link_shared;
2670
                    $friendHtml .= $statusIcon.'<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'">'.$name_user.'</a>';
2671
                    $friendHtml .= '</div>';
2672
                    $friendHtml .= '</li>';
2673
                }
2674
                $j++;
2675
            }
2676
            $friendHtml .= '</ul>';
2677
        } else {
2678
            $friendHtml .= '<div class="">'.get_lang('NoFriendsInYourContactList').'<br />
2679
                <a class="btn btn-primary" href="'.api_get_path(WEB_PATH).'whoisonline.php">
2680
                <em class="fa fa-search"></em> '.get_lang('TryAndFindSomeFriends').'</a></div>';
2681
        }
2682
2683
        $friendHtml = Display::panel($friendHtml, get_lang('SocialFriend').' ('.$number_friends.')');
2684
2685
        return $friendHtml;
2686
    }
2687
2688
    /**
2689
     * @param int $user_id
2690
     * @param $link_shared
2691
     * @param bool $showLinkToChat
2692
     *
2693
     * @return string
2694
     */
2695
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
2696
    {
2697
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
2698
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
2699
        $numberFriends = count($friends);
2700
        $friendHtml = '';
2701
2702
        if (!empty($numberFriends)) {
2703
            $friendHtml .= '<div class="list-group contact-list">';
2704
            $j = 1;
2705
2706
            usort(
2707
                $friends,
2708
                function ($a, $b) {
2709
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
2710
                }
2711
            );
2712
2713
            foreach ($friends as $friend) {
2714
                if ($j > $numberFriends) {
2715
                    break;
2716
                }
2717
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2718
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2719
2720
                $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
2721
                $status = 0;
2722
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
2723
                    $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
2724
                    $status = 1;
2725
                }
2726
2727
                $friendAvatarMedium = UserManager::getUserPicture(
2728
                    $friend['friend_user_id'],
2729
                    USER_IMAGE_SIZE_MEDIUM
2730
                );
2731
                $friendAvatarSmall = UserManager::getUserPicture(
2732
                    $friend['friend_user_id'],
2733
                    USER_IMAGE_SIZE_SMALL
2734
                );
2735
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
2736
2737
                $relation = self::get_relation_between_contacts(
2738
                    $friend['friend_user_id'],
2739
                    api_get_user_id()
2740
                );
2741
2742
                if ($showLinkToChat) {
2743
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
2744
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2745
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2746
                } else {
2747
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
2748
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
2749
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2750
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2751
                }
2752
2753
                $friendHtml .= '</a>';
2754
2755
                $j++;
2756
            }
2757
            $friendHtml .= '</div>';
2758
        }
2759
2760
        return $friendHtml;
2761
    }
2762
2763
    /**
2764
     * @param string $urlForm
2765
     *
2766
     * @return string
2767
     */
2768
    public static function getWallForm($urlForm)
2769
    {
2770
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
2771
        $form = new FormValidator(
2772
            'social_wall_main',
2773
            'post',
2774
            $urlForm.$userId,
2775
            null,
2776
            ['enctype' => 'multipart/form-data'],
2777
            FormValidator::LAYOUT_HORIZONTAL
2778
        );
2779
2780
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang(
2781
            'SocialWallWhatAreYouThinkingAbout'
2782
        );
2783
2784
        $form->addTextarea(
2785
            'social_wall_new_msg_main',
2786
            null,
2787
            [
2788
                'placeholder' => $socialWallPlaceholder,
2789
                'cols-size' => [1, 10, 1],
2790
                'aria-label' => $socialWallPlaceholder,
2791
            ]
2792
        );
2793
        $form->addHtml('<div class="form-group">');
2794
        $form->addHtml('<div class="col-sm-4 col-md-offset-1">');
2795
        $form->addFile('picture', get_lang('UploadFile'), ['custom' => true]);
2796
        $form->addHtml('</div>');
2797
        $form->addHtml('<div class="col-sm-6">');
2798
        $form->addButtonSend(
2799
            get_lang('Post'),
2800
            'wall_post_button',
2801
            false,
2802
            [
2803
                'cols-size' => [1, 10, 1],
2804
                'custom' => true,
2805
            ]
2806
        );
2807
        $form->addHtml('</div>');
2808
        $form->addHtml('</div>');
2809
2810
        $form->addHidden('url_content', '');
2811
        $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
2812
2813
        return $html;
2814
    }
2815
2816
    /**
2817
     * @param int   $userId
2818
     * @param int   $start
2819
     * @param int   $length
2820
     * @param array $threadList
2821
     *
2822
     * @return array
2823
     */
2824
    public static function getMyWallMessages($userId, $start = 0, $length = 10, $threadList = [])
2825
    {
2826
        $userGroup = new UserGroup();
2827
        $groups = $userGroup->get_groups_by_user($userId, [GROUP_USER_PERMISSION_READER, GROUP_USER_PERMISSION_ADMIN]);
2828
        $groupList = [];
2829
        if (!empty($groups)) {
2830
            $groupList = array_column($groups, 'id');
2831
        }
2832
2833
        $friends = self::get_friends($userId, USER_RELATION_TYPE_FRIEND);
2834
        $friendList = [];
2835
        if (!empty($friends)) {
2836
            $friendList = array_column($friends, 'friend_user_id');
2837
        }
2838
2839
        $messages = self::getWallMessages(
2840
            $userId,
2841
            0,
2842
            $groupList,
2843
            $friendList,
2844
            '',
2845
            $start,
2846
            $length,
2847
            false,
2848
            $threadList
2849
        );
2850
2851
        $countPost = self::getCountWallMessagesByUser($userId, $groupList, $friendList, $threadList);
2852
        $messages = self::formatWallMessages($messages);
2853
2854
        $html = '';
2855
        foreach ($messages as $message) {
2856
            $post = $message['html'];
2857
            $comments = '';
2858
            if ($message['msg_status'] == MESSAGE_STATUS_WALL_POST) {
2859
                $comments = self::getWallPostComments($userId, $message);
2860
            }
2861
2862
            $html .= self::wrapPost($message, $post.$comments);
2863
        }
2864
2865
        return [
2866
            'posts' => $html,
2867
            'count' => $countPost,
2868
        ];
2869
    }
2870
2871
    /**
2872
     * @param string $message
2873
     * @param string $content
2874
     *
2875
     * @return string
2876
     */
2877
    public static function wrapPost($message, $content)
2878
    {
2879
        return Display::panel($content, '',
2880
            '',
2881
            'default',
2882
            '',
2883
            'post_'.$message['id']
2884
        );
2885
    }
2886
2887
    /**
2888
     * @param int $userId
2889
     *
2890
     * @return int
2891
     */
2892
    public static function getCountWallMessagesByUser($userId, $groupList = [], $friendList = [], $threadList = [])
2893
    {
2894
        $count = self::getWallMessages(
2895
            $userId,
2896
            0,
2897
            $groupList,
2898
            $friendList,
2899
            '',
2900
            0,
2901
            0,
2902
            true,
2903
            $threadList
2904
        );
2905
2906
        return $count;
2907
    }
2908
2909
    /**
2910
     * @param int $userId
2911
     *
2912
     * @return string
2913
     */
2914
    public static function getWallMessagesByUser($userId)
2915
    {
2916
        $messages = self::getWallMessages($userId);
2917
        $messages = self::formatWallMessages($messages);
2918
2919
        $html = '';
2920
        foreach ($messages as $message) {
2921
            $post = $message['html'];
2922
            $comments = self::getWallPostComments($userId, $message);
2923
            $html .= self::wrapPost($message, $post.$comments);
2924
        }
2925
2926
        return $html;
2927
    }
2928
2929
    /**
2930
     * Get HTML code block for user skills.
2931
     *
2932
     * @param int    $userId      The user ID
2933
     * @param string $orientation
2934
     *
2935
     * @return string
2936
     */
2937
    public static function getSkillBlock($userId, $orientation = 'horizontal')
2938
    {
2939
        if (Skill::isAllowed($userId, false) === false) {
2940
            return '';
2941
        }
2942
2943
        $skill = new Skill();
2944
        $ranking = $skill->getUserSkillRanking($userId);
2945
2946
        $template = new Template(null, false, false, false, false, false);
2947
        $template->assign('ranking', $ranking);
2948
        $template->assign('orientation', $orientation);
2949
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
2950
        $template->assign('user_id', $userId);
2951
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
2952
2953
        $skillBlock = $template->get_template('social/skills_block.tpl');
2954
2955
        return $template->fetch($skillBlock);
2956
    }
2957
2958
    /**
2959
     * @param int $user_id
2960
     *
2961
     * @return string|array
2962
     */
2963
    public static function getExtraFieldBlock($user_id, $isArray = false)
2964
    {
2965
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
2966
        $fieldVisibilityKeys = [];
2967
        if (isset($fieldVisibility['options'])) {
2968
            $fieldVisibility = $fieldVisibility['options'];
2969
            $fieldVisibilityKeys = array_keys($fieldVisibility);
2970
        }
2971
2972
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
2973
        $extra_user_data = UserManager::get_extra_user_data($user_id);
2974
2975
        $extra_information = '';
2976
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
2977
            $extra_information_value = '';
2978
            $extraField = new ExtraField('user');
2979
            $listType = [];
2980
            $extraFieldItem = [];
2981
            foreach ($extra_user_data as $key => $data) {
2982
                if (empty($data)) {
2983
                    continue;
2984
                }
2985
                if (in_array($key, $fieldVisibilityKeys) && $fieldVisibility[$key] === false) {
2986
                    continue;
2987
                }
2988
2989
                // Avoiding parameters
2990
                if (in_array(
2991
                    $key,
2992
                    [
2993
                        'mail_notify_invitation',
2994
                        'mail_notify_message',
2995
                        'mail_notify_group_message',
2996
                    ]
2997
                )) {
2998
                    continue;
2999
                }
3000
                // get display text, visibility and type from user_field table
3001
                $field_variable = str_replace('extra_', '', $key);
3002
3003
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
3004
                    $field_variable
3005
                );
3006
3007
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
3008
                    continue;
3009
                }
3010
3011
                // if is not visible skip
3012
                if ($extraFieldInfo['visible_to_self'] != 1) {
3013
                    continue;
3014
                }
3015
3016
                // if is not visible to others skip also
3017
                if ($extraFieldInfo['visible_to_others'] != 1) {
3018
                    continue;
3019
                }
3020
3021
                if (is_array($data)) {
3022
                    switch ($extraFieldInfo['field_type']) {
3023
                        case ExtraField::FIELD_TYPE_RADIO:
3024
                            $objEfOption = new ExtraFieldOption('user');
3025
                            $value = $data['extra_'.$extraFieldInfo['variable']];
3026
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
3027
                                $extraFieldInfo['id'],
3028
                                $value
3029
                            );
3030
3031
                            if ($optionInfo && isset($optionInfo[0])) {
3032
                                $optionInfo = $optionInfo[0];
3033
                                $extraFieldItem = [
3034
                                    'variable' => $extraFieldInfo['variable'],
3035
                                    'label' => ucfirst($extraFieldInfo['display_text']),
3036
                                    'value' => $optionInfo['display_text'],
3037
                                ];
3038
                            } else {
3039
                                $extraFieldItem = [
3040
                                    'variable' => $extraFieldInfo['variable'],
3041
                                    'label' => ucfirst($extraFieldInfo['display_text']),
3042
                                    'value' => implode(',', $data),
3043
                                ];
3044
                            }
3045
                            break;
3046
                        default:
3047
                            $extra_information_value .=
3048
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
3049
                                .' '.implode(',', $data).'</li>';
3050
                            $extraFieldItem = [
3051
                                'variable' => $extraFieldInfo['variable'],
3052
                                'label' => ucfirst($extraFieldInfo['display_text']),
3053
                                'value' => implode(',', $data),
3054
                            ];
3055
                            break;
3056
                    }
3057
                } else {
3058
                    switch ($extraFieldInfo['field_type']) {
3059
                        case ExtraField::FIELD_TYPE_RADIO:
3060
                            $objEfOption = new ExtraFieldOption('user');
3061
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
3062
                            break;
3063
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
3064
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
3065
                            $data = explode('::', $data);
3066
                            $data = $data[0];
3067
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
3068
                            $extraFieldItem = [
3069
                                'variable' => $extraFieldInfo['variable'],
3070
                                'label' => ucfirst($extraFieldInfo['display_text']),
3071
                                'value' => $data,
3072
                            ];
3073
                            break;
3074
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
3075
                            $id_options = explode('::', $data);
3076
                            $value_options = [];
3077
                            // get option display text from user_field_options table
3078
                            foreach ($id_options as $id_option) {
3079
                                $sql = "SELECT display_text 
3080
                                    FROM $t_ufo 
3081
                                    WHERE id = '$id_option'";
3082
                                $res_options = Database::query($sql);
3083
                                $row_options = Database::fetch_row($res_options);
3084
                                $value_options[] = $row_options[0];
3085
                            }
3086
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
3087
                                .' '.implode(' ', $value_options).'</li>';
3088
                            $extraFieldItem = [
3089
                                'variable' => $extraFieldInfo['variable'],
3090
                                'label' => ucfirst($extraFieldInfo['display_text']),
3091
                                'value' => $value_options,
3092
                            ];
3093
                            break;
3094
                        case ExtraField::FIELD_TYPE_TAG:
3095
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
3096
3097
                            $tag_tmp = '';
3098
                            foreach ($user_tags as $tags) {
3099
                                $tag_tmp .= '<a class="label label_tag"'
3100
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
3101
                                    .$tags['tag']
3102
                                    .'</a>';
3103
                            }
3104
                            if (is_array($user_tags) && count($user_tags) > 0) {
3105
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
3106
                                    .' '.$tag_tmp.'</li>';
3107
                            }
3108
                            $extraFieldItem = [
3109
                                'variable' => $extraFieldInfo['variable'],
3110
                                'label' => ucfirst($extraFieldInfo['display_text']),
3111
                                'value' => $tag_tmp,
3112
                            ];
3113
                            break;
3114
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
3115
                            $icon_path = UserManager::get_favicon_from_url($data);
3116
                            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...
3117
                                break;
3118
                            }
3119
                            $bottom = '0.2';
3120
                            //quick hack for hi5
3121
                            $domain = parse_url($icon_path, PHP_URL_HOST);
3122
                            if ($domain == 'www.hi5.com' || $domain == 'hi5.com') {
3123
                                $bottom = '-0.8';
3124
                            }
3125
                            $data = '<a href="'.$data.'">'
3126
                                .'<img src="'.$icon_path.'" alt="icon"'
3127
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
3128
                                .$extraFieldInfo['display_text']
3129
                                .'</a>';
3130
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
3131
                            $extraFieldItem = [
3132
                                'variable' => $extraFieldInfo['variable'],
3133
                                'label' => ucfirst($extraFieldInfo['display_text']),
3134
                                'value' => $data,
3135
                            ];
3136
                            break;
3137
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
3138
                            $parsedData = explode('::', $data);
3139
3140
                            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...
3141
                                break;
3142
                            }
3143
3144
                            $objEfOption = new ExtraFieldOption('user');
3145
                            $optionInfo = $objEfOption->get($parsedData[0]);
3146
3147
                            $extra_information_value .= '<li class="list-group-item">'
3148
                                .$optionInfo['display_text'].': '
3149
                                .$parsedData[1].'</li>';
3150
                            $extraFieldItem = [
3151
                                'variable' => $extraFieldInfo['variable'],
3152
                                'label' => ucfirst($extraFieldInfo['display_text']),
3153
                                'value' => $parsedData[1],
3154
                            ];
3155
                            break;
3156
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
3157
                            $optionIds = explode(';', $data);
3158
                            $optionValues = [];
3159
3160
                            foreach ($optionIds as $optionId) {
3161
                                $objEfOption = new ExtraFieldOption('user');
3162
                                $optionInfo = $objEfOption->get($optionId);
3163
3164
                                $optionValues[] = $optionInfo['display_text'];
3165
                            }
3166
                            $extra_information_value .= '<li class="list-group-item">'
3167
                                .ucfirst($extraFieldInfo['display_text']).': '
3168
                                .implode(' ', $optionValues).'</li>';
3169
                            $extraFieldItem = [
3170
                                'variable' => $extraFieldInfo['variable'],
3171
                                'label' => ucfirst($extraFieldInfo['display_text']),
3172
                                'value' => implode(' ', $optionValues),
3173
                            ];
3174
                            break;
3175
                        default:
3176
                            // Ofaj
3177
                            // Converts "Date of birth" into "age"
3178
                            if ($key === 'terms_datedenaissance') {
3179
                                $dataArray = date_to_str_ago($data, 'UTC', true);
3180
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
3181
                                if (!empty($dataToString)) {
3182
                                    $data = $dataToString;
3183
                                    $extraFieldInfo['display_text'] = get_lang('Age');
3184
                                }
3185
                            }
3186
3187
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
3188
                            $extraFieldItem = [
3189
                                'variable' => $extraFieldInfo['variable'],
3190
                                'label' => ucfirst($extraFieldInfo['display_text']),
3191
                                'value' => $data,
3192
                            ];
3193
                            break;
3194
                    }
3195
                }
3196
3197
                $listType[] = $extraFieldItem;
3198
            }
3199
3200
            if ($isArray) {
3201
                return $listType;
3202
            } else {
3203
                // if there are information to show
3204
                if (!empty($extra_information_value)) {
3205
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
3206
                    $extra_information .= Display::panelCollapse(
3207
                        get_lang('ExtraInformation'),
3208
                        $extra_information_value,
3209
                        'sn-extra-information',
3210
                        null,
3211
                        'sn-extra-accordion',
3212
                        'sn-extra-collapse'
3213
                    );
3214
                }
3215
            }
3216
        }
3217
3218
        return $extra_information;
3219
    }
3220
3221
    /**
3222
     * @param string $url
3223
     */
3224
    public static function handlePosts($url)
3225
    {
3226
        $friendId = isset($_GET['u']) ? (int) $_GET['u'] : api_get_user_id();
3227
        $url = Security::remove_XSS($url);
3228
3229
        // Main post
3230
        if (!empty($_POST['social_wall_new_msg_main']) || !empty($_FILES['picture']['tmp_name'])) {
3231
            $messageContent = $_POST['social_wall_new_msg_main'];
3232
            if (!empty($_POST['url_content'])) {
3233
                $messageContent = $_POST['social_wall_new_msg_main'].'<br /><br />'.$_POST['url_content'];
3234
            }
3235
3236
            $messageId = self::sendWallMessage(
3237
                api_get_user_id(),
3238
                $friendId,
3239
                $messageContent,
3240
                0,
3241
                MESSAGE_STATUS_WALL_POST
3242
            );
3243
3244
            if ($messageId && !empty($_FILES['picture']['tmp_name'])) {
3245
                self::sendWallMessageAttachmentFile(
3246
                    api_get_user_id(),
3247
                    $_FILES['picture'],
3248
                    $messageId
3249
                );
3250
            }
3251
3252
            Display::addFlash(Display::return_message(get_lang('MessageSent')));
3253
            header('Location: '.$url);
3254
            exit;
3255
        }
3256
    }
3257
3258
    /**
3259
     * @param int   $countPost
3260
     * @param array $htmlHeadXtra
3261
     */
3262
    public static function getScrollJs($countPost, &$htmlHeadXtra)
3263
    {
3264
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
3265
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
3266
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
3267
        $locale = api_get_language_isocode();
3268
3269
        // Add Jquery scroll pagination plugin
3270
        //$htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
3271
        // Add Jquery Time ago plugin
3272
        //$htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
3273
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
3274
        if (file_exists($timeAgoLocaleDir)) {
3275
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
3276
        }
3277
3278
        if ($countPost > self::DEFAULT_WALL_POSTS) {
3279
            $htmlHeadXtra[] = '<script>
3280
            $(function() {
3281
                var container = $("#wallMessages");
3282
                container.jscroll({
3283
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
3284
                    nextSelector: "a.nextPage:last",
3285
                    contentSelector: "",
3286
                    callback: timeAgo                    
3287
                });
3288
            });
3289
            </script>';
3290
        }
3291
3292
        $htmlHeadXtra[] = '<script>
3293
            function deleteMessage(id) 
3294
            {                      
3295
                $.ajax({
3296
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3297
                    success: function (result) {
3298
                        if (result) {
3299
                            $("#message_" + id).parent().parent().parent().parent().html(result);
3300
                        }
3301
                    }
3302
                });                        
3303
            }
3304
            
3305
            function deleteComment(id) 
3306
            {                      
3307
                $.ajax({
3308
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3309
                    success: function (result) {
3310
                        if (result) {
3311
                            $("#message_" + id).parent().parent().parent().html(result);
3312
                        }
3313
                    }
3314
                });                     
3315
            }           
3316
            
3317
            function submitComment(messageId) 
3318
            {
3319
                var data = $("#form_comment_"+messageId).serializeArray();                                
3320
                $.ajax({
3321
                    type : "POST",
3322
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
3323
                    data: data,
3324
                    success: function (result) {                        
3325
                        if (result) {
3326
                            $("#post_" + messageId + " textarea").val("");
3327
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
3328
                            $("#post_" + messageId + " .sub-mediapost").append(
3329
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved')).'</div>\')
3330
                            ); 
3331
                                                        
3332
                            $("#result_" + messageId + "").fadeIn("fast", function() {
3333
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
3334
                                    $(this).remove();
3335
                                }); 
3336
                            });
3337
                        }
3338
                    }
3339
                });  
3340
            } 
3341
            
3342
            $(function() {
3343
                timeAgo();
3344
                
3345
                /*$(".delete_message").on("click", function() {
3346
                    var id = $(this).attr("id");
3347
                    id = id.split("_")[1];          
3348
                    $.ajax({
3349
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3350
                        success: function (result) {
3351
                            if (result) {
3352
                                $("#message_" + id).parent().parent().parent().parent().html(result);
3353
                            }
3354
                        }
3355
                    });        
3356
                });                  
3357
                
3358
                
3359
                $(".delete_comment").on("click", function() {
3360
                    var id = $(this).attr("id");
3361
                    id = id.split("_")[1];                    
3362
                    $.ajax({
3363
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
3364
                        success: function (result) {
3365
                            if (result) {
3366
                                $("#message_" + id).parent().parent().parent().html(result);
3367
                            }
3368
                        }
3369
                    });
3370
                });          
3371
                */
3372
            });
3373
            
3374
            function timeAgo() {
3375
                $(".timeago").timeago();
3376
            }
3377
            </script>';
3378
    }
3379
3380
    /**
3381
     * @param int $userId
3382
     * @param int $countPost
3383
     *
3384
     * @return string
3385
     */
3386
    public static function getAutoExtendLink($userId, $countPost)
3387
    {
3388
        $userId = (int) $userId;
3389
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
3390
        $socialAutoExtendLink = '';
3391
        if ($countPost > self::DEFAULT_WALL_POSTS) {
3392
            $socialAutoExtendLink = Display::url(
3393
                get_lang('SeeMore'),
3394
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
3395
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
3396
                [
3397
                    'class' => 'nextPage next',
3398
                ]
3399
            );
3400
        }
3401
3402
        return $socialAutoExtendLink;
3403
    }
3404
3405
    /**
3406
     * @param int $userId
3407
     *
3408
     * @return array
3409
     */
3410
    public static function getThreadList($userId)
3411
    {
3412
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3413
3414
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
3415
3416
        $threads = [];
3417
        if (!empty($forumCourseId)) {
3418
            $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

3418
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
3419
            getNotificationsPerUser($userId, true, $forumCourseId);
3420
            $notification = Session::read('forum_notification');
3421
            Session::erase('forum_notification');
3422
3423
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
3424
                'cidReq' => $courseInfo['code'],
3425
            ]).'&';
3426
            if (isset($notification['thread']) && !empty($notification['thread'])) {
3427
                $threadList = array_filter(array_unique($notification['thread']));
3428
                $em = Database::getManager();
3429
                $repo = $em->getRepository('ChamiloCourseBundle:CForumThread');
3430
                foreach ($threadList as $threadId) {
3431
                    /** @var \Chamilo\CourseBundle\Entity\CForumThread $thread */
3432
                    $thread = $repo->find($threadId);
3433
                    if ($thread) {
3434
                        $threadUrl = $threadUrlBase.http_build_query([
3435
                            '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

3435
                            '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...
3436
                            'thread' => $thread->getIid(),
3437
                        ]);
3438
                        $threads[] = [
3439
                            'id' => $threadId,
3440
                            'url' => Display::url(
3441
                                $thread->getThreadTitle(),
3442
                                $threadUrl
3443
                            ),
3444
                            'name' => Display::url(
3445
                                $thread->getThreadTitle(),
3446
                                $threadUrl
3447
                            ),
3448
                            'description' => '',
3449
                        ];
3450
                    }
3451
                }
3452
            }
3453
        }
3454
3455
        return $threads;
3456
    }
3457
3458
    /**
3459
     * @param int $userId
3460
     *
3461
     * @return string
3462
     */
3463
    public static function getGroupBlock($userId)
3464
    {
3465
        $threadList = self::getThreadList($userId);
3466
        $userGroup = new UserGroup();
3467
3468
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
3469
        $courseInfo = null;
3470
        if (!empty($forumCourseId)) {
3471
            $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

3471
            $courseInfo = api_get_course_info_by_id(/** @scrutinizer ignore-type */ $forumCourseId);
Loading history...
3472
        }
3473
3474
        $social_group_block = '';
3475
        if (!empty($courseInfo)) {
3476
            if (!empty($threadList)) {
3477
                $social_group_block .= '<div class="list-group">';
3478
                foreach ($threadList as $group) {
3479
                    $social_group_block .= ' <li class="list-group-item">';
3480
                    $social_group_block .= $group['name'];
3481
                    $social_group_block .= '</li>';
3482
                }
3483
                $social_group_block .= '</div>';
3484
            }
3485
3486
            $social_group_block .= Display::url(
3487
                get_lang('SeeAllCommunities'),
3488
                api_get_path(WEB_CODE_PATH).'forum/index.php?cidReq='.$courseInfo['code']
3489
            );
3490
3491
            if (!empty($social_group_block)) {
3492
                $social_group_block = Display::panelCollapse(
3493
                    get_lang('MyCommunities'),
3494
                    $social_group_block,
3495
                    'sm-groups',
3496
                    null,
3497
                    'grups-acordion',
3498
                    'groups-collapse'
3499
                );
3500
            }
3501
        } else {
3502
            // Load my groups
3503
            $results = $userGroup->get_groups_by_user($userId,
3504
                [
3505
                    GROUP_USER_PERMISSION_ADMIN,
3506
                    GROUP_USER_PERMISSION_READER,
3507
                    GROUP_USER_PERMISSION_MODERATOR,
3508
                    GROUP_USER_PERMISSION_HRM,
3509
                ]
3510
            );
3511
3512
            $myGroups = [];
3513
            if (!empty($results)) {
3514
                foreach ($results as $result) {
3515
                    $id = $result['id'];
3516
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
3517
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
3518
3519
                    $group_url = "group_view.php?id=$id";
3520
3521
                    $link = Display::url(
3522
                        api_ucwords(cut($result['name'], 40, true)),
3523
                        $group_url
3524
                    );
3525
3526
                    $result['name'] = $link;
3527
3528
                    $picture = $userGroup->get_picture_group(
3529
                        $id,
3530
                        $result['picture'],
3531
                        null,
3532
                        GROUP_IMAGE_SIZE_BIG
3533
                    );
3534
3535
                    $result['picture'] = '<img class="img-responsive" src="'.$picture['file'].'" />';
3536
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
3537
                        get_lang('SeeMore').'</a></div>';
3538
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
3539
                    $myGroups[] = [
3540
                        'url' => Display::url(
3541
                            $result['picture'],
3542
                            $group_url
3543
                        ),
3544
                        'name' => $result['name'],
3545
                        'description' => $group_info.$group_actions,
3546
                    ];
3547
                }
3548
3549
                $social_group_block .= '<div class="list-group">';
3550
                foreach ($myGroups as $group) {
3551
                    $social_group_block .= ' <li class="list-group-item">';
3552
                    $social_group_block .= $group['name'];
3553
                    $social_group_block .= '</li>';
3554
                }
3555
                $social_group_block .= '</div>';
3556
3557
                $form = new FormValidator(
3558
                    'find_groups_form',
3559
                    'get',
3560
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
3561
                    null,
3562
                    null,
3563
                    FormValidator::LAYOUT_BOX_NO_LABEL
3564
                );
3565
                $form->addHidden('search_type', 2);
3566
3567
                $form->addText(
3568
                    'q',
3569
                    get_lang('Search'),
3570
                    false,
3571
                    [
3572
                        'aria-label' => get_lang('Search'),
3573
                        'custom' => true,
3574
                        'placeholder' => get_lang('Search'),
3575
                    ]
3576
                );
3577
3578
                $social_group_block .= $form->returnForm();
3579
3580
                if (!empty($social_group_block)) {
3581
                    $social_group_block = Display::panelCollapse(
3582
                        get_lang('MyGroups'),
3583
                        $social_group_block,
3584
                        'sm-groups',
3585
                        null,
3586
                        'grups-acordion',
3587
                        'groups-collapse'
3588
                    );
3589
                }
3590
            }
3591
        }
3592
3593
        return $social_group_block;
3594
    }
3595
3596
    /**
3597
     * Returns the formatted header message post.
3598
     *
3599
     * @param int   $authorInfo
3600
     * @param int   $receiverInfo
3601
     * @param array $message      Message data
3602
     *
3603
     * @return string $html       The formatted header message post
3604
     */
3605
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
3606
    {
3607
        $currentUserId = api_get_user_id();
3608
        $iconStatus = null;
3609
        $authorId = (int) $authorInfo['user_id'];
3610
        $receiverId = (int) $receiverInfo['user_id'];
3611
        $userStatus = (int) $authorInfo['status'];
3612
        $urlImg = api_get_path(WEB_IMG_PATH);
3613
        $isAdmin = self::is_admin($authorId);
3614
3615
        if ($userStatus === 5) {
3616
            if ($authorInfo['has_certificates']) {
3617
                $iconStatus = Display::return_icon('identifier_graduated.png',get_lang('User status'),['class' => 'float-left'],ICON_SIZE_SMALL);
3618
            } else {
3619
                $iconStatus = Display::return_icon('identifier_student.png',get_lang('User status'),['class' => 'float-left'],ICON_SIZE_SMALL);
3620
            }
3621
        } else {
3622
            if ($userStatus === 1) {
3623
                if ($isAdmin) {
3624
                    $iconStatus = Display::return_icon('identifier_admin.png',get_lang('User status'),['class' => 'float-left'],ICON_SIZE_SMALL);
3625
                } else {
3626
                    $iconStatus = Display::return_icon('identifier_teacher.png',get_lang('User status'),['class' => 'float-left'],ICON_SIZE_SMALL);
3627
                }
3628
            }
3629
        }
3630
3631
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
3632
        $avatarAuthor = $authorInfo['avatar'];
3633
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
3634
        $nameCompleteAuthor = $authorInfo['complete_name'];
3635
3636
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
3637
        $nameCompleteReceiver = $receiverInfo['complete_name'];
3638
3639
        $htmlReceiver = '';
3640
        if ($authorId !== $receiverId) {
3641
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
3642
        }
3643
3644
        if (!empty($message['group_info'])) {
3645
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
3646
        }
3647
        $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...
3648
3649
        if (!empty($message['thread_id'])) {
3650
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
3651
            $canEdit = false;
3652
        }
3653
3654
        $postAttachment = self::getPostAttachment($message);
3655
3656
        $html = '';
3657
        $html .= '<div class="top-mediapost" >';
3658
        $html .= '<div class="pull-right btn-group btn-group-sm">';
3659
3660
        $html .= MessageManager::getLikesButton(
3661
            $message['id'],
3662
            $currentUserId,
3663
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
3664
        );
3665
3666
        if ($canEdit) {
3667
            $htmlDelete = Display::url(
3668
                Display::returnFontAwesomeIcon('trash', '', true),
3669
                'javascript:void(0)',
3670
                [
3671
                    'id' => 'message_'.$message['id'],
3672
                    'title' => get_lang('SocialMessageDelete'),
3673
                    'onclick' => 'deleteMessage('.$message['id'].')',
3674
                    'class' => 'btn btn-default',
3675
                ]
3676
            );
3677
3678
            $html .= $htmlDelete;
3679
        }
3680
        $html .= '</div>';
3681
3682
        $html .= '<div class="user-image" >';
3683
        $html .= '<a href="'.$urlAuthor.'">
3684
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
3685
        $html .= '</div>';
3686
        $html .= '<div class="user-data">';
3687
        $html .= $iconStatus;
3688
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
3689
        $html .= '<div class="post-date">'.$date.'</div>';
3690
        $html .= '</div>';
3691
        $html .= '<div class="msg-content">';
3692
        if (!empty($postAttachment)) {
3693
            $html .= '<div class="post-attachment thumbnail">';
3694
            $html .= $postAttachment;
3695
            $html .= '</div>';
3696
        }
3697
        $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
3698
        $html .= '</div>';
3699
        $html .= '</div>'; // end mediaPost
3700
3701
        // Popularity post functionality
3702
        $html .= '<div class="popularity-mediapost"></div>';
3703
3704
        return $html;
3705
    }
3706
}
3707