Passed
Push — master ( f7e68c...d99f69 )
by Julito
17:56
created

SocialManager::getUserRssFeed()   B

Complexity

Conditions 11
Paths 21

Size

Total Lines 49
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 33
nc 21
nop 2
dl 0
loc 49
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
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 USER_UNKNOWN;
0 ignored issues
show
Bug introduced by
The constant USER_UNKNOWN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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_status = '.MESSAGE_STATUS_NEW.' OR msg_status = '.MESSAGE_STATUS_UNREAD.')) ';
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
     * get html data with OpenGrap passing the URL.
976
     *
977
     * @param $link url
978
     *
979
     * @return string data html
980
     */
981
    public static function readContentWithOpenGraph($link)
982
    {
983
        if (false === strpos($link, "://") && "/" != substr($link, 0, 1)) {
984
            $link = "http://".$link;
985
        }
986
        $graph = OpenGraph::fetch($link);
987
        $link = parse_url($link);
988
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
989
        if (!$graph) {
990
            return false;
991
        }
992
        $url = $graph->url;
993
        $image = $graph->image;
994
        $description = $graph->description;
995
        $title = $graph->title;
996
        $html = '<div class="thumbnail social-thumbnail">';
997
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'">
998
                <img class="img-responsive social-image" src="'.$image.'" /></a>';
999
        $html .= '<div class="social-description">';
1000
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
1001
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
1002
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
1003
        $html .= '</div>';
1004
        $html .= '</div>';
1005
1006
        return $html;
1007
    }
1008
1009
    /**
1010
     * verify if Url Exist - Using Curl.
1011
     *
1012
     * @param $uri url
1013
     *
1014
     * @return bool
1015
     */
1016
    public static function verifyUrl($uri)
1017
    {
1018
        $curl = curl_init($uri);
1019
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
1020
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
1021
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1022
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
1023
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
1024
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
1025
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
1026
        $response = curl_exec($curl);
1027
        curl_close($curl);
1028
        if (!empty($response)) {
1029
            return true;
1030
        }
1031
1032
        return false;
1033
    }
1034
1035
    /**
1036
     * Generate the social block for a user.
1037
     *
1038
     * @param int    $userId            The user id
1039
     * @param string $groupBlock        Optional. Highlight link possible values:
1040
     *                                  group_add, home, messages, messages_inbox, messages_compose,
1041
     *                                  messages_outbox, invitations, shared_profile, friends, groups, search
1042
     * @param int    $groupId           Optional. Group ID
1043
     * @param bool   $show_full_profile
1044
     *
1045
     * @return string The HTML code with the social block
1046
     */
1047
    public static function setSocialUserBlock(
1048
        Template $template,
1049
        $userId,
1050
        $groupBlock = '',
1051
        $groupId = 0,
1052
        $show_full_profile = true
1053
    ) {
1054
        if ('true' !== api_get_setting('allow_social_tool')) {
1055
            return '';
1056
        }
1057
1058
        $currentUserId = api_get_user_id();
1059
        $userId = (int) $userId;
1060
        $userRelationType = 0;
1061
1062
        $socialAvatarBlock = self::show_social_avatar_block(
1063
            $groupBlock,
1064
            $groupId,
1065
            $userId
1066
        );
1067
1068
        $profileEditionLink = null;
1069
        if ($currentUserId === $userId) {
1070
            $profileEditionLink = Display::getProfileEditionLink($userId);
1071
        } else {
1072
            $userRelationType = self::get_relation_between_contacts($currentUserId, $userId);
1073
        }
1074
1075
        $options = api_get_configuration_value('profile_fields_visibility');
1076
        if (isset($options['options'])) {
1077
            $options = $options['options'];
1078
        }
1079
1080
        $vCardUserLink = Display::getVCardUserLink($userId);
1081
        if (isset($options['vcard']) && false === $options['vcard']) {
1082
            $vCardUserLink = '';
1083
        }
1084
1085
        $userInfo = api_get_user_info($userId, true, false, true, true);
1086
1087
        if (isset($options['firstname']) && false === $options['firstname']) {
1088
            $userInfo['firstname'] = '';
1089
        }
1090
        if (isset($options['lastname']) && false === $options['lastname']) {
1091
            $userInfo['lastname'] = '';
1092
        }
1093
1094
        if (isset($options['email']) && false === $options['email']) {
1095
            $userInfo['email'] = '';
1096
        }
1097
1098
        // Ofaj
1099
        $hasCertificates = Certificate::getCertificateByUser($userId);
1100
        $userInfo['has_certificates'] = 0;
1101
        if (!empty($hasCertificates)) {
1102
            $userInfo['has_certificates'] = 1;
1103
        }
1104
1105
        $userInfo['is_admin'] = UserManager::is_admin($userId);
1106
        $languageId = api_get_language_from_iso($userInfo['language']);
1107
        $languageInfo = api_get_language_info($languageId);
1108
        if ($languageInfo) {
1109
            $userInfo['language'] = [
1110
                'label' => $languageInfo['original_name'],
1111
                'value' => $languageInfo['english_name'],
1112
                'code' => $languageInfo['isocode'],
1113
            ];
1114
        }
1115
1116
        if (isset($options['language']) && false === $options['language']) {
1117
            $userInfo['language'] = '';
1118
        }
1119
1120
        if (isset($options['photo']) && false === $options['photo']) {
1121
            $socialAvatarBlock = '';
1122
        }
1123
1124
        $extraFieldBlock = self::getExtraFieldBlock($userId, true);
1125
        $showLanguageFlag = api_get_configuration_value('social_show_language_flag_in_profile');
1126
1127
        $template->assign('user', $userInfo);
1128
        $template->assign('show_language_flag', $showLanguageFlag);
1129
        $template->assign('extra_info', $extraFieldBlock);
1130
        $template->assign('social_avatar_block', $socialAvatarBlock);
1131
        $template->assign('profile_edition_link', $profileEditionLink);
1132
        //Added the link to export the vCard to the Template
1133
1134
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
1135
        if ($show_full_profile) {
1136
            $template->assign('vcard_user_link', $vCardUserLink);
1137
        }
1138
1139
        if ('1' === api_get_setting('gamification_mode')) {
1140
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
1141
                $userId,
1142
                $userInfo['status']
1143
            );
1144
1145
            $template->assign('gamification_points', $gamificationPoints);
1146
        }
1147
        $chatEnabled = api_is_global_chat_enabled();
1148
1149
        if (isset($options['chat']) && false === $options['chat']) {
1150
            $chatEnabled = '';
1151
        }
1152
1153
        $template->assign('chat_enabled', $chatEnabled);
1154
        $template->assign('user_relation', $userRelationType);
1155
        $template->assign('user_relation_type_friend', UserRelUser::USER_RELATION_TYPE_FRIEND);
1156
        $template->assign('show_full_profile', $show_full_profile);
1157
1158
        $templateName = $template->get_template('social/user_block.tpl');
1159
1160
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
1161
            $templateName = $template->get_template('social/group_block.tpl');
1162
        }
1163
1164
        $template->assign('social_avatar_block', $template->fetch($templateName));
1165
    }
1166
1167
    /**
1168
     * @param int $user_id
1169
     * @param $link_shared
1170
     * @param bool $showLinkToChat
1171
     *
1172
     * @return string
1173
     */
1174
    public static function listMyFriendsBlock($user_id, $link_shared = '', $showLinkToChat = false)
1175
    {
1176
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1177
        $friends = self::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
0 ignored issues
show
Bug introduced by
The constant USER_RELATION_TYPE_FRIEND was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1178
        $numberFriends = count($friends);
1179
        $friendHtml = '';
1180
1181
        if (!empty($numberFriends)) {
1182
            $friendHtml .= '<div class="list-group contact-list">';
1183
            $j = 1;
1184
1185
            usort(
1186
                $friends,
1187
                function ($a, $b) {
1188
                    return strcmp($b['user_info']['user_is_online_in_chat'], $a['user_info']['user_is_online_in_chat']);
1189
                }
1190
            );
1191
1192
            foreach ($friends as $friend) {
1193
                if ($j > $numberFriends) {
1194
                    break;
1195
                }
1196
                $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
1197
                $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
1198
1199
                $statusIcon = Display::return_icon('statusoffline.png', get_lang('Offline'));
1200
                $status = 0;
1201
                if (!empty($user_info_friend['user_is_online_in_chat'])) {
1202
                    $statusIcon = Display::return_icon('statusonline.png', get_lang('Online'));
1203
                    $status = 1;
1204
                }
1205
1206
                $friendAvatarMedium = UserManager::getUserPicture(
1207
                    $friend['friend_user_id'],
1208
                    USER_IMAGE_SIZE_MEDIUM
1209
                );
1210
                $friendAvatarSmall = UserManager::getUserPicture(
1211
                    $friend['friend_user_id'],
1212
                    USER_IMAGE_SIZE_SMALL
1213
                );
1214
                $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
1215
1216
                $relation = self::get_relation_between_contacts(
1217
                    $friend['friend_user_id'],
1218
                    api_get_user_id()
1219
                );
1220
1221
                if ($showLinkToChat) {
1222
                    $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
1223
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
1224
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
1225
                } else {
1226
                    $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
1227
                    $friendHtml .= '<a href="profile.php?'.'u='.$friend['friend_user_id'].$link_shared.'" class="list-group-item">';
1228
                    $friendHtml .= $friend_avatar.' <span class="username">'.$name_user.'</span>';
1229
                    $friendHtml .= '<span class="status">'.$statusIcon.'</span>';
1230
                }
1231
1232
                $friendHtml .= '</a>';
1233
1234
                $j++;
1235
            }
1236
            $friendHtml .= '</div>';
1237
        } else {
1238
            $friendHtml = Display::return_message(get_lang('No friends in your contact list'), 'warning');
1239
        }
1240
1241
        return $friendHtml;
1242
    }
1243
1244
    /**
1245
     * @return string Get the JS code necessary for social wall to load open graph from URLs.
1246
     */
1247
    public static function getScriptToGetOpenGraph()
1248
    {
1249
        return '<script>
1250
            $(function() {
1251
                $("[name=\'social_wall_new_msg_main\']").on("paste", function(e) {
1252
                    $.ajax({
1253
                        contentType: "application/x-www-form-urlencoded",
1254
                        beforeSend: function() {
1255
                            $("[name=\'wall_post_button\']").prop( "disabled", true );
1256
                            $(".panel-preview").hide();
1257
                            $(".spinner").html("'
1258
                                .'<div class=\'text-center\'>'
1259
                                .'<em class=\'fa fa-spinner fa-pulse fa-1x\'></em>'
1260
                                .'<p>'.get_lang('Loading').' '.get_lang('Preview').'</p>'
1261
                                .'</div>'
1262
                            .'");
1263
                        },
1264
                        type: "POST",
1265
                        url: "'.api_get_path(WEB_AJAX_PATH).'social.ajax.php?a=read_url_with_open_graph",
1266
                        data: "social_wall_new_msg_main=" + e.originalEvent.clipboardData.getData("text"),
1267
                        success: function(response) {
1268
                            $("[name=\'wall_post_button\']").prop("disabled", false);
1269
                            if (!response == false) {
1270
                                $(".spinner").html("");
1271
                                $(".panel-preview").show();
1272
                                $(".url_preview").html(response);
1273
                                $("[name=\'url_content\']").val(response);
1274
                                $(".url_preview img").addClass("img-responsive");
1275
                            } else {
1276
                                $(".spinner").html("");
1277
                            }
1278
                        }
1279
                    });
1280
                });
1281
            });
1282
        </script>';
1283
    }
1284
1285
    /**
1286
     * @param string $urlForm
1287
     *
1288
     * @return string
1289
     */
1290
    public static function getWallForm($urlForm)
1291
    {
1292
        $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
1293
        $form = new FormValidator(
1294
            'social_wall_main',
1295
            'post',
1296
            $urlForm.$userId,
1297
            null,
1298
            ['enctype' => 'multipart/form-data'],
1299
            FormValidator::LAYOUT_HORIZONTAL
1300
        );
1301
1302
        $socialWallPlaceholder = isset($_GET['u']) ? get_lang('Write something on your friend\'s wall') : get_lang(
1303
            'Social wallWhatAreYouThinkingAbout'
1304
        );
1305
1306
        $form->addTextarea(
1307
            'social_wall_new_msg_main',
1308
            null,
1309
            [
1310
                'placeholder' => $socialWallPlaceholder,
1311
                'cols-size' => [1, 12, 1],
1312
                'aria-label' => $socialWallPlaceholder,
1313
            ]
1314
        );
1315
        $form->addHtml('<div class="form-group">');
1316
        $form->addHtml('<div class="col-sm-6">');
1317
        $form->addFile('picture', get_lang('File upload'), ['custom' => true]);
1318
        $form->addHtml('</div>');
1319
        $form->addHtml('<div class="col-sm-6 "><div class="pull-right">');
1320
        $form->addButtonSend(
1321
            get_lang('Post'),
1322
            'wall_post_button',
1323
            false,
1324
            [
1325
                'cols-size' => [1, 10, 1],
1326
                'custom' => true,
1327
            ]
1328
        );
1329
        $form->addHtml('</div></div>');
1330
        $form->addHtml('</div>');
1331
        $form->addHidden('url_content', '');
1332
        $html = Display::panel($form->returnForm(), get_lang('Social wall'));
1333
1334
        return $html;
1335
    }
1336
1337
    /**
1338
     * @param string $message
1339
     * @param string $content
1340
     *
1341
     * @return string
1342
     */
1343
    public static function wrapPost($message, $content)
1344
    {
1345
        $class = '';
1346
        if (MESSAGE_STATUS_PROMOTED === (int) $message['msg_status']) {
1347
            $class = 'promoted_post';
1348
        }
1349
1350
        return Display::panel($content, '',
1351
            '',
1352
            'default',
1353
            '',
1354
            'post_'.$message['id'],
1355
            null,
1356
            $class
1357
        );
1358
    }
1359
1360
    /**
1361
     * Get HTML code block for user skills.
1362
     *
1363
     * @param int    $userId      The user ID
1364
     * @param string $orientation
1365
     *
1366
     * @return string
1367
     */
1368
    public static function getSkillBlock($userId, $orientation = 'horizontal')
1369
    {
1370
        if (false === SkillModel::isAllowed($userId, false)) {
1371
            return '';
1372
        }
1373
1374
        $skill = new SkillModel();
1375
        $ranking = $skill->getUserSkillRanking($userId);
1376
1377
        $template = new Template(null, false, false, false, false, false);
1378
        $template->assign('ranking', $ranking);
1379
        $template->assign('orientation', $orientation);
1380
        $template->assign('skills', $skill->getUserSkillsTable($userId, 0, 0, false)['skills']);
1381
        $template->assign('user_id', $userId);
1382
        $template->assign('show_skills_report_link', api_is_student() || api_is_student_boss() || api_is_drh());
1383
1384
        $skillBlock = $template->get_template('social/skills_block.tpl');
1385
1386
        return $template->fetch($skillBlock);
1387
    }
1388
1389
    /**
1390
     * @param int  $user_id
1391
     * @param bool $isArray
1392
     *
1393
     * @return string|array
1394
     */
1395
    public static function getExtraFieldBlock($user_id, $isArray = false)
1396
    {
1397
        $fieldVisibility = api_get_configuration_value('profile_fields_visibility');
1398
        $fieldVisibilityKeys = [];
1399
        if (isset($fieldVisibility['options'])) {
1400
            $fieldVisibility = $fieldVisibility['options'];
1401
            $fieldVisibilityKeys = array_keys($fieldVisibility);
1402
        }
1403
1404
        $t_ufo = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
1405
        $extra_user_data = UserManager::get_extra_user_data($user_id);
1406
1407
        $extra_information = '';
1408
        if (is_array($extra_user_data) && count($extra_user_data) > 0) {
1409
            $extra_information_value = '';
1410
            $extraField = new ExtraField('user');
1411
            $listType = [];
1412
            $extraFieldItem = [];
1413
            foreach ($extra_user_data as $key => $data) {
1414
                if (empty($data)) {
1415
                    continue;
1416
                }
1417
                if (in_array($key, $fieldVisibilityKeys) && false === $fieldVisibility[$key]) {
1418
                    continue;
1419
                }
1420
1421
                // Avoiding parameters
1422
                if (in_array(
1423
                    $key,
1424
                    [
1425
                        'mail_notify_invitation',
1426
                        'mail_notify_message',
1427
                        'mail_notify_group_message',
1428
                    ]
1429
                )) {
1430
                    continue;
1431
                }
1432
                // get display text, visibility and type from user_field table
1433
                $field_variable = str_replace('extra_', '', $key);
1434
1435
                $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
1436
                    $field_variable
1437
                );
1438
1439
                if (in_array($extraFieldInfo['variable'], ['skype', 'linkedin_url'])) {
1440
                    continue;
1441
                }
1442
1443
                // if is not visible skip
1444
                if (1 != $extraFieldInfo['visible_to_self']) {
1445
                    continue;
1446
                }
1447
1448
                // if is not visible to others skip also
1449
                if (1 != $extraFieldInfo['visible_to_others']) {
1450
                    continue;
1451
                }
1452
1453
                if (is_array($data)) {
1454
                    switch ($extraFieldInfo['field_type']) {
1455
                        case ExtraField::FIELD_TYPE_RADIO:
1456
                            $objEfOption = new ExtraFieldOption('user');
1457
                            $value = $data['extra_'.$extraFieldInfo['variable']];
1458
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option(
1459
                                $extraFieldInfo['id'],
1460
                                $value
1461
                            );
1462
1463
                            if ($optionInfo && isset($optionInfo[0])) {
1464
                                $optionInfo = $optionInfo[0];
1465
                                $extraFieldItem = [
1466
                                    'variable' => $extraFieldInfo['variable'],
1467
                                    'label' => ucfirst($extraFieldInfo['display_text']),
1468
                                    'value' => $optionInfo['display_text'],
1469
                                ];
1470
                            } else {
1471
                                $extraFieldItem = [
1472
                                    'variable' => $extraFieldInfo['variable'],
1473
                                    'label' => ucfirst($extraFieldInfo['display_text']),
1474
                                    'value' => implode(',', $data),
1475
                                ];
1476
                            }
1477
                            break;
1478
                        default:
1479
                            $extra_information_value .=
1480
                                '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).' '
1481
                                .' '.implode(',', $data).'</li>';
1482
                            $extraFieldItem = [
1483
                                'variable' => $extraFieldInfo['variable'],
1484
                                'label' => ucfirst($extraFieldInfo['display_text']),
1485
                                'value' => implode(',', $data),
1486
                            ];
1487
                            break;
1488
                    }
1489
                } else {
1490
                    switch ($extraFieldInfo['field_type']) {
1491
                        case ExtraField::FIELD_TYPE_RADIO:
1492
                            $objEfOption = new ExtraFieldOption('user');
1493
                            $optionInfo = $objEfOption->get_field_option_by_field_and_option($extraFieldInfo['id'], $extraFieldInfo['value']);
1494
                            break;
1495
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION_COORDINATES:
1496
                        case ExtraField::FIELD_TYPE_GEOLOCALIZATION:
1497
                            $data = explode('::', $data);
1498
                            $data = $data[0];
1499
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
1500
                            $extraFieldItem = [
1501
                                'variable' => $extraFieldInfo['variable'],
1502
                                'label' => ucfirst($extraFieldInfo['display_text']),
1503
                                'value' => $data,
1504
                            ];
1505
                            break;
1506
                        case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
1507
                            $id_options = explode('::', $data);
1508
                            $value_options = [];
1509
                            // get option display text from user_field_options table
1510
                            foreach ($id_options as $id_option) {
1511
                                $sql = "SELECT display_text
1512
                                    FROM $t_ufo
1513
                                    WHERE id = '$id_option'";
1514
                                $res_options = Database::query($sql);
1515
                                $row_options = Database::fetch_row($res_options);
1516
                                $value_options[] = $row_options[0];
1517
                            }
1518
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
1519
                                .' '.implode(' ', $value_options).'</li>';
1520
                            $extraFieldItem = [
1521
                                'variable' => $extraFieldInfo['variable'],
1522
                                'label' => ucfirst($extraFieldInfo['display_text']),
1523
                                'value' => $value_options,
1524
                            ];
1525
                            break;
1526
                        case ExtraField::FIELD_TYPE_TAG:
1527
                            $user_tags = UserManager::get_user_tags($user_id, $extraFieldInfo['id']);
1528
1529
                            $tag_tmp = '';
1530
                            foreach ($user_tags as $tags) {
1531
                                $tag_tmp .= '<a class="label label_tag"'
1532
                                    .' href="'.api_get_path(WEB_PATH).'main/social/search.php?q='.$tags['tag'].'">'
1533
                                    .$tags['tag']
1534
                                    .'</a>';
1535
                            }
1536
                            if (is_array($user_tags) && count($user_tags) > 0) {
1537
                                $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '
1538
                                    .' '.$tag_tmp.'</li>';
1539
                            }
1540
                            $extraFieldItem = [
1541
                                'variable' => $extraFieldInfo['variable'],
1542
                                'label' => ucfirst($extraFieldInfo['display_text']),
1543
                                'value' => $tag_tmp,
1544
                            ];
1545
                            break;
1546
                        case ExtraField::FIELD_TYPE_SOCIAL_PROFILE:
1547
                            $icon_path = UserManager::get_favicon_from_url($data);
1548
                            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...
1549
                                break;
1550
                            }
1551
                            $bottom = '0.2';
1552
                            //quick hack for hi5
1553
                            $domain = parse_url($icon_path, PHP_URL_HOST);
1554
                            if ('www.hi5.com' == $domain || 'hi5.com' == $domain) {
1555
                                $bottom = '-0.8';
1556
                            }
1557
                            $data = '<a href="'.$data.'">'
1558
                                .'<img src="'.$icon_path.'" alt="icon"'
1559
                                .' style="margin-right:0.5em;margin-bottom:'.$bottom.'em;" />'
1560
                                .$extraFieldInfo['display_text']
1561
                                .'</a>';
1562
                            $extra_information_value .= '<li class="list-group-item">'.$data.'</li>';
1563
                            $extraFieldItem = [
1564
                                'variable' => $extraFieldInfo['variable'],
1565
                                'label' => ucfirst($extraFieldInfo['display_text']),
1566
                                'value' => $data,
1567
                            ];
1568
                            break;
1569
                        case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
1570
                            $parsedData = explode('::', $data);
1571
1572
                            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...
1573
                                break;
1574
                            }
1575
1576
                            $objEfOption = new ExtraFieldOption('user');
1577
                            $optionInfo = $objEfOption->get($parsedData[0]);
1578
1579
                            $extra_information_value .= '<li class="list-group-item">'
1580
                                .$optionInfo['display_text'].': '
1581
                                .$parsedData[1].'</li>';
1582
                            $extraFieldItem = [
1583
                                'variable' => $extraFieldInfo['variable'],
1584
                                'label' => ucfirst($extraFieldInfo['display_text']),
1585
                                'value' => $parsedData[1],
1586
                            ];
1587
                            break;
1588
                        case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
1589
                            $optionIds = explode(';', $data);
1590
                            $optionValues = [];
1591
1592
                            foreach ($optionIds as $optionId) {
1593
                                $objEfOption = new ExtraFieldOption('user');
1594
                                $optionInfo = $objEfOption->get($optionId);
1595
1596
                                $optionValues[] = $optionInfo['display_text'];
1597
                            }
1598
                            $extra_information_value .= '<li class="list-group-item">'
1599
                                .ucfirst($extraFieldInfo['display_text']).': '
1600
                                .implode(' ', $optionValues).'</li>';
1601
                            $extraFieldItem = [
1602
                                'variable' => $extraFieldInfo['variable'],
1603
                                'label' => ucfirst($extraFieldInfo['display_text']),
1604
                                'value' => implode(' ', $optionValues),
1605
                            ];
1606
                            break;
1607
                        default:
1608
                            // Ofaj
1609
                            // Converts "Date of birth" into "age"
1610
                            if ('terms_datedenaissance' === $key) {
1611
                                $dataArray = date_to_str_ago($data, 'UTC', true);
1612
                                $dataToString = isset($dataArray['years']) && !empty($dataArray['years']) ? $dataArray['years'] : 0;
1613
                                if (!empty($dataToString)) {
1614
                                    $data = $dataToString;
1615
                                    $extraFieldInfo['display_text'] = get_lang('Age');
1616
                                }
1617
                            }
1618
1619
                            $extra_information_value .= '<li class="list-group-item">'.ucfirst($extraFieldInfo['display_text']).': '.$data.'</li>';
1620
                            $extraFieldItem = [
1621
                                'variable' => $extraFieldInfo['variable'],
1622
                                'label' => ucfirst($extraFieldInfo['display_text']),
1623
                                'value' => $data,
1624
                            ];
1625
                            break;
1626
                    }
1627
                }
1628
1629
                $listType[] = $extraFieldItem;
1630
            }
1631
1632
            if ($isArray) {
1633
                return $listType;
1634
            } else {
1635
                // if there are information to show
1636
                if (!empty($extra_information_value)) {
1637
                    $extra_information_value = '<ul class="list-group">'.$extra_information_value.'</ul>';
1638
                    $extra_information .= Display::panelCollapse(
1639
                        get_lang('Extra information'),
1640
                        $extra_information_value,
1641
                        'sn-extra-information',
1642
                        null,
1643
                        'sn-extra-accordion',
1644
                        'sn-extra-collapse'
1645
                    );
1646
                }
1647
            }
1648
        }
1649
1650
        return $extra_information;
1651
    }
1652
1653
    /**
1654
     * @param int   $countPost
1655
     * @param array $htmlHeadXtra
1656
     */
1657
    public static function getScrollJs($countPost, &$htmlHeadXtra)
1658
    {
1659
        // $ajax_url = api_get_path(WEB_AJAX_PATH).'message.ajax.php';
1660
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
1661
        $javascriptDir = api_get_path(LIBRARY_PATH).'javascript/';
1662
        $locale = api_get_language_isocode();
1663
1664
        // Add Jquery scroll pagination plugin
1665
        //$htmlHeadXtra[] = api_get_js('jscroll/jquery.jscroll.js');
1666
        // Add Jquery Time ago plugin
1667
        //$htmlHeadXtra[] = api_get_asset('jquery-timeago/jquery.timeago.js');
1668
        $timeAgoLocaleDir = $javascriptDir.'jquery-timeago/locales/jquery.timeago.'.$locale.'.js';
1669
        if (file_exists($timeAgoLocaleDir)) {
1670
            $htmlHeadXtra[] = api_get_js('jquery-timeago/locales/jquery.timeago.'.$locale.'.js');
1671
        }
1672
1673
        if ($countPost > self::DEFAULT_WALL_POSTS) {
1674
            $htmlHeadXtra[] = '<script>
1675
            $(function() {
1676
                var container = $("#wallMessages");
1677
                container.jscroll({
1678
                    loadingHtml: "<div class=\"well_border\">'.get_lang('Loading').' </div>",
1679
                    nextSelector: "a.nextPage:last",
1680
                    contentSelector: "",
1681
                    callback: timeAgo
1682
                });
1683
            });
1684
            </script>';
1685
        }
1686
1687
        $htmlHeadXtra[] = '<script>
1688
            function deleteMessage(id)
1689
            {
1690
                $.ajax({
1691
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1692
                    success: function (result) {
1693
                        if (result) {
1694
                            $("#message_" + id).parent().parent().parent().parent().html(result);
1695
                        }
1696
                    }
1697
                });
1698
            }
1699
1700
            function deleteComment(id)
1701
            {
1702
                $.ajax({
1703
                    url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1704
                    success: function (result) {
1705
                        if (result) {
1706
                            $("#message_" + id).parent().parent().parent().html(result);
1707
                        }
1708
                    }
1709
                });
1710
            }
1711
1712
            function submitComment(messageId)
1713
            {
1714
                var data = $("#form_comment_"+messageId).serializeArray();
1715
                $.ajax({
1716
                    type : "POST",
1717
                    url: "'.$socialAjaxUrl.'?a=send_comment" + "&id=" + messageId,
1718
                    data: data,
1719
                    success: function (result) {
1720
                        if (result) {
1721
                            $("#post_" + messageId + " textarea").val("");
1722
                            $("#post_" + messageId + " .sub-mediapost").prepend(result);
1723
                            $("#post_" + messageId + " .sub-mediapost").append(
1724
                                $(\'<div id=result_\' + messageId +\'>'.addslashes(get_lang('Saved.')).'</div>\')
1725
                            );
1726
1727
                            $("#result_" + messageId + "").fadeIn("fast", function() {
1728
                                $("#result_" + messageId + "").delay(1000).fadeOut("fast", function() {
1729
                                    $(this).remove();
1730
                                });
1731
                            });
1732
                        }
1733
                    }
1734
                });
1735
            }
1736
1737
            $(function() {
1738
                timeAgo();
1739
1740
                /*$(".delete_message").on("click", function() {
1741
                    var id = $(this).attr("id");
1742
                    id = id.split("_")[1];
1743
                    $.ajax({
1744
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1745
                        success: function (result) {
1746
                            if (result) {
1747
                                $("#message_" + id).parent().parent().parent().parent().html(result);
1748
                            }
1749
                        }
1750
                    });
1751
                });
1752
1753
1754
                $(".delete_comment").on("click", function() {
1755
                    var id = $(this).attr("id");
1756
                    id = id.split("_")[1];
1757
                    $.ajax({
1758
                        url: "'.$socialAjaxUrl.'?a=delete_message" + "&id=" + id,
1759
                        success: function (result) {
1760
                            if (result) {
1761
                                $("#message_" + id).parent().parent().parent().html(result);
1762
                            }
1763
                        }
1764
                    });
1765
                });
1766
                */
1767
            });
1768
1769
            function timeAgo() {
1770
                $(".timeago").timeago();
1771
            }
1772
            </script>';
1773
    }
1774
1775
    /**
1776
     * @param int $userId
1777
     * @param int $countPost
1778
     *
1779
     * @return string
1780
     */
1781
    public static function getAutoExtendLink($userId, $countPost)
1782
    {
1783
        $userId = (int) $userId;
1784
        $socialAjaxUrl = api_get_path(WEB_AJAX_PATH).'social.ajax.php';
1785
        $socialAutoExtendLink = '';
1786
        if ($countPost > self::DEFAULT_WALL_POSTS) {
1787
            $socialAutoExtendLink = Display::url(
1788
                get_lang('See more'),
1789
                $socialAjaxUrl.'?u='.$userId.'&a=list_wall_message&start='.
1790
                self::DEFAULT_WALL_POSTS.'&length='.self::DEFAULT_SCROLL_NEW_POST,
1791
                [
1792
                    'class' => 'nextPage next',
1793
                ]
1794
            );
1795
        }
1796
1797
        return $socialAutoExtendLink;
1798
    }
1799
1800
    /**
1801
     * @param int $userId
1802
     *
1803
     * @return array
1804
     */
1805
    public static function getThreadList($userId)
1806
    {
1807
        return [];
1808
        $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...
1809
1810
        $threads = [];
1811
        if (!empty($forumCourseId)) {
1812
            $courseInfo = api_get_course_info_by_id($forumCourseId);
1813
            /*getNotificationsPerUser($userId, true, $forumCourseId);
1814
            $notification = Session::read('forum_notification');
1815
            Session::erase('forum_notification');*/
1816
1817
            $threadUrlBase = api_get_path(WEB_CODE_PATH).'forum/viewthread.php?'.http_build_query([
1818
                'cid' => $courseInfo['real_id'],
1819
            ]).'&';
1820
            if (isset($notification['thread']) && !empty($notification['thread'])) {
1821
                $threadList = array_filter(array_unique($notification['thread']));
1822
                $repo = Container::getForumThreadRepository();
1823
                foreach ($threadList as $threadId) {
1824
                    /** @var CForumThread $thread */
1825
                    $thread = $repo->find($threadId);
1826
                    if ($thread) {
1827
                        $threadUrl = $threadUrlBase.http_build_query([
1828
                            'forum' => $thread->getForum()->getIid(),
1829
                            'thread' => $thread->getIid(),
1830
                        ]);
1831
                        $threads[] = [
1832
                            'id' => $threadId,
1833
                            'url' => Display::url(
1834
                                $thread->getThreadTitle(),
1835
                                $threadUrl
1836
                            ),
1837
                            'name' => Display::url(
1838
                                $thread->getThreadTitle(),
1839
                                $threadUrl
1840
                            ),
1841
                            'description' => '',
1842
                        ];
1843
                    }
1844
                }
1845
            }
1846
        }
1847
1848
        return $threads;
1849
    }
1850
1851
    /**
1852
     * @param int $userId
1853
     *
1854
     * @return string
1855
     */
1856
    public static function getGroupBlock($userId)
1857
    {
1858
        $threadList = self::getThreadList($userId);
1859
        $userGroup = new UserGroupModel();
1860
1861
        $forumCourseId = api_get_configuration_value('global_forums_course_id');
1862
        $courseInfo = null;
1863
        if (!empty($forumCourseId)) {
1864
            $courseInfo = api_get_course_info_by_id($forumCourseId);
1865
        }
1866
1867
        $social_group_block = '';
1868
        if (!empty($courseInfo)) {
1869
            if (!empty($threadList)) {
1870
                $social_group_block .= '<div class="list-group">';
1871
                foreach ($threadList as $group) {
1872
                    $social_group_block .= ' <li class="list-group-item">';
1873
                    $social_group_block .= $group['name'];
1874
                    $social_group_block .= '</li>';
1875
                }
1876
                $social_group_block .= '</div>';
1877
            }
1878
1879
            $social_group_block .= Display::url(
1880
                get_lang('See all communities'),
1881
                api_get_path(WEB_CODE_PATH).'forum/index.php?cid='.$courseInfo['real_id']
1882
            );
1883
1884
            if (!empty($social_group_block)) {
1885
                $social_group_block = Display::panelCollapse(
1886
                    get_lang('My communities'),
1887
                    $social_group_block,
1888
                    'sm-groups',
1889
                    null,
1890
                    'grups-acordion',
1891
                    'groups-collapse'
1892
                );
1893
            }
1894
        } else {
1895
            // Load my groups
1896
            $results = $userGroup->get_groups_by_user(
1897
                $userId,
1898
                [
1899
                    GROUP_USER_PERMISSION_ADMIN,
1900
                    GROUP_USER_PERMISSION_READER,
1901
                    GROUP_USER_PERMISSION_MODERATOR,
1902
                    GROUP_USER_PERMISSION_HRM,
1903
                ]
1904
            );
1905
1906
            $myGroups = [];
1907
            if (!empty($results)) {
1908
                foreach ($results as $result) {
1909
                    $id = $result['id'];
1910
                    $result['description'] = Security::remove_XSS($result['description'], STUDENT, true);
1911
                    $result['name'] = Security::remove_XSS($result['name'], STUDENT, true);
1912
1913
                    $group_url = "group_view.php?id=$id";
1914
1915
                    $link = Display::url(
1916
                        api_ucwords(cut($result['name'], 40, true)),
1917
                        $group_url
1918
                    );
1919
1920
                    $result['name'] = $link;
1921
1922
                    $picture = $userGroup->get_picture_group(
1923
                        $id,
1924
                        $result['picture'],
1925
                        null,
1926
                        GROUP_IMAGE_SIZE_BIG
1927
                    );
1928
1929
                    $result['picture'] = '<img class="img-responsive" src="'.$picture.'" />';
1930
                    $group_actions = '<div class="group-more"><a class="btn btn-default" href="groups.php?#tab_browse-2">'.
1931
                        get_lang('See more').'</a></div>';
1932
                    $group_info = '<div class="description"><p>'.cut($result['description'], 120, true)."</p></div>";
1933
                    $myGroups[] = [
1934
                        'url' => Display::url(
1935
                            $result['picture'],
1936
                            $group_url
1937
                        ),
1938
                        'name' => $result['name'],
1939
                        'description' => $group_info.$group_actions,
1940
                    ];
1941
                }
1942
1943
                $social_group_block .= '<div class="list-group">';
1944
                foreach ($myGroups as $group) {
1945
                    $social_group_block .= ' <li class="list-group-item">';
1946
                    $social_group_block .= $group['name'];
1947
                    $social_group_block .= '</li>';
1948
                }
1949
                $social_group_block .= '</div>';
1950
1951
                $form = new FormValidator(
1952
                    'find_groups_form',
1953
                    'get',
1954
                    api_get_path(WEB_CODE_PATH).'social/search.php?search_type=2',
1955
                    null,
1956
                    null,
1957
                    FormValidator::LAYOUT_BOX_NO_LABEL
1958
                );
1959
                $form->addHidden('search_type', 2);
1960
1961
                $form->addText(
1962
                    'q',
1963
                    get_lang('Search'),
1964
                    false,
1965
                    [
1966
                        'aria-label' => get_lang('Search'),
1967
                        'custom' => true,
1968
                        'placeholder' => get_lang('Search'),
1969
                    ]
1970
                );
1971
1972
                $social_group_block .= $form->returnForm();
1973
1974
                if (!empty($social_group_block)) {
1975
                    $social_group_block = Display::panelCollapse(
1976
                        get_lang('My groups'),
1977
                        $social_group_block,
1978
                        'sm-groups',
1979
                        null,
1980
                        'grups-acordion',
1981
                        'groups-collapse'
1982
                    );
1983
                }
1984
            }
1985
        }
1986
1987
        return $social_group_block;
1988
    }
1989
1990
    /**
1991
     * @param string $selected
1992
     *
1993
     * @return string
1994
     */
1995
    public static function getHomeProfileTabs($selected = 'home')
1996
    {
1997
        $headers = [
1998
            [
1999
                'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
2000
                'content' => get_lang('Profile'),
2001
            ],
2002
        ];
2003
        $allowJustification = 'true' === api_get_plugin_setting('justification', 'tool_enable');
2004
        if ($allowJustification) {
2005
            $plugin = Justification::create();
2006
            $headers[] = [
2007
                'url' => api_get_path(WEB_CODE_PATH).'auth/justification.php',
2008
                'content' => $plugin->get_lang('Justification'),
2009
            ];
2010
        }
2011
2012
        $allowPauseTraining = 'true' === api_get_plugin_setting('pausetraining', 'tool_enable');
2013
        $allowEdit = 'true' === api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation');
2014
        if ($allowPauseTraining && $allowEdit) {
2015
            $plugin = PauseTraining::create();
2016
            $headers[] = [
2017
                'url' => api_get_path(WEB_CODE_PATH).'auth/pausetraining.php',
2018
                'content' => $plugin->get_lang('PauseTraining'),
2019
            ];
2020
        }
2021
2022
        $selectedItem = 1;
2023
        foreach ($headers as $header) {
2024
            $info = pathinfo($header['url']);
2025
            if ($selected === $info['filename']) {
2026
                break;
2027
            }
2028
            $selectedItem++;
2029
        }
2030
2031
        $tabs = '';
2032
        if (count($headers) > 1) {
2033
            $tabs = Display::tabsOnlyLink($headers, $selectedItem);
2034
        }
2035
2036
        return $tabs;
2037
    }
2038
2039
    /**
2040
     * Returns the formatted header message post.
2041
     *
2042
     * @param int   $authorInfo
2043
     * @param int   $receiverInfo
2044
     * @param array $message      Message data
2045
     *
2046
     * @return string $html       The formatted header message post
2047
     */
2048
    private static function headerMessagePost($authorInfo, $receiverInfo, $message)
2049
    {
2050
        $currentUserId = api_get_user_id();
2051
        $authorId = (int) $authorInfo['user_id'];
2052
        $receiverId = (int) $receiverInfo['user_id'];
2053
        $iconStatus = $authorInfo['icon_status'];
2054
2055
        $date = Display::dateToStringAgoAndLongDate($message['send_date']);
2056
        $avatarAuthor = $authorInfo['avatar'];
2057
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
2058
        $nameCompleteAuthor = $authorInfo['complete_name'];
2059
2060
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
2061
        $nameCompleteReceiver = $receiverInfo['complete_name'];
2062
2063
        $htmlReceiver = '';
2064
        if ($authorId !== $receiverId) {
2065
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">'.$nameCompleteReceiver.'</a> ';
2066
        }
2067
2068
        if (!empty($message['group_info'])) {
2069
            $htmlReceiver = ' > <a href="'.$message['group_info']['url'].'">'.$message['group_info']['name'].'</a> ';
2070
        }
2071
        $canEdit = ($currentUserId == $authorInfo['user_id'] || $currentUserId == $receiverInfo['user_id']) && empty($message['group_info']);
2072
2073
        if (!empty($message['thread_id'])) {
2074
            $htmlReceiver = ' > <a href="'.$message['thread_url'].'">'.$message['forum_title'].'</a> ';
2075
            $canEdit = false;
2076
        }
2077
2078
        $postAttachment = self::getPostAttachment($message);
2079
2080
        $html = '<div class="top-mediapost" >';
2081
        $html .= '<div class="pull-right btn-group btn-group-sm">';
2082
2083
        $html .= MessageManager::getLikesButton(
2084
            $message['id'],
2085
            $currentUserId,
2086
            !empty($message['group_info']['id']) ? (int) $message['group_info']['id'] : 0
2087
        );
2088
2089
        if ($canEdit) {
2090
            $htmlDelete = Display::url(
2091
                Display::returnFontAwesomeIcon('trash', '', true),
2092
                'javascript:void(0)',
2093
                [
2094
                    'id' => 'message_'.$message['id'],
2095
                    'title' => get_lang('Delete comment'),
2096
                    'onclick' => 'deleteMessage('.$message['id'].')',
2097
                    'class' => 'btn btn-default',
2098
                ]
2099
            );
2100
2101
            $html .= $htmlDelete;
2102
        }
2103
        $html .= '</div>';
2104
2105
        $html .= '<div class="user-image" >';
2106
        $html .= '<a href="'.$urlAuthor.'">
2107
                    <img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
2108
        $html .= '</div>';
2109
        $html .= '<div class="user-data">';
2110
        $html .= $iconStatus;
2111
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
2112
        $html .= '<div class="post-date">'.$date.'</div>';
2113
        $html .= '</div>';
2114
        $html .= '<div class="msg-content">';
2115
        if (!empty($postAttachment)) {
2116
            $html .= '<div class="post-attachment thumbnail">';
2117
            $html .= $postAttachment;
2118
            $html .= '</div>';
2119
        }
2120
        $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

2120
        $html .= '<div>'./** @scrutinizer ignore-type */ Security::remove_XSS($message['content']).'</div>';
Loading history...
2121
        $html .= '</div>';
2122
        $html .= '</div>'; // end mediaPost
2123
2124
        // Popularity post functionality
2125
        $html .= '<div class="popularity-mediapost"></div>';
2126
2127
        return $html;
2128
    }
2129
}
2130