Passed
Push — master ( ea9271...39d3dd )
by Julito
12:07
created

SocialManager::getWallMessagesHTML()   B

Complexity

Conditions 7
Paths 36

Size

Total Lines 85
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 61
nc 36
nop 6
dl 0
loc 85
rs 7.9175
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

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

276
                /** @scrutinizer ignore-type */ $messageId,
Loading history...
277
                Notification::NOTIFICATION_TYPE_INVITATION,
278
                [$friend_id],
279
                $message_title,
280
                $message_content,
281
                $senderInfo
282
            );
283
284
            return true;
285
        } else {
286
            // invitation already exist
287
            $sql = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
288
                    WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7';
289
            $res_if_exist = Database::query($sql);
290
            $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
291
            if ($row_if_exist['count'] == 1) {
292
                $sql = 'UPDATE '.$tbl_message.' SET
293
                        msg_status=5, content = "'.$clean_message_content.'"
294
                        WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7 ';
295
                Database::query($sql);
296
297
                return true;
298
            } else {
299
                return false;
300
            }
301
        }
302
    }
303
304
    /**
305
     * Get number messages of the inbox.
306
     *
307
     * @author isaac flores paz
308
     *
309
     * @param int user receiver id
310
     *
311
     * @return int
312
     */
313
    public static function get_message_number_invitation_by_user_id($user_receiver_id)
314
    {
315
        $table = Database::get_main_table(TABLE_MESSAGE);
316
        $user_receiver_id = (int) $user_receiver_id;
317
        $sql = 'SELECT COUNT(*) as count_message_in_box FROM '.$table.'
318
                WHERE
319
                    user_receiver_id='.$user_receiver_id.' AND
320
                    msg_status='.MESSAGE_STATUS_INVITATION_PENDING;
321
        $res = Database::query($sql);
322
        $row = Database::fetch_array($res, 'ASSOC');
323
324
        return $row['count_message_in_box'];
325
    }
326
327
    /**
328
     * Get number of messages sent to other users.
329
     *
330
     * @param int $sender_id
331
     *
332
     * @return int
333
     */
334
    public static function getCountMessagesSent($sender_id)
335
    {
336
        $table = Database::get_main_table(TABLE_MESSAGE);
337
        $sql = 'SELECT COUNT(*) FROM '.$table.'
338
                WHERE
339
                    user_sender_id='.intval($sender_id).' AND
340
                    msg_status < 5';
341
        $res = Database::query($sql);
342
        $row = Database::fetch_row($res);
343
344
        return $row[0];
345
    }
346
347
    /**
348
     * Get number of messages received from other users.
349
     *
350
     * @param int $receiver_id
351
     *
352
     * @return int
353
     */
354
    public static function getCountMessagesReceived($receiver_id)
355
    {
356
        $table = Database::get_main_table(TABLE_MESSAGE);
357
        $sql = 'SELECT COUNT(*) FROM '.$table.'
358
                WHERE
359
                    user_receiver_id='.intval($receiver_id).' AND
360
                    msg_status < 4';
361
        $res = Database::query($sql);
362
        $row = Database::fetch_row($res);
363
364
        return $row[0];
365
    }
366
367
    /**
368
     * Get number of messages posted on own wall.
369
     *
370
     * @param int $userId
371
     *
372
     * @return int
373
     */
374
    public static function getCountWallPostedMessages($userId)
375
    {
376
        $userId = (int) $userId;
377
378
        if (empty($userId)) {
379
            return 0;
380
        }
381
382
        $table = Database::get_main_table(TABLE_MESSAGE);
383
        $sql = 'SELECT COUNT(*) 
384
                FROM '.$table.'
385
                WHERE
386
                    user_sender_id='.$userId.' AND
387
                    (msg_status = '.MESSAGE_STATUS_WALL.' OR 
388
                    msg_status = '.MESSAGE_STATUS_WALL_POST.') AND 
389
                    parent_id = 0';
390
        $res = Database::query($sql);
391
        $row = Database::fetch_row($res);
392
393
        return $row[0];
394
    }
395
396
    /**
397
     * Get invitation list received by user.
398
     *
399
     * @author isaac flores paz
400
     *
401
     * @param int $userId
402
     *
403
     * @return array
404
     */
405
    public static function get_list_invitation_of_friends_by_user_id($userId)
406
    {
407
        $userId = (int) $userId;
408
409
        if (empty($userId)) {
410
            return [];
411
        }
412
413
        $table = Database::get_main_table(TABLE_MESSAGE);
414
        $sql = 'SELECT user_sender_id, send_date, title, content
415
                FROM '.$table.'
416
                WHERE
417
                    user_receiver_id = '.$userId.' AND
418
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
419
        $res = Database::query($sql);
420
        $list = [];
421
        while ($row = Database::fetch_array($res, 'ASSOC')) {
422
            $list[] = $row;
423
        }
424
425
        return $list;
426
    }
427
428
    /**
429
     * Get invitation list sent by user.
430
     *
431
     * @author Julio Montoya <[email protected]>
432
     *
433
     * @param int $userId
434
     *
435
     * @return array
436
     */
437
    public static function get_list_invitation_sent_by_user_id($userId)
438
    {
439
        $userId = (int) $userId;
440
441
        if (empty($userId)) {
442
            return [];
443
        }
444
445
        $table = Database::get_main_table(TABLE_MESSAGE);
446
        $sql = 'SELECT user_receiver_id, send_date,title,content
447
                FROM '.$table.'
448
                WHERE
449
                    user_sender_id = '.$userId.' AND
450
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
451
        $res = Database::query($sql);
452
        $list = [];
453
        while ($row = Database::fetch_array($res, 'ASSOC')) {
454
            $list[$row['user_receiver_id']] = $row;
455
        }
456
457
        return $list;
458
    }
459
460
    /**
461
     * Get count invitation sent by user.
462
     *
463
     * @author Julio Montoya <[email protected]>
464
     *
465
     * @param int $userId
466
     *
467
     * @return int
468
     */
469
    public static function getCountInvitationSent($userId)
470
    {
471
        if (empty($userId)) {
472
            return 0;
473
        }
474
475
        $table = Database::get_main_table(TABLE_MESSAGE);
476
        $sql = 'SELECT count(user_receiver_id) count
477
                FROM '.$table.'
478
                WHERE
479
                    user_sender_id = '.intval($userId).' AND
480
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
481
        $res = Database::query($sql);
482
        if (Database::num_rows($res)) {
483
            $row = Database::fetch_array($res, 'ASSOC');
484
485
            return (int) $row['count'];
486
        }
487
488
        return 0;
489
    }
490
491
    /**
492
     * Accepts invitation.
493
     *
494
     * @param int $user_send_id
495
     * @param int $user_receiver_id
496
     *
497
     * @return bool
498
     *
499
     * @author isaac flores paz
500
     * @author Julio Montoya <[email protected]> Cleaning code
501
     */
502
    public static function invitation_accepted($user_send_id, $user_receiver_id)
503
    {
504
        if (empty($user_send_id) || empty($user_receiver_id)) {
505
            return false;
506
        }
507
508
        $table = Database::get_main_table(TABLE_MESSAGE);
509
        $sql = "UPDATE $table
510
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
511
                WHERE
512
                    user_sender_id = ".((int) $user_send_id)." AND
513
                    user_receiver_id=".((int) $user_receiver_id)." AND
514
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
515
        Database::query($sql);
516
517
        return true;
518
    }
519
520
    /**
521
     * Denies invitation.
522
     *
523
     * @param int user sender id
524
     * @param int user receiver id
525
     *
526
     * @return bool
527
     *
528
     * @author isaac flores paz
529
     * @author Julio Montoya <[email protected]> Cleaning code
530
     */
531
    public static function invitation_denied($user_send_id, $user_receiver_id)
532
    {
533
        if (empty($user_send_id) || empty($user_receiver_id)) {
534
            return false;
535
        }
536
        $table = Database::get_main_table(TABLE_MESSAGE);
537
        $sql = 'DELETE FROM '.$table.'
538
                WHERE
539
                    user_sender_id =  '.((int) $user_send_id).' AND
540
                    user_receiver_id='.((int) $user_receiver_id).' AND
541
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
542
        Database::query($sql);
543
544
        return true;
545
    }
546
547
    /**
548
     * Allow attaching to group.
549
     *
550
     * @author Isaac Flores Paz
551
     *
552
     * @param int $id_friend_qualify User to qualify
553
     * @param int $type_qualify      Kind of rating
554
     *
555
     * @deprecated 2017-03
556
     */
557
    public static function qualify_friend($id_friend_qualify, $type_qualify)
558
    {
559
        $table = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
560
        $user_id = api_get_user_id();
561
        $sql = 'UPDATE '.$table.' SET relation_type='.((int) $type_qualify).'
562
                WHERE user_id = '.$user_id.' AND friend_user_id='.(int) $id_friend_qualify;
563
        Database::query($sql);
564
    }
565
566
    /**
567
     * Get user's feeds.
568
     *
569
     * @param int $user  User ID
570
     * @param int $limit Limit of posts per feed
571
     *
572
     * @return string HTML section with all feeds included
573
     *
574
     * @author  Yannick Warnier
575
     *
576
     * @since   Dokeos 1.8.6.1
577
     */
578
    public static function getUserRssFeed($user, $limit = 5)
579
    {
580
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
581
582
        if (empty($feed)) {
583
            return '';
584
        }
585
        $feeds = explode(';', $feed['rssfeeds']);
586
        if (count($feeds) == 0) {
587
            return '';
588
        }
589
        $res = '';
590
        foreach ($feeds as $url) {
591
            if (empty($url)) {
592
                continue;
593
            }
594
            try {
595
                $channel = Reader::import($url);
596
                $i = 1;
597
                if (!empty($channel)) {
598
                    $iconRss = '';
599
                    if (!empty($feed)) {
600
                        $iconRss = Display::url(
601
                            Display::return_icon('social_rss.png', '', [], 22),
602
                            Security::remove_XSS($feed['rssfeeds']),
603
                            ['target' => '_blank']
604
                        );
605
                    }
606
607
                    $res .= '<h3 class="title-rss">'.$iconRss.' '.$channel->getTitle().'</h3>';
608
                    $res .= '<div class="rss-items">';
609
                    /** @var Rss $item */
610
                    foreach ($channel as $item) {
611
                        if ($limit >= 0 and $i > $limit) {
612
                            break;
613
                        }
614
                        $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
615
                        $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
616
                        $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
617
                        $i++;
618
                    }
619
                    $res .= '</div>';
620
                }
621
            } catch (Exception $e) {
622
                error_log($e->getMessage());
623
            }
624
        }
625
626
        return $res;
627
    }
628
629
    /**
630
     * Sends invitations to friends.
631
     *
632
     * @param int    $userId
633
     * @param string $subject
634
     * @param string $content
635
     *
636
     * @return bool
637
     */
638
    public static function sendInvitationToUser($userId, $subject = '', $content = '')
639
    {
640
        $user_info = api_get_user_info($userId);
641
        $success = get_lang('MessageSentTo');
642
        $success .= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
643
644
        if (isset($subject) && isset($content) && isset($userId)) {
645
            $result = MessageManager::send_message($userId, $subject, $content);
646
647
            if ($result) {
648
                Display::addFlash(
649
                    Display::return_message($success, 'normal', false)
650
                );
651
            } else {
652
                Display::addFlash(
653
                    Display::return_message(get_lang('ErrorSendingMessage'), 'error', false)
654
                );
655
            }
656
657
            return false;
658
        } elseif (isset($userId) && !isset($subject)) {
659
            if (isset($userId) && $userId > 0) {
660
                $count = self::send_invitation_friend(
661
                    api_get_user_id(),
662
                    $userId,
663
                    get_lang('Invitation'),
664
                    $content
665
                );
666
667
                if ($count) {
668
                    Display::addFlash(
669
                        Display::return_message(
670
                            api_htmlentities(get_lang('InvitationHasBeenSent')),
671
                            'normal',
672
                            false
673
                        )
674
                    );
675
                } else {
676
                    Display::addFlash(
677
                        Display::return_message(
678
                            api_htmlentities(get_lang('YouAlreadySentAnInvitation')),
679
                            'warning',
680
                            false
681
                        )
682
                    );
683
                }
684
            }
685
        }
686
    }
687
688
    /**
689
     * Helper functions definition.
690
     */
691
    public static function get_logged_user_course_html($my_course, $count)
692
    {
693
        $result = '';
694
        // Table definitions
695
        $main_user_table = Database::get_main_table(TABLE_MAIN_USER);
696
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
697
        $course_directory = $my_course['course_info']['directory'];
698
        $course_title = $my_course['course_info']['title'];
699
        $course_visibility = $my_course['course_info']['visibility'];
700
701
        $user_in_course_status = CourseManager::getUserInCourseStatus(
702
            api_get_user_id(),
703
            $my_course['course_info']['real_id']
704
        );
705
706
        $course_path = api_get_path(SYS_COURSE_PATH).$course_directory; // course path
707
        if (api_get_setting('course_images_in_courses_list') === 'true') {
708
            if (file_exists($course_path.'/course-pic85x85.png')) {
709
                $image = $my_course['course_info']['course_image'];
710
                $imageCourse = Display::img($image, $course_title, ['class' => 'img-course']);
711
            } else {
712
                $imageCourse = Display::return_icon(
713
                    'session_default_small.png',
714
                    $course_title,
715
                    ['class' => 'img-course']
716
                );
717
            }
718
        } else {
719
            $imageCourse = Display::return_icon(
720
                'course.png',
721
                get_lang('Course'),
722
                ['class' => 'img-default']
723
            );
724
        }
725
726
        //display course entry
727
        if (api_get_setting('course_images_in_courses_list') === 'true') {
728
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:65px;">';
729
        } else {
730
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:44px;">';
731
        }
732
        $result .= $imageCourse;
733
734
        //show a hyperlink to the course, unless the course is closed and user is not course admin
735
        if ($course_visibility != COURSE_VISIBILITY_HIDDEN &&
736
            ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER)
737
        ) {
738
            $result .= '<span class="title">'.$course_title.'<span>';
739
        } else {
740
            $result .= $course_title.' '.get_lang('CourseClosed');
741
        }
742
743
        $result .= '</li>';
744
        $session = '';
745
        if (!empty($my_course['session_name']) && !empty($my_course['id_session'])) {
746
            // Request for the name of the general coach
747
            $sql = 'SELECT lastname, firstname
748
                    FROM '.$tbl_session.' ts
749
                    LEFT JOIN '.$main_user_table.' tu
750
                    ON ts.id_coach = tu.user_id
751
                    WHERE ts.id='.(int) $my_course['id_session'].' LIMIT 1';
752
            $rs = Database::query($sql);
753
            $sessioncoach = Database::store_result($rs);
754
            $sessioncoach = $sessioncoach[0];
755
756
            $session = [];
757
            $session['title'] = $my_course['session_name'];
758
            if ($my_course['access_start_date'] == '0000-00-00') {
759
                $session['dates'] = get_lang('WithoutTimeLimits');
760
                if (api_get_setting('show_session_coach') === 'true') {
761
                    $session['coach'] = get_lang('GeneralCoach').': '.
762
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
763
                }
764
            } else {
765
                $session['dates'] = ' - '.get_lang('From').' '.$my_course['access_start_date'].' '.get_lang('To').' '.$my_course['access_end_date'];
766
                if (api_get_setting('show_session_coach') === 'true') {
767
                    $session['coach'] = get_lang('GeneralCoach').': '.
768
                        api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
769
                }
770
            }
771
        }
772
773
        $my_course['id_session'] = isset($my_course['id_session']) ? $my_course['id_session'] : 0;
774
        $output = [
775
            $my_course['user_course_cat'],
776
            $result,
777
            $my_course['id_session'],
778
            $session,
779
        ];
780
781
        return $output;
782
    }
783
784
    /**
785
     * Shows the avatar block in social pages.
786
     *
787
     * @param string $show     highlight link possible values:
788
     *                         group_add,
789
     *                         home,
790
     *                         messages,
791
     *                         messages_inbox,
792
     *                         messages_compose,
793
     *                         messages_outbox,
794
     *                         invitations,
795
     *                         shared_profile,
796
     *                         friends,
797
     *                         groups search
798
     * @param int    $group_id
799
     * @param int    $user_id
800
     */
801
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
802
    {
803
        if (empty($user_id)) {
804
            $user_id = api_get_user_id();
805
        }
806
807
        $show_groups = [
808
            'groups',
809
            'group_messages',
810
            'messages_list',
811
            'group_add',
812
            'mygroups',
813
            'group_edit',
814
            'member_list',
815
            'invite_friends',
816
            'waiting_list',
817
            'browse_groups',
818
        ];
819
820
        $template = new Template(null, false, false, false, false, false);
821
822
        if (in_array($show, $show_groups) && !empty($group_id)) {
823
            // Group image
824
            $userGroup = new UserGroup();
825
            $group_info = $userGroup->get($group_id);
826
827
            $userGroupImage = $userGroup->get_picture_group(
828
                $group_id,
829
                $group_info['picture'],
830
                128,
831
                GROUP_IMAGE_SIZE_BIG
832
            );
833
834
            $template->assign('show_group', true);
835
            $template->assign('group_id', $group_id);
836
            $template->assign('user_group_image', $userGroupImage);
837
            //$template->assign('user_group', $group_info);
838
            $template->assign(
839
                'user_is_group_admin',
840
                $userGroup->is_group_admin(
841
                    $group_id,
842
                    api_get_user_id()
843
                )
844
            );
845
        } else {
846
            $template->assign('show_group', false);
847
            $template->assign('show_user', true);
848
            $template->assign(
849
                'user_image',
850
                [
851
                    'big' => UserManager::getUserPicture(
852
                        $user_id,
853
                        USER_IMAGE_SIZE_BIG
854
                    ),
855
                    'normal' => UserManager::getUserPicture(
856
                        $user_id,
857
                        USER_IMAGE_SIZE_MEDIUM
858
                    ),
859
                ]
860
            );
861
        }
862
863
        $skillBlock = $template->get_template('social/avatar_block.tpl');
864
865
        return $template->fetch($skillBlock);
866
    }
867
868
    /**
869
     * Shows the right menu of the Social Network tool.
870
     *
871
     * @param string $show                       highlight link possible values:
872
     *                                           group_add,
873
     *                                           home,
874
     *                                           messages,
875
     *                                           messages_inbox,
876
     *                                           messages_compose ,
877
     *                                           messages_outbox,
878
     *                                           invitations,
879
     *                                           shared_profile,
880
     *                                           friends,
881
     *                                           groups search
882
     * @param int    $group_id                   group id
883
     * @param int    $user_id                    user id
884
     * @param bool   $show_full_profile          show profile or not (show or hide the user image/information)
885
     * @param bool   $show_delete_account_button
886
     */
887
    public static function show_social_menu(
888
        $show = '',
889
        $group_id = 0,
890
        $user_id = 0,
891
        $show_full_profile = false,
892
        $show_delete_account_button = false
893
    ) {
894
        if (empty($user_id)) {
895
            $user_id = api_get_user_id();
896
        }
897
898
        $usergroup = new UserGroup();
899
        $show_groups = [
900
            'groups',
901
            'group_messages',
902
            'messages_list',
903
            'group_add',
904
            'mygroups',
905
            'group_edit',
906
            'member_list',
907
            'invite_friends',
908
            'waiting_list',
909
            'browse_groups',
910
        ];
911
912
        // get count unread message and total invitations
913
        $count_unread_message = MessageManager::getNumberOfMessages(true);
914
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
915
916
        $number_of_new_messages_of_friend = self::get_message_number_invitation_by_user_id(api_get_user_id());
917
        $group_pending_invitations = $usergroup->get_groups_by_user(
918
            api_get_user_id(),
919
            GROUP_USER_PERMISSION_PENDING_INVITATION,
920
            false
921
        );
922
        $group_pending_invitations = count($group_pending_invitations);
923
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
924
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
925
926
        $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), null, ICON_SIZE_SMALL);
927
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), null, ICON_SIZE_SMALL);
928
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), null, ICON_SIZE_SMALL);
929
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), null, ICON_SIZE_SMALL);
930
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), null, ICON_SIZE_SMALL);
931
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), null, ICON_SIZE_SMALL);
932
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
933
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), null, ICON_SIZE_SMALL);
934
        $portfolioIcon = Display::return_icon('wiki_task.png', get_lang('Portfolio'));
935
        $personalDataIcon = Display::return_icon('database.png', get_lang('PersonalDataReport'));
936
937
        $html = '';
938
        $active = null;
939
        if (!in_array(
940
            $show,
941
            ['shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends']
942
        )) {
943
            $links = '<ul class="nav navbar-nav">';
944
            $active = $show == 'home' ? 'active' : null;
945
            $links .= '
946
                <li class="home-icon '.$active.'">
947
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
948
                        '.$homeIcon.' '.get_lang('Home').'
949
                    </a>
950
                </li>';
951
            $active = $show == 'messages' ? 'active' : null;
952
            $links .= '
953
                <li class="messages-icon '.$active.'">
954
                    <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
955
                        '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
956
                    </a>
957
                </li>';
958
959
            //Invitations
960
            $active = $show == 'invitations' ? 'active' : null;
961
            $links .= '
962
                <li class="invitations-icon '.$active.'">
963
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
964
                        '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
965
                    </a>
966
                </li>';
967
968
            //Shared profile and groups
969
            $active = $show == 'shared_profile' ? 'active' : null;
970
            $links .= '
971
                <li class="shared-profile-icon'.$active.'">
972
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
973
                        '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
974
                    </a>
975
                </li>';
976
            $active = $show == 'friends' ? 'active' : null;
977
            $links .= '
978
                <li class="friends-icon '.$active.'">
979
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
980
                        '.$friendsIcon.' '.get_lang('Friends').'
981
                    </a>
982
                </li>';
983
            $active = $show == 'browse_groups' ? 'active' : null;
984
            $links .= '
985
                <li class="browse-groups-icon '.$active.'">
986
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/groups.php">
987
                        '.$groupsIcon.' '.get_lang('SocialGroups').'
988
                    </a>
989
                </li>';
990
991
            //Search users
992
            $active = $show == 'search' ? 'active' : null;
993
            $links .= '
994
                <li class="search-icon '.$active.'">
995
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
996
                        '.$searchIcon.' '.get_lang('Search').'
997
                    </a>
998
                </li>';
999
1000
            //My files
1001
            $active = $show == 'myfiles' ? 'active' : null;
1002
1003
            $myFiles = '
1004
                <li class="myfiles-icon '.$active.'">
1005
                    <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1006
                        '.$filesIcon.' '.get_lang('MyFiles').'
1007
                    </a>
1008
                </li>';
1009
1010
            if (api_get_setting('allow_my_files') === 'false') {
1011
                $myFiles = '';
1012
            }
1013
            $links .= $myFiles;
1014
            if (api_get_configuration_value('allow_portfolio_tool')) {
1015
                $links .= '
1016
                    <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1017
                        <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1018
                            '.$portfolioIcon.' '.get_lang('Portfolio').'
1019
                        </a>
1020
                    </li>
1021
                ';
1022
            }
1023
1024
            if (!api_get_configuration_value('disable_gdpr')) {
1025
                $active = $show == 'personal-data' ? 'active' : null;
1026
                $personalData = '
1027
                    <li class="personal-data-icon '.$active.'">
1028
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/personal_data.php">
1029
                            '.$personalDataIcon.' '.get_lang('PersonalDataReport').'
1030
                        </a>
1031
                    </li>';
1032
                $links .= $personalData;
1033
                $links .= '</ul>';
1034
            }
1035
1036
            $html .= Display::panelCollapse(
1037
                get_lang('SocialNetwork'),
1038
                $links,
1039
                'social-network-menu',
1040
                null,
1041
                'sn-sidebar',
1042
                'sn-sidebar-collapse'
1043
            );
1044
        }
1045
1046
        if (in_array($show, $show_groups) && !empty($group_id)) {
1047
            $html .= $usergroup->show_group_column_information(
1048
                $group_id,
1049
                api_get_user_id(),
1050
                $show
1051
            );
1052
        }
1053
1054
        if ($show == 'shared_profile') {
1055
            $links = '<ul class="nav navbar-nav">';
1056
            // My own profile
1057
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
1058
                $links .= '
1059
                    <li class="home-icon '.$active.'">
1060
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
1061
                            '.$homeIcon.' '.get_lang('Home').'
1062
                        </a>
1063
                    </li>
1064
                    <li class="messages-icon '.$active.'">
1065
                        <a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">
1066
                            '.$messagesIcon.' '.get_lang('Messages').$count_unread_message.'
1067
                        </a>
1068
                    </li>';
1069
                $active = $show == 'invitations' ? 'active' : null;
1070
                $links .= '
1071
                    <li class="invitations-icon'.$active.'">
1072
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">
1073
                            '.$invitationsIcon.' '.get_lang('Invitations').$total_invitations.'
1074
                        </a>
1075
                    </li>';
1076
1077
                $links .= '
1078
                    <li class="shared-profile-icon active">
1079
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/profile.php">
1080
                            '.$sharedProfileIcon.' '.get_lang('ViewMySharedProfile').'
1081
                        </a>
1082
                    </li>
1083
                    <li class="friends-icon">
1084
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/friends.php">
1085
                            '.$friendsIcon.' '.get_lang('Friends').'
1086
                        </a>
1087
                    </li>
1088
                    <li class="browse-groups-icon">
1089
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/groups.php">
1090
                            '.$groupsIcon.' '.get_lang('SocialGroups').'
1091
                        </a>
1092
                    </li>';
1093
                $active = $show == 'search' ? 'active' : null;
1094
                $links .= '
1095
                    <li class="search-icon '.$active.'">
1096
                        <a href="'.api_get_path(WEB_CODE_PATH).'social/search.php">
1097
                            '.$searchIcon.' '.get_lang('Search').'
1098
                        </a>
1099
                    </li>';
1100
                $active = $show == 'myfiles' ? 'active' : null;
1101
1102
                $myFiles = '
1103
                    <li class="myfiles-icon '.$active.'">
1104
                     <a href="'.api_get_path(WEB_CODE_PATH).'social/myfiles.php">
1105
                            '.$filesIcon.' '.get_lang('MyFiles').'
1106
                        </a>
1107
                    </li>';
1108
1109
                if (api_get_setting('allow_my_files') === 'false') {
1110
                    $myFiles = '';
1111
                }
1112
                $links .= $myFiles;
1113
1114
                if (api_get_configuration_value('allow_portfolio_tool')) {
1115
                    $links .= '
1116
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1117
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php">
1118
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1119
                            </a>
1120
                        </li>
1121
                    ';
1122
                }
1123
            }
1124
1125
            // My friend profile.
1126
            if ($user_id != api_get_user_id()) {
1127
                $sendMessageText = get_lang('SendMessage');
1128
                $sendMessageIcon = Display::return_icon(
1129
                    'new-message.png',
1130
                    $sendMessageText
1131
                );
1132
                $sendMessageUrl = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?'.http_build_query([
1133
                    'a' => 'get_user_popup',
1134
                    'user_id' => $user_id,
1135
                ]);
1136
1137
                $links .= '<li>';
1138
                $links .= Display::url(
1139
                    "$sendMessageIcon $sendMessageText",
1140
                    $sendMessageUrl,
1141
                    [
1142
                        'class' => 'ajax',
1143
                        'title' => $sendMessageText,
1144
                        'data-title' => $sendMessageText,
1145
                    ]
1146
                );
1147
                $links .= '</li>';
1148
1149
                if (api_get_configuration_value('allow_portfolio_tool')) {
1150
                    $links .= '
1151
                        <li class="portoflio-icon '.($show == 'portfolio' ? 'active' : '').'">
1152
                            <a href="'.api_get_path(WEB_CODE_PATH).'portfolio/index.php?user='.$user_id.'">
1153
                                '.$portfolioIcon.' '.get_lang('Portfolio').'
1154
                            </a>
1155
                        </li>
1156
                    ';
1157
                }
1158
            }
1159
1160
            // Check if I already sent an invitation message
1161
            $invitation_sent_list = self::get_list_invitation_sent_by_user_id(
1162
                api_get_user_id()
1163
            );
1164
1165
            if (isset($invitation_sent_list[$user_id]) && is_array($invitation_sent_list[$user_id]) &&
1166
                count($invitation_sent_list[$user_id]) > 0
1167
            ) {
1168
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.
1169
                    Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation'))
1170
                    .'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
1171
            } else {
1172
                if (!$show_full_profile) {
1173
                    $links .= '<li>
1174
                        <a class="btn-to-send-invitation" href="#" data-send-to="'.$user_id.'" title="'.get_lang('SendInvitation').'">'.
1175
                        Display::return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').
1176
                        '</a></li>';
1177
                }
1178
            }
1179
1180
            $links .= '</ul>';
1181
            $html .= Display::panelCollapse(
1182
                get_lang('SocialNetwork'),
1183
                $links,
1184
                'social-network-menu',
1185
                null,
1186
                'sn-sidebar',
1187
                'sn-sidebar-collapse'
1188
            );
1189
1190
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
1191
                $personal_course_list = UserManager::get_personal_session_course_list($user_id);
1192
                $course_list_code = [];
1193
                $i = 1;
1194
                if (is_array($personal_course_list)) {
1195
                    foreach ($personal_course_list as $my_course) {
1196
                        if ($i <= 10) {
1197
                            $course_list_code[] = ['code' => $my_course['code']];
1198
                        } else {
1199
                            break;
1200
                        }
1201
                        $i++;
1202
                    }
1203
                    // To avoid repeated courses
1204
                    $course_list_code = array_unique_dimensional($course_list_code);
1205
                }
1206
1207
                // Announcements
1208
                $my_announcement_by_user_id = intval($user_id);
1209
                $announcements = [];
1210
                foreach ($course_list_code as $course) {
1211
                    $course_info = api_get_course_info($course['code']);
1212
                    if (!empty($course_info)) {
1213
                        $content = AnnouncementManager::get_all_annoucement_by_user_course(
1214
                            $course_info['code'],
1215
                            $my_announcement_by_user_id
1216
                        );
1217
1218
                        if (!empty($content)) {
1219
                            $url = Display::url(
1220
                                Display::return_icon(
1221
                                    'announcement.png',
1222
                                    get_lang('Announcements')
1223
                                ).$course_info['name'].' ('.$content['count'].')',
1224
                                api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']
1225
                            );
1226
                            $announcements[] = Display::tag('li', $url);
1227
                        }
1228
                    }
1229
                }
1230
                if (!empty($announcements)) {
1231
                    $html .= '<div class="social_menu_items">';
1232
                    $html .= '<ul>';
1233
                    foreach ($announcements as $announcement) {
1234
                        $html .= $announcement;
1235
                    }
1236
                    $html .= '</ul>';
1237
                    $html .= '</div>';
1238
                }
1239
            }
1240
        }
1241
1242
        if ($show_delete_account_button) {
1243
            $html .= '<div class="panel panel-default"><div class="panel-body">';
1244
            $html .= '<ul class="nav nav-pills nav-stacked"><li>';
1245
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
1246
            $html .= Display::url(
1247
                Display::return_icon(
1248
                    'delete.png',
1249
                    get_lang('Unsubscribe'),
1250
                    [],
1251
                    ICON_SIZE_TINY
1252
                ).get_lang('Unsubscribe'),
1253
                $url
1254
            );
1255
            $html .= '</li></ul>';
1256
            $html .= '</div></div>';
1257
        }
1258
        $html .= '';
1259
1260
        return $html;
1261
    }
1262
1263
    /**
1264
     * Displays a sortable table with the list of online users.
1265
     *
1266
     * @param array $user_list The list of users to be shown
1267
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
1268
     *
1269
     * @return string HTML block or null if and ID was defined
1270
     * @assert (null) === false
1271
     */
1272
    public static function display_user_list($user_list, $wrap = true)
1273
    {
1274
        $html = null;
1275
1276
        if (isset($_GET['id']) || count($user_list) < 1) {
1277
            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...
1278
        }
1279
1280
        $course_url = '';
1281
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1282
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
1283
        }
1284
1285
        foreach ($user_list as $uid) {
1286
            $user_info = api_get_user_info($uid, true);
1287
            $lastname = $user_info['lastname'];
1288
            $firstname = $user_info['firstname'];
1289
            $completeName = $firstname.', '.$lastname;
1290
1291
            $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);
1292
            $status_icon_chat = null;
1293
            if (isset($user_info['user_is_online_in_chat']) && $user_info['user_is_online_in_chat'] == 1) {
1294
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1295
            } else {
1296
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1297
            }
1298
1299
            $userPicture = $user_info['avatar'];
1300
            $officialCode = '';
1301
            if (api_get_setting('show_official_code_whoisonline') == 'true') {
1302
                $officialCode .= '<div class="items-user-official-code"><p style="min-height: 30px;" title="'.get_lang('OfficialCode').'">'.$user_info['official_code'].'</p></div>';
1303
            }
1304
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1305
1306
            $url = null;
1307
            // Anonymous users can't have access to the profile
1308
            if (!api_is_anonymous()) {
1309
                if (api_get_setting('allow_social_tool') === 'true') {
1310
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1311
                } else {
1312
                    $url = '?id='.$uid.$course_url;
1313
                }
1314
            } else {
1315
                $url = null;
1316
            }
1317
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1318
1319
            $html .= '<div class="col-xs-6 col-md-2">
1320
                        <div class="items-user">
1321
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1322
                            <div class="items-user-name">
1323
                            '.$name.'
1324
                            </div>
1325
                            '.$officialCode.'
1326
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1327
                        </div>
1328
                      </div>';
1329
        }
1330
1331
        return $html;
1332
    }
1333
1334
    /**
1335
     * Displays the information of an individual user.
1336
     *
1337
     * @param int $user_id
1338
     *
1339
     * @return string
1340
     */
1341
    public static function display_individual_user($user_id)
1342
    {
1343
        global $interbreadcrumb;
1344
        $safe_user_id = intval($user_id);
1345
        $currentUserId = api_get_user_id();
1346
1347
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1348
        $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
1349
        $result = Database::query($sql);
1350
        $html = null;
1351
        if (Database::num_rows($result) == 1) {
1352
            $user_object = Database::fetch_object($result);
1353
            $userInfo = api_get_user_info($user_id);
1354
            $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
1355
            $status = get_status_from_code($user_object->status);
1356
            $interbreadcrumb[] = ['url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList')];
1357
1358
            $html .= '<div class ="thumbnail">';
1359
            $fullurl = $userInfo['avatar'];
1360
1361
            $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
1362
1363
            if (!empty($status)) {
1364
                $html .= '<div class="caption">'.$status.'</div>';
1365
            }
1366
            $html .= '</div>';
1367
1368
            if (api_get_setting('show_email_addresses') == 'true') {
1369
                $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
1370
            }
1371
1372
            if ($user_object->competences) {
1373
                $html .= Display::page_subheader(get_lang('MyCompetences'));
1374
                $html .= '<p>'.$user_object->competences.'</p>';
1375
            }
1376
            if ($user_object->diplomas) {
1377
                $html .= Display::page_subheader(get_lang('MyDiplomas'));
1378
                $html .= '<p>'.$user_object->diplomas.'</p>';
1379
            }
1380
            if ($user_object->teach) {
1381
                $html .= Display::page_subheader(get_lang('MyTeach'));
1382
                $html .= '<p>'.$user_object->teach.'</p>';
1383
            }
1384
            self::display_productions($user_object->user_id);
1385
            if ($user_object->openarea) {
1386
                $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
1387
                $html .= '<p>'.$user_object->openarea.'</p>';
1388
            }
1389
        } else {
1390
            $html .= '<div class="actions-title">';
1391
            $html .= get_lang('UsersOnLineList');
1392
            $html .= '</div>';
1393
        }
1394
1395
        return $html;
1396
    }
1397
1398
    /**
1399
     * Display productions in who is online.
1400
     *
1401
     * @param int $user_id User id
1402
     */
1403
    public static function display_productions($user_id)
1404
    {
1405
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1406
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1407
        $webdir = UserManager::getUserPathById($user_id, 'web');
1408
1409
        if (!is_dir($sysdir)) {
1410
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1411
        }
1412
1413
        $productions = UserManager::get_user_productions($user_id);
1414
1415
        if (count($productions) > 0) {
1416
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1417
            echo '<dd><ul>';
1418
            foreach ($productions as $file) {
1419
                // Only display direct file links to avoid browsing an empty directory
1420
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1421
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1422
                }
1423
                // Real productions are under a subdirectory by the User's id
1424
                if (is_dir($sysdir.$file)) {
1425
                    $subs = scandir($sysdir.$file);
1426
                    foreach ($subs as $my => $sub) {
1427
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1428
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1429
                        }
1430
                    }
1431
                }
1432
            }
1433
            echo '</ul></dd>';
1434
        }
1435
    }
1436
1437
    /**
1438
     * @param string $content
1439
     * @param string $span_count
1440
     *
1441
     * @return string
1442
     */
1443
    public static function social_wrapper_div($content, $span_count)
1444
    {
1445
        $span_count = (int) $span_count;
1446
        $html = '<div class="span'.$span_count.'">';
1447
        $html .= '<div class="well_border">';
1448
        $html .= $content;
1449
        $html .= '</div></div>';
1450
1451
        return $html;
1452
    }
1453
1454
    /**
1455
     * Dummy function.
1456
     */
1457
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1458
    {
1459
        $content = '';
1460
        switch ($place) {
1461
            case SOCIAL_CENTER_PLUGIN:
1462
                $social_plugins = [1, 2];
1463
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1464
                    $content .= '<div id="social-plugins">';
1465
                    foreach ($social_plugins as $plugin) {
1466
                        $content .= '<div class="social-plugin-item">';
1467
                        $content .= $plugin;
1468
                        $content .= '</div>';
1469
                    }
1470
                    $content .= '</div>';
1471
                }
1472
                break;
1473
            case SOCIAL_LEFT_PLUGIN:
1474
                break;
1475
            case SOCIAL_RIGHT_PLUGIN:
1476
                break;
1477
        }
1478
1479
        return $content;
1480
    }
1481
1482
    /**
1483
     * Sends a message to someone's wall.
1484
     *
1485
     * @param int    $userId         id of author
1486
     * @param int    $friendId       id where we send the message
1487
     * @param string $messageContent of the message
1488
     * @param int    $messageId      id parent
1489
     * @param string $messageStatus  status type of message
1490
     *
1491
     * @return int
1492
     *
1493
     * @author Yannick Warnier
1494
     */
1495
    public static function sendWallMessage(
1496
        $userId,
1497
        $friendId,
1498
        $messageContent,
1499
        $messageId = 0,
1500
        $messageStatus = ''
1501
    ) {
1502
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1503
        $userId = (int) $userId;
1504
        $friendId = (int) $friendId;
1505
        $messageId = (int) $messageId;
1506
1507
        if (empty($userId) || empty($friendId)) {
1508
            return 0;
1509
        }
1510
1511
        // Just in case we replace the and \n and \n\r while saving in the DB
1512
        $messageContent = str_replace(["\n", "\n\r"], '<br />', $messageContent);
1513
        $now = api_get_utc_datetime();
1514
1515
        $attributes = [
1516
            'user_sender_id' => $userId,
1517
            'user_receiver_id' => $friendId,
1518
            'msg_status' => $messageStatus,
1519
            'send_date' => $now,
1520
            'title' => '',
1521
            'content' => $messageContent,
1522
            'parent_id' => $messageId,
1523
            'group_id' => 0,
1524
            'update_date' => $now,
1525
        ];
1526
1527
        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...
1528
    }
1529
1530
    /**
1531
     * Send File attachment (jpg,png).
1532
     *
1533
     * @author Anibal Copitan
1534
     *
1535
     * @param int    $userId      id user
1536
     * @param array  $fileAttach
1537
     * @param int    $messageId   id message (relation with main message)
1538
     * @param string $fileComment description attachment file
1539
     *
1540
     * @return bool
1541
     */
1542
    public static function sendWallMessageAttachmentFile(
1543
        $userId,
1544
        $fileAttach,
1545
        $messageId,
1546
        $fileComment = ''
1547
    ) {
1548
        $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1549
1550
        // create directory
1551
        $social = '/social/';
1552
        $pathMessageAttach = UserManager::getUserPathById($userId, 'system').'message_attachments'.$social;
1553
        $safeFileComment = Database::escape_string($fileComment);
1554
        $safeFileName = Database::escape_string($fileAttach['name']);
1555
1556
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1557
        $allowedTypes = api_get_supported_image_extensions();
1558
        if (!in_array($extension, $allowedTypes)) {
1559
            $flag = false;
1560
        } else {
1561
            $newFileName = uniqid('').'.'.$extension;
1562
            if (!file_exists($pathMessageAttach)) {
1563
                @mkdir($pathMessageAttach, api_get_permissions_for_new_directories(), true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1563
                /** @scrutinizer ignore-unhandled */ @mkdir($pathMessageAttach, api_get_permissions_for_new_directories(), true);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1564
            }
1565
1566
            $newPath = $pathMessageAttach.$newFileName;
1567
            if (is_uploaded_file($fileAttach['tmp_name'])) {
1568
                @copy($fileAttach['tmp_name'], $newPath);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for copy(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

1568
                /** @scrutinizer ignore-unhandled */ @copy($fileAttach['tmp_name'], $newPath);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1569
            }
1570
1571
            $small = self::resize_picture($newPath, IMAGE_WALL_SMALL_SIZE);
0 ignored issues
show
Bug introduced by
The method resize_picture() does not exist on SocialManager. ( Ignorable by Annotation )

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

1571
            /** @scrutinizer ignore-call */ 
1572
            $small = self::resize_picture($newPath, IMAGE_WALL_SMALL_SIZE);

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...
1572
            $medium = self::resize_picture($newPath, IMAGE_WALL_MEDIUM_SIZE);
1573
1574
            $big = new Image($newPath);
1575
            $ok = $small && $small->send_image($pathMessageAttach.IMAGE_WALL_SMALL.'_'.$newFileName) &&
1576
                $medium && $medium->send_image($pathMessageAttach.IMAGE_WALL_MEDIUM.'_'.$newFileName) &&
1577
                $big && $big->send_image($pathMessageAttach.IMAGE_WALL_BIG.'_'.$newFileName);
1578
1579
            // Insert
1580
            $newFileName = $social.$newFileName;
1581
1582
            $params = [
1583
                'filename' => $safeFileName,
1584
                'comment' => $safeFileComment,
1585
                'path' => $newFileName,
1586
                'message_id' => $messageId,
1587
                'size' => $fileAttach['size'],
1588
            ];
1589
            Database::insert($table, $params);
1590
            $flag = true;
1591
        }
1592
1593
        return $flag;
1594
    }
1595
1596
    /**
1597
     * Gets all messages from someone's wall (within specific limits).
1598
     *
1599
     * @param int        $userId        id of wall shown
1600
     * @param string     $messageStatus status wall message
1601
     * @param int|string $parentId      id message (Post main)
1602
     * @param string     $start         Date from which we want to show the messages, in UTC time
1603
     * @param int        $limit         Limit for the number of parent messages we want to show
1604
     * @param int        $offset        Wall message query offset
1605
     *
1606
     * @return array
1607
     *
1608
     * @author Yannick Warnier
1609
     */
1610
    public static function getWallMessages(
1611
        $userId,
1612
        $messageStatus,
1613
        $parentId = '',
1614
        $start = null,
1615
        $limit = 10,
1616
        $offset = 0
1617
    ) {
1618
        if (empty($start)) {
1619
            $start = '0000-00-00';
1620
        }
1621
1622
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1623
        $tblMessageAttachment = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1624
1625
        $userId = intval($userId);
1626
        $start = Database::escape_string($start);
1627
        $limit = intval($limit);
1628
1629
        $sql = "SELECT
1630
                    id,
1631
                    user_sender_id,
1632
                    user_receiver_id,
1633
                    send_date,
1634
                    content,
1635
                    parent_id,
1636
                    (
1637
                        SELECT ma.path FROM $tblMessageAttachment ma
1638
                        WHERE  ma.message_id = tm.id 
1639
                    ) as path,
1640
                    (
1641
                        SELECT ma.filename FROM $tblMessageAttachment ma 
1642
                        WHERE ma.message_id = tm.id 
1643
                    ) as filename
1644
                    FROM $tblMessage tm
1645
                WHERE
1646
                    user_receiver_id = $userId AND 
1647
                    send_date > '$start'
1648
        ";
1649
1650
        $sql .= (empty($messageStatus) || is_null($messageStatus)) ? '' : " AND msg_status = '$messageStatus' ";
1651
        $sql .= (empty($parentId) || is_null($parentId)) ? '' : " AND parent_id = '$parentId' ";
1652
        $sql .= " ORDER BY send_date DESC LIMIT $offset, $limit ";
1653
        $messages = [];
1654
        $res = Database::query($sql);
1655
        if (Database::num_rows($res) > 0) {
1656
            while ($row = Database::fetch_array($res)) {
1657
                $messages[] = $row;
1658
            }
1659
        }
1660
1661
        return $messages;
1662
    }
1663
1664
    /**
1665
     * Gets all messages from someone's wall (within specific limits), formatted.
1666
     *
1667
     * @param int    $userId    USER ID of the person's wall
1668
     * @param int    $friendId  id person
1669
     * @param int    $idMessage id message
1670
     * @param string $start     Start date (from when we want the messages until today)
1671
     * @param int    $limit     Limit to the number of messages we want
1672
     * @param int    $offset    Wall messages offset
1673
     *
1674
     * @return string HTML formatted string to show messages
1675
     */
1676
    public static function getWallMessagesHTML(
1677
        $userId,
1678
        $friendId,
1679
        $idMessage,
1680
        $start = null,
1681
        $limit = 10,
1682
        $offset = 0
1683
    ) {
1684
        if (empty($start)) {
1685
            $start = '0000-00-00';
1686
        }
1687
1688
        $isOwnWall = api_get_user_id() == $userId && $userId == $friendId;
1689
        $messages = self::getWallMessages(
1690
            $userId,
1691
            MESSAGE_STATUS_WALL,
1692
            $idMessage,
1693
            $start,
1694
            $limit,
1695
            $offset
1696
        );
1697
        $formattedList = '<div class="sub-mediapost">';
1698
        $users = [];
1699
1700
        // The messages are ordered by date descendant, for comments we need ascendant
1701
        krsort($messages);
1702
        foreach ($messages as $message) {
1703
            $date = api_get_local_time($message['send_date']);
1704
            $userIdLoop = $message['user_sender_id'];
1705
            if (!isset($users[$userIdLoop])) {
1706
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1707
            }
1708
1709
            $nameComplete = api_is_western_name_order()
1710
                ? $users[$userIdLoop]['firstname'].' '.$users[$userIdLoop]['lastname']
1711
                : $users[$userIdLoop]['lastname'].' '.$users[$userIdLoop]['firstname'];
1712
            $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$userIdLoop;
1713
            $media = '';
1714
            $media .= '<div class="rep-post">';
1715
            $media .= '<div class="col-md-2 col-xs-2 social-post-answers">';
1716
            $media .= '<div class="user-image pull-right">';
1717
            $media .= '<a href="'.$url.'" ><img src="'.$users[$userIdLoop]['avatar'].
1718
                       '" alt="'.$users[$userIdLoop]['complete_name'].'" class="avatar-thumb"></a>';
1719
            $media .= '</div>';
1720
            $media .= '</div>';
1721
            $media .= '<div class="col-md-9 col-xs-9 social-post-answers">';
1722
            $media .= '<div class="user-data">';
1723
            $media .= '<div class="username">'.'<a href="'.$url.'">'.$nameComplete.'</a> 
1724
                        <span>'.Security::remove_XSS($message['content']).'</span>
1725
                       </div>';
1726
            $media .= '<div class="time timeago" title="'.$date.'">'.$date.'</div>';
1727
            $media .= '<br />';
1728
            $media .= '</div>';
1729
            $media .= '</div>';
1730
            $media .= '</div>';
1731
            if ($isOwnWall) {
1732
                $media .= '<div class="col-md-1 col-xs-1 social-post-answers">';
1733
                $media .= '<div class="pull-right deleted-mgs">';
1734
                $url = api_get_path(WEB_CODE_PATH).'social/profile.php?messageId='.$message['id'];
1735
                $media .= Display::url(
1736
                    Display::returnFontAwesomeIcon('trash'),
1737
                    $url,
1738
                    ['title' => get_lang("SocialMessageDelete")]
1739
                );
1740
                $media .= '</div>';
1741
                $media .= '</div>';
1742
            }
1743
1744
            $formattedList .= $media;
1745
        }
1746
1747
        $formattedList .= '</div>';
1748
1749
        $formattedList .= '<div class="mediapost-form">';
1750
        $formattedList .= '<form name="social_wall_message" method="POST">
1751
                <label for="social_wall_new_msg" class="hide">'.get_lang('SocialWriteNewComment').'</label>
1752
                <input type="hidden" name = "messageId" value="'.$idMessage.'" />
1753
                <textarea placeholder="'.get_lang('SocialWriteNewComment').
1754
                '" name="social_wall_new_msg" rows="1" style="width:80%;" ></textarea>
1755
                <button type="submit" name="social_wall_new_msg_submit"
1756
                class="pull-right btn btn-default" /><em class="fa fa-pencil"></em> '.get_lang('Post').'</button>
1757
                </form>';
1758
        $formattedList .= '</div>';
1759
1760
        return $formattedList;
1761
    }
1762
1763
    /**
1764
     * Gets all user's starting wall messages (within specific limits).
1765
     *
1766
     * @param int  $userId   User's id
1767
     * @param int  $friendId Friend's id
1768
     * @param date $start    Start date (from when we want the messages until today)
1769
     * @param int  $limit    Limit to the number of messages we want
1770
     * @param int  $offset   Wall messages offset
1771
     *
1772
     * @return array $data       return user's starting wall messages along with message extra data
1773
     */
1774
    public static function getWallMessagesPostHTML(
1775
        $userId,
1776
        $friendId = 0,
1777
        $start = null,
1778
        $limit = 10,
1779
        $offset = 0
1780
    ) {
1781
        if (empty($start)) {
1782
            $start = '0000-00-00';
1783
        }
1784
        $isOwnWall = api_get_user_id() == $userId && $userId == $friendId;
1785
        $messages = self::getWallMessages(
1786
            $userId,
1787
            MESSAGE_STATUS_WALL_POST,
1788
            null,
1789
            $start,
1790
            $limit,
1791
            $offset
1792
        );
1793
        $users = [];
1794
        $data = [];
1795
        foreach ($messages as $key => $message) {
1796
            $userIdLoop = $message['user_sender_id'];
1797
            $userFriendIdLoop = $message['user_receiver_id'];
1798
1799
            if (!isset($users[$userIdLoop])) {
1800
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1801
            }
1802
1803
            if (!isset($users[$userFriendIdLoop])) {
1804
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
1805
            }
1806
1807
            $html = '';
1808
            $html .= self::headerMessagePost(
1809
                $message['user_sender_id'],
1810
                $message['user_receiver_id'],
1811
                $users,
1812
                $message,
1813
                $isOwnWall
1814
            );
1815
1816
            $data[$key]['id'] = $message['id'];
1817
            $data[$key]['html'] = $html;
1818
        }
1819
1820
        return $data;
1821
    }
1822
1823
    /**
1824
     * get html data with OpenGrap passing the Url.
1825
     *
1826
     * @param $link url
1827
     *
1828
     * @return string data html
1829
     */
1830
    public static function readContentWithOpenGraph($link)
1831
    {
1832
        if (strpos($link, "://") === false && substr($link, 0, 1) != "/") {
1833
            $link = "http://".$link;
1834
        }
1835
        $graph = OpenGraph::fetch($link);
1836
        $link = parse_url($link);
1837
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
1838
        if (!$graph) {
1839
            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...
1840
        }
1841
        $url = $graph->url;
1842
        $image = $graph->image;
1843
        $description = $graph->description;
1844
        $title = $graph->title;
1845
        $html = '<div class="thumbnail social-thumbnail">';
1846
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
1847
                <img class="img-responsive social-image" src="'.$image.'" /></a>';
1848
        $html .= '<div class="social-description">';
1849
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
1850
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
1851
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
1852
        $html .= '</div>';
1853
        $html .= '</div>';
1854
1855
        return $html;
1856
    }
1857
1858
    /**
1859
     * verify if Url Exist - Using Curl.
1860
     *
1861
     * @param $uri url
1862
     *
1863
     * @return bool
1864
     */
1865
    public static function verifyUrl($uri)
1866
    {
1867
        $curl = curl_init($uri);
1868
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
1869
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
1870
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1871
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
1872
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
1873
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
1874
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
1875
        $response = curl_exec($curl);
1876
        curl_close($curl);
1877
        if (!empty($response)) {
1878
            return true;
1879
        }
1880
1881
        return false;
1882
    }
1883
1884
    /**
1885
     * Delete messages delete logic.
1886
     *
1887
     * @param int $id id message to delete
1888
     *
1889
     * @return bool status query
1890
     */
1891
    public static function deleteMessage($id)
1892
    {
1893
        $id = (int) $id;
1894
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1895
        $statusMessage = MESSAGE_STATUS_WALL_DELETE;
1896
        $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
1897
1898
        return Database::query($sql);
0 ignored issues
show
Bug Best Practice introduced by
The expression return Database::query($sql) returns the type Doctrine\DBAL\Driver\Statement which is incompatible with the documented return type boolean.
Loading history...
1899
    }
1900
1901
    /**
1902
     * Generate the social block for a user.
1903
     *
1904
     * @param Template $template
1905
     * @param int      $userId            The user id
1906
     * @param string   $groupBlock        Optional. Highlight link possible values:
1907
     *                                    group_add, home, messages, messages_inbox, messages_compose,
1908
     *                                    messages_outbox, invitations, shared_profile, friends, groups, search
1909
     * @param int      $groupId           Optional. Group ID
1910
     * @param bool     $show_full_profile
1911
     *
1912
     * @return string The HTML code with the social block
1913
     */
1914
    public static function setSocialUserBlock(
1915
        Template $template,
1916
        $userId,
1917
        $groupBlock = '',
1918
        $groupId = 0,
1919
        $show_full_profile = true
1920
    ) {
1921
        if (api_get_setting('allow_social_tool') != 'true') {
1922
            return '';
1923
        }
1924
1925
        $currentUserId = api_get_user_id();
1926
        $userId = (int) $userId;
1927
        $userRelationType = 0;
1928
1929
        $socialAvatarBlock = self::show_social_avatar_block(
1930
            $groupBlock,
1931
            $groupId,
1932
            $userId
1933
        );
1934
1935
        $profileEditionLink = null;
1936
        if ($currentUserId === $userId) {
1937
            $profileEditionLink = Display::getProfileEditionLink($userId);
1938
        } else {
1939
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
1940
        }
1941
1942
        $vCardUserLink = Display::getVCardUserLink($userId);
1943
1944
        $userInfo = api_get_user_info($userId, true, false, true, true);
1945
1946
        $template->assign('user', $userInfo);
1947
        $template->assign('social_avatar_block', $socialAvatarBlock);
1948
        $template->assign('profile_edition_link', $profileEditionLink);
1949
        //Added the link to export the vCard to the Template
1950
1951
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
1952
        if ($show_full_profile) {
1953
            $template->assign('vcard_user_link', $vCardUserLink);
1954
        }
1955
1956
        if (api_get_setting('gamification_mode') === '1') {
1957
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
1958
                $userId,
1959
                $userInfo['status']
1960
            );
1961
1962
            $template->assign('gamification_points', $gamificationPoints);
1963
        }
1964
        $chatEnabled = api_is_global_chat_enabled();
1965
        $template->assign('chat_enabled', $chatEnabled);
1966
        $template->assign('user_relation', $userRelationType);
1967
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
1968
        $template->assign('show_full_profile', $show_full_profile);
1969
1970
        $inGroup = in_array($groupBlock, ['groups', 'group_edit', 'member_list']);
1971
        $template->assign('in_group', $inGroup);
1972
        $templateName = $template->get_template('social/user_block.tpl');
1973
        $template->assign('social_avatar_block', $template->fetch($templateName));
1974
    }
1975
1976
    /**
1977
     * @param int $user_id
1978
     * @param $link_shared
1979
     * @param $show_full_profile
1980
     *
1981
     * @return string
1982
     */
1983
    public static function listMyFriends($user_id, $link_shared, $show_full_profile)
1984
    {
1985
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1986
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
1987
        $number_of_images = 30;
1988
        $number_friends = count($friends);
1989
        $friendHtml = '';
1990
        if ($number_friends != 0) {
1991
            if ($number_friends > $number_of_images) {
1992
                if (api_get_user_id() == $user_id) {
1993
                    $friendHtml .= ' <span><a href="friends.php">'.get_lang('SeeAll').'</a></span>';
1994
                } else {
1995
                    $friendHtml .= ' <span>'
1996
                        .'<a href="'.api_get_path(WEB_CODE_PATH).'social/profile_friends_and_groups.inc.php'
1997
                        .'?view=friends&height=390&width=610&user_id='.$user_id.'"'
1998
                        .'class="ajax" data-title="'.get_lang('SeeAll').'" title="'.get_lang('SeeAll').'" >'.get_lang('SeeAll').'</a></span>';
1999
                }
2000
            }
2001
2002
            $friendHtml .= '<ul class="nav nav-list">';
2003
            $j = 1;
2004
            for ($k = 0; $k < $number_friends; $k++) {
2005
                if ($j > $number_of_images) {
2006
                    break;
2007
                }
2008
                if (isset($friends[$k])) {
2009
                    $friend = $friends[$k];
2010
                    $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2011
                    $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2012
2013
                    if ($user_info_friend['user_is_online']) {
2014
                        $statusIcon = Display::span('', ['class' => 'online_user_in_text']);
2015
                    } else {
2016
                        $statusIcon = Display::span('', ['class' => 'offline_user_in_text']);
2017
                    }
2018
2019
                    $friendHtml .= '<li>';
2020
                    $friendHtml .= '<div>';
2021
2022
                    // the height = 92 must be the same in the image_friend_network span style in default.css
2023
                    $friends_profile = UserManager::getUserPicture(
2024
                        $friend['friend_user_id'],
2025
                        USER_IMAGE_SIZE_SMALL
2026
                    );
2027
                    $friendHtml .= '<img src="'.$friends_profile.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'"/>';
2028
                    $link_shared = (empty($link_shared)) ? '' : '&'.$link_shared;
2029
                    $friendHtml .= $statusIcon.'<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'">'.$name_user.'</a>';
2030
                    $friendHtml .= '</div>';
2031
                    $friendHtml .= '</li>';
2032
                }
2033
                $j++;
2034
            }
2035
            $friendHtml .= '</ul>';
2036
        } else {
2037
            $friendHtml .= '<div class="">'.get_lang('NoFriendsInYourContactList').'<br />
2038
                <a class="btn btn-primary" href="'.api_get_path(WEB_PATH).'whoisonline.php">
2039
                <em class="fa fa-search"></em> '.get_lang('TryAndFindSomeFriends').'</a></div>';
2040
        }
2041
2042
        $friendHtml = Display::panel($friendHtml, get_lang('SocialFriend').' ('.$number_friends.')');
2043
2044
        return $friendHtml;
2045
    }
2046
2047
    /**
2048
     * @param int $user_id
2049
     * @param $link_shared
2050
     * @param $show_full_profile
2051
     *
2052
     * @return string
2053
     */
2054
    public static function listMyFriendsBlock($user_id, $link_shared = '', $show_full_profile = '')
2055
    {
2056
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
2057
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
2058
        $number_of_images = 30;
2059
        $number_friends = count($friends);
2060
        $friendHtml = '';
2061
2062
        if ($number_friends != 0) {
2063
            $friendHtml .= '<div class="list-group">';
2064
            $j = 1;
2065
            for ($k = 0; $k < $number_friends; $k++) {
2066
                if ($j > $number_of_images) {
2067
                    break;
2068
                }
2069
                if (isset($friends[$k])) {
2070
                    $friend = $friends[$k];
2071
                    $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
2072
                    $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
2073
2074
                    if (!empty($user_info_friend['user_is_online_in_chat'])) {
2075
                        $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
2076
                        $status = 1;
2077
                    } else {
2078
                        $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
2079
                        $status = 0;
2080
                    }
2081
2082
                    $friendAvatarMedium = UserManager::getUserPicture(
2083
                        $friend['friend_user_id'],
2084
                        USER_IMAGE_SIZE_MEDIUM
2085
                    );
2086
                    $friendAvatarSmall = UserManager::getUserPicture(
2087
                        $friend['friend_user_id'],
2088
                        USER_IMAGE_SIZE_SMALL
2089
                    );
2090
                    $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
2091
2092
                    $relation = SocialManager::get_relation_between_contacts(
2093
                        $friend['friend_user_id'],
2094
                        api_get_user_id()
2095
                    );
2096
                    $showLinkToChat = api_is_global_chat_enabled() && $friend['friend_user_id'] != api_get_user_id() && $relation == USER_RELATION_TYPE_FRIEND;
2097
2098
                    if ($showLinkToChat) {
2099
                        $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
2100
                        $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
2101
                        $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
2102
                    } else {
2103
                        $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
2104
                        $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
2105
                        $friendHtml .= $friend_avatar.' <span class="username-all">'.$name_user.'</span>';
2106
                    }
2107
2108
                    $friendHtml .= '</a>';
2109
                }
2110
                $j++;
2111
            }
2112
            $friendHtml .= '</div>';
2113
        } else {
2114
            $friendHtml .= '<div class="help">'.get_lang('NoFriendsInYourContactList').' 
2115
                    <a href="'.api_get_path(WEB_PATH).'whoisonline.php">
2116
                    <em class="fa fa-search"></em> '.get_lang('TryAndFindSomeFriends').'</a></div>';
2117
        }
2118
2119
        return $friendHtml;
2120
    }
2121
2122
    /**
2123
     * @return string
2124
     */
2125
    public static function getWallForm($show_full_profile = true)
2126
    {
2127
        if ($show_full_profile) {
2128
            $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
2129
            $form = new FormValidator(
2130
                'social_wall_main',
2131
                'post',
2132
                api_get_path(WEB_CODE_PATH).'social/profile.php'.$userId,
2133
                null,
2134
                ['enctype' => 'multipart/form-data'],
2135
                FormValidator::LAYOUT_HORIZONTAL
2136
            );
2137
2138
            $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang('SocialWallWhatAreYouThinkingAbout');
2139
2140
            $form->addTextarea(
2141
                'social_wall_new_msg_main',
2142
                null,
2143
                [
2144
                    'placeholder' => $socialWallPlaceholder,
2145
                    'cols-size' => [1, 10, 1],
2146
                    'aria-label' => $socialWallPlaceholder,
2147
                ]
2148
            );
2149
            $form->addHidden('url_content', '');
2150
            $form->addButtonSend(
2151
                get_lang('Post'),
2152
                'wall_post_button',
2153
                false,
2154
                ['cols-size' => [1, 10, 1]]
2155
            );
2156
            $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
2157
2158
            return $html;
2159
        }
2160
    }
2161
2162
    /**
2163
     * @param int $userId
2164
     * @param int $friendId
2165
     *
2166
     * @return string
2167
     */
2168
    public static function getWallMessagesByUser($userId, $friendId)
2169
    {
2170
        $messages = self::getWallMessagesPostHTML($userId, $friendId);
2171
        $html = '';
2172
2173
        foreach ($messages as $message) {
2174
            $post = $message['html'];
2175
            $comment = self::getWallMessagesHTML($userId, $friendId, $message['id']);
2176
            $html .= Display::panel($post.$comment, '');
2177
        }
2178
2179
        return $html;
2180
    }
2181
2182
    /**
2183
     * Get HTML code block for user skills.
2184
     *
2185
     * @param int $userId The user ID
2186
     *
2187
     * @return string
2188
     */
2189
    public static function getSkillBlock($userId)
2190
    {
2191
        if (Skill::isAllowed($userId, false) === false) {
2192
            return '';
2193
        }
2194
2195
        $skill = new Skill();
2196
        $ranking = $skill->getUserSkillRanking($userId);
2197
2198
        $template = new Template(null, false, false, false, false, false);
2199
        $template->assign('ranking', $ranking);
2200
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['table']);
2201
        $template->assign('user_id', $userId);
2202
        $template->assign(
2203
            'show_skills_report_link',
2204
            api_is_student() || api_is_student_boss() || api_is_drh()
2205
        );
2206
2207
        $skillBlock = $template->get_template('social/skills_block.tpl');
2208
2209
        return $template->fetch($skillBlock);
2210
    }
2211
2212
    /**
2213
     * Returns the formatted header message post.
2214
     *
2215
     * @param int   $authorId   Author's id
2216
     * @param int   $receiverId Receiver's id
2217
     * @param array $users      Author's and receiver's data
2218
     * @param array $message    Message data
2219
     * @param bool  $isOwnWall  Determines if the author is in its own social wall or not
2220
     *
2221
     * @return string $html       The formatted header message post
2222
     */
2223
    private static function headerMessagePost($authorId, $receiverId, $users, $message, $isOwnWall = false)
2224
    {
2225
        $date = api_get_local_time($message['send_date']);
2226
        $avatarAuthor = $users[$authorId]['avatar'];
2227
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
2228
        $nameCompleteAuthor = api_get_person_name(
2229
            $users[$authorId]['firstname'],
2230
            $users[$authorId]['lastname']
2231
        );
2232
2233
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
2234
        $nameCompleteReceiver = api_get_person_name(
2235
            $users[$receiverId]['firstname'],
2236
            $users[$receiverId]['lastname']
2237
        );
2238
2239
        $htmlReceiver = '';
2240
        if ($authorId != $receiverId) {
2241
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
2242
        }
2243
2244
        $wallImage = '';
2245
        if (!empty($message['path'])) {
2246
            $imageBig = UserManager::getUserPicture($authorId, USER_IMAGE_SIZE_BIG);
2247
            $imageSmall = UserManager::getUserPicture($authorId, USER_IMAGE_SIZE_SMALL);
2248
2249
            $wallImage = '<a class="thumbnail ajax" href="'.$imageBig.'"><img src="'.$imageSmall.'"></a>';
2250
        }
2251
2252
        $htmlDelete = '';
2253
        if ($isOwnWall) {
2254
            $url = api_get_path(WEB_CODE_PATH).'social/profile.php?messageId='.$message['id'];
2255
            $htmlDelete .= Display::url(
2256
                Display::returnFontAwesomeIcon('trash'),
2257
                $url,
2258
                ['title' => get_lang('SocialMessageDelete')]
2259
            );
2260
        }
2261
2262
        $html = '';
2263
        $html .= '<div class="top-mediapost" >';
2264
        if ($isOwnWall) {
2265
            $html .= '<div class="pull-right deleted-mgs">';
2266
            $html .= $htmlDelete;
2267
            $html .= '</div>';
2268
        }
2269
        $html .= '<div class="user-image" >';
2270
        $html .= '<a href="'.$urlAuthor.'">
2271
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
2272
        $html .= '</div>';
2273
        $html .= '<div class="user-data">';
2274
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
2275
        $html .= '<div class="time timeago" title="'.$date.'">'.$date.'</div>';
2276
        $html .= '</div>';
2277
        $html .= '<div class="msg-content">';
2278
        $html .= '<div class="img-post">';
2279
        $html .= $wallImage;
2280
        $html .= '</div>';
2281
        $html .= '<p>'.Security::remove_XSS($message['content']).'</p>';
2282
        $html .= '</div>';
2283
        $html .= '</div>'; // end mediaPost
2284
2285
        // Popularity post functionality
2286
        $html .= '<div class="popularity-mediapost"></div>';
2287
2288
        return $html;
2289
    }
2290
}
2291