Completed
Push — 1.11.x ( 3fe7c1...e0a156 )
by José
63:55 queued 32:00
created

SocialManager::get_logged_user_course_html()   D

Complexity

Conditions 13
Paths 120

Size

Total Lines 90
Code Lines 59

Duplication

Lines 6
Ratio 6.67 %

Importance

Changes 0
Metric Value
cc 13
eloc 59
nc 120
nop 2
dl 6
loc 90
rs 4.6605
c 0
b 0
f 0

How to fix   Long Method    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
/* For licensing terms, see /license.txt */
3
4
use Zend\Feed\Reader\Reader;
5
use Zend\Feed\Reader\Entry\Rss;
6
7
/**
8
 * Class SocialManager
9
 *
10
 * This class provides methods for the social network management.
11
 * Include/require it in your code to use its features.
12
 *
13
 * @package chamilo.social
14
 */
15
class SocialManager extends UserManager
16
{
17
    /**
18
     * Constructor
19
     */
20
    public function __construct()
21
    {
22
23
    }
24
25
    /**
26
     * Allow to see contacts list
27
     * @author isaac flores paz
28
     * @return array
29
     */
30 View Code Duplication
    public static function show_list_type_friends()
31
    {
32
        $friend_relation_list = array();
33
        $tbl_my_friend_relation_type = Database :: get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
34
        $sql = 'SELECT id,title FROM '.$tbl_my_friend_relation_type.'
35
                WHERE id<>6 ORDER BY id ASC';
36
        $result = Database::query($sql);
37
        while ($row = Database::fetch_array($result, 'ASSOC')) {
38
            $friend_relation_list[] = $row;
39
        }
40
        $count_list = count($friend_relation_list);
41
        if ($count_list == 0) {
42
            $friend_relation_list[] = get_lang('Unknown');
43
        } else {
44
            return $friend_relation_list;
45
        }
46
    }
47
48
    /**
49
     * Get relation type contact by name
50
     * @param string names of the kind of relation
51
     * @return int
52
     * @author isaac flores paz
53
     */
54
    public static function get_relation_type_by_name($relation_type_name)
55
    {
56
        $list_type_friend = self::show_list_type_friends();
57
        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...
58
            if (strtolower($value_type_friend['title']) == $relation_type_name) {
59
60
                return $value_type_friend['id'];
61
            }
62
        }
63
    }
64
65
    /**
66
     * Get the kind of relation between contacts
67
     * @param int user id
68
     * @param int user friend id
69
     * @param string
70
     * @author isaac flores paz
71
     */
72
    public static function get_relation_between_contacts($user_id, $user_friend)
73
    {
74
        $tbl_my_friend_relation_type = Database :: get_main_table(TABLE_MAIN_USER_FRIEND_RELATION_TYPE);
75
        $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
76
        $sql = 'SELECT rt.id as id FROM '.$tbl_my_friend_relation_type.' rt
77
                WHERE rt.id = (
78
                    SELECT uf.relation_type FROM '.$tbl_my_friend.' uf
79
                    WHERE
80
                        user_id='.((int) $user_id).' AND
81
                        friend_user_id='.((int) $user_friend).' AND
82
                        uf.relation_type <> '.USER_RELATION_TYPE_RRHH.'
83
                    LIMIT 1
84
                )';
85
        $res = Database::query($sql);
86
        if (Database::num_rows($res) > 0) {
87
            $row = Database::fetch_array($res, 'ASSOC');
88
89
            return $row['id'];
90
        } else {
91
            return USER_UNKNOW;
92
        }
93
    }
94
95
    /**
96
     * Gets friends id list
97
     * @param int  user id
98
     * @param int group id
99
     * @param string name to search
100
     * @param bool true will load firstname, lastname, and image name
101
     * @return array
102
     * @author Julio Montoya <[email protected]> Cleaning code, function renamed, $load_extra_info option added
103
     * @author isaac flores paz
104
     */
105
    public static function get_friends($user_id, $id_group = null, $search_name = null, $load_extra_info = true)
106
    {
107
        $list_ids_friends = array();
108
        $tbl_my_friend = Database :: get_main_table(TABLE_MAIN_USER_REL_USER);
109
        $tbl_my_user = Database :: get_main_table(TABLE_MAIN_USER);
110
        $sql = 'SELECT friend_user_id FROM '.$tbl_my_friend.'
111
                WHERE
112
                    relation_type NOT IN ('.USER_RELATION_TYPE_DELETED.', '.USER_RELATION_TYPE_RRHH.') AND
113
                    friend_user_id<>'.((int) $user_id).' AND
114
                    user_id='.((int) $user_id);
115
        if (isset($id_group) && $id_group > 0) {
116
            $sql.=' AND relation_type='.$id_group;
117
        }
118
        if (isset($search_name)) {
119
            $search_name = trim($search_name);
120
            $search_name = str_replace(' ', '', $search_name);
121
            $sql.=' AND friend_user_id IN (
122
                SELECT user_id FROM '.$tbl_my_user.'
123
                WHERE
124
                    firstName LIKE "%'.Database::escape_string($search_name).'%" OR
125
                    lastName LIKE "%'.Database::escape_string($search_name).'%" OR
126
                    '.(api_is_western_name_order() ? 'concat(firstName, lastName)' : 'concat(lastName, firstName)').' LIKE concat("%","'.Database::escape_string($search_name).'","%")
127
                ) ';
128
        }
129
130
        $res = Database::query($sql);
131
        while ($row = Database::fetch_array($res, 'ASSOC')) {
132
            if ($load_extra_info) {
133
                $my_user_info = api_get_user_info($row['friend_user_id']);
134
                $list_ids_friends[] = array(
135
                    'friend_user_id' => $row['friend_user_id'],
136
                    'firstName' => $my_user_info['firstName'],
137
                    'lastName' => $my_user_info['lastName'],
138
                    'username' => $my_user_info['username'],
139
                    'image' => $my_user_info['avatar'],
140
                );
141
            } else {
142
                $list_ids_friends[] = $row;
143
            }
144
        }
145
146
        return $list_ids_friends;
147
    }
148
149
    /**
150
     * get web path of user invitate
151
     * @author isaac flores paz
152
     * @author Julio Montoya setting variable array
153
     * @param int user id
154
     *
155
     * @return array
156
     */
157
    public static function get_list_web_path_user_invitation_by_user_id($user_id)
158
    {
159
        $list_ids = self::get_list_invitation_of_friends_by_user_id($user_id);
160
        $list = array();
161
        foreach ($list_ids as $values_ids) {
162
            $list[] = UserManager::get_user_picture_path_by_id(
163
                $values_ids['user_sender_id'],
164
                'web'
165
            );
166
        }
167
168
        return $list;
169
    }
170
171
    /**
172
     * Sends an invitation to contacts
173
     * @param int user id
174
     * @param int user friend id
175
     * @param string title of the message
176
     * @param string content of the message
177
     * @return boolean
178
     * @author isaac flores paz
179
     * @author Julio Montoya <[email protected]> Cleaning code
180
     */
181
    public static function send_invitation_friend($user_id, $friend_id, $message_title, $message_content)
182
    {
183
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
184
        $user_id = intval($user_id);
185
        $friend_id = intval($friend_id);
186
187
        //Just in case we replace the and \n and \n\r while saving in the DB
188
        $message_content = str_replace(array("\n", "\n\r"), '<br />', $message_content);
189
190
        $clean_message_content = Database::escape_string($message_content);
191
192
        $now = api_get_utc_datetime();
193
194
        $sql = 'SELECT COUNT(*) AS count FROM '.$tbl_message.'
195
                WHERE
196
                    user_sender_id='.$user_id.' AND
197
                    user_receiver_id='.$friend_id.' AND
198
                    msg_status IN('.MESSAGE_STATUS_INVITATION_PENDING.', '.MESSAGE_STATUS_INVITATION_ACCEPTED.', '.MESSAGE_STATUS_INVITATION_DENIED.');
199
                ';
200
        $res_exist = Database::query($sql);
201
        $row_exist = Database::fetch_array($res_exist, 'ASSOC');
202
203
        if ($row_exist['count'] == 0) {
204
205
            $params = [
206
                'user_sender_id' => $user_id,
207
                'user_receiver_id' => $friend_id,
208
                'msg_status' => MESSAGE_STATUS_INVITATION_PENDING,
209
                'send_date' => $now,
210
                'title' => $message_title,
211
                'content'  => $message_content,
212
                'group_id' => 0,
213
                'parent_id' => 0,
214
                'update_date' => $now
215
            ];
216
            Database::insert($tbl_message, $params);
217
218
            $sender_info = api_get_user_info($user_id);
219
            $notification = new Notification();
220
            $notification->save_notification(
221
                Notification::NOTIFICATION_TYPE_INVITATION,
222
                array($friend_id),
223
                $message_title,
224
                $message_content,
225
                $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 218 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...
226
            );
227
228
            return true;
229
        } else {
230
            // invitation already exist
231
            $sql = 'SELECT COUNT(*) AS count, id FROM '.$tbl_message.'
232
                    WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7';
233
            $res_if_exist = Database::query($sql);
234
            $row_if_exist = Database::fetch_array($res_if_exist, 'ASSOC');
235
            if ($row_if_exist['count'] == 1) {
236
                $sql = 'UPDATE '.$tbl_message.' SET
237
                        msg_status=5, content = "'.$clean_message_content.'"
238
                        WHERE user_sender_id='.$user_id.' AND user_receiver_id='.$friend_id.' AND msg_status = 7 ';
239
                Database::query($sql);
240
                return true;
241
            } else {
242
                return false;
243
            }
244
        }
245
    }
246
247
    /**
248
     * Get number messages of the inbox
249
     * @author isaac flores paz
250
     * @param int user receiver id
251
     * @return int
252
     */
253 View Code Duplication
    public static function get_message_number_invitation_by_user_id($user_receiver_id)
254
    {
255
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
256
        $sql = 'SELECT COUNT(*) as count_message_in_box FROM '.$tbl_message.'
257
                WHERE
258
                    user_receiver_id='.intval($user_receiver_id).' AND
259
                    msg_status='.MESSAGE_STATUS_INVITATION_PENDING;
260
        $res = Database::query($sql);
261
        $row = Database::fetch_array($res, 'ASSOC');
262
263
        return $row['count_message_in_box'];
264
    }
265
266
    /**
267
     * Get invitation list received by user
268
     * @author isaac flores paz
269
     * @param int user id
270
     * @return array
271
     */
272 View Code Duplication
    public static function get_list_invitation_of_friends_by_user_id($user_id)
273
    {
274
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
275
        $sql = 'SELECT user_sender_id, send_date, title, content
276
                FROM '.$tbl_message.'
277
                WHERE
278
                    user_receiver_id = '.intval($user_id).' AND
279
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
280
        $res = Database::query($sql);
281
        $list_friend_invitation = array();
282
        while ($row = Database::fetch_array($res, 'ASSOC')) {
283
            $list_friend_invitation[] = $row;
284
        }
285
286
        return $list_friend_invitation;
287
    }
288
289
    /**
290
     * Get invitation list sent by user
291
     * @author Julio Montoya <[email protected]>
292
     * @param int user id
293
     * @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...
294
     */
295 View Code Duplication
    public static function get_list_invitation_sent_by_user_id($user_id)
296
    {
297
        $list_friend_invitation = array();
298
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
299
        $sql = 'SELECT user_receiver_id, send_date,title,content
300
                FROM '.$tbl_message.'
301
                WHERE
302
                    user_sender_id = '.intval($user_id).' AND
303
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
304
        $res = Database::query($sql);
305
        while ($row = Database::fetch_array($res, 'ASSOC')) {
306
            $list_friend_invitation[$row['user_receiver_id']] = $row;
307
        }
308
309
        return $list_friend_invitation;
310
    }
311
312
    /**
313
     * Accepts invitation
314
     * @param int $user_send_id
315
     * @param int $user_receiver_id
316
     * @author isaac flores paz
317
     * @author Julio Montoya <[email protected]> Cleaning code
318
     */
319
    public static function invitation_accepted($user_send_id, $user_receiver_id)
320
    {
321
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
322
        $sql = "UPDATE $tbl_message
323
                SET msg_status = ".MESSAGE_STATUS_INVITATION_ACCEPTED."
324
                WHERE
325
                    user_sender_id = ".((int) $user_send_id)." AND
326
                    user_receiver_id=".((int) $user_receiver_id)." AND
327
                    msg_status = ".MESSAGE_STATUS_INVITATION_PENDING;
328
        Database::query($sql);
329
    }
330
331
    /**
332
     * Denies invitation
333
     * @param int user sender id
334
     * @param int user receiver id
335
     * @author isaac flores paz
336
     * @author Julio Montoya <[email protected]> Cleaning code
337
     */
338
    public static function invitation_denied($user_send_id, $user_receiver_id)
339
    {
340
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
341
        $sql = 'DELETE FROM '.$tbl_message.'
342
                WHERE
343
                    user_sender_id =  '.((int) $user_send_id).' AND
344
                    user_receiver_id='.((int) $user_receiver_id).' AND
345
                    msg_status = '.MESSAGE_STATUS_INVITATION_PENDING;
346
        Database::query($sql);
347
    }
348
349
    /**
350
     * allow attach to group
351
     * @author isaac flores paz
352
     * @param int user to qualify
353
     * @param int kind of rating
354
     * @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...
355
     */
356 View Code Duplication
    public static function qualify_friend($id_friend_qualify, $type_qualify)
357
    {
358
        $tbl_user_friend = Database::get_main_table(TABLE_MAIN_USER_REL_USER);
359
        $user_id = api_get_user_id();
360
        $sql = 'UPDATE '.$tbl_user_friend.' SET relation_type='.((int) $type_qualify).'
361
                WHERE user_id = '.((int) $user_id).' AND friend_user_id='.(int) $id_friend_qualify;
362
        Database::query($sql);
363
    }
364
365
    /**
366
     * Get user's feeds
367
     * @param   int User ID
368
     * @param   int Limit of posts per feed
369
     * @return  string  HTML section with all feeds included
370
     * @author  Yannick Warnier
371
     * @since   Dokeos 1.8.6.1
372
     */
373
    public static function get_user_feeds($user, $limit = 5)
374
    {
375
        $feed = UserManager::get_extra_user_data_by_field($user, 'rssfeeds');
376
377
        if (empty($feed)) {
378
            return '';
379
        }
380
        $feeds = explode(';', $feed['rssfeeds']);
381
        if (count($feeds) == 0) {
382
            return '';
383
        }
384
        $res = '';
385
386
        foreach ($feeds as $url) {
387
            if (empty($url)) {
388
                continue;
389
            }
390
            $channel = Reader::import($url);
391
392
            $i = 1;
393
            if (!empty($channel)) {
394
                $icon_rss = '';
395
                if (!empty($feed)) {
396
                    $icon_rss = Display::url(
397
                        Display::return_icon('social_rss.png', '', array(), 22),
398
                        Security::remove_XSS($feed['rssfeeds']),
399
                        array('target' => '_blank')
400
                    );
401
                }
402
403
                $res .= '<h3 class="title-rss">'.$icon_rss.' '.$channel->getTitle().'</h3>';
404
                $res .= '<div class="rss-items">';
405
                /** @var Rss $item */
406
                foreach ($channel as $item) {
0 ignored issues
show
Bug introduced by
The expression $channel of type object<Zend\Feed\Reader\...d\Feed\Reader\Feed\Rss> 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...
407
                    if ($limit >= 0 and $i > $limit) {
408
                        break;
409
                    }
410
                    $res .= '<h4 class="rss-title"><a href="'.$item->getLink().'">'.$item->getTitle().'</a></h4>';
411
                    $res .= '<div class="rss-date">'.api_get_local_time($item->getDateCreated()).'</div>';
412
                    $res .= '<div class="rss-content"><p>'.$item->getDescription().'</p></div>';
413
                    $i++;
414
                }
415
                $res .= '</div>';
416
            }
417
        }
418
419
        return $res;
420
    }
421
422
    /**
423
     * Sends invitations to friends
424
     *
425
     * @param int  $userId
426
     * @param string $subject
427
     * @param string $content
428
     *
429
     * @return string message invitation
430
     */
431
    public static function sendInvitationToUser($userId, $subject = '', $content = '')
432
    {
433
        $user_info = api_get_user_info($userId);
434
        $success = get_lang('MessageSentTo');
435
        $success.= ' : '.api_get_person_name($user_info['firstName'], $user_info['lastName']);
436
437
        if (isset($subject) && isset($content) && isset($userId)) {
438
            $result = MessageManager::send_message($userId, $subject, $content);
439
440
            if ($result) {
441
                Display::addFlash(
442
                    Display::return_message($success, 'normal', false)
443
                );
444
            } else {
445
                Display::addFlash(
446
                    Display::return_message(get_lang('ErrorSendingMessage'), 'error', false)
447
                );
448
            }
449
            return false;
450
        } elseif (isset($userId) && !isset($subject)) {
451
            if (isset($userId) && $userId > 0) {
452
453
                $count = self::send_invitation_friend(
454
                    api_get_user_id(),
455
                    $userId,
456
                    get_lang('Invitation'),
457
                    $content
458
                );
459
460 View Code Duplication
                if ($count) {
461
                    Display::addFlash(
462
                        Display::return_message(
463
                            api_htmlentities(get_lang('InvitationHasBeenSent')),
464
                            'normal',
465
                            false
466
                        )
467
                    );
468
                } else {
469
                    Display::addFlash(
470
                        Display::return_message(
471
                            api_htmlentities(get_lang('YouAlreadySentAnInvitation')),
472
                            'warning',
473
                            false
474
                        )
475
                    );
476
                }
477
            }
478
        }
479
    }
480
481
    /**
482
     * Helper functions definition
483
     */
484
    public static function get_logged_user_course_html($my_course, $count)
485
    {
486
        $result = '';
487
        // Table definitions
488
        $main_user_table = Database :: get_main_table(TABLE_MAIN_USER);
489
        $tbl_session = Database :: get_main_table(TABLE_MAIN_SESSION);
490
491
        $course_code = $my_course['code'];
492
        $course_directory = $my_course['course_info']['directory'];
493
        $course_title = $my_course['course_info']['title'];
494
        $course_access_settings = CourseManager :: get_access_settings($course_code);
495
496
        $course_visibility = $course_access_settings['visibility'];
497
498
        $user_in_course_status = CourseManager :: get_user_in_course_status(api_get_user_id(), $course_code);
499
500
        //$valor = api_get_settings_params();
501
        $course_path = api_get_path(SYS_COURSE_PATH).$course_directory;   // course path
502
        if (api_get_setting('course_images_in_courses_list') === 'true') {
503
            if (file_exists($course_path.'/course-pic85x85.png')) {
504
                $image = $my_course['course_info']['course_image'];
505
                $imageCourse = Display::img($image, $course_title, array('class'=>'img-course'));
506
            } else {
507
                $imageCourse = Display::return_icon(
508
                    'session_default_small.png',
509
                    $course_title,
510
                    array('class' => 'img-course')
511
                );
512
            }
513
        } else {
514
            $imageCourse = Display::return_icon('course.png', get_lang('Course'), array('class' => 'img-default'));
515
        }
516
517
        //display course entry
518
        if (api_get_setting('course_images_in_courses_list') === 'true') {
519
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:65px;">';
520
        } else {
521
            $result .= '<li id="course_'.$count.'" class="list-group-item" style="min-height:44px;">';
522
        }
523
        $result .= $imageCourse;
524
525
        //show a hyperlink to the course, unless the course is closed and user is not course admin
526
        if ($course_visibility != COURSE_VISIBILITY_HIDDEN &&
527
            ($course_visibility != COURSE_VISIBILITY_CLOSED || $user_in_course_status == COURSEMANAGER)
528
        ) {
529
           $result .= '<span class="title">' . $course_title . '<span>';
530
        } else {
531
            $result .= $course_title." ".get_lang('CourseClosed');
532
        }
533
534
        $result .= '</li>';
535
536
537
        $session = '';
538
        if (!empty($my_course['session_name']) && !empty($my_course['id_session'])) {
539
540
            // Request for the name of the general coach
541
            $sql = 'SELECT lastname, firstname
542
                    FROM '.$tbl_session.' ts
543
                    LEFT JOIN '.$main_user_table.' tu
544
                    ON ts.id_coach = tu.user_id
545
                    WHERE ts.id='.(int) $my_course['id_session'].' LIMIT 1';
546
            $rs = Database::query($sql);
547
            $sessioncoach = Database::store_result($rs);
548
            $sessioncoach = $sessioncoach[0];
549
550
            $session = array();
551
            $session['title'] = $my_course['session_name'];
552
            if ($my_course['access_start_date'] == '0000-00-00') {
553
                $session['dates'] = get_lang('WithoutTimeLimits');
554 View Code Duplication
                if (api_get_setting('show_session_coach') === 'true') {
555
                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
556
                }
557
            } else {
558
                $session ['dates'] = ' - '.get_lang('From').' '.$my_course['access_start_date'].' '.get_lang('To').' '.$my_course['access_end_date'];
559 View Code Duplication
                if (api_get_setting('show_session_coach') === 'true') {
560
                    $session['coach'] = get_lang('GeneralCoach').': '.api_get_person_name($sessioncoach['firstname'], $sessioncoach['lastname']);
561
                }
562
            }
563
        }
564
        $my_course['id_session'] = isset($my_course['id_session']) ? $my_course['id_session'] : 0;
565
        $output = array(
566
            $my_course['user_course_cat'],
567
            $result,
568
            $my_course['id_session'],
569
            $session
570
        );
571
572
        return $output;
573
    }
574
575
    /**
576
     * Shows the avatar block in social pages
577
     *
578
     * @param string $show highlight link possible values:
579
     * group_add,
580
     * home,
581
     * messages,
582
     * messages_inbox,
583
     * messages_compose,
584
     * messages_outbox,
585
     * invitations,
586
     * shared_profile,
587
     * friends,
588
     * groups search
589
     * @param int $group_id
590
     * @param int $user_id
591
     *
592
     */
593
    public static function show_social_avatar_block($show = '', $group_id = 0, $user_id = 0)
594
    {
595
        if (empty($user_id)) {
596
            $user_id = api_get_user_id();
597
        }
598
599
        $show_groups = array(
600
            'groups',
601
            'group_messages',
602
            'messages_list',
603
            'group_add',
604
            'mygroups',
605
            'group_edit',
606
            'member_list',
607
            'invite_friends',
608
            'waiting_list',
609
            'browse_groups',
610
        );
611
612
        $template = new Template(null, false, false, false, false, false);
613
614
        if (in_array($show, $show_groups) && !empty($group_id)) {
615
            // Group image
616
            $userGroup = new UserGroup();
617
618
            $group_info = $userGroup->get($group_id);
619
620
            $userGroupImage = $userGroup->get_picture_group(
621
                $group_id,
622
                $group_info['picture'],
623
                128,
624
                GROUP_IMAGE_SIZE_BIG
625
            );
626
627
            $template->assign('show_group', true);
628
            $template->assign('group_id', $group_id);
629
            $template->assign('user_group_image', $userGroupImage);
630
            //$template->assign('user_group', $group_info);
631
            $template->assign(
632
                'user_is_group_admin',
633
                $userGroup->is_group_admin(
634
                    $group_id,
635
                    api_get_user_id()
636
                )
637
            );
638
        } else {
639
            $template->assign('show_user', true);
640
            $template->assign(
641
                'user_image',
642
                [
643
                    'big' => UserManager::getUserPicture(
644
                        $user_id,
645
                        USER_IMAGE_SIZE_BIG
646
                    ),
647
                    'normal' => UserManager::getUserPicture(
648
                        $user_id,
649
                        USER_IMAGE_SIZE_MEDIUM
650
                    )
651
                ]
652
            );
653
        }
654
655
        $skillBlock = $template->get_template('social/avatar_block.tpl');
656
657
        return $template->fetch($skillBlock);
658
    }
659
660
    /**
661
     * Shows the right menu of the Social Network tool
662
     *
663
     * @param string $show highlight link possible values:
664
     * group_add,
665
     * home,
666
     * messages,
667
     * messages_inbox,
668
     * messages_compose ,
669
     * messages_outbox,
670
     * invitations,
671
     * shared_profile,
672
     * friends,
673
     * groups search
674
     * @param int $group_id group id
675
     * @param int $user_id user id
676
     * @param bool $show_full_profile show profile or not (show or hide the user image/information)
677
     * @param bool $show_delete_account_button
678
     *
679
     */
680
    public static function show_social_menu(
681
        $show = '',
682
        $group_id = 0,
683
        $user_id = 0,
684
        $show_full_profile = false,
685
        $show_delete_account_button = false
686
    ) {
687
        if (empty($user_id)) {
688
            $user_id = api_get_user_id();
689
        }
690
691
        $usergroup = new UserGroup();
692
        $show_groups = array(
693
            'groups',
694
            'group_messages',
695
            'messages_list',
696
            'group_add',
697
            'mygroups',
698
            'group_edit',
699
            'member_list',
700
            'invite_friends',
701
            'waiting_list',
702
            'browse_groups',
703
        );
704
705
        // get count unread message and total invitations
706
        $count_unread_message = MessageManager::get_number_of_messages(true);
707
        $count_unread_message = !empty($count_unread_message) ? Display::badge($count_unread_message) : null;
708
709
        $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id(api_get_user_id());
710
        $group_pending_invitations = $usergroup->get_groups_by_user(
711
            api_get_user_id(),
712
            GROUP_USER_PERMISSION_PENDING_INVITATION,
713
            false
714
        );
715
        $group_pending_invitations = count($group_pending_invitations);
716
        $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
717
        $total_invitations = (!empty($total_invitations) ? Display::badge($total_invitations) : '');
718
719
        $filesIcon = Display::return_icon('sn-files.png', get_lang('MyFiles'), '', ICON_SIZE_SMALL);
720
        $friendsIcon = Display::return_icon('sn-friends.png', get_lang('Friends'), '', ICON_SIZE_SMALL);
721
        $groupsIcon = Display::return_icon('sn-groups.png', get_lang('SocialGroups'), '', ICON_SIZE_SMALL);
722
        $homeIcon = Display::return_icon('sn-home.png', get_lang('Home'), '', ICON_SIZE_SMALL);
723
        $invitationsIcon = Display::return_icon('sn-invitations.png', get_lang('Invitations'), '', ICON_SIZE_SMALL);
724
        $messagesIcon = Display::return_icon('sn-message.png', get_lang('Messages'), '', ICON_SIZE_SMALL);
725
        $sharedProfileIcon = Display::return_icon('sn-profile.png', get_lang('ViewMySharedProfile'));
726
        $searchIcon = Display::return_icon('sn-search.png', get_lang('Search'), '', ICON_SIZE_SMALL);
727
728
        $html = '';
729
        $active = null;
730
        if (!in_array(
731
            $show,
732
            array('shared_profile', 'groups', 'group_edit', 'member_list', 'waiting_list', 'invite_friends')
733
        )) {
734
            $links = '<ul class="nav nav-pills nav-stacked">';
735
            $active = $show == 'home' ? 'active' : null;
736
            $links .= '
737
                <li class="home-icon ' . $active . '">
738
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/home.php">
739
                        ' . $homeIcon . ' ' . get_lang('Home') . '
740
                    </a>
741
                </li>';
742
            $active = $show == 'messages' ? 'active' : null;
743
            $links .= '
744
                <li class="messages-icon ' . $active . '">
745
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'messages/inbox.php?f=social">
746
                        ' . $messagesIcon . ' ' . get_lang('Messages') . $count_unread_message . '
747
                    </a>
748
                </li>';
749
750
            //Invitations
751
            $active = $show == 'invitations' ? 'active' : null;
752
            $links .= '
753
                <li class="invitations-icon ' . $active . '">
754
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/invitations.php">
755
                        ' . $invitationsIcon . ' ' . get_lang('Invitations') . $total_invitations . '
756
                    </a>
757
                </li>';
758
759
            //Shared profile and groups
760
            $active = $show == 'shared_profile' ? 'active' : null;
761
            $links .= '
762
                <li class="shared-profile-icon' . $active . '">
763
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/profile.php">
764
                        ' . $sharedProfileIcon . ' ' . get_lang('ViewMySharedProfile') . '
765
                    </a>
766
                </li>';
767
            $active = $show == 'friends' ? 'active' : null;
768
            $links .= '
769
                <li class="friends-icon ' . $active . '">
770
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/friends.php">
771
                        ' . $friendsIcon . ' ' . get_lang('Friends') . '
772
                    </a>
773
                </li>';
774
            $active = $show == 'browse_groups' ? 'active' : null;
775
            $links .= '
776
                <li class="browse-groups-icon ' . $active . '">
777
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/groups.php">
778
                        ' . $groupsIcon . ' ' . get_lang('SocialGroups') . '
779
                    </a>
780
                </li>';
781
782
            //Search users
783
            $active = $show == 'search' ? 'active' : null;
784
            $links .= '
785
                <li class="search-icon ' . $active . '">
786
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/search.php">
787
                        ' . $searchIcon . ' ' . get_lang('Search') . '
788
                    </a>
789
                </li>';
790
791
            //My files
792
            $active = $show == 'myfiles' ? 'active' : null;
793
794
            $myFiles = '
795
                <li class="myfiles-icon ' . $active . '">
796
                    <a href="' . api_get_path(WEB_CODE_PATH) . 'social/myfiles.php">
797
                        ' . $filesIcon . ' ' . get_lang('MyFiles') . '
798
                    </a>
799
                </li>';
800
801
            if (api_get_setting('allow_my_files') === 'false') {
802
                $myFiles = '';
803
            }
804
            $links .= $myFiles;
805
            $links .='</ul>';
806
807
            $html .= Display::panelCollapse(
808
                get_lang('SocialNetwork'),
809
                $links,
810
                'social-network-menu',
811
                null,
812
                'sn-sidebar',
813
                'sn-sidebar-collapse'
814
            );
815
        }
816
817
        if (in_array($show, $show_groups) && !empty($group_id)) {
818
            $html .= $usergroup->show_group_column_information(
819
                $group_id,
820
                api_get_user_id(),
821
                $show
822
            );
823
        }
824
825
        if ($show == 'shared_profile') {
826
            $links =  '<ul class="nav nav-pills nav-stacked">';
827
            // My own profile
828
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
829
                $links .= '
830
                    <li class="home-icon ' . $active . '">
831
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/home.php">
832
                            ' . $homeIcon . ' ' . get_lang('Home') . '
833
                        </a>
834
                    </li>
835
                    <li class="messages-icon ' . $active . '">
836
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'messages/inbox.php?f=social">
837
                            ' . $messagesIcon . ' ' . get_lang('Messages') . $count_unread_message . '
838
                        </a>
839
                    </li>';
840
                $active = $show == 'invitations' ? 'active' : null;
841
                $links .= '
842
                    <li class="invitations-icon' . $active . '">
843
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/invitations.php">
844
                            ' . $invitationsIcon . ' ' . get_lang('Invitations') . $total_invitations . '
845
                        </a>
846
                    </li>';
847
848
                $links .= '
849
                    <li class="shared-profile-icon active">
850
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/profile.php">
851
                            ' . $sharedProfileIcon . ' ' . get_lang('ViewMySharedProfile') . '
852
                        </a>
853
                    </li>
854
                    <li class="friends-icon">
855
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/friends.php">
856
                            ' . $friendsIcon . ' ' . get_lang('Friends') . '
857
                        </a>
858
                    </li>
859
                    <li class="browse-groups-icon">
860
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/groups.php">
861
                            ' . $groupsIcon . ' ' . get_lang('SocialGroups') . '
862
                        </a>
863
                    </li>';
864
                $active = $show == 'search' ? 'active' : null;
865
                $links .= '
866
                    <li class="search-icon ' . $active . '">
867
                        <a href="' . api_get_path(WEB_CODE_PATH) . 'social/search.php">
868
                            ' . $searchIcon . ' ' . get_lang('Search') . '
869
                        </a>
870
                    </li>';
871
                $active = $show == 'myfiles' ? 'active' : null;
872
873
                $myFiles = '
874
                    <li class="myfiles-icon ' . $active . '">
875
                     <a href="' . api_get_path(WEB_CODE_PATH) . 'social/myfiles.php">
876
                            ' . $filesIcon . ' ' . get_lang('MyFiles') . '
877
                        </a>
878
                    </li>';
879
880
                if (api_get_setting('allow_my_files') === 'false') {
881
                    $myFiles = '';
882
                }
883
                $links .= $myFiles;
884
            }
885
886
            // My friend profile.
887
            if ($user_id != api_get_user_id()) {
888
                $sendMessageText = get_lang('SendMessage');
889
                $sendMessageIcon = Display::return_icon(
890
                    'new-message.png',
891
                    $sendMessageText
892
                );
893
                $sendMesssageUrl = api_get_path(WEB_AJAX_PATH)
894
                    . 'user_manager.ajax.php?'
895
                    . http_build_query([
896
                        'a' => 'get_user_popup',
897
                        'user_id' => $user_id,
898
                    ]);
899
900
                $links .= '<li>';
901
                $links .= Display::url(
902
                    "$sendMessageIcon $sendMessageText",
903
                    $sendMesssageUrl,
904
                    [
905
                        'class' => 'ajax',
906
                        'title' => $sendMessageText,
907
                        'data-title' => $sendMessageText,
908
                    ]
909
                );
910
                $links .= '</li>';
911
            }
912
913
            // Check if I already sent an invitation message
914
            $invitation_sent_list = SocialManager::get_list_invitation_sent_by_user_id(
915
                api_get_user_id()
916
            );
917
918
            if (isset($invitation_sent_list[$user_id]) && is_array($invitation_sent_list[$user_id]) && count($invitation_sent_list[$user_id]) > 0) {
919
                $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>';
920
            } else {
921
                if (!$show_full_profile) {
922
                    $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>';
923
                }
924
            }
925
926
            $links .= '</ul>';
927
            $html .= Display::panelCollapse(
928
                get_lang('SocialNetwork'),
929
                $links,
930
                'social-network-menu',
931
                null,
932
                'sn-sidebar',
933
                'sn-sidebar-collapse'
934
            );
935
936
            if ($show_full_profile && $user_id == intval(api_get_user_id())) {
937
                $personal_course_list = UserManager::get_personal_session_course_list($user_id);
938
                $course_list_code = array();
939
                $i = 1;
940
                if (is_array($personal_course_list)) {
941
                    foreach ($personal_course_list as $my_course) {
942
                        if ($i <= 10) {
943
                            $course_list_code[] = array('code' => $my_course['code']);
944
                        } else {
945
                            break;
946
                        }
947
                        $i++;
948
                    }
949
                    // To avoid repeated courses
950
                    $course_list_code = array_unique_dimensional($course_list_code);
951
                }
952
953
                // Announcements
954
                $my_announcement_by_user_id = intval($user_id);
955
                $announcements = array();
956
                foreach ($course_list_code as $course) {
957
                    $course_info = api_get_course_info($course['code']);
958
                    if (!empty($course_info)) {
959
                        $content = AnnouncementManager::get_all_annoucement_by_user_course(
960
                            $course_info['code'],
961
                            $my_announcement_by_user_id
962
                        );
963
964
                        if (!empty($content)) {
965
                            $url = Display::url(
966
                                Display::return_icon('announcement.png', get_lang('Announcements')).$course_info['name'].' ('.$content['count'].')',
967
                                api_get_path(WEB_CODE_PATH).'announcements/announcements.php?cidReq='.$course['code']
968
                            );
969
                            $announcements[] = Display::tag('li', $url);
970
                        }
971
                    }
972
                }
973
                if (!empty($announcements)) {
974
                    $html .= '<div class="social_menu_items">';
975
                    $html .= '<ul>';
976
                    foreach ($announcements as $announcement) {
977
                        $html .= $announcement;
978
                    }
979
                    $html .= '</ul>';
980
                    $html .= '</div>';
981
                }
982
            }
983
        }
984
985
        if ($show_delete_account_button) {
986
            $html .= '<div class="panel panel-default"><div class="panel-body">';
987
            $html .= '<ul class="nav nav-pills nav-stacked"><li>';
988
            $url = api_get_path(WEB_CODE_PATH).'auth/unsubscribe_account.php';
989
            $html .= Display::url(
990
                Display::return_icon(
991
                    'delete.png',
992
                    get_lang('Unsubscribe'),
993
                    array(),
994
                    ICON_SIZE_TINY
995
                ).get_lang('Unsubscribe'),
996
                $url
997
            );
998
            $html .= '</li></ul>';
999
            $html .= '</div></div>';
1000
        }
1001
        $html .= '';
1002
1003
        return $html;
1004
    }
1005
1006
    /**
1007
     * Displays a sortable table with the list of online users.
1008
     * @param array $user_list The list of users to be shown
1009
     * @param bool $wrap Whether we want the function to wrap the spans list in a div or not
1010
     * @return string HTML block or null if and ID was defined
1011
     * @assert (null) === false
1012
     */
1013
    public static function display_user_list($user_list, $wrap = true)
1014
    {
1015
        $html = null;
1016
1017
        if (isset($_GET['id']) or count($user_list) < 1) {
1018
            return false;
1019
        }
1020
1021
        $course_url = '';
1022 View Code Duplication
        if (isset($_GET['cidReq']) && strlen($_GET['cidReq']) > 0) {
1023
            $course_url = '&amp;cidReq='.Security::remove_XSS($_GET['cidReq']);
1024
        }
1025
1026
        foreach ($user_list as $uid) {
1027
            $user_info = api_get_user_info($uid, $checkIfUserOnline = true);
1028
            $lastname = $user_info['lastname'];
1029
            $firstname =  $user_info['firstname'];
1030
            $completeName = $firstname.', '.$lastname;
1031
1032
            $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);
1033
            $status_icon_chat = null;
1034
            if ($user_info['user_is_online_in_chat'] == 1) {
1035
                $status_icon_chat = Display::return_icon('online.png', get_lang('Online'));
1036
            } else {
1037
                $status_icon_chat = Display::return_icon('offline.png', get_lang('Offline'));
1038
            }
1039
1040
            $userPicture = $user_info['avatar'];
1041
            $officialCode = '';
1042
            if (api_get_setting('show_official_code_whoisonline') == 'true') {
1043
                $officialCode .= '<div class="items-user-official-code"><p style="min-height: 30px;" title="'.get_lang('OfficialCode').'">'.$user_info['official_code'].'</p></div>';
1044
            }
1045
            $img = '<img class="img-responsive img-circle" title="'.$completeName.'" alt="'.$completeName.'" src="'.$userPicture.'">';
1046
1047
            $url =  null;
1048
            // Anonymous users can't have access to the profile
1049
            if (!api_is_anonymous()) {
1050
                if (api_get_setting('allow_social_tool') === 'true') {
1051
                    $url = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$uid.$course_url;
1052
                } else {
1053
                    $url = '?id='.$uid.$course_url;
1054
                }
1055
            } else {
1056
                $url = null;
1057
            }
1058
            $name = '<a href="'.$url.'">'.$firstname.'<br>'.$lastname.'</a>';
1059
1060
            $html .= '<div class="col-xs-6 col-md-2">
1061
                        <div class="items-user">
1062
                            <div class="items-user-avatar"><a href="'.$url.'">'.$img.'</a></div>
1063
                            <div class="items-user-name">
1064
                            '.$name.'
1065
                            </div>
1066
                            '.$officialCode.'
1067
                            <div class="items-user-status">'.$status_icon_chat.' '.$user_rol.'</div>
1068
                        </div>
1069
                      </div>';
1070
1071
        }
1072
1073
        return $html;
1074
    }
1075
1076
    /**
1077
     * Displays the information of an individual user
1078
     * @param int $user_id
1079
     */
1080
    public static function display_individual_user($user_id)
1081
    {
1082
        global $interbreadcrumb;
1083
        $safe_user_id = intval($user_id);
1084
        $currentUserId = api_get_user_id();
1085
1086
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1087
        $sql = "SELECT * FROM $user_table WHERE user_id = ".$safe_user_id;
1088
        $result = Database::query($sql);
1089
        $html = null;
1090
        if (Database::num_rows($result) == 1) {
1091
            $user_object = Database::fetch_object($result);
1092
            $userInfo = api_get_user_info($user_id);
1093
            $alt = $userInfo['complete_name'].($currentUserId == $user_id ? '&nbsp;('.get_lang('Me').')' : '');
1094
            $status = get_status_from_code($user_object->status);
1095
            $interbreadcrumb[] = array('url' => 'whoisonline.php', 'name' => get_lang('UsersOnLineList'));
1096
1097
            $html .= '<div class ="thumbnail">';
1098
            $fullurl = $userInfo['avatar'];
1099
1100
            $html .= '<img src="'.$fullurl.'" alt="'.$alt.'" />';
1101
1102
            if (!empty($status)) {
1103
                $html .= '<div class="caption">'.$status.'</div>';
1104
            }
1105
            $html .= '</div>';
1106
1107
            if (api_get_setting('show_email_addresses') == 'true') {
1108
                $html .= Display::encrypted_mailto_link($user_object->email, $user_object->email).'<br />';
1109
            }
1110
1111
            if ($user_object->competences) {
1112
                $html .= Display::page_subheader(get_lang('MyCompetences'));
1113
                $html .= '<p>'.$user_object->competences.'</p>';
1114
            }
1115
            if ($user_object->diplomas) {
1116
                $html .= Display::page_subheader(get_lang('MyDiplomas'));
1117
                $html .= '<p>'.$user_object->diplomas.'</p>';
1118
            }
1119
            if ($user_object->teach) {
1120
                $html .= Display::page_subheader(get_lang('MyTeach'));
1121
                $html .= '<p>'.$user_object->teach.'</p>';
1122
            }
1123
            SocialManager::display_productions($user_object->user_id);
1124
            if ($user_object->openarea) {
1125
                $html .= Display::page_subheader(get_lang('MyPersonalOpenArea'));
1126
                $html .= '<p>'.$user_object->openarea.'</p>';
1127
            }
1128
        } else {
1129
            $html .= '<div class="actions-title">';
1130
            $html .= get_lang('UsersOnLineList');
1131
            $html .= '</div>';
1132
        }
1133
1134
        return $html;
1135
    }
1136
1137
    /**
1138
     * Display productions in who is online
1139
     * @param int $user_id User id
1140
     */
1141
    public static function display_productions($user_id)
1142
    {
1143
        $webdir_array = UserManager::get_user_picture_path_by_id($user_id, 'web');
1144
        $sysdir = UserManager::getUserPathById($user_id, 'system');
1145
        $webdir = UserManager::getUserPathById($user_id, 'web');
1146
1147
        if (!is_dir($sysdir)) {
1148
            mkdir($sysdir, api_get_permissions_for_new_directories(), true);
1149
        }
1150
1151
        $productions = UserManager::get_user_productions($user_id);
1152
1153
        if (count($productions) > 0) {
1154
            echo '<dt><strong>'.get_lang('Productions').'</strong></dt>';
1155
            echo '<dd><ul>';
1156
            foreach ($productions as $file) {
1157
                // Only display direct file links to avoid browsing an empty directory
1158
                if (is_file($sysdir.$file) && $file != $webdir_array['file']) {
1159
                    echo '<li><a href="'.$webdir.urlencode($file).'" target=_blank>'.$file.'</a></li>';
1160
                }
1161
                // Real productions are under a subdirectory by the User's id
1162
                if (is_dir($sysdir.$file)) {
1163
                    $subs = scandir($sysdir.$file);
1164
                    foreach ($subs as $my => $sub) {
1165
                        if (substr($sub, 0, 1) != '.' && is_file($sysdir.$file.'/'.$sub)) {
1166
                            echo '<li><a href="'.$webdir.urlencode($file).'/'.urlencode($sub).'" target=_blank>'.$sub.'</a></li>';
1167
                        }
1168
                    }
1169
                }
1170
            }
1171
            echo '</ul></dd>';
1172
        }
1173
    }
1174
1175
    /**
1176
     * @param string $content
1177
     * @param string $span_count
1178
     * @return string
1179
     */
1180
    public static function social_wrapper_div($content, $span_count)
1181
    {
1182
        $span_count = intval($span_count);
1183
        $html = '<div class="span'.$span_count.'">';
1184
        $html .= '<div class="well_border">';
1185
        $html .= $content;
1186
        $html .= '</div></div>';
1187
1188
        return $html;
1189
    }
1190
1191
    /**
1192
     * Dummy function
1193
     *
1194
     */
1195
    public static function get_plugins($place = SOCIAL_CENTER_PLUGIN)
1196
    {
1197
        $content = '';
1198
        switch ($place) {
1199
            case SOCIAL_CENTER_PLUGIN:
1200
                $social_plugins = array(1, 2);
1201
                if (is_array($social_plugins) && count($social_plugins) > 0) {
1202
                    $content.= '<div id="social-plugins">';
1203
                    foreach ($social_plugins as $plugin) {
1204
                        $content.= '<div class="social-plugin-item">';
1205
                        $content.= $plugin;
1206
                        $content.= '</div>';
1207
                    }
1208
                    $content.= '</div>';
1209
                }
1210
                break;
1211
            case SOCIAL_LEFT_PLUGIN:
1212
                break;
1213
            case SOCIAL_RIGHT_PLUGIN:
1214
                break;
1215
        }
1216
1217
        return $content;
1218
    }
1219
    /**
1220
     * Sends a message to someone's wall
1221
     * @param int $userId id of author
1222
     * @param int $friendId id where we send the message
1223
     * @param string $messageContent of the message
1224
     * @param int $messageId id parent
1225
     * @param string $messageStatus status type of message
1226
     * @return boolean
1227
     * @author Yannick Warnier
1228
     */
1229
    public static function sendWallMessage($userId, $friendId, $messageContent, $messageId = 0, $messageStatus = '')
1230
    {
1231
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1232
        $userId = intval($userId);
1233
        $friendId = intval($friendId);
1234
        $messageId = intval($messageId);
1235
1236
        // Just in case we replace the and \n and \n\r while saving in the DB
1237
        $messageContent = str_replace(array("\n", "\n\r"), '<br />', $messageContent);
1238
        $now = api_get_utc_datetime();
1239
1240
        $attributes = array(
1241
            'user_sender_id' => $userId,
1242
            'user_receiver_id' => $friendId,
1243
            'msg_status' => $messageStatus,
1244
            'send_date' => $now,
1245
            'title' => '',
1246
            'content' => $messageContent,
1247
            'parent_id' => $messageId,
1248
            'group_id' => 0,
1249
            'update_date' => $now
1250
        );
1251
1252
        return Database::insert($tblMessage, $attributes);
1253
    }
1254
1255
    /**
1256
     * Send File attachment (jpg,png)
1257
     * @author Anibal Copitan
1258
     * @param int $userId id user
1259
     * @param array $fileAttach
1260
     * @param int $messageId id message (relation with main message)
1261
     * @param string $fileComment description attachment file
1262
     * @return bool
1263
     */
1264
    public static function sendWallMessageAttachmentFile($userId, $fileAttach, $messageId, $fileComment = '')
1265
    {
1266
        $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1267
1268
        // create directory
1269
        $social = '/social/';
1270
        $pathMessageAttach = UserManager::getUserPathById($userId, 'system').'message_attachments'.$social;
1271
        $safeFileComment = Database::escape_string($fileComment);
1272
        $safeFileName = Database::escape_string($fileAttach['name']);
1273
1274
        $extension = strtolower(substr(strrchr($safeFileName, '.'), 1));
1275
        $allowedTypes = api_get_supported_image_extensions();
1276
        if (!in_array($extension, $allowedTypes)) {
1277
            $flag = false;
1278
        } else {
1279
            $newFileName = uniqid('') . '.' . $extension;
1280
            if (!file_exists($pathMessageAttach)) {
1281
                @mkdir($pathMessageAttach, api_get_permissions_for_new_directories(), true);
1282
            }
1283
1284
            $newPath = $pathMessageAttach . $newFileName;
1285
            if (is_uploaded_file($fileAttach['tmp_name'])) {
1286
                @copy($fileAttach['tmp_name'], $newPath);
1287
            }
1288
1289
            $small = self::resize_picture($newPath, IMAGE_WALL_SMALL_SIZE);
1290
            $medium = self::resize_picture($newPath, IMAGE_WALL_MEDIUM_SIZE);
1291
1292
            $big = new Image($newPath);
1293
            $ok = $small && $small->send_image($pathMessageAttach . IMAGE_WALL_SMALL . '_' . $newFileName) &&
1294
                $medium && $medium->send_image($pathMessageAttach . IMAGE_WALL_MEDIUM .'_' . $newFileName) &&
1295
                $big && $big->send_image($pathMessageAttach . IMAGE_WALL_BIG . '_' . $newFileName);
1296
1297
            // Insert
1298
            $newFileName = $social.$newFileName;
1299
1300
            $params = [
1301
                'filename' => $safeFileName,
1302
                'comment' => $safeFileComment,
1303
                'path' => $newFileName,
1304
                'message_id' => $messageId,
1305
                'size' => $fileAttach['size'],
1306
            ];
1307
            Database::insert($tbl_message_attach, $params);
1308
            $flag = true;
1309
        }
1310
1311
        return $flag;
1312
    }
1313
1314
    /**
1315
     * Gets all messages from someone's wall (within specific limits)
1316
     * @param int $userId id of wall shown
1317
     * @param string $messageStatus status wall message
1318
     * @param int|string $parentId id message (Post main)
1319
     * @param date $start Date from which we want to show the messages, in UTC time
1320
     * @param int $limit Limit for the number of parent messages we want to show
1321
     * @param int $offset Wall message query offset
1322
     * @return boolean
1323
     * @author Yannick Warnier
1324
     */
1325
    public static function getWallMessages($userId, $messageStatus, $parentId = '', $start = null, $limit = 10, $offset = 0)
1326
    {
1327
        if (empty($start)) {
1328
            $start = '0000-00-00';
1329
        }
1330
1331
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1332
        $tblMessageAttachment = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1333
1334
        $userId = intval($userId);
1335
        $start = Database::escape_string($start);
1336
        $limit = intval($limit);
1337
1338
        $sql = "SELECT
1339
                    id,
1340
                    user_sender_id,
1341
                    user_receiver_id,
1342
                    send_date,
1343
                    content,
1344
                    parent_id,
1345
                    (
1346
                        SELECT ma.path FROM $tblMessageAttachment ma
1347
                        WHERE  ma.message_id = tm.id 
1348
                    ) as path,
1349
                    (
1350
                        SELECT ma.filename FROM $tblMessageAttachment ma 
1351
                        WHERE ma.message_id = tm.id 
1352
                    ) 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
            $media .= '<div class="col-md-2 col-xs-2 social-post-answers">';
1410
            $media .= '<div class="user-image pull-right">';
1411
            $media .= '<a href="'.$url.'" ><img src="'. $users[$userIdLoop]['avatar'] .
1412
                       '" alt="'.$users[$userIdLoop]['complete_name'].'" class="avatar-thumb"></a>';
1413
            $media .= '</div>';
1414
            $media .= '</div>';
1415
            $media .= '<div class="col-md-9 col-xs-9 social-post-answers">';
1416
            $media .= '<div class="user-data">';
1417
            $media .= '<div class="username">' . '<a href="'.$url.'">'.$nameComplete.'</a> <span>'.Security::remove_XSS($message['content']).'</span></div>';
1418
            $media .= '<div class="time timeago" title="'.$date.'">'.$date.'</div>';
1419
            $media .= '<br />';
1420
            $media .= '</div>';
1421
            $media .= '</div>';
1422
            $media .= '</div>';
1423
            if ($isOwnWall) {
1424
                $media .= '<div class="col-md-1 col-xs-1 social-post-answers">';
1425
                $media .= '<div class="pull-right deleted-mgs">';
1426
                $media .= '<a title="'.get_lang("SocialMessageDelete").'" href="'.api_get_path(WEB_CODE_PATH).'social/profile.php?messageId='.
1427
                    $message['id'].'">x</a>';
1428
                $media .= '</div>';
1429
                $media .= '</div>';
1430
            }
1431
1432
            $formattedList .= $media;
1433
        }
1434
1435
        $formattedList .= '</div>';
1436
1437
        $formattedList .= '<div class="mediapost-form">';
1438
            $formattedList .= '<form name="social_wall_message" method="POST">
1439
                <label for="social_wall_new_msg" class="hide">'.get_lang('SocialWriteNewComment').'</label>
1440
                <input type="hidden" name = "messageId" value="'.$idMessage.'" />
1441
                <textarea placeholder="'.get_lang('SocialWriteNewComment').
1442
                '" name="social_wall_new_msg" rows="1" style="width:80%;" ></textarea>
1443
                <button type="submit" name="social_wall_new_msg_submit"
1444
                class="pull-right btn btn-default" /><em class="fa fa-pencil"></em> '.get_lang('Post').'</button>
1445
                </form>';
1446
        $formattedList .= '</div>';
1447
1448
        return $formattedList;
1449
    }
1450
1451
    /**
1452
     * Gets all user's starting wall messages (within specific limits)
1453
     * @param   int     $userId     User's id
1454
     * @param   int     $friendId   Friend's id
1455
     * @param   date    $start      Start date (from when we want the messages until today)
1456
     * @param   int     $limit      Limit to the number of messages we want
1457
     * @param   int     $offset     Wall messages offset
1458
     * @return  array   $data       return user's starting wall messages along with message extra data
1459
     */
1460
    public static function getWallMessagesPostHTML($userId, $friendId = 0, $start = null, $limit = 10, $offset= 0)
1461
    {
1462
        if (empty($start)) {
1463
            $start = '0000-00-00';
1464
        }
1465
        $isOwnWall = (api_get_user_id() == $userId  && $userId == $friendId);
1466
        $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 1463 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...
1467
        $users = array();
1468
        $data = array();
1469
        foreach ($messages as $key => $message) {
1470
            $userIdLoop = $message['user_sender_id'];
1471
            $userFriendIdLoop = $message['user_receiver_id'];
1472
1473
            if (!isset($users[$userIdLoop])) {
1474
                $users[$userIdLoop] = api_get_user_info($userIdLoop);
1475
            }
1476
1477
            if (!isset($users[$userFriendIdLoop])) {
1478
                $users[$userFriendIdLoop] = api_get_user_info($userFriendIdLoop);
1479
            }
1480
1481
            $html = '';
1482
            $html .= self::headerMessagePost(
1483
                $message['user_sender_id'],
1484
                $message['user_receiver_id'],
1485
                $users,
1486
                $message,
1487
                $isOwnWall
1488
            );
1489
1490
            $data[$key]['id'] = $message['id'];
1491
            $data[$key]['html'] = $html;
1492
        }
1493
1494
        return $data;
1495
    }
1496
1497
    /**
1498
     * Returns the formatted header message post
1499
     * @param   int     $authorId   Author's id
1500
     * @param   int     $receiverId Receiver's id
1501
     * @param   array   $users      Author's and receiver's data
1502
     * @param   array   $message    Message data
1503
     * @param   boolean $isOwnWall  Determines if the author is in its own social wall or not
1504
     * @return  string  $html       The formatted header message post
1505
     */
1506
    private static function headerMessagePost($authorId, $receiverId, $users, $message, $isOwnWall = false)
1507
    {
1508
        $date = api_get_local_time($message['send_date']);
1509
        $avatarAuthor = $users[$authorId]['avatar'];
1510
        $urlAuthor = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$authorId;
1511
        $nameCompleteAuthor = api_get_person_name(
1512
            $users[$authorId]['firstname'],
1513
            $users[$authorId]['lastname']
1514
        );
1515
1516
        $urlReceiver = api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$receiverId;
1517
        $nameCompleteReceiver = api_get_person_name(
1518
            $users[$receiverId]['firstname'],
1519
            $users[$receiverId]['lastname']
1520
        );
1521
1522
        $htmlReceiver = '';
1523
        if ($authorId != $receiverId) {
1524
            $htmlReceiver = ' > <a href="'.$urlReceiver.'">' . $nameCompleteReceiver . '</a> ';
1525
        }
1526
1527
        $wallImage = '';
1528
        if (!empty($message['path'])) {
1529
            $imageBig = UserManager::getUserPicture($authorId, USER_IMAGE_SIZE_BIG);
1530
            $imageSmall = UserManager::getUserPicture($authorId, USER_IMAGE_SIZE_SMALL);
1531
1532
            $wallImage = '<a class="thumbnail ajax" href="'.$imageBig.'"><img src="'.$imageSmall.'"></a>';
1533
        }
1534
1535
        $htmlDelete = '';
1536
        if ($isOwnWall) {
1537
            $htmlDelete .= '<a title="'.get_lang("SocialMessageDelete").'" href="'.api_get_path(WEB_CODE_PATH).'social/profile.php?messageId='.
1538
            $message['id'].'">x</a>';
1539
        }
1540
1541
        $html = '';
1542
        $html .= '<div class="top-mediapost" >';
1543
        if ($isOwnWall) {
1544
            $html .= '<div class="pull-right deleted-mgs">';
1545
            $html .= $htmlDelete;
1546
            $html .= '</div>';
1547
        }
1548
        $html .= '<div class="user-image" >';
1549
        $html .= '<a href="'.$urlAuthor.'">'.'<img class="avatar-thumb" src="'.$avatarAuthor.'" alt="'.$nameCompleteAuthor.'"></a>';
1550
        $html .= '</div>';
1551
        $html .= '<div class="user-data">';
1552
        $html .= '<div class="username"><a href="'.$urlAuthor.'">'.$nameCompleteAuthor.'</a>'.$htmlReceiver.'</div>';
1553
        $html .= '<div class="time timeago" title="'.$date.'">'.$date.'</div>';
1554
        $html .= '</div>';
1555
        $html .= '<div class="msg-content">';
1556
        $html .= '<div class="img-post">';
1557
        $html .= $wallImage;
1558
        $html .= '</div>';
1559
        $html .= '<p>'. Security::remove_XSS($message['content']).'</p>';
1560
        $html .= '</div>';
1561
        $html .= '</div>'; // end mediaPost
1562
1563
        // Popularity post functionality
1564
        $html .= '<div class="popularity-mediapost"></div>';
1565
1566
        return $html;
1567
    }
1568
1569
    /**
1570
     * get html data with OpenGrap passing the Url
1571
     * @param $link url
1572
     * @return string data html
1573
     */
1574
    public static function readContentWithOpenGraph($link)
1575
    {
1576
        if (strpos($link, "://") === false && substr($link, 0, 1) != "/") {
1577
            $link = "http://".$link;
1578
        }
1579
        $graph = OpenGraph::fetch($link);
1580
        $link = parse_url($link);
1581
        $host = $link['host'] ? strtoupper($link['host']) : $link['path'];
1582
        if (!$graph) {
1583
            return false;
1584
        }
1585
        $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...
1586
        $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...
1587
        $description = $graph->description;
0 ignored issues
show
Bug introduced by
The property description 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...
1588
        $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...
1589
        $html  = '<div class="thumbnail social-thumbnail">';
1590
        $html .= empty($image) ? '' : '<a target="_blank" href="'.$url.'"><img class="img-responsive social-image" src="'.$image.'" /></a>';
1591
        $html .= '<div class="social-description">';
1592
        $html .= '<a target="_blank" href="'.$url.'"><h5 class="social-title"><b>'.$title.'</b></h5></a>';
1593
        $html .= empty($description) ? '' : '<span>'.$description.'</span>';
1594
        $html .= empty($host) ? '' : '<p>'.$host.'</p>';
1595
        $html .= '</div>';
1596
        $html .= '</div>';
1597
1598
        return $html;
1599
    }
1600
1601
    /**
1602
     * verify if Url Exist - Using Curl
1603
     * @param $uri url
1604
     *
1605
     * @return boolean
1606
     */
1607 View Code Duplication
    public static function verifyUrl($uri)
1608
    {
1609
        $curl = curl_init($uri);
1610
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
1611
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
1612
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1613
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
1614
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
1615
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
1616
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
1617
        $response = curl_exec($curl);
1618
        curl_close($curl);
1619
        if (!empty($response)) {
1620
            return true;
1621
        } else {
1622
            return false;
1623
        }
1624
    }
1625
1626
    /**
1627
    * Delete messages delete logic
1628
    * @param int $id id message to delete.
1629
    * @return bool status query
1630
    */
1631
    public static function deleteMessage($id)
1632
    {
1633
        $id = intval($id);
1634
        $tblMessage = Database::get_main_table(TABLE_MESSAGE);
1635
        $statusMessage = MESSAGE_STATUS_WALL_DELETE;
1636
        $sql = "UPDATE $tblMessage SET msg_status = '$statusMessage' WHERE id = '{$id}' ";
1637
1638
        return Database::query($sql);
1639
    }
1640
1641
    /**
1642
     * Generate the social block for a user
1643
     * @param Template $template
1644
     * @param int $userId The user id
1645
     * @param string $groupBlock Optional. Highlight link possible values:
1646
     * group_add, home, messages, messages_inbox, messages_compose,
1647
     * messages_outbox, invitations, shared_profile, friends, groups, search
1648
     * @param int $groupId Optional. Group ID
1649
     * @return string The HTML code with the social block
1650
     */
1651
    public static function setSocialUserBlock(
1652
        Template $template,
1653
        $userId,
1654
        $groupBlock = '',
1655
        $groupId = 0,
1656
        $show_full_profile = true
1657
    ) {
1658
        if (api_get_setting('allow_social_tool') != 'true') {
1659
            return '';
1660
        }
1661
1662
        $currentUserId = api_get_user_id();
1663
        $userId = intval($userId);
1664
        $userRelationType = 0;
1665
1666
        $socialAvatarBlock = SocialManager::show_social_avatar_block(
1667
            $groupBlock,
1668
            $groupId,
1669
            $userId
1670
        );
1671
1672
        $profileEditionLink = null;
1673
1674
        if ($currentUserId === $userId) {
1675
            $profileEditionLink = Display::getProfileEditionLink($userId);
1676
        } else {
1677
            $userRelationType = SocialManager::get_relation_between_contacts(
1678
                $currentUserId,
1679
                $userId
1680
            );
1681
        }
1682
1683
        $vCardUserLink = Display::getVCardUserLink($userId);
1684
1685
        $userInfo = api_get_user_info($userId, true, false, true, true);
1686
1687
        $template->assign('user', $userInfo);
1688
        $template->assign('social_avatar_block', $socialAvatarBlock);
1689
        $template->assign('profile_edition_link', $profileEditionLink);
1690
        //Added the link to export the vCard to the Template
1691
1692
        //If not friend $show_full_profile is False and the user can't see Email Address and Vcard Download Link
1693
        if ($show_full_profile) {
1694
            $template->assign('vcard_user_link', $vCardUserLink);
1695
        }
1696
1697
        if (api_get_setting('gamification_mode') === '1') {
1698
            $gamificationPoints = GamificationUtils::getTotalUserPoints(
1699
                $userId,
1700
                $userInfo['status']
1701
            );
1702
1703
            $template->assign('gamification_points', $gamificationPoints);
1704
        }
1705
        $chatEnabled = api_is_global_chat_enabled();
1706
        $template->assign('chat_enabled', $chatEnabled);
1707
        $template->assign('user_relation', $userRelationType);
1708
        $template->assign('user_relation_type_friend', USER_RELATION_TYPE_FRIEND);
1709
        $template->assign('show_full_profile', $show_full_profile);
1710
        $templateName = $template->get_template('social/user_block.tpl');
1711
1712
        if (in_array($groupBlock, ['groups', 'group_edit', 'member_list'])) {
1713
            $templateName = $template->get_template('social/group_block.tpl');
1714
        }
1715
1716
        $template->assign('social_avatar_block', $template->fetch($templateName));
1717
    }
1718
1719
    /**
1720
     * @param int $user_id
1721
     * @param $link_shared
1722
     * @param $show_full_profile
1723
     * @return string
1724
     */
1725
    public static function listMyFriends($user_id, $link_shared, $show_full_profile)
1726
    {
1727
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1728
        $friends = SocialManager::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
1729
        $number_of_images = 30;
1730
        $number_friends = count($friends);
1731
        $friendHtml = '';
1732
        if ($number_friends != 0) {
1733 View Code Duplication
            if ($number_friends > $number_of_images) {
1734
                if (api_get_user_id() == $user_id) {
1735
                    $friendHtml.= ' <span><a href="friends.php">'.get_lang('SeeAll').'</a></span>';
1736
                } else {
1737
                    $friendHtml.= ' <span>'
1738
                        .'<a href="'.api_get_path(WEB_CODE_PATH).'social/profile_friends_and_groups.inc.php'
1739
                        .'?view=friends&height=390&width=610&user_id='.$user_id.'"'
1740
                        .'class="ajax" data-title="'.get_lang('SeeAll').'" title="'.get_lang('SeeAll').'" >'.get_lang('SeeAll').'</a></span>';
1741
                }
1742
            }
1743
1744
            $friendHtml.= '<ul class="nav nav-list">';
1745
            $j = 1;
1746
            for ($k=0; $k < $number_friends; $k++) {
1747
                if ($j > $number_of_images) break;
1748
1749
                if (isset($friends[$k])) {
1750
                    $friend = $friends[$k];
1751
                    $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
1752
                    $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
1753
1754
                    if ($user_info_friend['user_is_online']) {
1755
                        $statusIcon = Display::span('', array('class' => 'online_user_in_text'));
1756
                    } else {
1757
                        $statusIcon = Display::span('', array('class' => 'offline_user_in_text'));
1758
                    }
1759
1760
                    $friendHtml.= '<li>';
1761
                    $friendHtml.= '<div>';
1762
1763
                    // the height = 92 must be the same in the image_friend_network span style in default.css
1764
                    $friends_profile = UserManager::getUserPicture($friend['friend_user_id'], USER_IMAGE_SIZE_SMALL);
1765
                    $friendHtml.= '<img src="'.$friends_profile.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'"/>';
1766
                    $link_shared = (empty($link_shared)) ? '' : '&'.$link_shared;
1767
                    $friendHtml.= $statusIcon .'<a href="profile.php?' .'u=' . $friend['friend_user_id'] . $link_shared . '">' . $name_user .'</a>';
1768
                    $friendHtml.= '</div>';
1769
                    $friendHtml.= '</li>';
1770
                }
1771
                $j++;
1772
            }
1773
            $friendHtml.='</ul>';
1774 View Code Duplication
        } else {
1775
            $friendHtml.= '<div class="">'.get_lang('NoFriendsInYourContactList').'<br />'
1776
                .'<a class="btn btn-primary" href="'.api_get_path(WEB_PATH).'whoisonline.php"><em class="fa fa-search"></em> '. get_lang('TryAndFindSomeFriends').'</a></div>';
1777
        }
1778
1779
        $friendHtml = Display::panel($friendHtml, get_lang('SocialFriend').' (' . $number_friends . ')' );
1780
1781
        return $friendHtml;
1782
    }
1783
1784
    /**
1785
     * @param int $user_id
1786
     * @param $link_shared
1787
     * @param $show_full_profile
1788
     * @return string
1789
     */
1790
    public static function listMyFriendsBlock($user_id, $link_shared = '', $show_full_profile = '')
1791
    {
1792
        //SOCIALGOODFRIEND , USER_RELATION_TYPE_FRIEND, USER_RELATION_TYPE_PARENT
1793
        $friends = SocialManager::get_friends($user_id, USER_RELATION_TYPE_FRIEND);
1794
        $number_of_images = 30;
1795
        $number_friends = count($friends);
1796
        $friendHtml = '';
1797
1798
        if ($number_friends != 0) {
1799
1800
            $friendHtml.= '<div class="list-group">';
1801
            $j = 1;
1802
            for ($k=0; $k < $number_friends; $k++) {
1803
                if ($j > $number_of_images) {
1804
                    break;
1805
                }
1806
                if (isset($friends[$k])) {
1807
                    $friend = $friends[$k];
1808
                    $name_user = api_get_person_name($friend['firstName'], $friend['lastName']);
1809
                    $user_info_friend = api_get_user_info($friend['friend_user_id'], true);
1810
1811
                    if ($user_info_friend['user_is_online']) {
1812
                        $statusIcon = Display::return_icon('statusonline.png',get_lang('Online'));
1813
                        $status=1;
1814
                    } else {
1815
                        $statusIcon = Display::return_icon('statusoffline.png',get_lang('Offline'));
1816
                        $status=0;
1817
                    }
1818
1819
                    $friendAvatarMedium = UserManager::getUserPicture($friend['friend_user_id'], USER_IMAGE_SIZE_MEDIUM);
1820
                    $friendAvatarSmall = UserManager::getUserPicture($friend['friend_user_id'], USER_IMAGE_SIZE_SMALL);
1821
                    $friend_avatar = '<img src="'.$friendAvatarMedium.'" id="imgfriend_'.$friend['friend_user_id'].'" title="'.$name_user.'" class="user-image"/>';
1822
                    $showLinkToChat = api_is_global_chat_enabled() &&
1823
                        $friend['friend_user_id'] != api_get_user_id();
1824
1825
                    if ($showLinkToChat){
1826
                        $friendHtml .= '<a onclick="javascript:chatWith(\''.$friend['friend_user_id'].'\', \''.$name_user.'\', \''.$status.'\',\''.$friendAvatarSmall.'\')" href="javascript:void(0);" class="list-group-item">';
1827
                        $friendHtml .=  $friend_avatar.' <span class="username">' . $name_user . '</span>';
1828
                        $friendHtml .= '<span class="status">' . $statusIcon . '</span>';
1829
                    } else {
1830
                        $link_shared = empty($link_shared) ? '' : '&'.$link_shared;
1831
                        $friendHtml .= '<a href="profile.php?' .'u=' . $friend['friend_user_id'] . $link_shared . '" class="list-group-item">';
1832
                        $friendHtml .=  $friend_avatar.' <span class="username-all">' . $name_user . '</span>';
1833
                    }
1834
1835
                    $friendHtml .= '</a>';
1836
                }
1837
                $j++;
1838
            }
1839
            $friendHtml.='</div>';
1840 View Code Duplication
        } else {
1841
            $friendHtml.= '<div class="help">'.get_lang('NoFriendsInYourContactList').' '
1842
                .'<a href="'.api_get_path(WEB_PATH).'whoisonline.php"><em class="fa fa-search"></em> '. get_lang('TryAndFindSomeFriends').'</a></div>';
1843
        }
1844
1845
        return $friendHtml;
1846
    }
1847
1848
    /**
1849
     * @return string
1850
     */
1851
    public static function getWallForm($show_full_profile = true)
1852
    {
1853
        if ($show_full_profile) {
1854
            $userId = isset($_GET['u']) ? '?u='.intval($_GET['u']) : '';
1855
            $form = new FormValidator(
1856
                'social_wall_main',
1857
                'post',
1858
                api_get_path(WEB_CODE_PATH).'social/profile.php'.$userId,
1859
                null,
1860
                array('enctype' => 'multipart/form-data') ,
1861
                FormValidator::LAYOUT_HORIZONTAL
1862
            );
1863
1864
            $socialWallPlaceholder = isset($_GET['u']) ? get_lang('SocialWallWriteNewPostToFriend') : get_lang('SocialWallWhatAreYouThinkingAbout');
1865
1866
            $form->addTextarea(
1867
                'social_wall_new_msg_main',
1868
                null,
1869
                [
1870
                    'placeholder' => $socialWallPlaceholder,
1871
                    'cols-size' => [1, 10, 1],
1872
                ]
1873
            );
1874
            $form->addHidden('url_content', '');
1875
            $form->addButtonSend(get_lang('Post'), 'wall_post_button', false, ['cols-size' => [1, 10, 1]]);
1876
            $html = Display::panel($form->returnForm(), get_lang('SocialWall'));
1877
1878
            return $html;
1879
        }
1880
    }
1881
1882
    /**
1883
     * @param int $userId
1884
     * @param int $friendId
1885
     * @return string
1886
     */
1887
    public static function getWallMessagesByUser($userId, $friendId)
1888
    {
1889
        $messages = SocialManager::getWallMessagesPostHTML($userId, $friendId);
1890
        $html = '';
1891
1892
        foreach ($messages as $message) {
1893
            $post = $message['html'];
1894
            $comment = SocialManager::getWallMessagesHTML($userId, $friendId, $message['id']);
1895
            $html .= Display::panel($post.$comment, '');
1896
        }
1897
1898
        return $html;
1899
    }
1900
1901
    /**
1902
     * Get HTML code block for user skills
1903
     * @param int $userId The user ID
1904
     * @return string
1905
     */
1906
    public static function getSkillBlock($userId)
1907
    {
1908
        if (api_get_setting('allow_skills_tool') !== 'true') {
1909
            return null;
1910
        }
1911
1912
        $skill = new Skill();
1913
        $ranking = $skill->get_user_skill_ranking($userId);
1914
        $skills = $skill->get_user_skills($userId, true);
1915
1916
        $template = new Template(null, false, false, false, false, false);
1917
        $template->assign('ranking', $ranking);
1918
        $template->assign('skills', $skills);
1919
        $template->assign('user_id', $userId);
1920
        $template->assign(
1921
            'show_skills_report_link',
1922
            api_is_student() || api_is_student_boss() || api_is_drh()
1923
        );
1924
1925
        $skillBlock = $template->get_template('social/skills_block.tpl');
1926
1927
        return $template->fetch($skillBlock);
1928
    }
1929
}
1930