Passed
Pull Request — 1.10.x (#986)
by
unknown
182:31 queued 134:48
created

SocialManager::readContentWithOpenGraph()   C

Complexity

Conditions 7
Paths 25

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 28
rs 6.7272
cc 7
eloc 20
nc 25
nop 1
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class SocialManager
6
 *
7
 * This class provides methods for the social network management.
8
 * Include/require it in your code to use its features.
9
 *
10
 * @package chamilo.social
11
 */
12
class SocialManager extends UserManager
13
{
14
    /**
15
     * Constructor
16
     */
17
    public function __construct()
18
    {
19
20
    }
21
22
    /**
23
     * Allow to see contacts list
24
     * @author isaac flores paz
25
     * @return array
26
     */
27 View Code Duplication
    public static function show_list_type_friends()
28
    {
29
        $friend_relation_list = array();
30
        $tbl_my_friend_relation_type = Database :: get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
31
        $sql = 'SELECT id,title FROM '.$tbl_my_friend_relation_type.'
32
                WHERE id<>6 ORDER BY id ASC';
33
        $result = Database::query($sql);
34
        while ($row = Database::fetch_array($result, 'ASSOC')) {
35
            $friend_relation_list[] = $row;
36
        }
37
        $count_list = count($friend_relation_list);
38
        if ($count_list == 0) {
39
            $friend_relation_list[] = get_lang('Unknown');
40
        } else {
41
            return $friend_relation_list;
42
        }
43
    }
44
45
    /**
46
     * Get relation type contact by name
47
     * @param string names of the kind of relation
48
     * @return int
49
     * @author isaac flores paz
50
     */
51
    public static function get_relation_type_by_name($relation_type_name)
52
    {
53
        $list_type_friend = self::show_list_type_friends();
54
        foreach ($list_type_friend as $value_type_friend) {
0 ignored issues
show
Bug introduced by
The expression $list_type_friend of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
55
            if (strtolower($value_type_friend['title']) == $relation_type_name) {
56
                return $value_type_friend['id'];
57
            }
58
        }
59
    }
60
61
    /**
62
     * Get the kind of relation between contacts
63
     * @param int user id
64
     * @param int user friend id
65
     * @param string
66
     * @author isaac flores paz
67
     */
68
    public static function get_relation_between_contacts($user_id, $user_friend)
69
    {
70
        $tbl_my_friend_relation_type = Database :: get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
71
        $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
72
        $sql = 'SELECT rt.id as id FROM '.$tbl_my_friend_relation_type.' rt
73
                WHERE rt.id = (
74
                    SELECT uf.relation_type FROM '.$tbl_my_friend.' uf
75
                    WHERE
76
                        user_id='.((int) $user_id).' AND
77
                        friend_user_id='.((int) $user_friend).' AND
78
                        uf.relation_type <> '.USER_RELATION_TYPE_RRHH.'
79
                    LIMIT 1
80
                )';
81
        $res = Database::query($sql);
82
        if (Database::num_rows($res) > 0) {
83
            $row = Database::fetch_array($res, 'ASSOC');
84
85
            return $row['id'];
86
        } else {
87
            return USER_UNKNOW;
88
        }
89
    }
90
91
    /**
92
     * Gets friends id list
93
     * @param int  user id
94
     * @param int group id
95
     * @param string name to search
96
     * @param bool true will load firstname, lastname, and image name
97
     * @return array
98
     * @author Julio Montoya <[email protected]> Cleaning code, function renamed, $load_extra_info option added
99
     * @author isaac flores paz
100
     */
101
    public static function get_friends($user_id, $id_group = null, $search_name = null, $load_extra_info = true)
102
    {
103
        $list_ids_friends = array();
104
        $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
105
        $tbl_my_user = Database :: get_main_table(TABLE_MAIN_USER);
106
        $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
107
                WHERE
108
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
109
                    friend_user_id<>'.((int) $user_id).' AND
110
                    user_id='.((int) $user_id);
111
        if (isset($id_group) && $id_group > 0) {
112
            $sql.=' AND relation_type='.$id_group;
113
        }
114
        if (isset($search_name)) {
115
            $search_name = trim($search_name);
116
            $search_name = str_replace(' ', '', $search_name);
117
            $sql.=' AND friend_user_id IN (
118
                SELECT user_id FROM '.$tbl_my_user.'
119
                WHERE
120
                    firstName LIKE "%'.Database::escape_string($search_name).'%" OR
121
                    lastName LIKE "%'.Database::escape_string($search_name).'%" OR
122
                    '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
123
                ) ';
124
        }
125
126
        $res = Database::query($sql);
127
        while ($row = Database::fetch_array($res, 'ASSOC')) {
128
            if ($load_extra_info) {
129
                $my_user_info = api_get_user_info($row['friend_user_id']);
130
                $list_ids_friends[] = array(
131
                    'friend_user_id' => $row['friend_user_id'],
132
                    'firstName' => $my_user_info['firstName'],
133
                    'lastName' => $my_user_info['lastName'],
134
                    'username' => $my_user_info['username'],
135
                    'image' => $my_user_info['avatar']
136
                );
137
            } else {
138
                $list_ids_friends[] = $row;
139
            }
140
        }
141
142
        return $list_ids_friends;
143
    }
144
145
    /**
146
     * get web path of user invitate
147
     * @author isaac flores paz
148
     * @author Julio Montoya setting variable array
149
     * @param int user id
150
     *
151
     * @return array
152
     */
153
    public static function get_list_web_path_user_invitation_by_user_id($user_id)
154
    {
155
        $list_ids = self::get_list_invitation_of_friends_by_user_id($user_id);
156
        $list = array();
157
        foreach ($list_ids as $values_ids) {
158
            $list[] = UserManager::get_user_picture_path_by_id(
159
                $values_ids['user_sender_id'],
160
                'web'
161
            );
162
        }
163
164
        return $list;
165
    }
166
167
    /**
168
     * Sends an invitation to contacts
169
     * @param int user id
170
     * @param int user friend id
171
     * @param string title of the message
172
     * @param string content of the message
173
     * @return boolean
174
     * @author isaac flores paz
175
     * @author Julio Montoya <[email protected]> Cleaning code
176
     */
177
    public static function send_invitation_friend($user_id, $friend_id, $message_title, $message_content)
178
    {
179
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
180
        $user_id = intval($user_id);
181
        $friend_id = intval($friend_id);
182
183
        //Just in case we replace the and \n and \n\r while saving in the DB
184
        $message_content = str_replace(array("\n", "\n\r"), '<br />', $message_content);
185
186
        $clean_message_content = Database::escape_string($message_content);
187
188
        $now = api_get_utc_datetime();
189
190
        $sql = 'SELECT COUNT(*) AS count FROM '.$tbl_message.'
191
                WHERE
192
                    user_sender_id='.$user_id.' AND
193
                    user_receiver_id='.$friend_id.' AND
194
                    msg_status IN(5,6,7);
195
                ';
196
        $res_exist = Database::query($sql);
197
        $row_exist = Database::fetch_array($res_exist, 'ASSOC');
198
199
        if ($row_exist['count'] == 0) {
200
201
            $params = [
202
                'user_sender_id' => $user_id,
203
                'user_receiver_id' => $friend_id,
204
                'msg_status' => MESSAGE_STATUS_INVITATION_PENDING,
205
                'send_date' => $now,
206
                'title' => $message_title,
207
                'content'  => $message_content,
208
            ];
209
            Database::insert($tbl_message, $params);
210
211
            $sender_info = api_get_user_info($user_id);
212
            $notification = new Notification();
213
            $notification->save_notification(
214
                Notification::NOTIFICATION_TYPE_INVITATION,
215
                array($friend_id),
216
                $message_title,
217
                $message_content,
218
                $sender_info
0 ignored issues
show
Security Bug introduced by
It seems like $sender_info defined by api_get_user_info($user_id) on line 211 can also be of type false; however, Notification::save_notification() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
219
            );
220
221
            return true;
222
        } else {
223
            // invitation already exist
224
            $sql = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
225
                    WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7';
226
            $res_if_exist = Database::query($sql);
227
            $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
228
            if ($row_if_exist['count'] == 1) {
229
                $sql = 'UPDATE '.$tbl_message.' SET
230
                        msg_status=5, content = "'.$clean_message_content.'"
231
                        WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7 ';
232
                Database::query($sql);
233
                return true;
234
            } else {
235
                return false;
236
            }
237
        }
238
    }
239
240
    /**
241
     * Get number messages of the inbox
242
     * @author isaac flores paz
243
     * @param int user receiver id
244
     * @return int
245
     */
246
    public static function get_message_number_invitation_by_user_id($user_receiver_id)
247
    {
248
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
249
        $sql = 'SELECT COUNT(*) as count_message_in_box FROM '.$tbl_message.'
250
                WHERE
251
                    user_receiver_id='.intval($user_receiver_id).' AND
252
                    msg_status='.MESSAGE_STATUS_INVITATION_PENDING;
253
        $res = Database::query($sql);
254
        $row = Database::fetch_array($res, 'ASSOC');
255
256
        return $row['count_message_in_box'];
257
    }
258
259
    /**
260
     * Get invitation list received by user
261
     * @author isaac flores paz
262
     * @param int user id
263
     * @return array
264
     */
265 View Code Duplication
    public static function get_list_invitation_of_friends_by_user_id($user_id)
266
    {
267
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
268
        $sql = 'SELECT user_sender_id, send_date, title, content
269
                FROM '.$tbl_message.'
270
                WHERE
271
                    user_receiver_id = '.intval($user_id).' AND
272
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
273
        $res = Database::query($sql);
274
        $list_friend_invitation = array();
275
        while ($row = Database::fetch_array($res, 'ASSOC')) {
276
            $list_friend_invitation[] = $row;
277
        }
278
279
        return $list_friend_invitation;
280
    }
281
282
    /**
283
     * Get invitation list sent by user
284
     * @author Julio Montoya <[email protected]>
285
     * @param int user id
286
     * @return array()
0 ignored issues
show
Documentation introduced by
The doc-type array() could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
287
     */
288 View Code Duplication
    public static function get_list_invitation_sent_by_user_id($user_id)
289
    {
290
        $list_friend_invitation = array();
291
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
292
        $sql = 'SELECT user_receiver_id, send_date,title,content
293
                FROM '.$tbl_message.'
294
                WHERE
295
                    user_sender_id = '.intval($user_id).' AND
296
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
297
        $res = Database::query($sql);
298
        while ($row = Database::fetch_array($res, 'ASSOC')) {
299
            $list_friend_invitation[$row['user_receiver_id']] = $row;
300
        }
301
302
        return $list_friend_invitation;
303
    }
304
305
    /**
306
     * Accepts invitation
307
     * @param int $user_send_id
308
     * @param int $user_receiver_id
309
     * @author isaac flores paz
310
     * @author Julio Montoya <[email protected]> Cleaning code
311
     */
312
    public static function invitation_accepted($user_send_id, $user_receiver_id)
313
    {
314
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
315
        $sql = "UPDATE $tbl_message
316
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
317
                WHERE
318
                    user_sender_id = ".((int) $user_send_id)." AND
319
                    user_receiver_id=".((int) $user_receiver_id)." AND
320
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
321
        Database::query($sql);
322
    }
323
324
    /**
325
     * Denies invitation
326
     * @param int user sender id
327
     * @param int user receiver id
328
     * @author isaac flores paz
329
     * @author Julio Montoya <[email protected]> Cleaning code
330
     */
331
    public static function invitation_denied($user_send_id, $user_receiver_id)
332
    {
333
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
334
        $sql = 'DELETE FROM '.$tbl_message.'
335
                WHERE
336
                    user_sender_id =  '.((int) $user_send_id).' AND
337
                    user_receiver_id='.((int) $user_receiver_id).' AND
338
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
339
        Database::query($sql);
340
    }
341
342
    /**
343
     * allow attach to group
344
     * @author isaac flores paz
345
     * @param int user to qualify
346
     * @param int kind of rating
347
     * @return void()
0 ignored issues
show
Documentation introduced by
The doc-type void() could not be parsed: Expected "|" or "end of type", but got "(" at position 4. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
348
     */
349 View Code Duplication
    public static function qualify_friend($id_friend_qualify, $type_qualify)
350
    {
351
        $tbl_user_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
352
        $user_id = api_get_user_id();
353
        $sql = 'UPDATE '.$tbl_user_friend.' SET relation_type='.((int) $type_qualify).'
354
                WHERE user_id = '.((int) $user_id).' AND friend_user_id='.(int) $id_friend_qualify;
355
        Database::query($sql);
356
    }
357
358
    /**
359
     * Sends invitations to friends
360
     * @author Isaac Flores Paz <[email protected]>
361
     * @author Julio Montoya <[email protected]> Cleaning code
362
     * @param void
363
     * @return string message invitation
364
     */
365
    public static function send_invitation_friend_user($userfriend_id, $subject_message = '', $content_message = '')
366
    {
367
        global $charset;
368
369
        $user_info = api_get_user_info($userfriend_id);
370
        $succes = get_lang('MessageSentTo');
371
        $succes.= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
372
373
        if (isset($subject_message) && isset($content_message) && isset($userfriend_id)) {
374
            $send_message = MessageManager::send_message($userfriend_id, $subject_message, $content_message);
375
376 View Code Duplication
            if ($send_message) {
377
                Display::addFlash(
378
                    Display::display_confirmation_message($succes, true, true)
379
                );
380
            } else {
381
                Display::addFlash(
382
                    Display::display_error_message(get_lang('ErrorSendingMessage'), true, true)
383
                );
384
            }
385
            return false;
386
        } elseif (isset($userfriend_id) && !isset($subject_message)) {
387
            $count_is_true = false;
388
            if (isset($userfriend_id) && $userfriend_id > 0) {
389
                $message_title = get_lang('Invitation');
390
                $count_is_true = self::send_invitation_friend(api_get_user_id(), $userfriend_id, $message_title, $content_message);
391
392 View Code Duplication
                if ($count_is_true) {
393
                    Display::addFlash(
394
                        Display::display_confirmation_message(
395
                            api_htmlentities(get_lang('InvitationHasBeenSent'), ENT_QUOTES, $charset),
396
                            false,
397
                            true
398
                        )
399
                    );
400
                } else {
401
                    Display::addFlash(
402
                        Display::display_warning_message(
403
                            api_htmlentities(get_lang('YouAlreadySentAnInvitation'), ENT_QUOTES, $charset),
404
                            false,
405
                            true
406
                        )
407
                    );
408
                }
409
            }
410
        }
411
    }
412
413
    /**
414
     * Get user's feeds
415
     * @param   int User ID
416
     * @param   int Limit of posts per feed
417
     * @return  string  HTML section with all feeds included
418
     * @author  Yannick Warnier
419
     * @since   Dokeos 1.8.6.1
420
     */
421
    public static function get_user_feeds($user, $limit = 5)
422
    {
423
        if (!function_exists('fetch_rss')) {
424
            return '';
425
        }
426
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
427
        if (empty($feed)) {
428
            return '';
429
        }
430
        $feeds = explode(';', $feed['rssfeeds']);
431
        if (count($feeds) == 0) {
432
            return '';
433
        }
434
        $res = '';
435
        foreach ($feeds as $url) {
436
            if (empty($url)) {
437
                continue;
438
            }
439
            $rss = @fetch_rss($url);
440
            $i = 1;
441
            if (!empty($rss->items)) {
442
                $icon_rss = '';
443
                if (!empty($feed)) {
444
                    $icon_rss = Display::url(
445
                        Display::return_icon('social_rss.png', '', array(), 22),
446
                        Security::remove_XSS($feed['rssfeeds']),
447
                        array('target' => '_blank')
448
                    );
449
                }
450
451
                $res .= '<h3 class="title-rss">'.$icon_rss.' '.$rss->channel['title'].'</h3>';
452
                $res .= '<div class="rss-items">';
453
                foreach ($rss->items as $item) {
454
                    if ($limit >= 0 and $i > $limit) {
455
                        break;
456
                    }
457
                    $res .= '<h4 class="rss-title"><a href="'.$item['link'].'">'.$item['title'].'</a></h4>';
458
                    $res .= '<div class="rss-date">'.api_get_local_time($item['date_timestamp']).'</div>';
459
                    $res .= '<div class="rss-content"><p>'.$item['description'].'</p></div>';
460
                    $i++;
461
                }
462
                $res .= '</div>';
463
            }
464
        }
465
        return $res;
466
    }
467
468
    /**
469
     * Helper functions definition
470
     */
471
    public static function get_logged_user_course_html($my_course, $count)
472
    {
473
        $result = '';
474
        // Table definitions
475
        $main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
476
        $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
477
478
        $course_code = $my_course['code'];
479
        $course_directory = $my_course['course_info']['directory'];
480
        $course_title = $my_course['course_info']['title'];
481
        $course_access_settings = CourseManager :: get_access_settings($course_code);
482
483
        $course_visibility = $course_access_settings['visibility'];
484
485
        $user_in_course_status = CourseManager :: get_user_in_course_status(api_get_user_id(), $course_code);
486
487
        //$valor = api_get_settings_params();
488
        $course_path = api_get_path(SYS_COURSE_PATH).$course_directory;   // course path
489
        if (api_get_setting('course_images_in_courses_list') === 'true') {
490
            if (file_exists($course_path.'/course-pic85x85.png')) {
491
                $image = $my_course['course_info']['course_image'];
492
                $imageCourse = Display::img($image, $course_title, array('class'=>'img-course'));
493
            } else {
494
                $imageCourse = Display::return_icon('session_default_small.png', $course_title, array('class' => 'img-course'));
495
496
            }
497
        } else {
498
            $imageCourse = Display::return_icon('course.png', get_lang('Course'), array('class' => 'img-default'));
499
        }
500
501
        //display course entry
502
        if (api_get_setting('course_images_in_courses_list') === 'true') {
503
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:65px;">';
504
        } else {
505
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:44px;">';
506
        }
507
        $result .= $imageCourse;
508
509
        //show a hyperlink to the course, unless the course is closed and user is not course admin
510
        if ($course_visibility != COURSE_VISIBILITY_HIDDEN &&
511
            ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER)
512
        ) {
513
           $result .= '<span class="title">' . $course_title . '<span>';
514
        } else {
515
            $result .= $course_title." "." ".get_lang('CourseClosed')."";
516
        }
517
518
        $result .= '</li>';
519
520
521
        $session = '';
522
        if (!empty($my_course['session_name']) && !empty($my_course['id_session'])) {
523
524
            // Request for the name of the general coach
525
            $sql = 'SELECT lastname, firstname
526
                    FROM '.$tbl_session.' ts
527
                    LEFT JOIN '.$main_user_table.' tu
528
                    ON ts.id_coach = tu.user_id
529
                    WHERE ts.id='.(int) $my_course['id_session'].' LIMIT 1';
530
            $rs = Database::query($sql);
531
            $sessioncoach = Database::store_result($rs);
532
            $sessioncoach = $sessioncoach[0];
533
534
            $session = array();
535
            $session['title'] = $my_course['session_name'];
536
            if ($my_course['access_start_date'] == '0000-00-00') {
537
                $session['dates'] = get_lang('WithoutTimeLimits');
538 View Code Duplication
                if (api_get_setting('show_session_coach') === 'true') {
539
                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
540
                }
541
            } else {
542
                $session ['dates'] = ' - '.get_lang('From').' '.$my_course['access_start_date'].' '.get_lang('To').' '.$my_course['access_end_date'];
543 View Code Duplication
                if (api_get_setting('show_session_coach') === 'true') {
544
                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
545
                }
546
            }
547
        }
548
        $my_course['id_session'] = isset($my_course['id_session']) ? $my_course['id_session'] : 0;
549
        $output = array(
550
            $my_course['user_course_cat'],
551
            $result,
552
            $my_course['id_session'],
553
            $session,
554
        );
555
556
        return $output;
557
    }
558
559
    /**
560
     * Shows the avatar block in social pages
561
     *
562
     * @param string highlight link possible values:
563
     * group_add,
564
     * home,
565
     * messages,
566
     * messages_inbox,
567
     * messages_compose,
568
     * messages_outbox,
569
     * invitations,
570
     * shared_profile,
571
     * friends,
572
     * groups search
573
     * @param int group id
574
     * @param int user id
575
     *
576
     */
577
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
578
    {
579
        if (empty($user_id)) {
580
            $user_id = api_get_user_id();
581
        }
582
583
        $show_groups = array(
584
            'groups',
585
            'group_messages',
586
            'messages_list',
587
            'group_add',
588
            'mygroups',
589
            'group_edit',
590
            'member_list',
591
            'invite_friends',
592
            'waiting_list',
593
            'browse_groups'
594
        );
595
596
        $template = new Template(null, false, false, false, false, false);
597
598
        if (in_array($show, $show_groups) && !empty($group_id)) {
599
            // Group image
600
            $userGroup = new UserGroup();
601
602
            $group_info = $userGroup->get($group_id);
603
604
            $userGroupImage = $userGroup->get_picture_group(
605
                $group_id,
606
                $group_info['picture'],
607
                160,
608
                GROUP_IMAGE_SIZE_BIG
609
            );
610
611
            $template->assign('show_group', true);
612
            $template->assign('group_id', $group_id);
613
            $template->assign('user_group_image', $userGroupImage);
614
            $template->assign('user_group', $group_info);
615
            $template->assign(
616
                'user_is_group_admin',
617
                $userGroup->is_group_admin(
618
                    $group_id,
619
                    api_get_user_id()
620
                )
621
            );
622
        } else {
623
            $template->assign('show_user', true);
624
            $template->assign(
625
                'user_image',
626
                [
627
                    'big' => UserManager::getUserPicture(
628
                        $user_id,
629
                        USER_IMAGE_SIZE_BIG
630
                    ),
631
                    'normal' => UserManager::getUserPicture(
632
                        $user_id,
633
                        USER_IMAGE_SIZE_MEDIUM
634
                    )
635
                ]
636
            );
637
        }
638
639
        $skillBlock = $template->get_template('social/avatar_block.tpl');
640
641
642
        return $template->fetch($skillBlock);
643
    }
644
645
    /**
646
     * Shows the right menu of the Social Network tool
647
     *
648
     * @param string $show highlight link possible values:
649
     * group_add,
650
     * home,
651
     * messages,
652
     * messages_inbox,
653
     * messages_compose ,
654
     * messages_outbox,
655
     * invitations,
656
     * shared_profile,
657
     * friends,
658
     * groups search
659
     * @param int $group_id group id
660
     * @param int $user_id user id
661
     * @param bool $show_full_profile show profile or not (show or hide the user image/information)
662
     * @param bool $show_delete_account_button
663
     *
664
     */
665
    public static function show_social_menu(
666
        $show = '',
667
        $group_id = 0,
668
        $user_id = 0,
669
        $show_full_profile = false,
670
        $show_delete_account_button = false
671
    ) {
672
        if (empty($user_id)) {
673
            $user_id = api_get_user_id();
674
        }
675
        $usergroup = new UserGroup();
676
677
        $user_info = api_get_user_info($user_id, true);
678
        $current_user_id = api_get_user_id();
679
        $current_user_info = api_get_user_info($current_user_id, true);
680
681
        if ($current_user_id == $user_id) {
682
            $user_friend_relation = null;
683
        } else {
684
            $user_friend_relation = SocialManager::get_relation_between_contacts($current_user_id, $user_id);
685
        }
686
687
        $show_groups = array(
688
            'groups',
689
            'group_messages',
690
            'messages_list',
691
            'group_add',
692
            'mygroups',
693
            'group_edit',
694
            'member_list',
695
            'invite_friends',
696
            'waiting_list',
697
            'browse_groups'
698
        );
699
700
        // get count unread message and total invitations
701
        $count_unread_message = MessageManager::get_number_of_messages(true);
702
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
703
704
        $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id(api_get_user_id());
705
        $group_pending_invitations = $usergroup->get_groups_by_user(
706
            api_get_user_id(),
707
            GROUP_USER_PERMISSION_PENDING_INVITATION,
708
            false
709
        );
710
        $group_pending_invitations = count($group_pending_invitations);
711
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
712
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
713
714
        $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), '', ICON_SIZE_SMALL);
715
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), '', ICON_SIZE_SMALL);
716
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), '', ICON_SIZE_SMALL);
717
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), '', ICON_SIZE_SMALL);
718
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), '', ICON_SIZE_SMALL);
719
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), '', ICON_SIZE_SMALL);
720
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
721
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), '', ICON_SIZE_SMALL);
722
723
        $html = '';
724
        $active = null;
725
        if (!in_array(
726
            $show,
727
            array('shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends')
728
        )) {
729
            $links = '<ul class="nav nav-pills nav-stacked">';
730
            $active = $show == 'home' ? 'active' : null;
731
            $links .= '
732
                <li class="home-icon ' . $active . '">
733
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/home.php">
734
                        ' . $homeIcon . ' ' . get_lang('Home') . '
735
                    </a>
736
                </li>';
737
            $active = $show == 'messages' ? 'active' : null;
738
            $links .= '
739
                <li class="messages-icon ' . $active . '">
740
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'messages/inbox.php?f=social">
741
                        ' . $messagesIcon . ' ' . get_lang('Messages') . $count_unread_message . '
742
                    </a>
743
                </li>';
744
745
            //Invitations
746
            $active = $show == 'invitations' ? 'active' : null;
747
            $links .= '
748
                <li class="invitations-icon ' . $active . '">
749
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/invitations.php">
750
                        ' . $invitationsIcon . ' ' . get_lang('Invitations') . $total_invitations . '
751
                    </a>
752
                </li>';
753
754
            //Shared profile and groups
755
            $active = $show == 'shared_profile' ? 'active' : null;
756
            $links .= '
757
                <li class="shared-profile-icon' . $active . '">
758
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/profile.php">
759
                        ' . $sharedProfileIcon . ' ' . get_lang('ViewMySharedProfile') . '
760
                    </a>
761
                </li>';
762
            $active = $show == 'friends' ? 'active' : null;
763
            $links .= '
764
                <li class="friends-icon ' . $active . '">
765
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/friends.php">
766
                        ' . $friendsIcon . ' ' . get_lang('Friends') . '
767
                    </a>
768
                </li>';
769
            $active = $show == 'browse_groups' ? 'active' : null;
770
            $links .= '
771
                <li class="browse-groups-icon ' . $active . '">
772
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/groups.php">
773
                        ' . $groupsIcon . ' ' . get_lang('SocialGroups') . '
774
                    </a>
775
                </li>';
776
777
            //Search users
778
            $active = $show == 'search' ? 'active' : null;
779
            $links .= '
780
                <li class="search-icon ' . $active . '">
781
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/search.php">
782
                        ' . $searchIcon . ' ' . get_lang('Search') . '
783
                    </a>
784
                </li>';
785
786
            //My files
787
            $active = $show == 'myfiles' ? 'active' : null;
788
789
            $myFiles = '
790
                <li class="myfiles-icon ' . $active . '">
791
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/myfiles.php">
792
                        ' . $filesIcon . ' ' . get_lang('MyFiles') . '
793
                    </a>
794
                </li>';
795
796
            if (api_get_setting('allow_my_files') === 'false') {
797
                $myFiles = '';
798
            }
799
            $links .= $myFiles;
800
801
            $links .='</ul>';
802
            
803
            $html .= Display::panelCollapse(
804
                    get_lang('SocialNetwork'),
805
                    $links,
806
                    'social-network-menu',
807
                    null,
808
                    'sn-sidebar',
809
                    'sn-sidebar-collapse'
810
                    );
811
        }
812
813
        if (in_array($show, $show_groups) && !empty($group_id)) {
814
            $html .= $usergroup->show_group_column_information(
815
                $group_id,
816
                api_get_user_id(),
817
                $show
818
            );
819
        }
820
821
        if ($show == 'shared_profile') {
822
            $links =  '<ul class="nav nav-pills nav-stacked">';
823
            // My own profile
824
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
825
                $links .= '
826
                    <li class="home-icon ' . $active . '">
827
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/home.php">
828
                            ' . $homeIcon . ' ' . get_lang('Home') . '
829
                        </a>
830
                    </li>
831
                    <li class="messages-icon ' . $active . '">
832
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'messages/inbox.php?f=social">
833
                            ' . $messagesIcon . ' ' . get_lang('Messages') . $count_unread_message . '
834
                        </a>
835
                    </li>';
836
                $active = $show == 'invitations' ? 'active' : null;
837
                $links .= '
838
                    <li class="invitations-icon' . $active . '">
839
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/invitations.php">
840
                            ' . $invitationsIcon . ' ' . get_lang('Invitations') . $total_invitations . '
841
                        </a>
842
                    </li>';
843
844
                $links .= '
845
                    <li class="shared-profile-icon active">
846
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/profile.php">
847
                            ' . $sharedProfileIcon . ' ' . get_lang('ViewMySharedProfile') . '
848
                        </a>
849
                    </li>
850
                    <li class="friends-icon">
851
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/friends.php">
852
                            ' . $friendsIcon . ' ' . get_lang('Friends') . '
853
                        </a>
854
                    </li>
855
                    <li class="browse-groups-icon">
856
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/groups.php">
857
                            ' . $groupsIcon . ' ' . get_lang('SocialGroups') . '
858
                        </a>
859
                    </li>';
860
                $active = $show == 'search' ? 'active' : null;
861
                $links .= '
862
                    <li class="search-icon ' . $active . '">
863
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/search.php">
864
                            ' . $searchIcon . ' ' . get_lang('Search') . '
865
                        </a>
866
                    </li>';
867
                $active = $show == 'myfiles' ? 'active' : null;
868
869
                $myFiles = '
870
                    <li class="myfiles-icon ' . $active . '">
871
                     <a href="' . api_get_path(WEB_CODE_PATH) . 'social/myfiles.php">
872
                            ' . $filesIcon . ' ' . get_lang('MyFiles') . '
873
                        </a>
874
                    </li>';
875
876
                if (api_get_setting('allow_my_files') === 'false') {
877
                    $myFiles = '';
878
                }
879
                $links .= $myFiles;
880
            }
881
882
            // My friend profile.
883
            if ($user_id != api_get_user_id()) {
884
                $sendMessageText = get_lang('SendMessage');
885
                $sendMessageIcon = Display::return_icon(
886
                    'new-message.png',
887
                    $sendMessageText
888
                );
889
                $sendMesssageUrl = api_get_path(WEB_AJAX_PATH)
890
                    . 'user_manager.ajax.php?'
891
                    . http_build_query([
892
                        'a' => 'get_user_popup',
893
                        'user_id' => $user_id
894
                    ]);
895
896
                $links .= '<li>';
897
                $links .= Display::url(
898
                    "$sendMessageIcon $sendMessageText",
899
                    $sendMesssageUrl,
900
                    [
901
                        'class' => 'ajax',
902
                        'title' => $sendMessageText,
903
                        'data-title' => $sendMessageText
904
                    ]
905
                );
906
                $links .= '</li>';
907
            }
908
909
            // Check if I already sent an invitation message
910
            $invitation_sent_list = SocialManager::get_list_invitation_sent_by_user_id(
911
                api_get_user_id()
912
            );
913
914
            if (isset($invitation_sent_list[$user_id]) && is_array($invitation_sent_list[$user_id]) && count($invitation_sent_list[$user_id]) > 0) {
915
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/invitations.php">'.Display::return_icon('invitation.png', get_lang('YouAlreadySentAnInvitation')).'&nbsp;&nbsp;'.get_lang('YouAlreadySentAnInvitation').'</a></li>';
916
            } else {
917
                if (!$show_full_profile) {
918
                    $links .= '<li><a class="btn-to-send-invitation" href="#" data-send-to="' . $user_id . '" title="'.get_lang('SendInvitation').'">'.Display :: return_icon('invitation.png', get_lang('SocialInvitationToFriends')).'&nbsp;'.get_lang('SendInvitation').'</a></li>';
919
                }
920
            }
921
922
            $links .= '</ul>';
923
            $html .= Display::panelCollapse(
924
                get_lang('SocialNetwork'),
925
                $links,
926
                'social-network-menu',
927
                null,
928
                'sn-sidebar',
929
                'sn-sidebar-collapse'
930
            );
931
932
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
933
                $personal_course_list = UserManager::get_personal_session_course_list($user_id);
934
                $course_list_code = array();
935
                $i = 1;
936
                if (is_array($personal_course_list)) {
937
                    foreach ($personal_course_list as $my_course) {
938
                        if ($i <= 10) {
939
                            $course_list_code[] = array('code' => $my_course['code']);
940
                        } else {
941
                            break;
942
                        }
943
                        $i++;
944
                    }
945
                    // To avoid repeated courses
946
                    $course_list_code = array_unique_dimensional($course_list_code);
947
                }
948
949
                // Announcements
950
                $my_announcement_by_user_id = intval($user_id);
951
                $announcements = array();
952
                foreach ($course_list_code as $course) {
953
                    $course_info = api_get_course_info($course['code']);
954
                    if (!empty($course_info)) {
955
                        $content = AnnouncementManager::get_all_annoucement_by_user_course(
956
                            $course_info['code'],
957
                            $my_announcement_by_user_id
958
                        );
959
960
                        if (!empty($content)) {
961
                            $url = Display::url(Display::return_icon('announcement.png', get_lang('Announcements')).$course_info['name'].' ('.$content['count'].')', api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']);
962
                            $announcements[] = Display::tag('li', $url);
963
                        }
964
                    }
965
                }
966
                if (!empty($announcements)) {
967
                    $html .= '<div class="social_menu_items">';
968
                    $html .= '<ul>';
969
                    foreach ($announcements as $announcement) {
970
                        $html .= $announcement;
971
                    }
972
                    $html .= '</ul>';
973
                    $html .= '</div>';
974
                }
975
            }
976
        }
977
978
        if ($show_delete_account_button) {
979
            $html .= '<div class="sidebar-nav"><ul><li>';
980
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
981
            $html .= Display::url(
982
                Display::return_icon(
983
                    'delete.png',
984
                    get_lang('Unsubscribe'),
985
                    array(),
986
                    ICON_SIZE_TINY
987
                ).get_lang('Unsubscribe'),
988
                $url
989
            );
990
            $html .= '</li></ul></div>';
991
        }
992
        $html .= '';
993
994
        return $html;
995
    }
996
997
    /**
998
     * Displays a sortable table with the list of online users.
999
     * @param array $user_list The list of users to be shown
1000
     * @param bool $wrap Whether we want the function to wrap the spans list in a div or not
1001
     * @return string HTML block or null if and ID was defined
1002
     * @assert (null) === false
1003
     */
1004
    public static function display_user_list($user_list, $wrap = true)
1005
    {
1006
        $html = null;
1007
        if (isset($_GET['id']) or count($user_list) < 1) {
1008
            return false;
1009
        }
1010
        $column_size = '12';
1011
        $add_row = false;
1012
        if (api_is_anonymous()) {
1013
            $add_row = true;
1014
        }
1015
1016
        $extra_params = array();
1017
        $course_url = '';
1018 View Code Duplication
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1019
            $extra_params['cidReq'] = Security::remove_XSS($_GET['cidReq']);
1020
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
1021
        }
1022
1023
        $html .= '<div class="row">';
1024
1025
        foreach ($user_list as $uid) {
1026
            $user_info = api_get_user_info($uid, $checkIfUserOnline = true);
1027
            $lastname = $user_info['lastname'];
1028
            $firstname =  $user_info['firstname'];
1029
            $completeName = $firstname.', '.$lastname;
1030
1031
            $user_rol = $user_info['status'] == 1 ? Display::return_icon('teacher.png',get_lang('Teacher'),null,ICON_SIZE_TINY) : Display::return_icon('user.png',get_lang('Student'),null,ICON_SIZE_TINY);
1032
            $status_icon_chat = null;
1033
            if ($user_info['user_is_online_in_chat'] == 1) {
1034
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1035
            } else {
1036
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1037
            }
1038
1039
            $userPicture = $user_info['avatar'];
1040
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1041
1042
            $url =  null;
1043
            // Anonymous users can't have access to the profile
1044
            if (!api_is_anonymous()) {
1045
                if (api_get_setting('allow_social_tool') == 'true') {
1046
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1047
                } else {
1048
                    $url = '?id='.$uid.$course_url;
1049
                }
1050
            } else {
1051
                $url = null;
1052
            }
1053
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1054
1055
            $html .= '<div class="col-xs-6 col-md-2">
1056
                        <div class="items-user">
1057
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1058
                            <div class="items-user-name">
1059
                            '.$name.'
1060
                            </div>
1061
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1062
                        </div>
1063
                      </div>';
1064
1065
        }
1066
        $counter = $_SESSION['who_is_online_counter'];
1067
1068
        if ($wrap) {
1069
            $html .= '</div>';
1070
        }
1071
        if (count($user_list) >= 9) {
1072
            $html .= '<div class="col-md-'.$column_size.'">
1073
                        <a class="btn btn-large btn-default" id="link_load_more_items" data_link="'.$counter.'" >'.get_lang('More').'</a></div>';
1074
        }
1075
        if ($wrap && $add_row) {
1076
            $html .= '</div>';
1077
        }
1078
1079
        return $html;
1080
    }
1081
1082
    /**
1083
     * Displays the information of an individual user
1084
     * @param int $user_id
1085
     */
1086
    public static function display_individual_user($user_id)
1087
    {
1088
        global $interbreadcrumb;
1089
        $safe_user_id = intval($user_id);
1090
        $currentUserId = api_get_user_id();
1091
1092
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1093
        $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
1094
        $result = Database::query($sql);
1095
        $html = null;
1096
        if (Database::num_rows($result) == 1) {
1097
            $user_object = Database::fetch_object($result);
1098
            $userInfo = api_get_user_info($user_id);
1099
            $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
1100
            $status = get_status_from_code($user_object->status);
1101
            $interbreadcrumb[] = array('url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList'));
1102
1103
            $html .= '<div class ="thumbnail">';
1104
            $fullurl = $userInfo['avatar'];
1105
1106
            $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
1107
1108
            if (!empty($status)) {
1109
                $html .= '<div class="caption">'.$status.'</div>';
1110
            }
1111
            $html .= '</div>';
1112
1113
            if (api_get_setting('show_email_addresses') == 'true') {
1114
                $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
1115
            }
1116
1117
            if ($user_object->competences) {
1118
                $html .= Display::page_subheader(get_lang('MyCompetences'));
1119
                $html .= '<p>'.$user_object->competences.'</p>';
1120
            }
1121
            if ($user_object->diplomas) {
1122
                $html .= Display::page_subheader(get_lang('MyDiplomas'));
1123
                $html .= '<p>'.$user_object->diplomas.'</p>';
1124
            }
1125
            if ($user_object->teach) {
1126
                $html .= Display::page_subheader(get_lang('MyTeach'));
1127
                $html .= '<p>'.$user_object->teach.'</p>';
1128
            }
1129
            SocialManager::display_productions($user_object->user_id);
1130
            if ($user_object->openarea) {
1131
                $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
1132
                $html .= '<p>'.$user_object->openarea.'</p>';
1133
            }
1134
        } else {
1135
            $html .= '<div class="actions-title">';
1136
            $html .= get_lang('UsersOnLineList');
1137
            $html .= '</div>';
1138
        }
1139
1140
        return $html;
1141
    }
1142
1143
    /**
1144
     * Display productions in who is online
1145
     * @param int $user_id User id
1146
     */
1147
    public static function display_productions($user_id)
1148
    {
1149
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1150
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1151
        $webdir = UserManager::getUserPathById($user_id, 'web');
1152
1153
        if (!is_dir($sysdir)) {
1154
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1155
        }
1156
1157
        $productions = UserManager::get_user_productions($user_id);
1158
1159
        if (count($productions) > 0) {
1160
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1161
            echo '<dd><ul>';
1162
            foreach ($productions as $file) {
1163
                // Only display direct file links to avoid browsing an empty directory
1164
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1165
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1166
                }
1167
                // Real productions are under a subdirectory by the User's id
1168
                if (is_dir($sysdir.$file)) {
1169
                    $subs = scandir($sysdir.$file);
1170
                    foreach ($subs as $my => $sub) {
1171
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1172
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1173
                        }
1174
                    }
1175
                }
1176
            }
1177
            echo '</ul></dd>';
1178
        }
1179
    }
1180
1181
    /**
1182
     * @param string $content
1183
     * @param string $span_count
1184
     * @return string
1185
     */
1186
    public static function social_wrapper_div($content, $span_count)
1187
    {
1188
        $span_count = intval($span_count);
1189
        $html = '<div class="span'.$span_count.'">';
1190
        $html .= '<div class="well_border">';
1191
        $html .= $content;
1192
        $html .= '</div></div>';
1193
1194
        return $html;
1195
    }
1196
1197
    /**
1198
     * Dummy function
1199
     *
1200
     */
1201
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1202
    {
1203
        $content = '';
1204
        switch ($place) {
1205
            case SOCIAL_CENTER_PLUGIN:
1206
                $social_plugins = array(1, 2);
1207
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1208
                    $content.= '<div id="social-plugins">';
1209
                    foreach ($social_plugins as $plugin) {
1210
                        $content.= '<div class="social-plugin-item">';
1211
                        $content.= $plugin;
1212
                        $content.= '</div>';
1213
                    }
1214
                    $content.= '</div>';
1215
                }
1216
                break;
1217
            case SOCIAL_LEFT_PLUGIN:
1218
                break;
1219
            case SOCIAL_RIGHT_PLUGIN:
1220
                break;
1221
        }
1222
1223
        return $content;
1224
    }
1225
    /**
1226
     * Sends a message to someone's wall
1227
     * @param int $userId id of author
1228
     * @param int $friendId id where we send the message
1229
     * @param string $messageContent of the message
1230
     * @param int $messageId id parent
1231
     * @param string $messageStatus status type of message
1232
     * @return boolean
1233
     * @author Yannick Warnier
1234
     */
1235
    public static function sendWallMessage($userId, $friendId, $messageContent, $messageId = 0, $messageStatus = '')
1236
    {
1237
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1238
        $userId = intval($userId);
1239
        $friendId = intval($friendId);
1240
        $messageId = intval($messageId);
1241
1242
        //Just in case we replace the and \n and \n\r while saving in the DB
1243
        $messageContent = str_replace(array("\n", "\n\r"), '<br />', $messageContent);
1244
1245
        $attributes = array(
1246
            'user_sender_id' => $userId,
1247
            'user_receiver_id' => $friendId,
1248
            'msg_status' => $messageStatus,
1249
            'send_date' => api_get_utc_datetime(),
1250
            'title' => '',
1251
            'content' => $messageContent,
1252
            'parent_id' => $messageId
1253
        );
1254
1255
        return Database::insert($tblMessage, $attributes);
1256
    }
1257
1258
    /**
1259
     * Send File attachment (jpg,png)
1260
     * @author Anibal Copitan
1261
     * @param int $userId id user
1262
     * @param array $fileAttach
1263
     * @param int $messageId id message (relation with main message)
1264
     * @param string $fileComment description attachment file
1265
     * @return bool
1266
     */
1267
    public static function sendWallMessageAttachmentFile($userId, $fileAttach, $messageId, $fileComment = '')
1268
    {
1269
        $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1270
1271
        // create directory
1272
        $social = '/social/';
1273
        $pathMessageAttach = UserManager::getUserPathById($userId, 'system').'message_attachments'.$social;
1274
        $safeFileComment = Database::escape_string($fileComment);
1275
        $safeFileName = Database::escape_string($fileAttach['name']);
1276
1277
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1278
        $allowedTypes = api_get_supported_image_extensions();
1279
        if (!in_array($extension, $allowedTypes)) {
1280
            $flag = false;
1281
        } else {
1282
            $newFileName = uniqid('') . '.' . $extension;
1283
            if (!file_exists($pathMessageAttach)) {
1284
                @mkdir($pathMessageAttach, api_get_permissions_for_new_directories(), true);
1285
            }
1286
1287
            $newPath = $pathMessageAttach . $newFileName;
1288
            if (is_uploaded_file($fileAttach['tmp_name'])) {
1289
                @copy($fileAttach['tmp_name'], $newPath);
1290
            }
1291
1292
            $small = self::resize_picture($newPath, IMAGE_WALL_SMALL_SIZE);
1293
            $medium = self::resize_picture($newPath, IMAGE_WALL_MEDIUM_SIZE);
1294
1295
            $big = new Image($newPath);
1296
            $ok = $small && $small->send_image($pathMessageAttach . IMAGE_WALL_SMALL . '_' . $newFileName) &&
1297
                $medium && $medium->send_image($pathMessageAttach . IMAGE_WALL_MEDIUM .'_' . $newFileName) &&
1298
                $big && $big->send_image($pathMessageAttach . IMAGE_WALL_BIG . '_' . $newFileName);
1299
1300
            // Insert
1301
            $newFileName = $social.$newFileName;
1302
1303
            $params = [
1304
                'filename' => $safeFileName,
1305
                'comment' => $safeFileComment,
1306
                'path' => $newFileName,
1307
                'message_id' => $messageId,
1308
                'size' => $fileAttach['size'],
1309
            ];
1310
            Database::insert($tbl_message_attach, $params);
1311
            $flag = true;
1312
        }
1313
1314
        return $flag;
1315
    }
1316
1317
    /**
1318
     * Gets all messages from someone's wall (within specific limits)
1319
     * @param int $userId id of wall shown
1320
     * @param string $messageStatus status wall message
1321
     * @param int|string $parentId id message (Post main)
1322
     * @param date $start Date from which we want to show the messages, in UTC time
1323
     * @param int $limit Limit for the number of parent messages we want to show
1324
     * @param int $offset Wall message query offset
1325
     * @return boolean
1326
     * @author Yannick Warnier
1327
     */
1328
    public static function getWallMessages($userId, $messageStatus, $parentId = '', $start = null, $limit = 10, $offset = 0)
1329
    {
1330
        if (empty($start)) {
1331
            $start = '0000-00-00';
1332
        }
1333
1334
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1335
        $tblMessageAttachment = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1336
1337
        $userId = intval($userId);
1338
        $start = Database::escape_string($start);
1339
        $limit = intval($limit);
1340
1341
        $sql = "
1342
        SELECT
1343
          id,
1344
          user_sender_id,
1345
          user_receiver_id,
1346
          send_date,
1347
          content,
1348
          parent_id,
1349
          (SELECT ma.path FROM $tblMessageAttachment ma
1350
           WHERE  ma.message_id = tm.id ) as path,
1351
          (SELECT ma.filename FROM $tblMessageAttachment ma
1352
          WHERE  ma.message_id = tm.id ) as filename
1353
        FROM $tblMessage tm
1354
        WHERE
1355
            user_receiver_id = $userId AND
1356
            send_date > '$start'
1357
        ";
1358
1359
        $sql .= (empty($messageStatus) || is_null($messageStatus)) ? '' : " AND msg_status = '$messageStatus' ";
1360
        $sql .= (empty($parentId) || is_null($parentId)) ? '' : " AND parent_id = '$parentId' ";
1361
        $sql .= " ORDER BY send_date DESC LIMIT $offset, $limit ";
1362
        $messages = array();
1363
        $res = Database::query($sql);
1364
        if (Database::num_rows($res) > 0) {
1365
            while ($row = Database::fetch_array($res)) {
1366
                $messages[] = $row;
1367
            }
1368
        }
1369
1370
        return $messages;
1371
    }
1372
1373
    /**
1374
     * Gets all messages from someone's wall (within specific limits), formatted
1375
     * @param int       $userId     USER ID of the person's wall
1376
     * @param int       $friendId   id person
1377
     * @param int       $idMessage  id message
1378
     * @param string    $start      Start date (from when we want the messages until today)
1379
     * @param int       $limit      Limit to the number of messages we want
1380
     * @param int       $offset     Wall messages offset
1381
     * @return string  HTML formatted string to show messages
1382
     */
1383
    public static function getWallMessagesHTML($userId, $friendId, $idMessage, $start = null, $limit = 10, $offset = 0)
1384
    {
1385
        if (empty($start)) {
1386
            $start = '0000-00-00';
1387
        }
1388
1389
        $isOwnWall = (api_get_user_id() == $userId  && $userId == $friendId);
1390
        $messages = self::getWallMessages($userId, MESSAGE_STATUS_WALL, $idMessage, $start, $limit, $offset);
1391
        $formattedList = '<div class="sub-mediapost">';
1392
        $users = array();
1393
1394
        // The messages are ordered by date descendant, for comments we need ascendant
1395
        krsort($messages);
1396
        foreach ($messages as $message) {
1397
            $date = api_get_local_time($message['send_date']);
1398
            $userIdLoop = $message['user_sender_id'];
1399
            if (!isset($users[$userIdLoop])) {
1400
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1401
            }
1402
1403
            $nameComplete = api_is_western_name_order()
1404
                ? $users[$userIdLoop]['firstname'] .' ' . $users[$userIdLoop]['lastname']
1405
                : $users[$userIdLoop]['lastname'] . ' ' . $users[$userIdLoop]['firstname'];
1406
            $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$userIdLoop;
1407
            $media = '';
1408
            $media .= '<div class="rep-post">';
1409
            if ($isOwnWall) {
1410
                $media .= '<div class="pull-right deleted-mgs">';
1411
                $media .= '<a title="'.get_lang("SocialMessageDelete").'" href="'.api_get_path(WEB_CODE_PATH).'social/profile.php?messageId='.
1412
                    $message['id'].'">x</a>';
1413
                $media .= '</div>';
1414
            }
1415
            $media .= '<div class="user-image">';
1416
            $media .= '<a href="'.$url.'" ><img src="'. $users[$userIdLoop]['avatar'] .
1417
                       '" alt="'.$users[$userIdLoop]['complete_name'].'" class="avatar-thumb"></a>';
1418
            $media .= '</div>';
1419
            $media .= '<div class="user-data">';
1420
            $media .= '<div class="username">' . '<a href="'.$url.'">'.$nameComplete.'</a></div>';
1421
            $media .= '<div class="time timeago" title="'.$date.'">'.$date.'</div>';
1422
            $media .= '</div>';
1423
            $media .= '<div class="msg-content">';
1424
            $media .= '<p>'.Security::remove_XSS($message['content']).'</p>';
1425
            $media .= '</div></div>';
1426
1427
            $formattedList .= $media;
1428
        }
1429
1430
        $formattedList .= '</div>';
1431
1432
        $formattedList .= '<div class="mediapost-form">';
1433
            $formattedList .= '<form name="social_wall_message" method="POST">
1434
                <label for="social_wall_new_msg" class="hide">'.get_lang('SocialWriteNewComment').'</label>
1435
                <input type="hidden" name = "messageId" value="'.$idMessage.'" />
1436
                <textarea placeholder="'.get_lang('SocialWriteNewComment').
1437
                '" name="social_wall_new_msg" rows="1" style="width:80%;" ></textarea>
1438
                <button type="submit" name="social_wall_new_msg_submit"
1439
                class="pull-right btn btn-default" /><em class="fa fa-pencil"></em> '.get_lang('Post').'</button>
1440
                </form>';
1441
        $formattedList .= '</div>';
1442
1443
        return $formattedList;
1444
    }
1445
1446
    /**
1447
     * Gets all user's starting wall messages (within specific limits)
1448
     * @param   int     $userId     User's id
1449
     * @param   int     $friendId   Friend's id
1450
     * @param   date    $start      Start date (from when we want the messages until today)
1451
     * @param   int     $limit      Limit to the number of messages we want
1452
     * @param   int     $offset     Wall messages offset
1453
     * @return  array   $data       return user's starting wall messages along with message extra data
1454
     */
1455
    public static function getWallMessagesPostHTML($userId, $friendId = 0, $start = null, $limit = 10, $offset= 0)
1456
    {
1457
        if (empty($start)) {
1458
            $start = '0000-00-00';
1459
        }
1460
        $isOwnWall = (api_get_user_id() == $userId  && $userId == $friendId);
1461
        $messages = self::getWallMessages($userId, MESSAGE_STATUS_WALL_POST, null, $start, $limit, $offset);
0 ignored issues
show
Bug introduced by
It seems like $start defined by '0000-00-00' on line 1458 can also be of type string; however, SocialManager::getWallMessages() does only seem to accept object<date>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1462
        $users = array();
1463
        $data = array();
1464
        foreach ($messages as $key => $message) {
1465
            $userIdLoop = $message['user_sender_id'];
1466
            $userFriendIdLoop = $message['user_receiver_id'];
1467
1468
            if (!isset($users[$userIdLoop])) {
1469
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1470
            }
1471
1472
            if (!isset($users[$userFriendIdLoop])) {
1473
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
1474
            }
1475
1476
            $html = '';
1477
            $html .= self::headerMessagePost(
1478
                $message['user_sender_id'],
1479
                $message['user_receiver_id'],
1480
                $users,
1481
                $message,
1482
                $isOwnWall
1483
            );
1484
1485
            $data[$key]['id'] = $message['id'];
1486
            $data[$key]['html'] = $html;
1487
        }
1488
1489
        return $data;
1490
    }
1491
1492
    /**
1493
     * Returns the formatted header message post
1494
     * @param   int     $authorId   Author's id
1495
     * @param   int     $receiverId Receiver's id
1496
     * @param   array   $users      Author's and receiver's data
1497
     * @param   array   $message    Message data
1498
     * @param   boolean $isOwnWall  Determines if the author is in its own social wall or not
1499
     * @return  string  $html       The formatted header message post
1500
     */
1501
    private static function headerMessagePost($authorId, $receiverId, $users, $message, $isOwnWall = false)
1502
    {
1503
        $date = api_get_local_time($message['send_date']);
1504
        $avatarAuthor = $users[$authorId]['avatar'];
1505
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
1506
        $nameCompleteAuthor = api_get_person_name(
1507
            $users[$authorId]['firstname'],
1508
            $users[$authorId]['lastname']
1509
        );
1510
1511
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
1512
        $nameCompleteReceiver = api_get_person_name(
1513
            $users[$receiverId]['firstname'],
1514
            $users[$receiverId]['lastname']
1515
        );
1516
1517
        $htmlReceiver = '';
1518
        if ($authorId != $receiverId) {
1519
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">' . $nameCompleteReceiver . '</a> ';
1520
        }
1521
1522
        $wallImage = '';
1523
        if (!empty($message['path'])) {
1524
            $imageBig = UserManager::getUserPicture($authorId, USER_IMAGE_SIZE_BIG);
1525
            $imageSmall = UserManager::getUserPicture($authorId, USER_IMAGE_SIZE_SMALL);
1526
1527
            $wallImage = '<a class="thumbnail ajax" href="'.$imageBig.'"><img src="'.$imageSmall.'"></a>';
1528
        }
1529
1530
        $htmlDelete = '';
1531
        if ($isOwnWall) {
1532
            $htmlDelete .= '<a title="'.get_lang("SocialMessageDelete").'" href="'.api_get_path(WEB_CODE_PATH).'social/profile.php?messageId='.
1533
            $message['id'].'">x</a>';
1534
        }
1535
1536
        $html = '';
1537
        $html .= '<div class="top-mediapost" >';
1538
        if ($isOwnWall) {
1539
            $html .= '<div class="pull-right deleted-mgs">';
1540
            $html .= $htmlDelete;
1541
            $html .= '</div>';
1542
        }
1543
        $html .= '<div class="user-image" >';
1544
        $html .= '<a href="'.$urlAuthor.'">'.'<img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
1545
        $html .= '</div>';
1546
        $html .= '<div class="user-data">';
1547
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
1548
        $html .= '<div class="time timeago" title="'.$date.'">'.$date.'</div>';
1549
        $html .= '</div>';
1550
        $html .= '<div class="msg-content">';
1551
        $html .= '<div class="img-post">';
1552
        $html .= $wallImage;
1553
        $html .= '</div>';
1554
        $html .= '<p>'. Security::remove_XSS($message['content']).'</p>';
1555
        $html .= '</div>';
1556
        $html .= '</div>'; // end mediaPost
1557
1558
        return $html;
1559
    }
1560
1561
    /**
1562
     * get html data with OpenGrap passing the Url
1563
     * @param $link url
1564
     * @return string data html
1565
     */
1566
    public static function readContentWithOpenGraph($link)
1567
    {
1568
        $graph = OpenGraph::fetch($link);
1569
        if (!$graph) {
1570
            return false;
1571
        }
1572
        $url = $graph->url;
0 ignored issues
show
Bug introduced by
The property url does not seem to exist in OpenGraph.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1573
        $image = $graph->image;
0 ignored issues
show
Bug introduced by
The property image does not seem to exist in OpenGraph.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1574
        $domain = empty($url) ? parse_url($link) : parse_url($url);
1575
        $domain = $domain['scheme'].'://'.$domain['host'];
1576
        // Trick to verify if the Image Url Exist because of some bad metatag dev
1577
        if (self::verifyUrl($image) == false){
1578
            if (!($image[0] == '/')){
1579
                $domain = $domain . '/';
1580
            }
1581
            $image = $domain . $image;
1582
        }
1583
        $title = $graph->title;
0 ignored issues
show
Bug introduced by
The property title does not seem to exist in OpenGraph.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1584
        
1585
        $html  = '<div class="thumbnail">';
1586
        $html .= '<a target="_blank" href="'.$link.'"><h3>'.$title.'</h3>';
1587
        $html .= empty($image) ? '' : '<img alt="" src="'.$image.'" /></a>';
1588
        $html .= empty($graph->description) ? '' : '<p class="description">'.$graph->description.'</p>';
1589
        $html .= '<a href="'.$link.'">'.$link.'</a>';
1590
        $html .= '</div>';
1591
1592
        return $html;
1593
    }
1594
1595
    /**
1596
     * verify if Url Exist - Using Curl
1597
     * @param $uri url
1598
     *
1599
     * @return boolean
1600
     */
1601 View Code Duplication
    public static function verifyUrl($uri)
1602
    {
1603
        $curl = curl_init($uri);
1604
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
1605
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
1606
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1607
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
1608
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
1609
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
1610
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
1611
        $response = curl_exec($curl);
1612
        curl_close($curl);
1613
        if (!empty($response)) {
1614
            return true;
1615
        } else {
1616
            return false;
1617
        }
1618
    }
1619
1620
1621
    /**
1622
     * Get full image path from a path and a size
1623
     * @param   string  $path
1624
     * @return  string
1625
     */
1626
    private static function getImagePath($path, $size = '')
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
1627
    {
1628
        $name = '';
1629
        $array = preg_split('#\/#', $path);
1630
        if (isset($array[2]) && !empty($array[2])) {
1631
1632
            if ($size == IMAGE_WALL_SMALL) {
1633
                $name = IMAGE_WALL_SMALL. '_' . $array[2];
1634
            }else if($size == IMAGE_WALL_MEDIUM){
1635
                $name = IMAGE_WALL_MEDIUM. '_' . $array[2];
1636
            }else if($size == IMAGE_WALL_BIG){
1637
                $name = IMAGE_WALL_BIG. '_' . $array[2];
1638
            }else {
1639
                $name = IMAGE_WALL_SMALL. '_' . $array[2];
1640
            }
1641
            $lessImage = str_replace($array[2], '', $path);
1642
            $name = $lessImage . $name;
1643
        }
1644
1645
        return $name;
1646
    }
1647
    /**
1648
    * Delete messages delete logic
1649
    * @param int $id id message to delete.
1650
    * @return bool status query
1651
    */
1652 View Code Duplication
    public static function deleteMessage($id)
1653
    {
1654
        $id = intval($id);
1655
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1656
        $statusMessage = MESSAGE_STATUS_WALL_DELETE;
1657
        $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
1658
1659
        return Database::query($sql);
1660
    }
1661
1662
    /**
1663
     * Generate the social block for a user
1664
     * @param Template $template
1665
     * @param int $userId The user id
1666
     * @param string $groupBlock Optional. Highlight link possible values:
1667
     * group_add, home, messages, messages_inbox, messages_compose,
1668
     * messages_outbox, invitations, shared_profile, friends, groups, search
1669
     * @param int $groupId Optional. Group ID
1670
     * @return string The HTML code with the social block
1671
     */
1672
    public static function setSocialUserBlock(Template $template, $userId, $groupBlock = '', $groupId = 0, $show_full_profile = true)
1673
    {
1674
        if (api_get_setting('allow_social_tool') != 'true') {
1675
            return '';
1676
        }
1677
1678
        $currentUserId = api_get_user_id();
1679
        $userId = intval($userId);
1680
        $userRelationType = 0;
1681
1682
        $socialAvatarBlock = SocialManager::show_social_avatar_block(
1683
            $groupBlock,
1684
            $groupId,
1685
            $userId
1686
        );
1687
1688
        $profileEditionLink = null;
1689
1690
        if ($currentUserId === $userId) {
1691
            $profileEditionLink = Display::getProfileEditionLink($userId);
1692
        } else {
1693
            $userRelationType = SocialManager::get_relation_between_contacts(
1694
                $currentUserId,
1695
                $userId
1696
            );
1697
        }
1698
1699
        $vCardUserLink = Display::getVCardUserLink($userId);
1700
1701
        $userInfo = api_get_user_info($userId, true, false, true, true);
1702
1703
        $template->assign('user', $userInfo);
1704
        $template->assign('social_avatar_block', $socialAvatarBlock);
1705
        $template->assign('profile_edition_link', $profileEditionLink);
1706
        
1707
        $plugin = BuyCoursesPlugin::create();
1708
        $includeServices = $plugin->get('include_services') === 'true';
1709
        $serviceNode = null;
1710
        if ($includeServices) {
1711
            $serviceNode = $plugin->CheckServiceSubscribed(BuyCoursesPlugin::SERVICE_TYPE_USER, $userInfo['user_id']);
1712
            $template->assign('user_services', $serviceNode ? $serviceNode : false);
1713
        }
1714
        
1715
        //Added the link to export the vCard to the Template
1716
        
1717
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
1718
        if ($show_full_profile) {
1719
            $template->assign('vcard_user_link', $vCardUserLink);
1720
        }
1721
1722
        if (api_get_setting('gamification_mode') === '1') {
1723
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
1724
                $userId,
1725
                $userInfo['status']
1726
            );
1727
1728
            $template->assign('gamification_points', $gamificationPoints);
1729
        }
1730
        $chatEnabled = api_is_global_chat_enabled();
1731
        $template->assign('chat_enabled', $chatEnabled);
1732
        $template->assign('user_relation', $userRelationType);
1733
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
1734
        $templateName = $template->get_template('social/user_block.tpl');
1735
1736
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
1737
            $templateName = $template->get_template('social/group_block.tpl');
1738
        }
1739
1740
        $template->assign('social_avatar_block', $template->fetch($templateName));
1741
    }
1742
1743
    /**
1744
     * @param int $user_id
1745
     * @param $link_shared
1746
     * @param $show_full_profile
1747
     * @return string
1748
     */
1749
    public static function listMyFriends($user_id, $link_shared, $show_full_profile)
1750
    {
1751
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1752
        $friends = SocialManager::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
1753
        $number_of_images = 30;
1754
        $number_friends = count($friends);
1755
        $friendHtml = '';
1756
        if ($number_friends != 0) {
1757 View Code Duplication
            if ($number_friends > $number_of_images) {
1758
                if (api_get_user_id() == $user_id) {
1759
                    $friendHtml.= ' <span><a href="friends.php">'.get_lang('SeeAll').'</a></span>';
1760
                } else {
1761
                    $friendHtml.= ' <span>'
1762
                        .'<a href="'.api_get_path(WEB_CODE_PATH).'social/profile_friends_and_groups.inc.php'
1763
                        .'?view=friends&height=390&width=610&user_id='.$user_id.'"'
1764
                        .'class="ajax" data-title="'.get_lang('SeeAll').'" title="'.get_lang('SeeAll').'" >'.get_lang('SeeAll').'</a></span>';
1765
                }
1766
            }
1767
1768
            $friendHtml.= '<ul class="nav nav-list">';
1769
            $j = 1;
1770
            for ($k=0; $k < $number_friends; $k++) {
1771
                if ($j > $number_of_images) break;
1772
1773
                if (isset($friends[$k])) {
1774
                    $friend = $friends[$k];
1775
                    $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
1776
                    $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
1777
1778
                    if ($user_info_friend['user_is_online']) {
1779
                        $statusIcon = Display::span('', array('class' => 'online_user_in_text'));
1780
                    } else {
1781
                        $statusIcon = Display::span('', array('class' => 'offline_user_in_text'));
1782
                    }
1783
1784
                    $friendHtml.= '<li>';
1785
                    $friendHtml.= '<div>';
1786
1787
                    // the height = 92 must be the same in the image_friend_network span style in default.css
1788
                    $friends_profile = UserManager::getUserPicture($friend['friend_user_id'], USER_IMAGE_SIZE_SMALL);
1789
                    $friendHtml.= '<img src="'.$friends_profile.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'"/>';
1790
                    $link_shared = (empty($link_shared)) ? '' : '&'.$link_shared;
1791
                    $friendHtml.= $statusIcon .'<a href="profile.php?' .'u=' . $friend['friend_user_id'] . $link_shared . '">' . $name_user .'</a>';
1792
                    $friendHtml.= '</div>';
1793
                    $friendHtml.= '</li>';
1794
                }
1795
                $j++;
1796
            }
1797
            $friendHtml.='</ul>';
1798 View Code Duplication
        } else {
1799
            $friendHtml.= '<div class="">'.get_lang('NoFriendsInYourContactList').'<br />'
1800
                .'<a class="btn btn-primary" href="'.api_get_path(WEB_PATH).'whoisonline.php"><em class="fa fa-search"></em> '. get_lang('TryAndFindSomeFriends').'</a></div>';
1801
        }
1802
1803
        $friendHtml = Display::panel($friendHtml, get_lang('SocialFriend').' (' . $number_friends . ')' );
1804
1805
        return $friendHtml;
1806
    }
1807
1808
    /**
1809
     * @param int $user_id
1810
     * @param $link_shared
1811
     * @param $show_full_profile
1812
     * @return string
1813
     */
1814
    public static function listMyFriendsBlock($user_id, $link_shared, $show_full_profile)
1815
    {
1816
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1817
        $friends = SocialManager::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
1818
        $number_of_images = 30;
1819
        $number_friends = count($friends);
1820
        $friendHtml = '';
1821
1822
        if ($number_friends != 0) {
1823
1824
            $friendHtml.= '<div class="list-group">';
1825
            $j = 1;
1826
            for ($k=0; $k < $number_friends; $k++) {
1827
                if ($j > $number_of_images) break;
1828
1829
                if (isset($friends[$k])) {
1830
                    $friend = $friends[$k];
1831
                    $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
1832
                    $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
1833
1834
                    if ($user_info_friend['user_is_online']) {
1835
                        $statusIcon = Display::return_icon('statusonline.png',get_lang('Online'));
1836
                        $status=1;
1837
                    } else {
1838
                        $statusIcon = Display::return_icon('statusoffline.png',get_lang('Offline'));
1839
                        $status=0;
1840
                    }
1841
1842
                    $friendAvatarMedium = UserManager::getUserPicture($friend['friend_user_id'], USER_IMAGE_SIZE_MEDIUM);
1843
                    $friendAvatarSmall = UserManager::getUserPicture($friend['friend_user_id'], USER_IMAGE_SIZE_SMALL);
1844
                    $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
1845
                    $showLinkToChat = api_is_global_chat_enabled() &&
1846
                        $friend['friend_user_id'] != api_get_user_id();
1847
1848
                    if ($showLinkToChat){
1849
                        $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
1850
                        $friendHtml .=  $friend_avatar.' <span class="username">' . $name_user . '</span>';
1851
                        $friendHtml .= '<span class="status">' . $statusIcon . '</span>';
1852
                    } else {
1853
                        $link_shared = (empty($link_shared)) ? '' : '&'.$link_shared;
1854
                        $friendHtml .= '<a href="profile.php?' .'u=' . $friend['friend_user_id'] . $link_shared . '" class="list-group-item">';
1855
                        $friendHtml .=  $friend_avatar.' <span class="username-all">' . $name_user . '</span>';
1856
                    }
1857
1858
                    $friendHtml .= '</a>';
1859
                }
1860
                $j++;
1861
            }
1862
            $friendHtml.='</div>';
1863 View Code Duplication
        } else {
1864
            $friendHtml.= '<div class="help">'.get_lang('NoFriendsInYourContactList').' '
1865
                .'<a href="'.api_get_path(WEB_PATH).'whoisonline.php"><em class="fa fa-search"></em> '. get_lang('TryAndFindSomeFriends').'</a></div>';
1866
        }
1867
1868
        return $friendHtml;
1869
    }
1870
1871
    /**
1872
     * @return string
1873
     */
1874
    public static function getWallForm($show_full_profile = true)
1875
    {
1876
        if ($show_full_profile) {
1877
            $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
1878
            $form = new FormValidator(
1879
                'social_wall_main',
1880
                'post',
1881
                api_get_path(WEB_CODE_PATH).'social/profile.php'.$userId,
1882
                null,
1883
                array('enctype' => 'multipart/form-data') ,
1884
                FormValidator::LAYOUT_HORIZONTAL    
1885
            );
1886
1887
            $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang('SocialWallWhatAreYouThinkingAbout');
1888
1889
            $form->addTextarea(
1890
                'social_wall_new_msg_main',
1891
                null,
1892
                [
1893
                    'placeholder' => $socialWallPlaceholder,
1894
                    'cols-size' => [1, 10, 1]
1895
                ]
1896
            );
1897
            $form->addHidden('url_content', '');
1898
            $form->addButtonSend(get_lang('Post'), 'wall_post_button', false, ['cols-size' => [1, 10, 1]]);
1899
            $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
1900
1901
            return $html;
1902
        }
1903
    }
1904
1905
    /**
1906
     * @param int $userId
1907
     * @param int $friendId
1908
     * @return string
1909
     */
1910
    public static function getWallMessagesByUser($userId, $friendId)
1911
    {
1912
        $messages = SocialManager::getWallMessagesPostHTML($userId, $friendId);
1913
        $html = '';
1914
1915
        foreach ($messages as $message) {
1916
            $post = $message['html'];
1917
            $comment = SocialManager::getWallMessagesHTML($userId, $friendId, $message['id']);
1918
1919
            $html .= $post.$comment;
1920
        }
1921
1922
        return $html;
1923
    }
1924
1925
    /**
1926
     * Get HTML code block for user skills
1927
     * @param int $userId The user ID
1928
     * @return string
1929
     */
1930
    public static function getSkillBlock($userId)
1931
    {
1932
        if (api_get_setting('allow_skills_tool') !== 'true') {
1933
            return null;
1934
        }
1935
1936
        $skill = new Skill();
1937
1938
        $ranking = $skill->get_user_skill_ranking($userId);
1939
        $skills = $skill->get_user_skills($userId, true);
1940
1941
        $template = new Template(null, false, false, false, false, false);
1942
        $template->assign('ranking', $ranking);
1943
        $template->assign('skills', $skills);
1944
        $template->assign('user_id', $userId);
1945
        $template->assign(
1946
            'show_skills_report_link',
1947
            api_is_student() || api_is_student_boss() || api_is_drh()
1948
        );
1949
1950
        $skillBlock = $template->get_template('social/skills_block.tpl');
1951
1952
        return $template->fetch($skillBlock);
1953
    }
1954
}
1955