Passed
Push — master ( 87bc65...75b6f5 )
by Julito
10:39
created

SocialManager::verifyUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 13
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 17
rs 9.8333
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
     * Display productions in who is online.
1336
     *
1337
     * @param int $user_id User id
1338
     */
1339
    public static function display_productions($user_id)
1340
    {
1341
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1342
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1343
        $webdir = UserManager::getUserPathById($user_id, 'web');
1344
1345
        if (!is_dir($sysdir)) {
1346
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1347
        }
1348
1349
        $productions = UserManager::get_user_productions($user_id);
1350
1351
        if (count($productions) > 0) {
1352
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1353
            echo '<dd><ul>';
1354
            foreach ($productions as $file) {
1355
                // Only display direct file links to avoid browsing an empty directory
1356
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1357
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1358
                }
1359
                // Real productions are under a subdirectory by the User's id
1360
                if (is_dir($sysdir.$file)) {
1361
                    $subs = scandir($sysdir.$file);
1362
                    foreach ($subs as $my => $sub) {
1363
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1364
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1365
                        }
1366
                    }
1367
                }
1368
            }
1369
            echo '</ul></dd>';
1370
        }
1371
    }
1372
1373
    /**
1374
     * @param string $content
1375
     * @param string $span_count
1376
     *
1377
     * @return string
1378
     */
1379
    public static function social_wrapper_div($content, $span_count)
1380
    {
1381
        $span_count = (int) $span_count;
1382
        $html = '<div class="span'.$span_count.'">';
1383
        $html .= '<div class="well_border">';
1384
        $html .= $content;
1385
        $html .= '</div></div>';
1386
1387
        return $html;
1388
    }
1389
1390
    /**
1391
     * Dummy function.
1392
     */
1393
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1394
    {
1395
        $content = '';
1396
        switch ($place) {
1397
            case SOCIAL_CENTER_PLUGIN:
1398
                $social_plugins = [1, 2];
1399
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1400
                    $content .= '<div id="social-plugins">';
1401
                    foreach ($social_plugins as $plugin) {
1402
                        $content .= '<div class="social-plugin-item">';
1403
                        $content .= $plugin;
1404
                        $content .= '</div>';
1405
                    }
1406
                    $content .= '</div>';
1407
                }
1408
                break;
1409
            case SOCIAL_LEFT_PLUGIN:
1410
                break;
1411
            case SOCIAL_RIGHT_PLUGIN:
1412
                break;
1413
        }
1414
1415
        return $content;
1416
    }
1417
1418
    /**
1419
     * Sends a message to someone's wall.
1420
     *
1421
     * @param int    $userId         id of author
1422
     * @param int    $friendId       id where we send the message
1423
     * @param string $messageContent of the message
1424
     * @param int    $messageId      id parent
1425
     * @param string $messageStatus  status type of message
1426
     *
1427
     * @return int
1428
     *
1429
     * @author Yannick Warnier
1430
     */
1431
    public static function sendWallMessage(
1432
        $userId,
1433
        $friendId,
1434
        $messageContent,
1435
        $messageId = 0,
1436
        $messageStatus = ''
1437
    ) {
1438
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1439
        $userId = (int) $userId;
1440
        $friendId = (int) $friendId;
1441
        $messageId = (int) $messageId;
1442
1443
        if (empty($userId) || empty($friendId)) {
1444
            return 0;
1445
        }
1446
1447
        // Just in case we replace the and \n and \n\r while saving in the DB
1448
        $messageContent = str_replace(["\n", "\n\r"], '<br />', $messageContent);
1449
        $now = api_get_utc_datetime();
1450
1451
        $attributes = [
1452
            'user_sender_id' => $userId,
1453
            'user_receiver_id' => $friendId,
1454
            'msg_status' => $messageStatus,
1455
            'send_date' => $now,
1456
            'title' => '',
1457
            'content' => $messageContent,
1458
            'parent_id' => $messageId,
1459
            'group_id' => 0,
1460
            'update_date' => $now,
1461
        ];
1462
1463
        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...
1464
    }
1465
1466
    /**
1467
     * Send File attachment (jpg,png).
1468
     *
1469
     * @author Anibal Copitan
1470
     *
1471
     * @param int    $userId      id user
1472
     * @param array  $fileAttach
1473
     * @param int    $messageId   id message (relation with main message)
1474
     * @param string $fileComment description attachment file
1475
     *
1476
     * @return bool
1477
     */
1478
    public static function sendWallMessageAttachmentFile(
1479
        $userId,
1480
        $fileAttach,
1481
        $messageId,
1482
        $fileComment = ''
1483
    ) {
1484
        $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1485
1486
        // create directory
1487
        $social = '/social/';
1488
        $pathMessageAttach = UserManager::getUserPathById($userId, 'system').'message_attachments'.$social;
1489
        $safeFileComment = Database::escape_string($fileComment);
1490
        $safeFileName = Database::escape_string($fileAttach['name']);
1491
1492
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1493
        $allowedTypes = api_get_supported_image_extensions();
1494
        if (!in_array($extension, $allowedTypes)) {
1495
            $flag = false;
1496
        } else {
1497
            $newFileName = uniqid('').'.'.$extension;
1498
            if (!file_exists($pathMessageAttach)) {
1499
                @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

1499
                /** @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...
1500
            }
1501
1502
            $newPath = $pathMessageAttach.$newFileName;
1503
            if (is_uploaded_file($fileAttach['tmp_name'])) {
1504
                @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

1504
                /** @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...
1505
            }
1506
1507
            $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

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