Passed
Push — master ( 0ccaf0...5c51ef )
by Julito
08:24
created

SocialManager::getScriptToGetOpenGraph()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 0
dl 0
loc 19
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Message;
6
use Chamilo\CoreBundle\Entity\MessageAttachment;
7
use Chamilo\CoreBundle\Entity\UserRelUser;
8
use Chamilo\CoreBundle\Framework\Container;
9
use Chamilo\CourseBundle\Entity\CForumPost;
10
use Chamilo\CourseBundle\Entity\CForumThread;
11
use ChamiloSession as Session;
12
use Laminas\Feed\Reader\Entry\Rss;
13
use Laminas\Feed\Reader\Reader;
14
15
/**
16
 * Class SocialManager.
17
 *
18
 * This class provides methods for the social network management.
19
 * Include/require it in your code to use its features.
20
 */
21
class SocialManager extends UserManager
22
{
23
    const DEFAULT_WALL_POSTS = 10;
24
    const DEFAULT_SCROLL_NEW_POST = 5;
25
26
    /**
27
     * Constructor.
28
     */
29
    public function __construct()
30
    {
31
    }
32
33
    /**
34
     * Allow to see contacts list.
35
     *
36
     * @author isaac flores paz
37
     *
38
     * @return array
39
     */
40
    public static function show_list_type_friends()
41
    {
42
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
43
        $sql = 'SELECT id, title FROM '.$table.'
44
                WHERE id<>6
45
                ORDER BY id ASC';
46
        $result = Database::query($sql);
47
        $friend_relation_list = [];
48
        while ($row = Database::fetch_array($result, 'ASSOC')) {
49
            $friend_relation_list[] = $row;
50
        }
51
        $count_list = count($friend_relation_list);
52
        if (0 == $count_list) {
53
            $friend_relation_list[] = get_lang('Unknown');
54
        } else {
55
            return $friend_relation_list;
56
        }
57
    }
58
59
    /**
60
     * Get the kind of relation between contacts.
61
     *
62
     * @param int  $user_id     user id
63
     * @param int  $user_friend user friend id
64
     * @param bool $includeRH   include the RH relationship
65
     *
66
     * @return int
67
     *
68
     * @author isaac flores paz
69
     */
70
    public static function get_relation_between_contacts($user_id, $user_friend, $includeRH = false)
71
    {
72
        $table = Database::get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
73
        $userRelUserTable = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
74
        if (false == $includeRH) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
75
            $sql = 'SELECT rt.id as id
76
                FROM '.$table.' rt
77
                WHERE rt.id = (
78
                    SELECT uf.relation_type
79
                    FROM '.$userRelUserTable.' uf
80
                    WHERE
81
                        user_id='.((int) $user_id).' AND
82
                        friend_user_id='.((int) $user_friend).' AND
83
                        uf.relation_type <> '.UserRelUser::USER_RELATION_TYPE_RRHH.'
84
                    LIMIT 1
85
                )';
86
        } else {
87
            $sql = 'SELECT rt.id as id
88
                FROM '.$table.' rt
89
                WHERE rt.id = (
90
                    SELECT uf.relation_type
91
                    FROM '.$userRelUserTable.' uf
92
                    WHERE
93
                        user_id='.((int) $user_id).' AND
94
                        friend_user_id='.((int) $user_friend).'
95
                    LIMIT 1
96
                )';
97
        }
98
        $res = Database::query($sql);
99
        if (Database::num_rows($res) > 0) {
100
            $row = Database::fetch_array($res, 'ASSOC');
101
102
            return (int) $row['id'];
103
        } else {
104
            if (api_get_configuration_value('social_make_teachers_friend_all')) {
105
                $adminsList = UserManager::get_all_administrators();
106
                foreach ($adminsList as $admin) {
107
                    if (api_get_user_id() == $admin['user_id']) {
108
                        return UserRelUser::USER_RELATION_TYPE_GOODFRIEND;
109
                    }
110
                }
111
                $targetUserCoursesList = CourseManager::get_courses_list_by_user_id(
112
                    $user_id,
113
                    true,
114
                    false
115
                );
116
                $currentUserId = api_get_user_id();
117
                foreach ($targetUserCoursesList as $course) {
118
                    $teachersList = CourseManager::get_teacher_list_from_course_code($course['code']);
119
                    foreach ($teachersList as $teacher) {
120
                        if ($currentUserId == $teacher['user_id']) {
121
                            return UserRelUser::USER_RELATION_TYPE_GOODFRIEND;
122
                        }
123
                    }
124
                }
125
            } else {
126
                return UserRelUser::USER_UNKNOWN;
127
            }
128
        }
129
    }
130
131
    /**
132
     * Gets friends id list.
133
     *
134
     * @param int  user id
135
     * @param int group id
136
     * @param string name to search
137
     * @param bool true will load firstname, lastname, and image name
138
     *
139
     * @return array
140
     *
141
     * @author Julio Montoya <[email protected]> Cleaning code, function renamed, $load_extra_info option added
142
     * @author isaac flores paz
143
     */
144
    public static function get_friends(
145
        $user_id,
146
        $id_group = null,
147
        $search_name = null,
148
        $load_extra_info = true
149
    ) {
150
        $user_id = (int) $user_id;
151
152
        $tbl_my_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
153
        $tbl_my_user = Database::get_main_table(TABLE_MAIN_USER);
154
        $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
155
                WHERE
156
                    relation_type NOT IN ('.UserRelUser::USER_RELATION_TYPE_DELETED.', '.UserRelUser::USER_RELATION_TYPE_RRHH.') AND
157
                    friend_user_id<>'.$user_id.' AND
158
                    user_id='.$user_id;
159
        if (isset($id_group) && $id_group > 0) {
160
            $sql .= ' AND relation_type='.$id_group;
161
        }
162
        if (isset($search_name)) {
163
            $search_name = trim($search_name);
164
            $search_name = str_replace(' ', '', $search_name);
165
            $sql .= ' AND friend_user_id IN (
166
                SELECT user_id FROM '.$tbl_my_user.'
167
                WHERE
168
                    firstName LIKE "%'.Database::escape_string($search_name).'%" OR
169
                    lastName LIKE "%'.Database::escape_string($search_name).'%" OR
170
                    '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
171
                ) ';
172
        }
173
174
        $res = Database::query($sql);
175
        $list = [];
176
        while ($row = Database::fetch_array($res, 'ASSOC')) {
177
            if ($load_extra_info) {
178
                $userInfo = api_get_user_info($row['friend_user_id']);
179
                $list[] = [
180
                    'friend_user_id' => $row['friend_user_id'],
181
                    'firstName' => $userInfo['firstName'],
182
                    'lastName' => $userInfo['lastName'],
183
                    'username' => $userInfo['username'],
184
                    'image' => $userInfo['avatar'],
185
                    'user_info' => $userInfo,
186
                ];
187
            } else {
188
                $list[] = $row;
189
            }
190
        }
191
192
        return $list;
193
    }
194
195
    /**
196
     * Get number of messages sent to other users.
197
     *
198
     * @param int $userId
199
     *
200
     * @return int
201
     */
202
    public static function getCountMessagesSent($userId)
203
    {
204
        $userId = (int) $userId;
205
        $table = Database::get_main_table(TABLE_MESSAGE);
206
        $sql = 'SELECT COUNT(*) FROM '.$table.'
207
                WHERE
208
                    user_sender_id='.$userId.' AND
209
                    msg_status < 5';
210
        $res = Database::query($sql);
211
        $row = Database::fetch_row($res);
212
213
        return $row[0];
214
    }
215
216
    /**
217
     * Get number of messages received from other users.
218
     *
219
     * @param int $receiver_id
220
     *
221
     * @return int
222
     */
223
    public static function getCountMessagesReceived($receiver_id)
224
    {
225
        $table = Database::get_main_table(TABLE_MESSAGE);
226
        $sql = 'SELECT COUNT(*) FROM '.$table.'
227
                WHERE
228
                    user_receiver_id='.intval($receiver_id).' AND
229
                    msg_status < 4';
230
        $res = Database::query($sql);
231
        $row = Database::fetch_row($res);
232
233
        return $row[0];
234
    }
235
236
    /**
237
     * Get number of messages posted on own wall.
238
     *
239
     * @param int $userId
240
     *
241
     * @return int
242
     */
243
    public static function getCountWallPostedMessages($userId)
244
    {
245
        $userId = (int) $userId;
246
247
        if (empty($userId)) {
248
            return 0;
249
        }
250
251
        $table = Database::get_main_table(TABLE_MESSAGE);
252
        $sql = 'SELECT COUNT(*)
253
                FROM '.$table.'
254
                WHERE
255
                    user_sender_id='.$userId.' AND
256
                    (msg_status = '.MESSAGE_STATUS_WALL.' OR
257
                    msg_status = '.MESSAGE_STATUS_WALL_POST.') AND
258
                    parent_id = 0';
259
        $res = Database::query($sql);
260
        $row = Database::fetch_row($res);
261
262
        return $row[0];
263
    }
264
265
    /**
266
     * Get invitation list received by user.
267
     *
268
     * @author isaac flores paz
269
     *
270
     * @param int $userId
271
     * @param int $limit
272
     *
273
     * @return array
274
     */
275
    public static function get_list_invitation_of_friends_by_user_id($userId, $limit = 0)
276
    {
277
        $userId = (int) $userId;
278
        $limit = (int) $limit;
279
280
        if (empty($userId)) {
281
            return [];
282
        }
283
284
        $table = Database::get_main_table(TABLE_MESSAGE);
285
        $sql = 'SELECT user_sender_id, send_date, title, content
286
                FROM '.$table.'
287
                WHERE
288
                    user_receiver_id = '.$userId.' AND
289
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
290
        if (null != $limit && $limit > 0) {
291
            $sql .= ' LIMIT '.$limit;
292
        }
293
        $res = Database::query($sql);
294
        $list = [];
295
        while ($row = Database::fetch_array($res, 'ASSOC')) {
296
            $list[] = $row;
297
        }
298
299
        return $list;
300
    }
301
302
    /**
303
     * Get invitation list sent by user.
304
     *
305
     * @author Julio Montoya <[email protected]>
306
     *
307
     * @param int $userId
308
     *
309
     * @return array
310
     */
311
    public static function get_list_invitation_sent_by_user_id($userId)
312
    {
313
        $userId = (int) $userId;
314
315
        if (empty($userId)) {
316
            return [];
317
        }
318
319
        $table = Database::get_main_table(TABLE_MESSAGE);
320
        $sql = 'SELECT user_receiver_id, send_date,title,content
321
                FROM '.$table.'
322
                WHERE
323
                    user_sender_id = '.$userId.' AND
324
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
325
        $res = Database::query($sql);
326
        $list = [];
327
        while ($row = Database::fetch_array($res, 'ASSOC')) {
328
            $list[$row['user_receiver_id']] = $row;
329
        }
330
331
        return $list;
332
    }
333
334
    /**
335
     * Get count invitation sent by user.
336
     *
337
     * @author Julio Montoya <[email protected]>
338
     *
339
     * @param int $userId
340
     *
341
     * @return int
342
     */
343
    public static function getCountInvitationSent($userId)
344
    {
345
        $userId = (int) $userId;
346
347
        if (empty($userId)) {
348
            return 0;
349
        }
350
351
        $table = Database::get_main_table(TABLE_MESSAGE);
352
        $sql = 'SELECT count(user_receiver_id) count
353
                FROM '.$table.'
354
                WHERE
355
                    user_sender_id = '.$userId.' AND
356
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
357
        $res = Database::query($sql);
358
        if (Database::num_rows($res)) {
359
            $row = Database::fetch_array($res, 'ASSOC');
360
361
            return (int) $row['count'];
362
        }
363
364
        return 0;
365
    }
366
367
    /**
368
     * Accepts invitation.
369
     *
370
     * @param int $user_send_id
371
     * @param int $user_receiver_id
372
     *
373
     * @return bool
374
     *
375
     * @author isaac flores paz
376
     * @author Julio Montoya <[email protected]> Cleaning code
377
     */
378
    public static function invitation_accepted($user_send_id, $user_receiver_id)
379
    {
380
        if (empty($user_send_id) || empty($user_receiver_id)) {
381
            return false;
382
        }
383
384
        $table = Database::get_main_table(TABLE_MESSAGE);
385
        $sql = "UPDATE $table
386
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
387
                WHERE
388
                    user_sender_id = ".((int) $user_send_id)." AND
389
                    user_receiver_id=".((int) $user_receiver_id)." AND
390
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
391
        Database::query($sql);
392
393
        return true;
394
    }
395
396
    /**
397
     * Denies invitation.
398
     *
399
     * @param int user sender id
400
     * @param int user receiver id
401
     *
402
     * @return bool
403
     *
404
     * @author isaac flores paz
405
     * @author Julio Montoya <[email protected]> Cleaning code
406
     */
407
    public static function invitation_denied($user_send_id, $user_receiver_id)
408
    {
409
        if (empty($user_send_id) || empty($user_receiver_id)) {
410
            return false;
411
        }
412
        $table = Database::get_main_table(TABLE_MESSAGE);
413
        $sql = 'DELETE FROM '.$table.'
414
                WHERE
415
                    user_sender_id =  '.((int) $user_send_id).' AND
416
                    user_receiver_id='.((int) $user_receiver_id).' AND
417
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
418
        Database::query($sql);
419
420
        return true;
421
    }
422
423
    /**
424
     * Get user's feeds.
425
     *
426
     * @param int $user  User ID
427
     * @param int $limit Limit of posts per feed
428
     *
429
     * @return string HTML section with all feeds included
430
     *
431
     * @author  Yannick Warnier
432
     *
433
     * @since   Dokeos 1.8.6.1
434
     */
435
    public static function getUserRssFeed($user, $limit = 5)
436
    {
437
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
438
439
        if (empty($feed)) {
440
            return '';
441
        }
442
        $feeds = explode(';', $feed['rssfeeds']);
443
        if (0 == count($feeds)) {
444
            return '';
445
        }
446
        $res = '';
447
        foreach ($feeds as $url) {
448
            if (empty($url)) {
449
                continue;
450
            }
451
            try {
452
                $channel = Reader::import($url);
453
                $i = 1;
454
                if (!empty($channel)) {
455
                    $iconRss = '';
456
                    if (!empty($feed)) {
457
                        $iconRss = Display::url(
458
                            Display::return_icon('social_rss.png', '', [], 22),
459
                            Security::remove_XSS($feed['rssfeeds']),
460
                            ['target' => '_blank']
461
                        );
462
                    }
463
464
                    $res .= '<h3 class="title-rss">'.$iconRss.' '.$channel->getTitle().'</h3>';
465
                    $res .= '<div class="rss-items">';
466
                    /** @var Rss $item */
467
                    foreach ($channel as $item) {
468
                        if ($limit >= 0 and $i > $limit) {
469
                            break;
470
                        }
471
                        $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
472
                        $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
473
                        $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
474
                        $i++;
475
                    }
476
                    $res .= '</div>';
477
                }
478
            } catch (Exception $e) {
479
                error_log($e->getMessage());
480
            }
481
        }
482
483
        return $res;
484
    }
485
486
    /**
487
     * Shows the avatar block in social pages.
488
     *
489
     * @param string $show     highlight link possible values:
490
     *                         group_add,
491
     *                         home,
492
     *                         messages,
493
     *                         messages_inbox,
494
     *                         messages_compose,
495
     *                         messages_outbox,
496
     *                         invitations,
497
     *                         shared_profile,
498
     *                         friends,
499
     *                         groups search
500
     * @param int    $group_id
501
     * @param int    $user_id
502
     */
503
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
504
    {
505
        $user_id = (int) $user_id;
506
        $group_id = (int) $group_id;
507
508
        if (empty($user_id)) {
509
            $user_id = api_get_user_id();
510
        }
511
512
        $show_groups = [
513
            'groups',
514
            'group_messages',
515
            'messages_list',
516
            'group_add',
517
            'mygroups',
518
            'group_edit',
519
            'member_list',
520
            'invite_friends',
521
            'waiting_list',
522
            'browse_groups',
523
        ];
524
525
        $template = new Template(null, false, false, false, false, false);
526
527
        if (in_array($show, $show_groups) && !empty($group_id)) {
528
            // Group image
529
            $userGroup = new UserGroupModel();
530
            $group_info = $userGroup->get($group_id);
531
            $userGroupImage = $userGroup->get_picture_group(
532
                $group_id,
533
                $group_info['picture'],
534
                128,
535
                GROUP_IMAGE_SIZE_BIG
536
            );
537
            $template->assign('show_group', true);
538
            $template->assign('group_id', $group_id);
539
            $template->assign('user_group_image', $userGroupImage);
540
            $template->assign(
541
                'user_is_group_admin',
542
                $userGroup->is_group_admin(
543
                    $group_id,
544
                    api_get_user_id()
545
                )
546
            );
547
        } else {
548
            $template->assign('show_group', false);
549
            $template->assign('show_user', true);
550
            $template->assign(
551
                'user_image',
552
                [
553
                    'big' => UserManager::getUserPicture(
554
                        $user_id,
555
                        USER_IMAGE_SIZE_BIG
556
                    ),
557
                    'normal' => UserManager::getUserPicture(
558
                        $user_id,
559
                        USER_IMAGE_SIZE_MEDIUM
560
                    ),
561
                ]
562
            );
563
        }
564
565
        return $template->fetch($template->get_template('social/avatar_block.tpl'));
566
    }
567
568
    /**
569
     * Displays a sortable table with the list of online users.
570
     *
571
     * @param array $user_list The list of users to be shown
572
     * @param bool  $wrap      Whether we want the function to wrap the spans list in a div or not
573
     *
574
     * @return string HTML block or null if and ID was defined
575
     * @assert (null) === false
576
     */
577
    public static function display_user_list($user_list, $wrap = true)
578
    {
579
        $html = '';
580
581
        if (isset($_GET['id']) || count($user_list) < 1) {
582
            return false;
583
        }
584
585
        $course_url = '';
586
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
587
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($_GET['cidReq']) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

587
            $course_url = '&amp;cidReq='./** @scrutinizer ignore-type */ Security::remove_XSS($_GET['cidReq']);
Loading history...
588
        }
589
590
        $hide = api_get_configuration_value('hide_complete_name_in_whoisonline');
591
        foreach ($user_list as $uid) {
592
            $user_info = api_get_user_info($uid, true);
593
            $lastname = $user_info['lastname'];
594
            $firstname = $user_info['firstname'];
595
            $completeName = $firstname.', '.$lastname;
596
            $user_rol = 1 == $user_info['status'] ? Display::return_icon('teacher.png', get_lang('Trainer'), null, ICON_SIZE_TINY) : Display::return_icon('user.png', get_lang('Learner'), null, ICON_SIZE_TINY);
597
            $status_icon_chat = null;
598
            if (isset($user_info['user_is_online_in_chat']) && 1 == $user_info['user_is_online_in_chat']) {
599
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
600
            } else {
601
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
602
            }
603
604
            $userPicture = $user_info['avatar'];
605
            $officialCode = '';
606
            if ('true' === api_get_setting('show_official_code_whoisonline')) {
607
                $officialCode .= '<div class="items-user-official-code">
608
                    <p style="min-height: 30px;" title="'.get_lang('Code').'">'.$user_info['official_code'].'</p></div>';
609
            }
610
611
            if (true === $hide) {
612
                $completeName = '';
613
                $firstname = '';
614
                $lastname = '';
615
            }
616
617
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
618
619
            $url = null;
620
            // Anonymous users can't have access to the profile
621
            if (!api_is_anonymous()) {
622
                if ('true' === api_get_setting('allow_social_tool')) {
623
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
624
                } else {
625
                    $url = '?id='.$uid.$course_url;
626
                }
627
            } else {
628
                $url = null;
629
            }
630
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
631
632
            $html .= '<div class="col-xs-6 col-md-2">
633
                        <div class="items-user">
634
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
635
                            <div class="items-user-name">
636
                            '.$name.'
637
                            </div>
638
                            '.$officialCode.'
639
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
640
                        </div>
641
                      </div>';
642
        }
643
644
        return $html;
645
    }
646
647
    /**
648
     * @param string $content
649
     * @param string $span_count
650
     *
651
     * @return string
652
     */
653
    public static function social_wrapper_div($content, $span_count)
654
    {
655
        $span_count = (int) $span_count;
656
        $html = '<div class="span'.$span_count.'">';
657
        $html .= '<div class="well_border">';
658
        $html .= $content;
659
        $html .= '</div></div>';
660
661
        return $html;
662
    }
663
664
    /**
665
     * Dummy function.
666
     */
667
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
668
    {
669
        $content = '';
670
        switch ($place) {
671
            case SOCIAL_CENTER_PLUGIN:
672
                $social_plugins = [1, 2];
673
                if (is_array($social_plugins) && count($social_plugins) > 0) {
674
                    $content .= '<div id="social-plugins">';
675
                    foreach ($social_plugins as $plugin) {
676
                        $content .= '<div class="social-plugin-item">';
677
                        $content .= $plugin;
678
                        $content .= '</div>';
679
                    }
680
                    $content .= '</div>';
681
                }
682
                break;
683
            case SOCIAL_LEFT_PLUGIN:
684
                break;
685
            case SOCIAL_RIGHT_PLUGIN:
686
                break;
687
        }
688
689
        return $content;
690
    }
691
692
    /**
693
     * Gets all messages from someone's wall (within specific limits).
694
     *
695
     * @param int        $userId     id of wall shown
696
     * @param int|string $parentId   id message (Post main)
697
     * @param int|array  $groupId
698
     * @param int|array  $friendId
699
     * @param string     $startDate  Date from which we want to show the messages, in UTC time
700
     * @param int        $start      Limit for the number of parent messages we want to show
701
     * @param int        $length     Wall message query offset
702
     * @param bool       $getCount
703
     * @param array      $threadList
704
     *
705
     * @return array|int
706
     *
707
     * @author Yannick Warnier
708
     */
709
    public static function getWallMessages(
710
        $userId,
711
        $parentId = 0,
712
        $groupId = 0,
713
        $friendId = 0,
714
        $startDate = '',
715
        $start = 0,
716
        $length = 10,
717
        $getCount = false,
718
        $threadList = []
719
    ) {
720
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
721
722
        $parentId = (int) $parentId;
723
        $userId = (int) $userId;
724
        $start = (int) $start;
725
        $length = (int) $length;
726
727
        $select = " SELECT
728
                    id,
729
                    user_sender_id,
730
                    user_receiver_id,
731
                    send_date,
732
                    content,
733
                    parent_id,
734
                    msg_status,
735
                    group_id,
736
                    '' as forum_id,
737
                    '' as thread_id,
738
                    '' as c_id
739
                  ";
740
741
        if ($getCount) {
742
            $select = ' SELECT count(id) as count_items ';
743
        }
744
745
        $sqlBase = "$select FROM $tblMessage m WHERE ";
746
        $sql = [];
747
        $sql[1] = $sqlBase."msg_status <> ".MESSAGE_STATUS_WALL_DELETE.' AND ';
748
749
        // Get my own posts
750
        $userReceiverCondition = ' (
751
            user_receiver_id = '.$userId.' AND
752
            msg_status IN ('.MESSAGE_STATUS_WALL_POST.', '.MESSAGE_STATUS_WALL.') AND
753
            parent_id = '.$parentId.'
754
        )';
755
756
        $sql[1] .= $userReceiverCondition;
757
758
        $sql[2] = $sqlBase.' msg_status = '.MESSAGE_STATUS_PROMOTED.' ';
759
760
        // Get my group posts
761
        $groupCondition = '';
762
        if (!empty($groupId)) {
763
            if (is_array($groupId)) {
764
                $groupId = array_map('intval', $groupId);
765
                $groupId = implode(",", $groupId);
766
                $groupCondition = " ( group_id IN ($groupId) ";
767
            } else {
768
                $groupId = (int) $groupId;
769
                $groupCondition = " ( group_id = $groupId ";
770
            }
771
            $groupCondition .= ' AND (msg_type = '.Message::MESSAGE_TYPE_GROUP.') ';
772
        }
773
        if (!empty($groupCondition)) {
774
            $sql[3] = $sqlBase.$groupCondition;
775
        }
776
777
        // Get my friend posts
778
        $friendCondition = '';
779
        if (!empty($friendId)) {
780
            if (is_array($friendId)) {
781
                $friendId = array_map('intval', $friendId);
782
                $friendId = implode(",", $friendId);
783
                $friendCondition = " ( user_receiver_id IN ($friendId) ";
784
            } else {
785
                $friendId = (int) $friendId;
786
                $friendCondition = " ( user_receiver_id = $friendId ";
787
            }
788
            $friendCondition .= ' AND msg_status = '.MESSAGE_STATUS_WALL_POST.' AND parent_id = 0) ';
789
        }
790
        if (!empty($friendCondition)) {
791
            $sql[4] = $sqlBase.$friendCondition;
792
        }
793
794
        if (!empty($threadList)) {
795
            if ($getCount) {
796
                $select = ' SELECT count(iid) count_items ';
797
            } else {
798
                $select = " SELECT
799
                                iid as id,
800
                                poster_id as user_sender_id,
801
                                '' as user_receiver_id,
802
                                post_date as send_date,
803
                                post_text as content,
804
                                '' as parent_id,
805
                                ".MESSAGE_STATUS_FORUM." as msg_status,
806
                                '' as group_id,
807
                                forum_id,
808
                                thread_id,
809
                                c_id
810
                            ";
811
            }
812
813
            $threadList = array_map('intval', $threadList);
814
            $threadList = implode("','", $threadList);
815
            $condition = " thread_id IN ('$threadList') ";
816
            $sql[5] = "$select
817
                    FROM c_forum_post
818
                    WHERE $condition
819
                ";
820
        }
821
822
        if ($getCount) {
823
            $count = 0;
824
            foreach ($sql as $oneQuery) {
825
                if (!empty($oneQuery)) {
826
                    $res = Database::query($oneQuery);
827
                    $row = Database::fetch_array($res);
828
                    $count += (int) $row['count_items'];
829
                }
830
            }
831
832
            return $count;
833
        }
834
835
        $sqlOrder = ' ORDER BY send_date DESC ';
836
        $sqlLimit = " LIMIT $start, $length ";
837
        $messages = [];
838
        foreach ($sql as $index => $oneQuery) {
839
            if (5 === $index) {
840
                // Exception only for the forum query above (field name change)
841
                $oneQuery .= ' ORDER BY post_date DESC '.$sqlLimit;
842
            } else {
843
                $oneQuery .= $sqlOrder.$sqlLimit;
844
            }
845
            $res = Database::query($oneQuery);
846
            $em = Database::getManager();
847
            if (Database::num_rows($res) > 0) {
848
                $repo = $em->getRepository(CForumPost::class);
849
                $repoThread = $em->getRepository(CForumThread::class);
850
                $groups = [];
851
                $userGroup = new UserGroupModel();
852
                $urlGroup = api_get_path(WEB_CODE_PATH).'social/group_view.php?id=';
853
                while ($row = Database::fetch_array($res, 'ASSOC')) {
854
                    $row['group_info'] = [];
855
                    if (!empty($row['group_id'])) {
856
                        if (!in_array($row['group_id'], $groups)) {
857
                            $group = $userGroup->get($row['group_id']);
858
                            $group['url'] = $urlGroup.$group['id'];
859
                            $groups[$row['group_id']] = $group;
860
                            $row['group_info'] = $group;
861
                        } else {
862
                            $row['group_info'] = $groups[$row['group_id']];
863
                        }
864
                    }
865
866
                    // Forums
867
                    $row['post_title'] = '';
868
                    $row['forum_title'] = '';
869
                    $row['thread_url'] = '';
870
                    if (MESSAGE_STATUS_FORUM === (int) $row['msg_status']) {
871
                        // @todo use repositories to get post and threads.
872
                        /** @var CForumPost $post */
873
                        $post = $repo->find($row['id']);
874
                        /** @var CForumThread $thread */
875
                        $thread = $repoThread->find($row['thread_id']);
876
                        if ($post && $thread) {
877
                            //$courseInfo = api_get_course_info_by_id($post->getCId());
878
                            $row['post_title'] = $post->getForum()->getForumTitle();
879
                            $row['forum_title'] = $thread->getThreadTitle();
880
                            $row['thread_url'] = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
881
                                    //'cid' => $courseInfo['real_id'],
882
                                    'forum' => $post->getForum()->getIid(),
883
                                    'thread' => $post->getThread()->getIid(),
884
                                    'post_id' => $post->getIid(),
885
                                ]).'#post_id_'.$post->getIid();
886
                        }
887
                    }
888
889
                    $messages[$row['id']] = $row;
890
                }
891
            }
892
        }
893
        // Reordering messages by ID (reverse order) is enough to have the
894
        // latest first, as there is currently no option to edit messages
895
        // afterwards
896
        krsort($messages);
897
898
        return $messages;
899
    }
900
901
    /**
902
     * @return array
903
     */
904
    public static function getAttachmentPreviewList(Message $message)
905
    {
906
        $list = [];
907
        //if (empty($message['group_id'])) {
908
        $files = $message->getAttachments();
909
        if ($files) {
0 ignored issues
show
introduced by
$files is of type Doctrine\Common\Collections\Collection, thus it always evaluated to true.
Loading history...
910
            $repo = Container::getMessageAttachmentRepository();
911
            /** @var MessageAttachment $file */
912
            foreach ($files as $file) {
913
                $url = $repo->getResourceFileUrl($file);
914
                $display = Display::fileHtmlGuesser($file->getFilename(), $url);
915
                $list[] = $display;
916
            }
917
        }
918
        /*} else {
919
            $list = MessageManager::getAttachmentLinkList($messageId, 0);
920
        }*/
921
922
        return $list;
923
    }
924
925
    /**
926
     * @param array $message
927
     *
928
     * @return string
929
     */
930
    public static function getPostAttachment($message)
931
    {
932
        $previews = self::getAttachmentPreviewList($message);
933
934
        if (empty($previews)) {
935
            return '';
936
        }
937
938
        return implode('', $previews);
939
    }
940
941
    /**
942
     * @param array $messages
943
     *
944
     * @return array
945
     */
946
    public static function formatWallMessages($messages)
947
    {
948
        $data = [];
949
        $users = [];
950
        foreach ($messages as $key => $message) {
951
            $userIdLoop = $message['user_sender_id'];
952
            $userFriendIdLoop = $message['user_receiver_id'];
953
            if (!isset($users[$userIdLoop])) {
954
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
955
            }
956
957
            if (!isset($users[$userFriendIdLoop])) {
958
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
959
            }
960
961
            $html = self::headerMessagePost(
962
                $users[$userIdLoop],
963
                $users[$userFriendIdLoop],
964
                $message
965
            );
966
967
            $data[$key] = $message;
968
            $data[$key]['html'] = $html;
969
        }
970
971
        return $data;
972
    }
973
974
    /**
975
     * verify if Url Exist - Using Curl.
976
     *
977
     * @param $uri url
978
     *
979
     * @return bool
980
     */
981
    public static function verifyUrl($uri)
982
    {
983
        $curl = curl_init($uri);
984
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
985
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
986
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
987
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
988
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
989
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
990
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
991
        $response = curl_exec($curl);
992
        curl_close($curl);
993
        if (!empty($response)) {
994
            return true;
995
        }
996
997
        return false;
998
    }
999
1000
    /**
1001
     * Generate the social block for a user.
1002
     *
1003
     * @param int    $userId            The user id
1004
     * @param string $groupBlock        Optional. Highlight link possible values:
1005
     *                                  group_add, home, messages, messages_inbox, messages_compose,
1006
     *                                  messages_outbox, invitations, shared_profile, friends, groups, search
1007
     * @param int    $groupId           Optional. Group ID
1008
     * @param bool   $show_full_profile
1009
     *
1010
     * @return string The HTML code with the social block
1011
     */
1012
    public static function setSocialUserBlock(
1013
        Template $template,
1014
        $userId,
1015
        $groupBlock = '',
1016
        $groupId = 0,
1017
        $show_full_profile = true
1018
    ) {
1019
        if ('true' !== api_get_setting('allow_social_tool')) {
1020
            return '';
1021
        }
1022
1023
        $currentUserId = api_get_user_id();
1024
        $userId = (int) $userId;
1025
        $userRelationType = 0;
1026
1027
        $socialAvatarBlock = self::show_social_avatar_block(
1028
            $groupBlock,
1029
            $groupId,
1030
            $userId
1031
        );
1032
1033
        $profileEditionLink = null;
1034
        if ($currentUserId === $userId) {
1035
            $profileEditionLink = Display::getProfileEditionLink($userId);
1036
        } else {
1037
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
1038
        }
1039
1040
        $options = api_get_configuration_value('profile_fields_visibility');
1041
        if (isset($options['options'])) {
1042
            $options = $options['options'];
1043
        }
1044
1045
        $vCardUserLink = Display::getVCardUserLink($userId);
1046
        if (isset($options['vcard']) && false === $options['vcard']) {
1047
            $vCardUserLink = '';
1048
        }
1049
1050
        $userInfo = api_get_user_info($userId, true, false, true, true);
1051
1052
        if (isset($options['firstname']) && false === $options['firstname']) {
1053
            $userInfo['firstname'] = '';
1054
        }
1055
        if (isset($options['lastname']) && false === $options['lastname']) {
1056
            $userInfo['lastname'] = '';
1057
        }
1058
1059
        if (isset($options['email']) && false === $options['email']) {
1060
            $userInfo['email'] = '';
1061
        }
1062
1063
        // Ofaj
1064
        $hasCertificates = Certificate::getCertificateByUser($userId);
1065
        $userInfo['has_certificates'] = 0;
1066
        if (!empty($hasCertificates)) {
1067
            $userInfo['has_certificates'] = 1;
1068
        }
1069
1070
        $userInfo['is_admin'] = UserManager::is_admin($userId);
1071
        $languageId = api_get_language_from_iso($userInfo['language']);
1072
        $languageInfo = api_get_language_info($languageId);
1073
        if ($languageInfo) {
1074
            $userInfo['language'] = [
1075
                'label' => $languageInfo['original_name'],
1076
                'value' => $languageInfo['english_name'],
1077
                'code' => $languageInfo['isocode'],
1078
            ];
1079
        }
1080
1081
        if (isset($options['language']) && false === $options['language']) {
1082
            $userInfo['language'] = '';
1083
        }
1084
1085
        if (isset($options['photo']) && false === $options['photo']) {
1086
            $socialAvatarBlock = '';
1087
        }
1088
1089
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
1090
        $showLanguageFlag = api_get_configuration_value('social_show_language_flag_in_profile');
1091
1092
        $template->assign('user', $userInfo);
1093
        $template->assign('show_language_flag', $showLanguageFlag);
1094
        $template->assign('extra_info', $extraFieldBlock);
1095
        $template->assign('social_avatar_block', $socialAvatarBlock);
1096
        $template->assign('profile_edition_link', $profileEditionLink);
1097
        //Added the link to export the vCard to the Template
1098
1099
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
1100
        if ($show_full_profile) {
1101
            $template->assign('vcard_user_link', $vCardUserLink);
1102
        }
1103
1104
        if ('1' === api_get_setting('gamification_mode')) {
1105
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
1106
                $userId,
1107
                $userInfo['status']
1108
            );
1109
1110
            $template->assign('gamification_points', $gamificationPoints);
1111
        }
1112
        $chatEnabled = api_is_global_chat_enabled();
1113
1114
        if (isset($options['chat']) && false === $options['chat']) {
1115
            $chatEnabled = '';
1116
        }
1117
1118
        $template->assign('chat_enabled', $chatEnabled);
1119
        $template->assign('user_relation', $userRelationType);
1120
        $template->assign('user_relation_type_friend', UserRelUser::USER_RELATION_TYPE_FRIEND);
1121
        $template->assign('show_full_profile', $show_full_profile);
1122
1123
        $templateName = $template->get_template('social/user_block.tpl');
1124
1125
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
1126
            $templateName = $template->get_template('social/group_block.tpl');
1127
        }
1128
1129
        $template->assign('social_avatar_block', $template->fetch($templateName));
1130
    }
1131
1132
    /**
1133
     * @param int $user_id
1134
     * @param $link_shared
1135
     * @param bool $showLinkToChat
1136
     *
1137
     * @return string
1138
     */
1139
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
1140
    {
1141
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1142
        $friends = self::get_friends($user_id, UserRelUser::USER_RELATION_TYPE_FRIEND);
1143
        $numberFriends = count($friends);
1144
        $friendHtml = '';
1145
1146
        if (!empty($numberFriends)) {
1147
            $friendHtml .= '<div class="list-group contact-list">';
1148
            $j = 1;
1149
1150
            usort(
1151
                $friends,
1152
                function ($a, $b) {
1153
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
1154
                }
1155
            );
1156
1157
            foreach ($friends as $friend) {
1158
                if ($j > $numberFriends) {
1159
                    break;
1160
                }
1161
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
1162
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
1163
1164
                $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
1165
                $status = 0;
1166
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
1167
                    $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
1168
                    $status = 1;
1169
                }
1170
1171
                $friendAvatarMedium = UserManager::getUserPicture(
1172
                    $friend['friend_user_id'],
1173
                    USER_IMAGE_SIZE_MEDIUM
1174
                );
1175
                $friendAvatarSmall = UserManager::getUserPicture(
1176
                    $friend['friend_user_id'],
1177
                    USER_IMAGE_SIZE_SMALL
1178
                );
1179
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
1180
1181
                $relation = self::get_relation_between_contacts(
1182
                    $friend['friend_user_id'],
1183
                    api_get_user_id()
1184
                );
1185
1186
                if ($showLinkToChat) {
1187
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
1188
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
1189
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
1190
                } else {
1191
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
1192
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
1193
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
1194
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
1195
                }
1196
1197
                $friendHtml .= '</a>';
1198
1199
                $j++;
1200
            }
1201
            $friendHtml .= '</div>';
1202
        } else {
1203
            $friendHtml = Display::return_message(get_lang('No friends in your contact list'), 'warning');
1204
        }
1205
1206
        return $friendHtml;
1207
    }
1208
1209
    /**
1210
     * @param string $urlForm
1211
     *
1212
     * @return string
1213
     */
1214
    public static function getWallForm($urlForm)
1215
    {
1216
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
1217
        $form = new FormValidator(
1218
            'social_wall_main',
1219
            'post',
1220
            $urlForm.$userId,
1221
            null,
1222
            ['enctype' => 'multipart/form-data'],
1223
            FormValidator::LAYOUT_HORIZONTAL
1224
        );
1225
1226
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('Write something on your friend\'s wall') : get_lang(
1227
            'Social wallWhatAreYouThinkingAbout'
1228
        );
1229
1230
        $form->addTextarea(
1231
            'social_wall_new_msg_main',
1232
            null,
1233
            [
1234
                'placeholder' => $socialWallPlaceholder,
1235
                'cols-size' => [1, 12, 1],
1236
                'aria-label' => $socialWallPlaceholder,
1237
            ]
1238
        );
1239
        $form->addHtml('<div class="form-group">');
1240
        $form->addHtml('<div class="col-sm-6">');
1241
        $form->addFile('picture', get_lang('File upload'), ['custom' => true]);
1242
        $form->addHtml('</div>');
1243
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
1244
        $form->addButtonSend(
1245
            get_lang('Post'),
1246
            'wall_post_button',
1247
            false,
1248
            [
1249
                'cols-size' => [1, 10, 1],
1250
                'custom' => true,
1251
            ]
1252
        );
1253
        $form->addHtml('</div></div>');
1254
        $form->addHtml('</div>');
1255
        $form->addHidden('url_content', '');
1256
        $html = Display::panel($form->returnForm(), get_lang('Social wall'));
1257
1258
        return $html;
1259
    }
1260
1261
    /**
1262
     * @param string $message
1263
     * @param string $content
1264
     *
1265
     * @return string
1266
     */
1267
    public static function wrapPost($message, $content)
1268
    {
1269
        $class = '';
1270
        if (MESSAGE_STATUS_PROMOTED === (int) $message['msg_status']) {
1271
            $class = 'promoted_post';
1272
        }
1273
1274
        return Display::panel($content, '',
1275
            '',
1276
            'default',
1277
            '',
1278
            'post_'.$message['id'],
1279
            null,
1280
            $class
1281
        );
1282
    }
1283
1284
    /**
1285
     * Get HTML code block for user skills.
1286
     *
1287
     * @param int    $userId      The user ID
1288
     * @param string $orientation
1289
     *
1290
     * @return string
1291
     */
1292
    public static function getSkillBlock($userId, $orientation = 'horizontal')
1293
    {
1294
        if (false === SkillModel::isAllowed($userId, false)) {
1295
            return '';
1296
        }
1297
1298
        $skill = new SkillModel();
1299
        $ranking = $skill->getUserSkillRanking($userId);
1300
1301
        $template = new Template(null, false, false, false, false, false);
1302
        $template->assign('ranking', $ranking);
1303
        $template->assign('orientation', $orientation);
1304
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
1305
        $template->assign('user_id', $userId);
1306
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
1307
1308
        $skillBlock = $template->get_template('social/skills_block.tpl');
1309
1310
        return $template->fetch($skillBlock);
1311
    }
1312
1313
    /**
1314
     * @param int  $user_id
1315
     * @param bool $isArray
1316
     *
1317
     * @return string|array
1318
     */
1319
    public static function getExtraFieldBlock($user_id, $isArray = false)
1320
    {
1321
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
1322
        $fieldVisibilityKeys = [];
1323
        if (isset($fieldVisibility['options'])) {
1324
            $fieldVisibility = $fieldVisibility['options'];
1325
            $fieldVisibilityKeys = array_keys($fieldVisibility);
1326
        }
1327
1328
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
1329
        $extra_user_data = UserManager::get_extra_user_data($user_id);
1330
1331
        $extra_information = '';
1332
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
1333
            $extra_information_value = '';
1334
            $extraField = new ExtraField('user');
1335
            $listType = [];
1336
            $extraFieldItem = [];
1337
            foreach ($extra_user_data as $key => $data) {
1338
                if (empty($data)) {
1339
                    continue;
1340
                }
1341
                if (in_array($key, $fieldVisibilityKeys) && false === $fieldVisibility[$key]) {
1342
                    continue;
1343
                }
1344
1345
                // Avoiding parameters
1346
                if (in_array(
1347
                    $key,
1348
                    [
1349
                        'mail_notify_invitation',
1350
                        'mail_notify_message',
1351
                        'mail_notify_group_message',
1352
                    ]
1353
                )) {
1354
                    continue;
1355
                }
1356
                // get display text, visibility and type from user_field table
1357
                $field_variable = str_replace('extra_', '', $key);
1358
1359
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
1360
                    $field_variable
1361
                );
1362
1363
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
1364
                    continue;
1365
                }
1366
1367
                // if is not visible skip
1368
                if (1 != $extraFieldInfo['visible_to_self']) {
1369
                    continue;
1370
                }
1371
1372
                // if is not visible to others skip also
1373
                if (1 != $extraFieldInfo['visible_to_others']) {
1374
                    continue;
1375
                }
1376
1377
                if (is_array($data)) {
1378
                    switch ($extraFieldInfo['field_type']) {
1379
                        case ExtraField::FIELD_TYPE_RADIO:
1380
                            $objEfOption = new ExtraFieldOption('user');
1381
                            $value = $data['extra_'.$extraFieldInfo['variable']];
1382
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
1383
                                $extraFieldInfo['id'],
1384
                                $value
1385
                            );
1386
1387
                            if ($optionInfo && isset($optionInfo[0])) {
1388
                                $optionInfo = $optionInfo[0];
1389
                                $extraFieldItem = [
1390
                                    'variable' => $extraFieldInfo['variable'],
1391
                                    'label' => ucfirst($extraFieldInfo['display_text']),
1392
                                    'value' => $optionInfo['display_text'],
1393
                                ];
1394
                            } else {
1395
                                $extraFieldItem = [
1396
                                    'variable' => $extraFieldInfo['variable'],
1397
                                    'label' => ucfirst($extraFieldInfo['display_text']),
1398
                                    'value' => implode(',', $data),
1399
                                ];
1400
                            }
1401
                            break;
1402
                        default:
1403
                            $extra_information_value .=
1404
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
1405
                                .' '.implode(',', $data).'</li>';
1406
                            $extraFieldItem = [
1407
                                'variable' => $extraFieldInfo['variable'],
1408
                                'label' => ucfirst($extraFieldInfo['display_text']),
1409
                                'value' => implode(',', $data),
1410
                            ];
1411
                            break;
1412
                    }
1413
                } else {
1414
                    switch ($extraFieldInfo['field_type']) {
1415
                        case ExtraField::FIELD_TYPE_RADIO:
1416
                            $objEfOption = new ExtraFieldOption('user');
1417
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
1418
                            break;
1419
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
1420
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
1421
                            $data = explode('::', $data);
1422
                            $data = $data[0];
1423
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
1424
                            $extraFieldItem = [
1425
                                'variable' => $extraFieldInfo['variable'],
1426
                                'label' => ucfirst($extraFieldInfo['display_text']),
1427
                                'value' => $data,
1428
                            ];
1429
                            break;
1430
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
1431
                            $id_options = explode('::', $data);
1432
                            $value_options = [];
1433
                            // get option display text from user_field_options table
1434
                            foreach ($id_options as $id_option) {
1435
                                $sql = "SELECT display_text
1436
                                    FROM $t_ufo
1437
                                    WHERE id = '$id_option'";
1438
                                $res_options = Database::query($sql);
1439
                                $row_options = Database::fetch_row($res_options);
1440
                                $value_options[] = $row_options[0];
1441
                            }
1442
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
1443
                                .' '.implode(' ', $value_options).'</li>';
1444
                            $extraFieldItem = [
1445
                                'variable' => $extraFieldInfo['variable'],
1446
                                'label' => ucfirst($extraFieldInfo['display_text']),
1447
                                'value' => $value_options,
1448
                            ];
1449
                            break;
1450
                        case ExtraField::FIELD_TYPE_TAG:
1451
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
1452
1453
                            $tag_tmp = '';
1454
                            foreach ($user_tags as $tags) {
1455
                                $tag_tmp .= '<a class="label label_tag"'
1456
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
1457
                                    .$tags['tag']
1458
                                    .'</a>';
1459
                            }
1460
                            if (is_array($user_tags) && count($user_tags) > 0) {
1461
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
1462
                                    .' '.$tag_tmp.'</li>';
1463
                            }
1464
                            $extraFieldItem = [
1465
                                'variable' => $extraFieldInfo['variable'],
1466
                                'label' => ucfirst($extraFieldInfo['display_text']),
1467
                                'value' => $tag_tmp,
1468
                            ];
1469
                            break;
1470
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
1471
                            $icon_path = UserManager::get_favicon_from_url($data);
1472
                            if (false == self::verifyUrl($icon_path)) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1473
                                break;
1474
                            }
1475
                            $bottom = '0.2';
1476
                            //quick hack for hi5
1477
                            $domain = parse_url($icon_path, PHP_URL_HOST);
1478
                            if ('www.hi5.com' == $domain || 'hi5.com' == $domain) {
1479
                                $bottom = '-0.8';
1480
                            }
1481
                            $data = '<a href="'.$data.'">'
1482
                                .'<img src="'.$icon_path.'" alt="icon"'
1483
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
1484
                                .$extraFieldInfo['display_text']
1485
                                .'</a>';
1486
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
1487
                            $extraFieldItem = [
1488
                                'variable' => $extraFieldInfo['variable'],
1489
                                'label' => ucfirst($extraFieldInfo['display_text']),
1490
                                'value' => $data,
1491
                            ];
1492
                            break;
1493
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
1494
                            $parsedData = explode('::', $data);
1495
1496
                            if (!$parsedData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsedData of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1497
                                break;
1498
                            }
1499
1500
                            $objEfOption = new ExtraFieldOption('user');
1501
                            $optionInfo = $objEfOption->get($parsedData[0]);
1502
1503
                            $extra_information_value .= '<li class="list-group-item">'
1504
                                .$optionInfo['display_text'].': '
1505
                                .$parsedData[1].'</li>';
1506
                            $extraFieldItem = [
1507
                                'variable' => $extraFieldInfo['variable'],
1508
                                'label' => ucfirst($extraFieldInfo['display_text']),
1509
                                'value' => $parsedData[1],
1510
                            ];
1511
                            break;
1512
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
1513
                            $optionIds = explode(';', $data);
1514
                            $optionValues = [];
1515
1516
                            foreach ($optionIds as $optionId) {
1517
                                $objEfOption = new ExtraFieldOption('user');
1518
                                $optionInfo = $objEfOption->get($optionId);
1519
1520
                                $optionValues[] = $optionInfo['display_text'];
1521
                            }
1522
                            $extra_information_value .= '<li class="list-group-item">'
1523
                                .ucfirst($extraFieldInfo['display_text']).': '
1524
                                .implode(' ', $optionValues).'</li>';
1525
                            $extraFieldItem = [
1526
                                'variable' => $extraFieldInfo['variable'],
1527
                                'label' => ucfirst($extraFieldInfo['display_text']),
1528
                                'value' => implode(' ', $optionValues),
1529
                            ];
1530
                            break;
1531
                        default:
1532
                            // Ofaj
1533
                            // Converts "Date of birth" into "age"
1534
                            if ('terms_datedenaissance' === $key) {
1535
                                $dataArray = date_to_str_ago($data, 'UTC', true);
1536
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
1537
                                if (!empty($dataToString)) {
1538
                                    $data = $dataToString;
1539
                                    $extraFieldInfo['display_text'] = get_lang('Age');
1540
                                }
1541
                            }
1542
1543
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
1544
                            $extraFieldItem = [
1545
                                'variable' => $extraFieldInfo['variable'],
1546
                                'label' => ucfirst($extraFieldInfo['display_text']),
1547
                                'value' => $data,
1548
                            ];
1549
                            break;
1550
                    }
1551
                }
1552
1553
                $listType[] = $extraFieldItem;
1554
            }
1555
1556
            if ($isArray) {
1557
                return $listType;
1558
            } else {
1559
                // if there are information to show
1560
                if (!empty($extra_information_value)) {
1561
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
1562
                    $extra_information .= Display::panelCollapse(
1563
                        get_lang('Extra information'),
1564
                        $extra_information_value,
1565
                        'sn-extra-information',
1566
                        null,
1567
                        'sn-extra-accordion',
1568
                        'sn-extra-collapse'
1569
                    );
1570
                }
1571
            }
1572
        }
1573
1574
        return $extra_information;
1575
    }
1576
1577
    /**
1578
     * @param int   $countPost
1579
     * @param array $htmlHeadXtra
1580
     */
1581
    public static function getScrollJs($countPost, &$htmlHeadXtra)
1582
    {
1583
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
1584
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
1585
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
1586
        $locale = api_get_language_isocode();
1587
1588
        // Add Jquery scroll pagination plugin
1589
        //$htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
1590
        // Add Jquery Time ago plugin
1591
        //$htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
1592
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
1593
        if (file_exists($timeAgoLocaleDir)) {
1594
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
1595
        }
1596
1597
        if ($countPost > self::DEFAULT_WALL_POSTS) {
1598
            $htmlHeadXtra[] = '<script>
1599
            $(function() {
1600
                var container = $("#wallMessages");
1601
                container.jscroll({
1602
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
1603
                    nextSelector: "a.nextPage:last",
1604
                    contentSelector: "",
1605
                    callback: timeAgo
1606
                });
1607
            });
1608
            </script>';
1609
        }
1610
1611
        $htmlHeadXtra[] = '<script>
1612
            function deleteMessage(id)
1613
            {
1614
                $.ajax({
1615
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1616
                    success: function (result) {
1617
                        if (result) {
1618
                            $("#message_" + id).parent().parent().parent().parent().html(result);
1619
                        }
1620
                    }
1621
                });
1622
            }
1623
1624
            function deleteComment(id)
1625
            {
1626
                $.ajax({
1627
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1628
                    success: function (result) {
1629
                        if (result) {
1630
                            $("#message_" + id).parent().parent().parent().html(result);
1631
                        }
1632
                    }
1633
                });
1634
            }
1635
1636
            function submitComment(messageId)
1637
            {
1638
                var data = $("#form_comment_"+messageId).serializeArray();
1639
                $.ajax({
1640
                    type : "POST",
1641
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
1642
                    data: data,
1643
                    success: function (result) {
1644
                        if (result) {
1645
                            $("#post_" + messageId + " textarea").val("");
1646
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
1647
                            $("#post_" + messageId + " .sub-mediapost").append(
1648
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved.')).'</div>\')
1649
                            );
1650
1651
                            $("#result_" + messageId + "").fadeIn("fast", function() {
1652
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
1653
                                    $(this).remove();
1654
                                });
1655
                            });
1656
                        }
1657
                    }
1658
                });
1659
            }
1660
1661
            $(function() {
1662
                timeAgo();
1663
1664
                /*$(".delete_message").on("click", function() {
1665
                    var id = $(this).attr("id");
1666
                    id = id.split("_")[1];
1667
                    $.ajax({
1668
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1669
                        success: function (result) {
1670
                            if (result) {
1671
                                $("#message_" + id).parent().parent().parent().parent().html(result);
1672
                            }
1673
                        }
1674
                    });
1675
                });
1676
1677
1678
                $(".delete_comment").on("click", function() {
1679
                    var id = $(this).attr("id");
1680
                    id = id.split("_")[1];
1681
                    $.ajax({
1682
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1683
                        success: function (result) {
1684
                            if (result) {
1685
                                $("#message_" + id).parent().parent().parent().html(result);
1686
                            }
1687
                        }
1688
                    });
1689
                });
1690
                */
1691
            });
1692
1693
            function timeAgo() {
1694
                $(".timeago").timeago();
1695
            }
1696
            </script>';
1697
    }
1698
1699
    /**
1700
     * @param int $userId
1701
     * @param int $countPost
1702
     *
1703
     * @return string
1704
     */
1705
    public static function getAutoExtendLink($userId, $countPost)
1706
    {
1707
        $userId = (int) $userId;
1708
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
1709
        $socialAutoExtendLink = '';
1710
        if ($countPost > self::DEFAULT_WALL_POSTS) {
1711
            $socialAutoExtendLink = Display::url(
1712
                get_lang('See more'),
1713
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
1714
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
1715
                [
1716
                    'class' => 'nextPage next',
1717
                ]
1718
            );
1719
        }
1720
1721
        return $socialAutoExtendLink;
1722
    }
1723
1724
    /**
1725
     * @param int $userId
1726
     *
1727
     * @return array
1728
     */
1729
    public static function getThreadList($userId)
1730
    {
1731
        return [];
1732
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
0 ignored issues
show
Unused Code introduced by
$forumCourseId = api_get...obal_forums_course_id') is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1733
1734
        $threads = [];
1735
        if (!empty($forumCourseId)) {
1736
            $courseInfo = api_get_course_info_by_id($forumCourseId);
1737
            /*getNotificationsPerUser($userId, true, $forumCourseId);
1738
            $notification = Session::read('forum_notification');
1739
            Session::erase('forum_notification');*/
1740
1741
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
1742
                'cid' => $courseInfo['real_id'],
1743
            ]).'&';
1744
            if (isset($notification['thread']) && !empty($notification['thread'])) {
1745
                $threadList = array_filter(array_unique($notification['thread']));
1746
                $repo = Container::getForumThreadRepository();
1747
                foreach ($threadList as $threadId) {
1748
                    /** @var CForumThread $thread */
1749
                    $thread = $repo->find($threadId);
1750
                    if ($thread) {
1751
                        $threadUrl = $threadUrlBase.http_build_query([
1752
                            'forum' => $thread->getForum()->getIid(),
1753
                            'thread' => $thread->getIid(),
1754
                        ]);
1755
                        $threads[] = [
1756
                            'id' => $threadId,
1757
                            'url' => Display::url(
1758
                                $thread->getThreadTitle(),
1759
                                $threadUrl
1760
                            ),
1761
                            'name' => Display::url(
1762
                                $thread->getThreadTitle(),
1763
                                $threadUrl
1764
                            ),
1765
                            'description' => '',
1766
                        ];
1767
                    }
1768
                }
1769
            }
1770
        }
1771
1772
        return $threads;
1773
    }
1774
1775
    /**
1776
     * @param int $userId
1777
     *
1778
     * @return string
1779
     */
1780
    public static function getGroupBlock($userId)
1781
    {
1782
        $threadList = self::getThreadList($userId);
1783
        $userGroup = new UserGroupModel();
1784
1785
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
1786
        $courseInfo = null;
1787
        if (!empty($forumCourseId)) {
1788
            $courseInfo = api_get_course_info_by_id($forumCourseId);
1789
        }
1790
1791
        $social_group_block = '';
1792
        if (!empty($courseInfo)) {
1793
            if (!empty($threadList)) {
1794
                $social_group_block .= '<div class="list-group">';
1795
                foreach ($threadList as $group) {
1796
                    $social_group_block .= ' <li class="list-group-item">';
1797
                    $social_group_block .= $group['name'];
1798
                    $social_group_block .= '</li>';
1799
                }
1800
                $social_group_block .= '</div>';
1801
            }
1802
1803
            $social_group_block .= Display::url(
1804
                get_lang('See all communities'),
1805
                api_get_path(WEB_CODE_PATH).'forum/index.php?cid='.$courseInfo['real_id']
1806
            );
1807
1808
            if (!empty($social_group_block)) {
1809
                $social_group_block = Display::panelCollapse(
1810
                    get_lang('My communities'),
1811
                    $social_group_block,
1812
                    'sm-groups',
1813
                    null,
1814
                    'grups-acordion',
1815
                    'groups-collapse'
1816
                );
1817
            }
1818
        } else {
1819
            // Load my groups
1820
            $results = $userGroup->get_groups_by_user(
1821
                $userId,
1822
                [
1823
                    GROUP_USER_PERMISSION_ADMIN,
1824
                    GROUP_USER_PERMISSION_READER,
1825
                    GROUP_USER_PERMISSION_MODERATOR,
1826
                    GROUP_USER_PERMISSION_HRM,
1827
                ]
1828
            );
1829
1830
            $myGroups = [];
1831
            if (!empty($results)) {
1832
                foreach ($results as $result) {
1833
                    $id = $result['id'];
1834
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
1835
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
1836
1837
                    $group_url = "group_view.php?id=$id";
1838
1839
                    $link = Display::url(
1840
                        api_ucwords(cut($result['name'], 40, true)),
1841
                        $group_url
1842
                    );
1843
1844
                    $result['name'] = $link;
1845
1846
                    $picture = $userGroup->get_picture_group(
1847
                        $id,
1848
                        $result['picture'],
1849
                        null,
1850
                        GROUP_IMAGE_SIZE_BIG
1851
                    );
1852
1853
                    $result['picture'] = '<img class="img-responsive" src="'.$picture.'" />';
1854
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
1855
                        get_lang('See more').'</a></div>';
1856
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
1857
                    $myGroups[] = [
1858
                        'url' => Display::url(
1859
                            $result['picture'],
1860
                            $group_url
1861
                        ),
1862
                        'name' => $result['name'],
1863
                        'description' => $group_info.$group_actions,
1864
                    ];
1865
                }
1866
1867
                $social_group_block .= '<div class="list-group">';
1868
                foreach ($myGroups as $group) {
1869
                    $social_group_block .= ' <li class="list-group-item">';
1870
                    $social_group_block .= $group['name'];
1871
                    $social_group_block .= '</li>';
1872
                }
1873
                $social_group_block .= '</div>';
1874
1875
                $form = new FormValidator(
1876
                    'find_groups_form',
1877
                    'get',
1878
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
1879
                    null,
1880
                    null,
1881
                    FormValidator::LAYOUT_BOX_NO_LABEL
1882
                );
1883
                $form->addHidden('search_type', 2);
1884
1885
                $form->addText(
1886
                    'q',
1887
                    get_lang('Search'),
1888
                    false,
1889
                    [
1890
                        'aria-label' => get_lang('Search'),
1891
                        'custom' => true,
1892
                        'placeholder' => get_lang('Search'),
1893
                    ]
1894
                );
1895
1896
                $social_group_block .= $form->returnForm();
1897
1898
                if (!empty($social_group_block)) {
1899
                    $social_group_block = Display::panelCollapse(
1900
                        get_lang('My groups'),
1901
                        $social_group_block,
1902
                        'sm-groups',
1903
                        null,
1904
                        'grups-acordion',
1905
                        'groups-collapse'
1906
                    );
1907
                }
1908
            }
1909
        }
1910
1911
        return $social_group_block;
1912
    }
1913
1914
    /**
1915
     * @param string $selected
1916
     *
1917
     * @return string
1918
     */
1919
    public static function getHomeProfileTabs($selected = 'home')
1920
    {
1921
        $headers = [
1922
            [
1923
                'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
1924
                'content' => get_lang('Profile'),
1925
            ],
1926
        ];
1927
        $allowJustification = 'true' === api_get_plugin_setting('justification', 'tool_enable');
1928
        if ($allowJustification) {
1929
            $plugin = Justification::create();
1930
            $headers[] = [
1931
                'url' => api_get_path(WEB_CODE_PATH).'auth/justification.php',
1932
                'content' => $plugin->get_lang('Justification'),
1933
            ];
1934
        }
1935
1936
        $allowPauseTraining = 'true' === api_get_plugin_setting('pausetraining', 'tool_enable');
1937
        $allowEdit = 'true' === api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation');
1938
        if ($allowPauseTraining && $allowEdit) {
1939
            $plugin = PauseTraining::create();
1940
            $headers[] = [
1941
                'url' => api_get_path(WEB_CODE_PATH).'auth/pausetraining.php',
1942
                'content' => $plugin->get_lang('PauseTraining'),
1943
            ];
1944
        }
1945
1946
        $selectedItem = 1;
1947
        foreach ($headers as $header) {
1948
            $info = pathinfo($header['url']);
1949
            if ($selected === $info['filename']) {
1950
                break;
1951
            }
1952
            $selectedItem++;
1953
        }
1954
1955
        $tabs = '';
1956
        if (count($headers) > 1) {
1957
            $tabs = Display::tabsOnlyLink($headers, $selectedItem);
1958
        }
1959
1960
        return $tabs;
1961
    }
1962
1963
    /**
1964
     * Returns the formatted header message post.
1965
     *
1966
     * @param int   $authorInfo
1967
     * @param int   $receiverInfo
1968
     * @param array $message      Message data
1969
     *
1970
     * @return string $html       The formatted header message post
1971
     */
1972
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
1973
    {
1974
        $currentUserId = api_get_user_id();
1975
        $authorId = (int) $authorInfo['user_id'];
1976
        $receiverId = (int) $receiverInfo['user_id'];
1977
        $iconStatus = $authorInfo['icon_status'];
1978
1979
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
1980
        $avatarAuthor = $authorInfo['avatar'];
1981
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
1982
        $nameCompleteAuthor = $authorInfo['complete_name'];
1983
1984
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
1985
        $nameCompleteReceiver = $receiverInfo['complete_name'];
1986
1987
        $htmlReceiver = '';
1988
        if ($authorId !== $receiverId) {
1989
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
1990
        }
1991
1992
        if (!empty($message['group_info'])) {
1993
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
1994
        }
1995
        $canEdit = ($currentUserId == $authorInfo['user_id'] || $currentUserId == $receiverInfo['user_id']) && empty($message['group_info']);
1996
1997
        if (!empty($message['thread_id'])) {
1998
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
1999
            $canEdit = false;
2000
        }
2001
2002
        $postAttachment = self::getPostAttachment($message);
2003
2004
        $html = '<div class="top-mediapost" >';
2005
        $html .= '<div class="pull-right btn-group btn-group-sm">';
2006
2007
        $html .= MessageManager::getLikesButton(
2008
            $message['id'],
2009
            $currentUserId,
2010
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
2011
        );
2012
2013
        if ($canEdit) {
2014
            $htmlDelete = Display::url(
2015
                Display::returnFontAwesomeIcon('trash', '', true),
2016
                'javascript:void(0)',
2017
                [
2018
                    'id' => 'message_'.$message['id'],
2019
                    'title' => get_lang('Delete comment'),
2020
                    'onclick' => 'deleteMessage('.$message['id'].')',
2021
                    'class' => 'btn btn-default',
2022
                ]
2023
            );
2024
2025
            $html .= $htmlDelete;
2026
        }
2027
        $html .= '</div>';
2028
2029
        $html .= '<div class="user-image" >';
2030
        $html .= '<a href="'.$urlAuthor.'">
2031
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
2032
        $html .= '</div>';
2033
        $html .= '<div class="user-data">';
2034
        $html .= $iconStatus;
2035
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
2036
        $html .= '<div class="post-date">'.$date.'</div>';
2037
        $html .= '</div>';
2038
        $html .= '<div class="msg-content">';
2039
        if (!empty($postAttachment)) {
2040
            $html .= '<div class="post-attachment thumbnail">';
2041
            $html .= $postAttachment;
2042
            $html .= '</div>';
2043
        }
2044
        $html .= '<div>'.Security::remove_XSS($message['content']).'</div>';
0 ignored issues
show
Bug introduced by
Are you sure Security::remove_XSS($message['content']) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

2044
        $html .= '<div>'./** @scrutinizer ignore-type */ Security::remove_XSS($message['content']).'</div>';
Loading history...
2045
        $html .= '</div>';
2046
        $html .= '</div>'; // end mediaPost
2047
2048
        // Popularity post functionality
2049
        $html .= '<div class="popularity-mediapost"></div>';
2050
2051
        return $html;
2052
    }
2053
}
2054