Passed
Push — master ( 15378b...a2dd4f )
by Julito
09:24
created

MessageManager::send_message()   F

Complexity

Conditions 37
Paths 14026

Size

Total Lines 269
Code Lines 167

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 37
eloc 167
nc 14026
nop 16
dl 0
loc 269
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\Message;
5
use Chamilo\UserBundle\Entity\User;
6
use ChamiloSession as Session;
7
8
/**
9
 * Class MessageManager.
10
 *
11
 * This class provides methods for messages management.
12
 * Include/require it in your code to use its features.
13
 *
14
 * @package chamilo.library
15
 */
16
class MessageManager
17
{
18
    /**
19
     * Get count new messages for the current user from the database.
20
     *
21
     * @return int
22
     */
23
    public static function getCountNewMessages()
24
    {
25
        $userId = api_get_user_id();
26
        if (empty($userId)) {
27
            return false;
28
        }
29
30
        static $count;
31
        if (!isset($count)) {
32
            $cacheAvailable = api_get_configuration_value('apc');
33
            if ($cacheAvailable === true) {
34
                $var = api_get_configuration_value('apc_prefix').'social_messages_unread_u_'.$userId;
35
                if (apcu_exists($var)) {
36
                    $count = apcu_fetch($var);
37
                } else {
38
                    $count = self::getCountNewMessagesFromDB($userId);
39
                    apcu_store($var, $count, 60);
40
                }
41
            } else {
42
                $count = self::getCountNewMessagesFromDB($userId);
43
            }
44
        }
45
46
        return $count;
47
    }
48
49
    /**
50
     * Gets the total number of messages, used for the inbox sortable table.
51
     *
52
     * @param array $params
53
     *
54
     * @return int
55
     */
56
    public static function getNumberOfMessages($params = [])
57
    {
58
        $messageStatus = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
59
        if (isset($params['message_status']) && !empty($params['message_status'])) {
60
            $messageStatus = $params['message_status'];
61
        }
62
        $messageStatus = array_map('intval', $messageStatus);
63
        $messageStatusCondition = implode("','", $messageStatus);
64
65
        $table = Database::get_main_table(TABLE_MESSAGE);
66
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
67
68
        $keywordCondition = '';
69
        if (!empty($keyword)) {
70
            $keyword = Database::escape_string($keyword);
71
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
72
        }
73
74
        $sql = "SELECT COUNT(id) as number_messages
75
                FROM $table
76
                WHERE 
77
                    msg_status IN ('$messageStatusCondition') AND
78
                    user_receiver_id = ".api_get_user_id()."
79
                    $keywordCondition
80
                ";
81
        $result = Database::query($sql);
82
        $result = Database::fetch_array($result);
83
84
        if ($result) {
85
            return (int) $result['number_messages'];
86
        }
87
88
        return 0;
89
    }
90
91
    /**
92
     * Gets information about some messages, used for the inbox sortable table.
93
     *
94
     * @param int    $from
95
     * @param int    $numberOfItems
96
     * @param string $column
97
     * @param string $direction
98
     * @param array  $extraParams
99
     *
100
     * @return array
101
     */
102
    public static function getMessageData(
103
        $from,
104
        $numberOfItems,
105
        $column,
106
        $direction,
107
        $extraParams = []
108
    ) {
109
        $from = (int) $from;
110
        $numberOfItems = (int) $numberOfItems;
111
        $userId = api_get_user_id();
112
113
        // Forcing this order.
114
        if (!isset($direction)) {
115
            $column = 2;
116
            $direction = 'DESC';
117
        } else {
118
            $column = (int) $column;
119
            if (!in_array($direction, ['ASC', 'DESC'])) {
120
                $direction = 'ASC';
121
            }
122
        }
123
124
        if (!in_array($column, [0, 1, 2])) {
125
            $column = 2;
126
        }
127
128
        $keyword = isset($extraParams['keyword']) ? $extraParams['keyword'] : '';
129
        $viewUrl = isset($extraParams['view_url']) ? $extraParams['view_url'] : api_get_path(WEB_CODE_PATH).'message/view_message.php';
130
131
        $keywordCondition = '';
132
        if (!empty($keyword)) {
133
            $keyword = Database::escape_string($keyword);
134
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
135
        }
136
137
        $messageStatus = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
138
        if (isset($extraParams['message_status']) && !empty($extraParams['message_status'])) {
139
            $messageStatus = $extraParams['message_status'];
140
        }
141
        $messageStatus = array_map('intval', $messageStatus);
142
        $messageStatusCondition = implode("','", $messageStatus);
143
144
        $table = Database::get_main_table(TABLE_MESSAGE);
145
        $sql = "SELECT 
146
                    id as col0, 
147
                    title as col1, 
148
                    send_date as col2, 
149
                    msg_status as col3,
150
                    user_sender_id
151
                FROM $table
152
                WHERE
153
                    user_receiver_id = $userId AND
154
                    msg_status IN ('$messageStatusCondition')
155
                    $keywordCondition
156
                ORDER BY col$column $direction
157
                LIMIT $from, $numberOfItems";
158
159
        $result = Database::query($sql);
160
        $messageList = [];
161
        $newMessageLink = api_get_path(WEB_CODE_PATH).'messages/new_message.php';
162
163
        $actions = $extraParams['actions'];
164
        $url = api_get_self();
165
        while ($row = Database::fetch_array($result, 'ASSOC')) {
166
            $messageId = $row['col0'];
167
            $title = $row['col1'];
168
            $sendDate = $row['col2'];
169
            $status = $row['col3'];
170
            $senderId = $row['user_sender_id'];
171
172
            $title = Security::remove_XSS($title, STUDENT, true);
173
            $title = cut($title, 80, true);
174
175
            $class = 'class = "read"';
176
            if ($status == 1) {
177
                $class = 'class = "unread"';
178
            }
179
180
            $userInfo = api_get_user_info($senderId);
181
            $message[3] = '';
182
            if (!empty($senderId) && !empty($userInfo)) {
183
                $message[1] = '<a '.$class.' href="'.$viewUrl.'?id='.$messageId.'">'.$title.'</a><br />';
184
                $message[1] .= $userInfo['complete_name_with_username'];
185
                if (in_array('reply', $actions)) {
186
                    $message[3] =
187
                        Display::url(
188
                            Display::returnFontAwesomeIcon('reply', 2),
189
                            $newMessageLink.'?re_id='.$messageId,
190
                            ['title' => get_lang('ReplyToMessage')]
191
                        );
192
                }
193
            } else {
194
                $message[1] = '<a '.$class.' href="'.$viewUrl.'?id='.$messageId.'">'.$title.'</a><br />';
195
                $message[1] .= get_lang('UnknownUser');
196
                if (in_array('reply', $actions)) {
197
                    $message[3] =
198
                        Display::url(
199
                            Display::returnFontAwesomeIcon('reply', 2),
200
                            '#',
201
                            ['title' => get_lang('ReplyToMessage')]
202
                        );
203
                }
204
            }
205
206
            $message[0] = $messageId;
207
            $message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
208
209
            // Actions
210
            if (in_array('edit', $actions)) {
211
                $message[3] .=
212
                    '&nbsp;&nbsp;'.
213
                    Display::url(
214
                        Display::returnFontAwesomeIcon('pencil', 2),
215
                        $newMessageLink.'?action=edit&id='.$messageId,
216
                        ['title' => get_lang('ForwardMessage')]
217
                    );
218
            }
219
220
            // Actions
221
            if (in_array('forward', $actions)) {
222
                $message[3] .=
223
                    '&nbsp;&nbsp;'.
224
                    Display::url(
225
                        Display::returnFontAwesomeIcon('share', 2),
226
                        $newMessageLink.'?forward_id='.$messageId,
227
                        ['title' => get_lang('ForwardMessage')]
228
                    );
229
            }
230
231
            if (in_array('delete', $actions)) {
232
                $message[3] .= '&nbsp;&nbsp;<a title="'.addslashes(
233
                    get_lang('DeleteMessage')
234
                ).'" onclick="javascript:if(!confirm('."'".addslashes(
235
                    api_htmlentities(get_lang('ConfirmDeleteMessage'))
236
                )."'".')) return false;" href="'.$url.'?action=deleteone&id='.$messageId.'">'.
237
                Display::returnFontAwesomeIcon('trash', 2).'</a>';
238
            }
239
240
            foreach ($message as $key => $value) {
241
                $message[$key] = api_xml_http_response_encode($value);
242
            }
243
            $messageList[] = $message;
244
        }
245
246
        return $messageList;
247
    }
248
249
    /**
250
     * @param array  $aboutUserInfo
251
     * @param array  $fromUserInfo
252
     * @param string $subject
253
     * @param string $content
254
     *
255
     * @return bool
256
     */
257
    public static function sendMessageAboutUser(
258
        $aboutUserInfo,
259
        $fromUserInfo,
260
        $subject,
261
        $content
262
    ) {
263
        if (empty($aboutUserInfo) || empty($fromUserInfo)) {
264
            return false;
265
        }
266
267
        if (empty($fromUserInfo['id']) || empty($aboutUserInfo['id'])) {
268
            return false;
269
        }
270
271
        $table = Database::get_main_table(TABLE_MESSAGE);
272
        $now = api_get_utc_datetime();
273
        $params = [
274
            'user_sender_id' => $fromUserInfo['id'],
275
            'user_receiver_id' => $aboutUserInfo['id'],
276
            'msg_status' => MESSAGE_STATUS_CONVERSATION,
277
            'send_date' => $now,
278
            'title' => $subject,
279
            'content' => $content,
280
            'group_id' => 0,
281
            'parent_id' => 0,
282
            'update_date' => $now,
283
        ];
284
        $id = Database::insert($table, $params);
285
286
        if ($id) {
287
            return true;
288
        }
289
290
        return false;
291
    }
292
293
    /**
294
     * @param array $aboutUserInfo
295
     *
296
     * @return array
297
     */
298
    public static function getMessagesAboutUser($aboutUserInfo)
299
    {
300
        if (!empty($aboutUserInfo)) {
301
            $table = Database::get_main_table(TABLE_MESSAGE);
302
            $sql = 'SELECT id FROM '.$table.'
303
                    WHERE 
304
                      user_receiver_id = '.$aboutUserInfo['id'].' AND 
305
                      msg_status = '.MESSAGE_STATUS_CONVERSATION.'                    
306
                    ';
307
            $result = Database::query($sql);
308
            $messages = [];
309
            $repo = Database::getManager()->getRepository('ChamiloCoreBundle:Message');
310
            while ($row = Database::fetch_array($result)) {
311
                $message = $repo->find($row['id']);
312
                $messages[] = $message;
313
            }
314
315
            return $messages;
316
        }
317
318
        return [];
319
    }
320
321
    /**
322
     * @param array $userInfo
323
     *
324
     * @return string
325
     */
326
    public static function getMessagesAboutUserToString($userInfo)
327
    {
328
        $messages = self::getMessagesAboutUser($userInfo);
329
        $html = '';
330
        if (!empty($messages)) {
331
            /** @var Message $message */
332
            foreach ($messages as $message) {
333
                $tag = 'message_'.$message->getId();
334
                $tagAccordion = 'accordion_'.$message->getId();
335
                $tagCollapse = 'collapse_'.$message->getId();
336
                $date = Display::dateToStringAgoAndLongDate(
337
                    $message->getSendDate()
338
                );
339
                $localTime = api_get_local_time(
340
                    $message->getSendDate(),
341
                    null,
342
                    null,
343
                    false,
344
                    false
345
                );
346
                $senderId = $message->getUserSenderId();
347
                $senderInfo = api_get_user_info($senderId);
348
                $html .= Display::panelCollapse(
349
                    $localTime.' '.$senderInfo['complete_name'].' '.$message->getTitle(),
350
                    $message->getContent().'<br />'.$date.'<br />'.get_lang(
351
                        'Author'
352
                    ).': '.$senderInfo['complete_name_with_message_link'],
353
                    $tag,
354
                    null,
355
                    $tagAccordion,
356
                    $tagCollapse,
357
                    false
358
                );
359
            }
360
        }
361
362
        return $html;
363
    }
364
365
    /**
366
     * @param int    $senderId
367
     * @param int    $receiverId
368
     * @param string $subject
369
     * @param string $message
370
     *
371
     * @return bool
372
     */
373
    public static function messageWasAlreadySent($senderId, $receiverId, $subject, $message)
374
    {
375
        $table = Database::get_main_table(TABLE_MESSAGE);
376
        $senderId = (int) $senderId;
377
        $receiverId = (int) $receiverId;
378
        $subject = Database::escape_string($subject);
379
        $message = Database::escape_string($message);
380
381
        $sql = "SELECT * FROM $table
382
                WHERE 
383
                    user_sender_id = $senderId AND
384
                    user_receiver_id = $receiverId AND 
385
                    title = '$subject' AND 
386
                    content = '$message' AND
387
                    (msg_status = ".MESSAGE_STATUS_UNREAD." OR msg_status = ".MESSAGE_STATUS_NEW.")                    
388
                ";
389
        $result = Database::query($sql);
390
391
        return Database::num_rows($result) > 0;
392
    }
393
394
    /**
395
     * Sends a message to a user/group.
396
     *
397
     * @param int    $receiver_user_id
398
     * @param string $subject
399
     * @param string $content
400
     * @param array  $attachments                files array($_FILES) (optional)
401
     * @param array  $fileCommentList            about attachment files (optional)
402
     * @param int    $group_id                   (optional)
403
     * @param int    $parent_id                  (optional)
404
     * @param int    $editMessageId              id for updating the message (optional)
405
     * @param int    $topic_id                   (optional) the default value is the current user_id
406
     * @param int    $sender_id
407
     * @param bool   $directMessage
408
     * @param int    $forwardId
409
     * @param array  $smsParameters
410
     * @param bool   $checkCurrentAudioId
411
     * @param bool   $forceTitleWhenSendingEmail force the use of $title as subject instead of "You have a new message"
412
     *
413
     * @return bool
414
     */
415
    public static function send_message(
416
        $receiver_user_id,
417
        $subject,
418
        $content,
419
        array $attachments = [],
420
        array $fileCommentList = [],
421
        $group_id = 0,
422
        $parent_id = 0,
423
        $editMessageId = 0,
424
        $topic_id = 0,
425
        $sender_id = 0,
426
        $directMessage = false,
427
        $forwardId = 0,
428
        $smsParameters = [],
429
        $checkCurrentAudioId = false,
430
        $forceTitleWhenSendingEmail = false,
431
        $status = 0
432
    ) {
433
        $table = Database::get_main_table(TABLE_MESSAGE);
434
        $group_id = (int) $group_id;
435
        $receiver_user_id = (int) $receiver_user_id;
436
        $parent_id = (int) $parent_id;
437
        $editMessageId = (int) $editMessageId;
438
        $topic_id = (int) $topic_id;
439
440
        $status = empty($status) ? MESSAGE_STATUS_UNREAD : (int) $status;
441
442
        if (!empty($receiver_user_id)) {
443
            $receiverUserInfo = api_get_user_info($receiver_user_id);
444
445
            // Disabling messages for inactive users.
446
            if ($receiverUserInfo['active'] == 0) {
447
                return false;
448
            }
449
        }
450
451
        $user_sender_id = empty($sender_id) ? api_get_user_id() : (int) $sender_id;
452
        if (empty($user_sender_id)) {
453
            Display::addFlash(Display::return_message(get_lang('UserDoesNotExist'), 'warning'));
454
455
            return false;
456
        }
457
458
        $totalFileSize = 0;
459
        $attachmentList = [];
460
        if (is_array($attachments)) {
461
            $counter = 0;
462
            foreach ($attachments as $attachment) {
463
                $attachment['comment'] = isset($fileCommentList[$counter]) ? $fileCommentList[$counter] : '';
464
                $fileSize = isset($attachment['size']) ? $attachment['size'] : 0;
465
                if (is_array($fileSize)) {
466
                    foreach ($fileSize as $size) {
467
                        $totalFileSize += $size;
468
                    }
469
                } else {
470
                    $totalFileSize += $fileSize;
471
                }
472
                $attachmentList[] = $attachment;
473
                $counter++;
474
            }
475
        }
476
477
        if ($checkCurrentAudioId) {
478
            // Add the audio file as an attachment
479
            $audioId = Session::read('current_audio_id');
480
            if (!empty($audioId)) {
481
                $file = api_get_uploaded_file('audio_message', api_get_user_id(), $audioId);
482
                if (!empty($file)) {
483
                    $audioAttachment = [
484
                        'name' => basename($file),
485
                        'comment' => 'audio_message',
486
                        'size' => filesize($file),
487
                        'tmp_name' => $file,
488
                        'error' => 0,
489
                        'type' => DocumentManager::file_get_mime_type(basename($file)),
490
                    ];
491
                    // create attachment from audio message
492
                    $attachmentList[] = $audioAttachment;
493
                }
494
            }
495
        }
496
497
        // Validating fields
498
        if (empty($subject) && empty($group_id)) {
499
            Display::addFlash(
500
                Display::return_message(
501
                    get_lang('YouShouldWriteASubject'),
502
                    'warning'
503
                )
504
            );
505
506
            return false;
507
        } elseif ($totalFileSize > intval(api_get_setting('message_max_upload_filesize'))) {
508
            $warning = sprintf(
509
                get_lang('FilesSizeExceedsX'),
510
                format_file_size(api_get_setting('message_max_upload_filesize'))
511
            );
512
513
            Display::addFlash(Display::return_message($warning, 'warning'));
514
515
            return false;
516
        }
517
518
        // Just in case we replace the and \n and \n\r while saving in the DB
519
        // $content = str_replace(array("\n", "\n\r"), '<br />', $content);
520
        $now = api_get_utc_datetime();
521
        if (!empty($receiver_user_id) || !empty($group_id)) {
522
            // message for user friend
523
            //@todo it's possible to edit a message? yes, only for groups
524
            if (!empty($editMessageId)) {
525
                $query = " UPDATE $table SET
526
                              update_date = '".$now."',
527
                              content = '".Database::escape_string($content)."'
528
                           WHERE id = '$editMessageId' ";
529
                Database::query($query);
530
                $messageId = $editMessageId;
531
            } else {
532
                $params = [
533
                    'user_sender_id' => $user_sender_id,
534
                    'msg_status' => $status,
535
                    'send_date' => $now,
536
                    'title' => $subject,
537
                    'content' => $content,
538
                    'group_id' => $group_id,
539
                    'parent_id' => $parent_id,
540
                    'update_date' => $now,
541
                ];
542
                if (!empty($receiver_user_id)) {
543
                    $params['user_receiver_id'] = $receiver_user_id;
544
                }
545
                $messageId = Database::insert($table, $params);
546
            }
547
548
            // Forward also message attachments
549
            if (!empty($forwardId)) {
550
                $attachments = self::getAttachmentList($forwardId);
551
                foreach ($attachments as $attachment) {
552
                    if (!empty($attachment['file_source'])) {
553
                        $file = [
554
                            'name' => $attachment['filename'],
555
                            'tmp_name' => $attachment['file_source'],
556
                            'size' => $attachment['size'],
557
                            'error' => 0,
558
                            'comment' => $attachment['comment'],
559
                        ];
560
561
                        // Inject this array so files can be added when sending and email with the mailer
562
                        $attachmentList[] = $file;
563
                    }
564
                }
565
            }
566
567
            // Save attachment file for inbox messages
568
            if (is_array($attachmentList)) {
569
                foreach ($attachmentList as $attachment) {
570
                    if ($attachment['error'] == 0) {
571
                        $comment = $attachment['comment'];
572
                        self::saveMessageAttachmentFile(
573
                            $attachment,
574
                            $comment,
575
                            $messageId,
576
                            null,
577
                            $receiver_user_id,
578
                            $group_id
579
                        );
580
                    }
581
                }
582
            }
583
584
            // Save message in the outbox for user friend or group.
585
            if (empty($group_id) && $status == MESSAGE_STATUS_UNREAD) {
586
                $params = [
587
                    'user_sender_id' => $user_sender_id,
588
                    'user_receiver_id' => $receiver_user_id,
589
                    'msg_status' => MESSAGE_STATUS_OUTBOX,
590
                    'send_date' => $now,
591
                    'title' => $subject,
592
                    'content' => $content,
593
                    'group_id' => $group_id,
594
                    'parent_id' => $parent_id,
595
                    'update_date' => $now,
596
                ];
597
                $outbox_last_id = Database::insert($table, $params);
598
599
                // save attachment file for outbox messages
600
                if (is_array($attachmentList)) {
601
                    foreach ($attachmentList as $attachment) {
602
                        if ($attachment['error'] == 0) {
603
                            $comment = $attachment['comment'];
604
                            self::saveMessageAttachmentFile(
605
                                $attachment,
606
                                $comment,
607
                                $outbox_last_id,
608
                                $user_sender_id
609
                            );
610
                        }
611
                    }
612
                }
613
            }
614
615
            // Load user settings.
616
            $notification = new Notification();
617
            $sender_info = api_get_user_info($user_sender_id);
618
619
            // add file attachment additional attributes
620
            $attachmentAddedByMail = [];
621
            foreach ($attachmentList as $attachment) {
622
                $attachmentAddedByMail[] = [
623
                    'path' => $attachment['tmp_name'],
624
                    'filename' => $attachment['name'],
625
                ];
626
            }
627
628
            if (empty($group_id)) {
629
                $type = Notification::NOTIFICATION_TYPE_MESSAGE;
630
                if ($directMessage) {
631
                    $type = Notification::NOTIFICATION_TYPE_DIRECT_MESSAGE;
632
                }
633
                $notification->saveNotification(
634
                    $messageId,
635
                    $type,
636
                    [$receiver_user_id],
637
                    $subject,
638
                    $content,
639
                    $sender_info,
640
                    $attachmentAddedByMail,
641
                    $smsParameters,
642
                    $forceTitleWhenSendingEmail
643
                );
644
            } else {
645
                $usergroup = new UserGroup();
646
                $group_info = $usergroup->get($group_id);
647
                $group_info['topic_id'] = $topic_id;
648
                $group_info['msg_id'] = $messageId;
649
650
                $user_list = $usergroup->get_users_by_group(
651
                    $group_id,
652
                    false,
653
                    [],
654
                    0,
655
                    1000
656
                );
657
658
                // Adding more sense to the message group
659
                $subject = sprintf(get_lang('ThereIsANewMessageInTheGroupX'), $group_info['name']);
660
                $new_user_list = [];
661
                foreach ($user_list as $user_data) {
662
                    $new_user_list[] = $user_data['id'];
663
                }
664
                $group_info = [
665
                    'group_info' => $group_info,
666
                    'user_info' => $sender_info,
667
                ];
668
                $notification->saveNotification(
669
                    $messageId,
670
                    Notification::NOTIFICATION_TYPE_GROUP,
671
                    $new_user_list,
672
                    $subject,
673
                    $content,
674
                    $group_info,
675
                    $attachmentAddedByMail,
676
                    $smsParameters
677
                );
678
            }
679
680
            return $messageId;
681
        }
682
683
        return false;
684
    }
685
686
    /**
687
     * @param int    $receiver_user_id
688
     * @param int    $subject
689
     * @param string $message
690
     * @param int    $sender_id
691
     * @param bool   $sendCopyToDrhUsers send copy to related DRH users
692
     * @param bool   $directMessage
693
     * @param array  $smsParameters
694
     * @param bool   $uploadFiles        Do not upload files using the MessageManager class
695
     * @param array  $attachmentList
696
     *
697
     * @return bool
698
     */
699
    public static function send_message_simple(
700
        $receiver_user_id,
701
        $subject,
702
        $message,
703
        $sender_id = 0,
704
        $sendCopyToDrhUsers = false,
705
        $directMessage = false,
706
        $smsParameters = [],
707
        $uploadFiles = true,
708
        $attachmentList = []
709
    ) {
710
        $files = $_FILES ? $_FILES : [];
711
        if ($uploadFiles === false) {
712
            $files = [];
713
        }
714
        // $attachmentList must have: tmp_name, name, size keys
715
        if (!empty($attachmentList)) {
716
            $files = $attachmentList;
717
        }
718
        $result = self::send_message(
719
            $receiver_user_id,
720
            $subject,
721
            $message,
722
            $files,
723
            [],
724
            null,
725
            null,
726
            null,
727
            null,
728
            $sender_id,
729
            $directMessage,
730
            0,
731
            $smsParameters
732
        );
733
734
        if ($sendCopyToDrhUsers) {
735
            $userInfo = api_get_user_info($receiver_user_id);
736
            $drhList = UserManager::getDrhListFromUser($receiver_user_id);
737
            if (!empty($drhList)) {
738
                foreach ($drhList as $drhInfo) {
739
                    $message = sprintf(
740
                        get_lang('CopyOfMessageSentToXUser'),
741
                        $userInfo['complete_name']
742
                    ).' <br />'.$message;
743
744
                    self::send_message_simple(
745
                        $drhInfo['user_id'],
746
                        $subject,
747
                        $message,
748
                        $sender_id,
749
                        false,
750
                        $directMessage
751
                    );
752
                }
753
            }
754
        }
755
756
        return $result;
757
    }
758
759
    /**
760
     * Update parent ids for other receiver user from current message in groups.
761
     *
762
     * @author Christian Fasanando Flores
763
     *
764
     * @param int $parent_id
765
     * @param int $receiver_user_id
766
     * @param int $messageId
767
     */
768
    public static function update_parent_ids_from_reply(
769
        $parent_id,
770
        $receiver_user_id,
771
        $messageId
772
    ) {
773
        $table = Database::get_main_table(TABLE_MESSAGE);
774
        $parent_id = intval($parent_id);
775
        $receiver_user_id = intval($receiver_user_id);
776
        $messageId = intval($messageId);
777
778
        // first get data from message id (parent)
779
        $sql = "SELECT * FROM $table WHERE id = '$parent_id'";
780
        $rs_message = Database::query($sql);
781
        $row_message = Database::fetch_array($rs_message);
782
783
        // get message id from data found early for other receiver user
784
        $sql = "SELECT id FROM $table
785
                WHERE
786
                    user_sender_id ='{$row_message['user_sender_id']}' AND
787
                    title='{$row_message['title']}' AND
788
                    content='{$row_message['content']}' AND
789
                    group_id='{$row_message['group_id']}' AND
790
                    user_receiver_id='$receiver_user_id'";
791
        $result = Database::query($sql);
792
        $row = Database::fetch_array($result);
793
794
        // update parent_id for other user receiver
795
        $sql = "UPDATE $table SET parent_id = ".$row['id']."
796
                WHERE id = $messageId";
797
        Database::query($sql);
798
    }
799
800
    /**
801
     * @param int $user_receiver_id
802
     * @param int $id
803
     *
804
     * @return bool
805
     */
806
    public static function delete_message_by_user_receiver($user_receiver_id, $id)
807
    {
808
        $table = Database::get_main_table(TABLE_MESSAGE);
809
        $id = (int) $id;
810
        $user_receiver_id = (int) $user_receiver_id;
811
812
        if (empty($id) || empty($user_receiver_id)) {
813
            return false;
814
        }
815
816
        $sql = "SELECT * FROM $table
817
                WHERE id = $id AND msg_status <> ".MESSAGE_STATUS_OUTBOX;
818
        $rs = Database::query($sql);
819
820
        if (Database::num_rows($rs) > 0) {
821
            // Delete attachment file.
822
            self::delete_message_attachment_file($id, $user_receiver_id);
823
            // Soft delete message.
824
            $query = "UPDATE $table 
825
                      SET msg_status = ".MESSAGE_STATUS_DELETED."
826
                      WHERE
827
                        id = $id AND 
828
                        user_receiver_id = $user_receiver_id ";
829
            Database::query($query);
830
831
            return true;
832
        }
833
834
        return false;
835
    }
836
837
    /**
838
     * Set status deleted.
839
     *
840
     * @author Isaac FLores Paz <[email protected]>
841
     *
842
     * @param  int
843
     * @param  int
844
     *
845
     * @return bool
846
     */
847
    public static function delete_message_by_user_sender($user_sender_id, $id)
848
    {
849
        if ($id != strval(intval($id))) {
850
            return false;
851
        }
852
853
        $table = Database::get_main_table(TABLE_MESSAGE);
854
855
        $id = intval($id);
856
        $user_sender_id = intval($user_sender_id);
857
858
        $sql = "SELECT * FROM $table WHERE id='$id'";
859
        $rs = Database::query($sql);
860
861
        if (Database::num_rows($rs) > 0) {
862
            // delete attachment file
863
            self::delete_message_attachment_file($id, $user_sender_id);
864
            // delete message
865
            $sql = "UPDATE $table
866
                    SET msg_status = ".MESSAGE_STATUS_DELETED."
867
                    WHERE user_sender_id='$user_sender_id' AND id='$id'";
868
            Database::query($sql);
869
870
            return true;
871
        }
872
873
        return false;
874
    }
875
876
    /**
877
     * Saves a message attachment files.
878
     *
879
     * @param array $file_attach $_FILES['name']
880
     * @param  string    a comment about the uploaded file
881
     * @param  int        message id
882
     * @param  int        receiver user id (optional)
883
     * @param  int        sender user id (optional)
884
     * @param  int        group id (optional)
885
     */
886
    public static function saveMessageAttachmentFile(
887
        $file_attach,
888
        $file_comment,
889
        $message_id,
890
        $receiver_user_id = 0,
891
        $sender_user_id = 0,
892
        $group_id = 0
893
    ) {
894
        $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
895
896
        // Try to add an extension to the file if it hasn't one
897
        $type = isset($file_attach['type']) ? $file_attach['type'] : '';
898
        if (empty($type)) {
899
            $type = DocumentManager::file_get_mime_type($file_attach['name']);
900
        }
901
        $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $type);
902
903
        // user's file name
904
        $file_name = $file_attach['name'];
905
        if (!filter_extension($new_file_name)) {
906
            Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
907
        } else {
908
            $new_file_name = uniqid('');
909
            if (!empty($receiver_user_id)) {
910
                $message_user_id = $receiver_user_id;
911
            } else {
912
                $message_user_id = $sender_user_id;
913
            }
914
915
            // User-reserved directory where photos have to be placed.*
916
            $userGroup = new UserGroup();
917
            if (!empty($group_id)) {
918
                $path_user_info = $userGroup->get_group_picture_path_by_id(
919
                    $group_id,
920
                    'system',
921
                    true
922
                );
923
            } else {
924
                $path_user_info['dir'] = UserManager::getUserPathById($message_user_id, 'system');
925
            }
926
927
            $path_message_attach = $path_user_info['dir'].'message_attachments/';
928
            // If this directory does not exist - we create it.
929
            if (!file_exists($path_message_attach)) {
930
                @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
931
            }
932
933
            $new_path = $path_message_attach.$new_file_name;
934
            $fileCopied = false;
935
            if (isset($file_attach['tmp_name']) && !empty($file_attach['tmp_name'])) {
936
                if (is_uploaded_file($file_attach['tmp_name'])) {
937
                    @copy($file_attach['tmp_name'], $new_path);
938
                    $fileCopied = true;
939
                } else {
940
                    // 'tmp_name' can be set by the ticket or when forwarding a message
941
                    if (file_exists($file_attach['tmp_name'])) {
942
                        @copy($file_attach['tmp_name'], $new_path);
943
                        $fileCopied = true;
944
                    }
945
                }
946
            }
947
948
            if ($fileCopied) {
949
                // Storing the attachments if any
950
                $params = [
951
                    'filename' => $file_name,
952
                    'comment' => $file_comment,
953
                    'path' => $new_file_name,
954
                    'message_id' => $message_id,
955
                    'size' => $file_attach['size'],
956
                ];
957
958
                return Database::insert($table, $params);
959
            }
960
        }
961
962
        return false;
963
    }
964
965
    /**
966
     * Delete message attachment files (logically updating the row with a suffix _DELETE_id).
967
     *
968
     * @param  int    message id
969
     * @param  int    message user id (receiver user id or sender user id)
970
     * @param  int    group id (optional)
971
     */
972
    public static function delete_message_attachment_file(
973
        $message_id,
974
        $message_uid,
975
        $group_id = 0
976
    ) {
977
        $message_id = (int) $message_id;
978
        $message_uid = (int) $message_uid;
979
        $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
980
981
        $sql = "SELECT * FROM $table_message_attach
982
                WHERE message_id = '$message_id'";
983
        $rs = Database::query($sql);
984
        while ($row = Database::fetch_array($rs)) {
985
            $path = $row['path'];
986
            $attach_id = (int) $row['id'];
987
            $new_path = $path.'_DELETED_'.$attach_id;
988
989
            if (!empty($group_id)) {
990
                $userGroup = new UserGroup();
991
                $path_user_info = $userGroup->get_group_picture_path_by_id(
992
                    $group_id,
993
                    'system',
994
                    true
995
                );
996
            } else {
997
                $path_user_info['dir'] = UserManager::getUserPathById(
998
                    $message_uid,
999
                    'system'
1000
                );
1001
            }
1002
1003
            $path_message_attach = $path_user_info['dir'].'message_attachments/';
1004
            if (is_file($path_message_attach.$path)) {
1005
                if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
1006
                    $sql = "UPDATE $table_message_attach 
1007
                            SET path = '$new_path'
1008
                            WHERE id = $attach_id ";
1009
                    Database::query($sql);
1010
                }
1011
            }
1012
        }
1013
    }
1014
1015
    /**
1016
     * @param int $user_id
1017
     * @param int $message_id
1018
     * @param int $type
1019
     *
1020
     * @return bool
1021
     */
1022
    public static function update_message_status($user_id, $message_id, $type)
1023
    {
1024
        $user_id = (int) $user_id;
1025
        $message_id = (int) $message_id;
1026
        $type = (int) $type;
1027
1028
        if (empty($user_id) || empty($message_id)) {
1029
            return false;
1030
        }
1031
1032
        $table_message = Database::get_main_table(TABLE_MESSAGE);
1033
        $sql = "UPDATE $table_message SET
1034
                    msg_status = '$type'
1035
                WHERE
1036
                    user_receiver_id = ".$user_id." AND
1037
                    id = '".$message_id."'";
1038
        Database::query($sql);
1039
    }
1040
1041
    /**
1042
     * get messages by group id.
1043
     *
1044
     * @param int $group_id group id
1045
     *
1046
     * @return array
1047
     */
1048
    public static function get_messages_by_group($group_id)
1049
    {
1050
        $group_id = (int) $group_id;
1051
1052
        if (empty($group_id)) {
1053
            return false;
1054
        }
1055
1056
        $table = Database::get_main_table(TABLE_MESSAGE);
1057
        $sql = "SELECT * FROM $table
1058
                WHERE
1059
                    group_id= $group_id AND
1060
                    msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
1061
                ORDER BY id";
1062
        $rs = Database::query($sql);
1063
        $data = [];
1064
        if (Database::num_rows($rs) > 0) {
1065
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1066
                $data[] = $row;
1067
            }
1068
        }
1069
1070
        return $data;
1071
    }
1072
1073
    /**
1074
     * get messages by group id.
1075
     *
1076
     * @param int $group_id
1077
     * @param int $message_id
1078
     *
1079
     * @return array
1080
     */
1081
    public static function get_messages_by_group_by_message($group_id, $message_id)
1082
    {
1083
        $group_id = (int) $group_id;
1084
1085
        if (empty($group_id)) {
1086
            return false;
1087
        }
1088
1089
        $table = Database::get_main_table(TABLE_MESSAGE);
1090
        $sql = "SELECT * FROM $table
1091
                WHERE
1092
                    group_id = $group_id AND
1093
                    msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
1094
                ORDER BY id ";
1095
1096
        $rs = Database::query($sql);
1097
        $data = [];
1098
        $parents = [];
1099
        if (Database::num_rows($rs) > 0) {
1100
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1101
                if ($message_id == $row['parent_id'] || in_array($row['parent_id'], $parents)) {
1102
                    $parents[] = $row['id'];
1103
                    $data[] = $row;
1104
                }
1105
            }
1106
        }
1107
1108
        return $data;
1109
    }
1110
1111
    /**
1112
     * Get messages by parent id optionally with limit.
1113
     *
1114
     * @param  int        parent id
1115
     * @param  int        group id (optional)
1116
     * @param  int        offset (optional)
1117
     * @param  int        limit (optional)
1118
     *
1119
     * @return array
1120
     */
1121
    public static function getMessagesByParent($parentId, $groupId = 0, $offset = 0, $limit = 0)
1122
    {
1123
        $table = Database::get_main_table(TABLE_MESSAGE);
1124
        $parentId = (int) $parentId;
1125
1126
        if (empty($parentId)) {
1127
            return [];
1128
        }
1129
1130
        $condition_group_id = '';
1131
        if (!empty($groupId)) {
1132
            $groupId = (int) $groupId;
1133
            $condition_group_id = " AND group_id = '$groupId' ";
1134
        }
1135
1136
        $condition_limit = '';
1137
        if ($offset && $limit) {
1138
            $offset = (int) $offset;
1139
            $limit = (int) $limit;
1140
            $offset = ($offset - 1) * $limit;
1141
            $condition_limit = " LIMIT $offset,$limit ";
1142
        }
1143
1144
        $sql = "SELECT * FROM $table
1145
                WHERE
1146
                    parent_id='$parentId' AND
1147
                    msg_status NOT IN (".MESSAGE_STATUS_OUTBOX.", ".MESSAGE_STATUS_WALL_DELETE.")
1148
                    $condition_group_id
1149
                ORDER BY send_date DESC $condition_limit ";
1150
        $rs = Database::query($sql);
1151
        $data = [];
1152
        if (Database::num_rows($rs) > 0) {
1153
            while ($row = Database::fetch_array($rs)) {
1154
                $data[$row['id']] = $row;
1155
            }
1156
        }
1157
1158
        return $data;
1159
    }
1160
1161
    /**
1162
     * Gets information about messages sent.
1163
     *
1164
     * @param int
1165
     * @param int
1166
     * @param string
1167
     * @param string
1168
     *
1169
     * @return array
1170
     */
1171
    public static function get_message_data_sent(
1172
        $from,
1173
        $numberOfItems,
1174
        $column,
1175
        $direction,
1176
        $extraParams = []
1177
    ) {
1178
        $from = (int) $from;
1179
        $numberOfItems = (int) $numberOfItems;
1180
        if (!isset($direction)) {
1181
            $column = 2;
1182
            $direction = 'DESC';
1183
        } else {
1184
            $column = (int) $column;
1185
            if (!in_array($direction, ['ASC', 'DESC'])) {
1186
                $direction = 'ASC';
1187
            }
1188
        }
1189
1190
        if (!in_array($column, [0, 1, 2])) {
1191
            $column = 2;
1192
        }
1193
        $table = Database::get_main_table(TABLE_MESSAGE);
1194
        $request = api_is_xml_http_request();
1195
        $keyword = isset($extraParams['keyword']) ? $extraParams['keyword'] : '';
1196
        $keywordCondition = '';
1197
        if (!empty($keyword)) {
1198
            $keyword = Database::escape_string($keyword);
1199
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
1200
        }
1201
1202
        $sql = "SELECT
1203
                    id as col0,
1204
                    title as col1,
1205
                    send_date as col2,
1206
                    user_receiver_id,
1207
                    msg_status,
1208
                    user_sender_id
1209
                FROM $table
1210
                WHERE
1211
                    user_sender_id = ".api_get_user_id()." AND
1212
                    msg_status = ".MESSAGE_STATUS_OUTBOX."
1213
                    $keywordCondition
1214
                ORDER BY col$column $direction
1215
                LIMIT $from, $numberOfItems";
1216
        $result = Database::query($sql);
1217
1218
        $message_list = [];
1219
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1220
            $messageId = $row['col0'];
1221
            $title = $row['col1'];
1222
            $sendDate = $row['col2'];
1223
            $senderId = $row['user_sender_id'];
1224
1225
            if ($request === true) {
1226
                $message[0] = '<input type="checkbox" value='.$messageId.' name="out[]">';
1227
            } else {
1228
                $message[0] = $messageId;
1229
            }
1230
1231
            $class = 'class = "read"';
1232
            $title = Security::remove_XSS($title);
1233
            $userInfo = api_get_user_info($senderId);
1234
            if ($request === true) {
1235
                $message[1] = '<a onclick="show_sent_message('.$messageId.')" href="javascript:void(0)">'.
1236
                    $userInfo['complete_name_with_username'].'</a>';
1237
                $message[2] = '<a onclick="show_sent_message('.$messageId.')" href="javascript:void(0)">'.str_replace(
1238
                        "\\",
1239
                        "",
1240
                        $title
1241
                    ).'</a>';
1242
                //date stays the same
1243
                $message[3] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
1244
                $message[4] = '&nbsp;&nbsp;<a title="'.addslashes(
1245
                        get_lang('DeleteMessage')
1246
                    ).'" onclick="delete_one_message_outbox('.$messageId.')" href="javascript:void(0)"  >'.
1247
                    Display::returnFontAwesomeIcon('trash', 2).'</a>';
1248
            } else {
1249
                $message[1] = '<a '.$class.' onclick="show_sent_message('.$messageId.')" href="../messages/view_message.php?id_send='.$messageId.'">'.$title.'</a><br />'.$userInfo['complete_name_with_username'];
1250
                $message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
1251
                $message[3] = '<a title="'.addslashes(
1252
                        get_lang('DeleteMessage')
1253
                    ).'" href="outbox.php?action=deleteone&id='.$messageId.'"  onclick="javascript:if(!confirm('."'".addslashes(
1254
                        api_htmlentities(get_lang('ConfirmDeleteMessage'))
1255
                    )."'".')) return false;" >'.
1256
                    Display::returnFontAwesomeIcon('trash', 2).'</a>';
1257
            }
1258
1259
            $message_list[] = $message;
1260
        }
1261
1262
        return $message_list;
1263
    }
1264
1265
    /**
1266
     * display message box in the inbox.
1267
     *
1268
     * @param int the message id
1269
     * @param string inbox or outbox strings are available
1270
     *
1271
     * @todo replace numbers with letters in the $row array pff...
1272
     *
1273
     * @return string html with the message content
1274
     */
1275
    public static function showMessageBox($messageId, $source = 'inbox')
1276
    {
1277
        $table = Database::get_main_table(TABLE_MESSAGE);
1278
        $messageId = (int) $messageId;
1279
        $currentUserId = api_get_user_id();
1280
1281
        if ($source === 'outbox') {
1282
            if (isset($messageId) && is_numeric($messageId)) {
1283
                $query = "SELECT * FROM $table
1284
                          WHERE
1285
                            user_sender_id = ".$currentUserId." AND
1286
                            id = $messageId AND
1287
                            msg_status = ".MESSAGE_STATUS_OUTBOX;
1288
                $result = Database::query($query);
1289
            }
1290
        } else {
1291
            if (is_numeric($messageId) && !empty($messageId)) {
1292
                $query = "UPDATE $table SET
1293
                          msg_status = '".MESSAGE_STATUS_NEW."'
1294
                          WHERE
1295
                            user_receiver_id=".$currentUserId." AND
1296
                            id = '".$messageId."'";
1297
                Database::query($query);
1298
1299
                $query = "SELECT * FROM $table
1300
                          WHERE
1301
                            msg_status<> ".MESSAGE_STATUS_OUTBOX." AND
1302
                            user_receiver_id = ".$currentUserId." AND
1303
                            id = '".$messageId."'";
1304
                $result = Database::query($query);
1305
            }
1306
        }
1307
        $row = Database::fetch_array($result, 'ASSOC');
1308
1309
        if (empty($row)) {
1310
            return '';
1311
        }
1312
1313
        $user_sender_id = $row['user_sender_id'];
1314
1315
        // get file attachments by message id
1316
        $files_attachments = self::getAttachmentLinkList(
1317
            $messageId,
1318
            $source
1319
        );
1320
1321
        $row['content'] = str_replace('</br>', '<br />', $row['content']);
1322
        $title = Security::remove_XSS($row['title'], STUDENT, true);
1323
        $content = Security::remove_XSS($row['content'], STUDENT, true);
1324
1325
        $name = get_lang('UnknownUser');
1326
        $fromUser = api_get_user_info($user_sender_id);
1327
        $userImage = '';
1328
        if (!empty($user_sender_id) && !empty($fromUser)) {
1329
            $name = $fromUser['complete_name_with_username'];
1330
            $userImage = Display::img(
1331
                $fromUser['avatar_small'],
1332
                $name,
1333
                ['title' => $name, 'class' => 'img-responsive img-circle', 'style' => 'max-width:35px'],
1334
                false
1335
            );
1336
        }
1337
1338
        $message_content = Display::page_subheader(str_replace("\\", "", $title));
1339
1340
        $receiverUserInfo = [];
1341
        if (!empty($row['user_receiver_id'])) {
1342
            $receiverUserInfo = api_get_user_info($row['user_receiver_id']);
1343
        }
1344
1345
        $message_content .= '<tr>';
1346
        if (api_get_setting('allow_social_tool') === 'true') {
1347
            $message_content .= '<div class="row">';
1348
            if ($source === 'outbox') {
1349
                $message_content .= '<div class="col-md-12">';
1350
                $message_content .= '<ul class="list-message">';
1351
                $message_content .= '<li>'.$userImage.'</li>';
1352
                $message_content .= '<li>'.$name.'&nbsp;';
1353
                if (!empty($receiverUserInfo)) {
1354
                    $message_content .= api_strtolower(
1355
                            get_lang('To')
1356
                        ).'&nbsp;<b>'.$receiverUserInfo['complete_name_with_username'].'</b></li>';
1357
                } else {
1358
                    $message_content .= api_strtolower(get_lang('To')).'&nbsp;<b>-</b></li>';
1359
                }
1360
1361
                $message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
1362
                $message_content .= '</ul>';
1363
                $message_content .= '</div>';
1364
            } else {
1365
                $message_content .= '<div class="col-md-12">';
1366
                $message_content .= '<ul class="list-message">';
1367
                if (!empty($user_sender_id)) {
1368
                    $message_content .= '<li>'.$userImage.'</li>';
1369
                    $message_content .= '<li><a href="'.api_get_path(
1370
                            WEB_PATH
1371
                        ).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a>';
1372
                } else {
1373
                    $message_content .= '<li>'.$name;
1374
                }
1375
1376
                if ($source === 'inbox') {
1377
                    $message_content .= '&nbsp;'.api_strtolower(get_lang('To')).'&nbsp;'.get_lang('Me');
1378
                }
1379
                $message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
1380
                $message_content .= '</ul>';
1381
                $message_content .= '</div>';
1382
            }
1383
            $message_content .= '</div>';
1384
        } else {
1385
            if ($source === 'outbox') {
1386
                $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
1387
                    $receiverUserInfo['complete_name_with_username'].'</b>';
1388
            } else {
1389
                $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
1390
                    get_lang('Me').'</b>';
1391
            }
1392
        }
1393
1394
        $message_content .= '
1395
		        <hr style="color:#ddd" />
1396
		        <table width="100%">
1397
		            <tr>
1398
		              <td valign=top class="view-message-content">'.str_replace("\\", "", $content).'</td>
1399
		            </tr>
1400
		        </table>
1401
		        <div id="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>
1402
		        <div style="padding: 15px 0px 5px 0px">';
1403
        $social_link = '';
1404
        if (isset($_GET['f']) && $_GET['f'] == 'social') {
1405
            $social_link = 'f=social';
1406
        }
1407
1408
        if ($source == 'outbox') {
1409
            $message_content .= '<a href="outbox.php?'.$social_link.'">'.
1410
                Display::return_icon('back.png', get_lang('ReturnToOutbox')).'</a> &nbsp';
1411
        } elseif ($source === 'inbox') {
1412
            $message_content .= '<a href="inbox.php?'.$social_link.'">'.
1413
                Display::return_icon('back.png', get_lang('ReturnToInbox')).'</a> &nbsp';
1414
            $message_content .= '<a href="new_message.php?re_id='.$messageId.'&'.$social_link.'">'.
1415
                Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a> &nbsp';
1416
        }
1417
        $urlMessage['delete'] = 'inbox.php?action=deleteone&id='.$messageId.'&'.$social_link;
1418
1419
        if (in_array($source, ['inbox', 'outbox'])) {
1420
            $message_content .= '<a href="inbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
1421
                Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
1422
        }
1423
1424
        $message_content .= '</div></td>
1425
		      <td width=10></td>
1426
		    </tr>
1427
		</table>';
1428
1429
        return $message_content;
1430
    }
1431
1432
    /**
1433
     * get user id by user email.
1434
     *
1435
     * @param string $user_email
1436
     *
1437
     * @return int user id
1438
     */
1439
    public static function get_user_id_by_email($user_email)
1440
    {
1441
        $table = Database::get_main_table(TABLE_MAIN_USER);
1442
        $sql = 'SELECT user_id
1443
                FROM '.$table.'
1444
                WHERE email="'.Database::escape_string($user_email).'";';
1445
        $rs = Database::query($sql);
1446
        $row = Database::fetch_array($rs, 'ASSOC');
1447
        if (isset($row['user_id'])) {
1448
            return $row['user_id'];
1449
        }
1450
1451
        return null;
1452
    }
1453
1454
    /**
1455
     * Displays messages of a group with nested view.
1456
     *
1457
     * @param int $groupId
1458
     *
1459
     * @return string
1460
     */
1461
    public static function display_messages_for_group($groupId)
1462
    {
1463
        global $my_group_role;
1464
1465
        $rows = self::get_messages_by_group($groupId);
1466
        $topics_per_page = 10;
1467
        $html_messages = '';
1468
        $query_vars = ['id' => $groupId, 'topics_page_nr' => 0];
1469
1470
        if (is_array($rows) && count($rows) > 0) {
1471
            // prepare array for topics with its items
1472
            $topics = [];
1473
            $x = 0;
1474
            foreach ($rows as $index => $value) {
1475
                if (empty($value['parent_id'])) {
1476
                    $topics[$value['id']] = $value;
1477
                }
1478
            }
1479
1480
            $new_topics = [];
1481
1482
            foreach ($topics as $id => $value) {
1483
                $rows = null;
1484
                $rows = self::get_messages_by_group_by_message($groupId, $value['id']);
1485
                if (!empty($rows)) {
1486
                    $count = count(self::calculate_children($rows, $value['id']));
1487
                } else {
1488
                    $count = 0;
1489
                }
1490
                $value['count'] = $count;
1491
                $new_topics[$id] = $value;
1492
            }
1493
1494
            $array_html = [];
1495
            foreach ($new_topics as $index => $topic) {
1496
                $html = '';
1497
                // topics
1498
                $user_sender_info = api_get_user_info($topic['user_sender_id']);
1499
                $name = $user_sender_info['complete_name'];
1500
                $html .= '<div class="groups-messages">';
1501
                $html .= '<div class="row">';
1502
1503
                $items = $topic['count'];
1504
                $reply_label = ($items == 1) ? get_lang('GroupReply') : get_lang('GroupReplies');
1505
                $label = '<i class="fa fa-envelope"></i> '.$items.' '.$reply_label;
1506
                $topic['title'] = trim($topic['title']);
1507
1508
                if (empty($topic['title'])) {
1509
                    $topic['title'] = get_lang('Untitled');
1510
                }
1511
1512
                $html .= '<div class="col-xs-8 col-md-10">';
1513
                $html .= Display::tag(
1514
                    'h4',
1515
                    Display::url(
1516
                        Security::remove_XSS($topic['title'], STUDENT, true),
1517
                        api_get_path(WEB_CODE_PATH).'social/group_topics.php?id='.$groupId.'&topic_id='.$topic['id']
1518
                    ),
1519
                    ['class' => 'title']
1520
                );
1521
                $actions = '';
1522
                if ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
1523
                    $my_group_role == GROUP_USER_PERMISSION_MODERATOR
1524
                ) {
1525
                    $actions = '<br />'.Display::url(
1526
                            get_lang('Delete'),
1527
                            api_get_path(
1528
                                WEB_CODE_PATH
1529
                            ).'social/group_topics.php?action=delete&id='.$groupId.'&topic_id='.$topic['id'],
1530
                            ['class' => 'btn btn-default']
1531
                        );
1532
                }
1533
1534
                $date = '';
1535
                if ($topic['send_date'] != $topic['update_date']) {
1536
                    if (!empty($topic['update_date'])) {
1537
                        $date .= '<i class="fa fa-calendar"></i> '.get_lang(
1538
                                'LastUpdate'
1539
                            ).' '.Display::dateToStringAgoAndLongDate($topic['update_date']);
1540
                    }
1541
                } else {
1542
                    $date .= '<i class="fa fa-calendar"></i> '.get_lang(
1543
                            'Created'
1544
                        ).' '.Display::dateToStringAgoAndLongDate($topic['send_date']);
1545
                }
1546
                $html .= '<div class="date">'.$label.' - '.$date.$actions.'</div>';
1547
                $html .= '</div>';
1548
1549
                $image = $user_sender_info['avatar'];
1550
1551
                $user_info = '<div class="author"><img class="img-responsive img-circle" src="'.$image.'" alt="'.$name.'"  width="64" height="64" title="'.$name.'" /></div>';
1552
                $user_info .= '<div class="name"><a href="'.api_get_path(
1553
                        WEB_PATH
1554
                    ).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a></div>';
1555
1556
                $html .= '<div class="col-xs-4 col-md-2">';
1557
                $html .= $user_info;
1558
                $html .= '</div>';
1559
                $html .= '</div>';
1560
                $html .= '</div>';
1561
1562
                $array_html[] = [$html];
1563
            }
1564
1565
            // grids for items and topics  with paginations
1566
            $html_messages .= Display::return_sortable_grid(
1567
                'topics',
1568
                [],
1569
                $array_html,
1570
                [
1571
                    'hide_navigation' => false,
1572
                    'per_page' => $topics_per_page,
1573
                ],
1574
                $query_vars,
1575
                false,
1576
                [true, true, true, false],
1577
                false
1578
            );
1579
        }
1580
1581
        return $html_messages;
1582
    }
1583
1584
    /**
1585
     * Displays messages of a group with nested view.
1586
     *
1587
     * @param $groupId
1588
     * @param $topic_id
1589
     * @param $is_member
1590
     * @param $messageId
1591
     *
1592
     * @return string
1593
     */
1594
    public static function display_message_for_group($groupId, $topic_id, $is_member, $messageId)
1595
    {
1596
        global $my_group_role;
1597
        $main_message = self::get_message_by_id($topic_id);
1598
        if (empty($main_message)) {
1599
            return false;
1600
        }
1601
1602
        $webCodePath = api_get_path(WEB_CODE_PATH);
1603
        $iconCalendar = Display::returnFontAwesomeIcon('calendar');
1604
1605
        $langEdit = get_lang('Edit');
1606
        $langReply = get_lang('Reply');
1607
        $langLastUpdated = get_lang('LastUpdated');
1608
        $langCreated = get_lang('Created');
1609
1610
        $rows = self::get_messages_by_group_by_message($groupId, $topic_id);
1611
        $rows = self::calculate_children($rows, $topic_id);
1612
        $current_user_id = api_get_user_id();
1613
1614
        $items_per_page = 50;
1615
        $query_vars = ['id' => $groupId, 'topic_id' => $topic_id, 'topics_page_nr' => 0];
1616
1617
        // Main message
1618
        $links = '';
1619
        $main_content = '';
1620
        $html = '';
1621
        $items_page_nr = null;
1622
1623
        $user_sender_info = api_get_user_info($main_message['user_sender_id']);
1624
        $files_attachments = self::getAttachmentLinkList($main_message['id']);
1625
        $name = $user_sender_info['complete_name'];
1626
1627
        $topic_page_nr = isset($_GET['topics_page_nr']) ? (int) $_GET['topics_page_nr'] : null;
1628
1629
        $links .= '<div class="pull-right">';
1630
        $links .= '<div class="btn-group btn-group-sm">';
1631
1632
        if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) ||
1633
            $main_message['user_sender_id'] == $current_user_id
1634
        ) {
1635
            $urlEdit = $webCodePath.'social/message_for_group_form.inc.php?'
1636
                .http_build_query(
1637
                    [
1638
                        'user_friend' => $current_user_id,
1639
                        'group_id' => $groupId,
1640
                        'message_id' => $main_message['id'],
1641
                        'action' => 'edit_message_group',
1642
                        'anchor_topic' => 'topic_'.$main_message['id'],
1643
                        'topics_page_nr' => $topic_page_nr,
1644
                        'items_page_nr' => $items_page_nr,
1645
                        'topic_id' => $main_message['id'],
1646
                    ]
1647
                );
1648
1649
            $links .= Display::toolbarButton(
1650
                $langEdit,
1651
                $urlEdit,
1652
                'pencil',
1653
                'default',
1654
                ['class' => 'ajax', 'data-title' => $langEdit, 'data-size' => 'lg'],
1655
                false
1656
            );
1657
        }
1658
1659
        $links .= self::getLikesButton($main_message['id'], $current_user_id, $groupId);
1660
1661
        $urlReply = $webCodePath.'social/message_for_group_form.inc.php?'
1662
            .http_build_query(
1663
                [
1664
                    'user_friend' => $current_user_id,
1665
                    'group_id' => $groupId,
1666
                    'message_id' => $main_message['id'],
1667
                    'action' => 'reply_message_group',
1668
                    'anchor_topic' => 'topic_'.$main_message['id'],
1669
                    'topics_page_nr' => $topic_page_nr,
1670
                    'topic_id' => $main_message['id'],
1671
                ]
1672
            );
1673
1674
        $links .= Display::toolbarButton(
1675
            $langReply,
1676
            $urlReply,
1677
            'commenting',
1678
            'default',
1679
            ['class' => 'ajax', 'data-title' => $langReply, 'data-size' => 'lg'],
1680
            false
1681
        );
1682
1683
        if (api_is_platform_admin()) {
1684
            $links .= Display::toolbarButton(
1685
                get_lang('Delete'),
1686
                'group_topics.php?action=delete&id='.$groupId.'&topic_id='.$topic_id,
1687
                'trash',
1688
                'default',
1689
                [],
1690
                false
1691
            );
1692
        }
1693
1694
        $links .= '</div>';
1695
        $links .= '</div>';
1696
1697
        $title = '<h4>'.Security::remove_XSS($main_message['title'], STUDENT, true).$links.'</h4>';
1698
1699
        $userPicture = $user_sender_info['avatar'];
1700
        $main_content .= '<div class="row">';
1701
        $main_content .= '<div class="col-md-2">';
1702
        $main_content .= '<div class="avatar-author">';
1703
        $main_content .= Display::img(
1704
            $userPicture,
1705
            $name,
1706
            ['width' => '60px', 'class' => 'img-responsive img-circle'],
1707
            false
1708
        );
1709
        $main_content .= '</div>';
1710
        $main_content .= '</div>';
1711
1712
        $date = '';
1713
        if ($main_message['send_date'] != $main_message['update_date']) {
1714
            if (!empty($main_message['update_date'])) {
1715
                $date = '<div class="date"> '
1716
                    ."$iconCalendar $langLastUpdated "
1717
                    .Display::dateToStringAgoAndLongDate($main_message['update_date'])
1718
                    .'</div>';
1719
            }
1720
        } else {
1721
            $date = '<div class="date"> '
1722
                ."$iconCalendar $langCreated "
1723
                .Display::dateToStringAgoAndLongDate($main_message['send_date'])
1724
                .'</div>';
1725
        }
1726
        $attachment = '<div class="message-attach">'
1727
            .(!empty($files_attachments) ? implode('<br />', $files_attachments) : '')
1728
            .'</div>';
1729
        $main_content .= '<div class="col-md-10">';
1730
        $user_link = Display::url(
1731
            $name,
1732
            $webCodePath.'social/profile.php?u='.$main_message['user_sender_id']
1733
        );
1734
        $main_content .= '<div class="message-content"> ';
1735
        $main_content .= '<div class="username">'.$user_link.'</div>';
1736
        $main_content .= $date;
1737
        $main_content .= '<div class="message">'.$main_message['content'].$attachment.'</div></div>';
1738
        $main_content .= '</div>';
1739
        $main_content .= '</div>';
1740
1741
        $html .= Display::div(
1742
            Display::div(
1743
                $title.$main_content,
1744
                ['class' => 'message-topic']
1745
            ),
1746
            ['class' => 'sm-groups-message']
1747
        );
1748
1749
        $topic_id = $main_message['id'];
1750
1751
        if (is_array($rows) && count($rows) > 0) {
1752
            $topics = $rows;
1753
            $array_html_items = [];
1754
1755
            foreach ($topics as $index => $topic) {
1756
                if (empty($topic['id'])) {
1757
                    continue;
1758
                }
1759
                $items_page_nr = isset($_GET['items_'.$topic['id'].'_page_nr'])
1760
                    ? (int) $_GET['items_'.$topic['id'].'_page_nr']
1761
                    : null;
1762
                $links = '';
1763
                $links .= '<div class="pull-right">';
1764
                $html_items = '';
1765
                $user_sender_info = api_get_user_info($topic['user_sender_id']);
1766
                $files_attachments = self::getAttachmentLinkList($topic['id']);
1767
                $name = $user_sender_info['complete_name'];
1768
1769
                $links .= '<div class="btn-group btn-group-sm">';
1770
                if (
1771
                    ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
1772
                        $my_group_role == GROUP_USER_PERMISSION_MODERATOR
1773
                    ) ||
1774
                    $topic['user_sender_id'] == $current_user_id
1775
                ) {
1776
                    $links .= Display::toolbarButton(
1777
                        $langEdit,
1778
                        $webCodePath.'social/message_for_group_form.inc.php?'
1779
                            .http_build_query(
1780
                                [
1781
                                    'user_friend' => $current_user_id,
1782
                                    'group_id' => $groupId,
1783
                                    'message_id' => $topic['id'],
1784
                                    'action' => 'edit_message_group',
1785
                                    'anchor_topic' => 'topic_'.$topic_id,
1786
                                    'topics_page_nr' => $topic_page_nr,
1787
                                    'items_page_nr' => $items_page_nr,
1788
                                    'topic_id' => $topic_id,
1789
                                ]
1790
                            ),
1791
                        'pencil',
1792
                        'default',
1793
                        ['class' => 'ajax', 'data-title' => $langEdit, 'data-size' => 'lg'],
1794
                        false
1795
                    );
1796
                }
1797
1798
                $links .= self::getLikesButton($topic['id'], $current_user_id, $groupId);
1799
1800
                $links .= Display::toolbarButton(
1801
                    $langReply,
1802
                    $webCodePath.'social/message_for_group_form.inc.php?'
1803
                        .http_build_query(
1804
                            [
1805
                                'user_friend' => $current_user_id,
1806
                                'group_id' => $groupId,
1807
                                'message_id' => $topic['id'],
1808
                                'action' => 'reply_message_group',
1809
                                'anchor_topic' => 'topic_'.$topic_id,
1810
                                'topics_page_nr' => $topic_page_nr,
1811
                                'items_page_nr' => $items_page_nr,
1812
                                'topic_id' => $topic_id,
1813
                            ]
1814
                        ),
1815
                    'commenting',
1816
                    'default',
1817
                    ['class' => 'ajax', 'data-title' => $langReply, 'data-size' => 'lg'],
1818
                    false
1819
                );
1820
                $links .= '</div>';
1821
                $links .= '</div>';
1822
1823
                $userPicture = $user_sender_info['avatar'];
1824
                $user_link = Display::url(
1825
                    $name,
1826
                    $webCodePath.'social/profile.php?u='.$topic['user_sender_id']
1827
                );
1828
                $html_items .= '<div class="row">';
1829
                $html_items .= '<div class="col-md-2">';
1830
                $html_items .= '<div class="avatar-author">';
1831
                $html_items .= Display::img(
1832
                    $userPicture,
1833
                    $name,
1834
                    ['width' => '60px', 'class' => 'img-responsive img-circle'],
1835
                    false
1836
                );
1837
                $html_items .= '</div>';
1838
                $html_items .= '</div>';
1839
1840
                $date = '';
1841
                if ($topic['send_date'] != $topic['update_date']) {
1842
                    if (!empty($topic['update_date'])) {
1843
                        $date = '<div class="date"> '
1844
                            ."$iconCalendar $langLastUpdated "
1845
                            .Display::dateToStringAgoAndLongDate($topic['update_date'])
1846
                            .'</div>';
1847
                    }
1848
                } else {
1849
                    $date = '<div class="date"> '
1850
                        ."$iconCalendar $langCreated "
1851
                        .Display::dateToStringAgoAndLongDate($topic['send_date'])
1852
                        .'</div>';
1853
                }
1854
                $attachment = '<div class="message-attach">'
1855
                    .(!empty($files_attachments) ? implode('<br />', $files_attachments) : '')
1856
                    .'</div>';
1857
                $html_items .= '<div class="col-md-10">'
1858
                    .'<div class="message-content">'
1859
                    .$links
1860
                    .'<div class="username">'.$user_link.'</div>'
1861
                    .$date
1862
                    .'<div class="message">'
1863
                    .Security::remove_XSS($topic['content'], STUDENT, true)
1864
                    .'</div>'.$attachment.'</div>'
1865
                    .'</div>'
1866
                    .'</div>';
1867
1868
                $base_padding = 20;
1869
1870
                if ($topic['indent_cnt'] == 0) {
1871
                    $indent = $base_padding;
1872
                } else {
1873
                    $indent = (int) $topic['indent_cnt'] * $base_padding + $base_padding;
1874
                }
1875
1876
                $html_items = Display::div($html_items, ['class' => 'message-post', 'id' => 'msg_'.$topic['id']]);
1877
                $html_items = Display::div($html_items, ['class' => '', 'style' => 'margin-left:'.$indent.'px']);
1878
                $array_html_items[] = [$html_items];
1879
            }
1880
1881
            // grids for items with paginations
1882
            $options = ['hide_navigation' => false, 'per_page' => $items_per_page];
1883
            $visibility = [true, true, true, false];
1884
1885
            $style_class = [
1886
                'item' => ['class' => 'user-post'],
1887
                'main' => ['class' => 'user-list'],
1888
            ];
1889
            if (!empty($array_html_items)) {
1890
                $html .= Display::return_sortable_grid(
1891
                    'items_'.$topic['id'],
1892
                    [],
1893
                    $array_html_items,
1894
                    $options,
1895
                    $query_vars,
1896
                    null,
1897
                    $visibility,
1898
                    false,
1899
                    $style_class
1900
                );
1901
            }
1902
        }
1903
1904
        return $html;
1905
    }
1906
1907
    /**
1908
     * Add children to messages by id is used for nested view messages.
1909
     *
1910
     * @param array $rows rows of messages
1911
     *
1912
     * @return array $first_seed new list adding the item children
1913
     */
1914
    public static function calculate_children($rows, $first_seed)
1915
    {
1916
        $rows_with_children = [];
1917
        foreach ($rows as $row) {
1918
            $rows_with_children[$row["id"]] = $row;
1919
            $rows_with_children[$row["parent_id"]]["children"][] = $row["id"];
1920
        }
1921
        $rows = $rows_with_children;
1922
        $sorted_rows = [0 => []];
1923
        self::message_recursive_sort($rows, $sorted_rows, $first_seed);
1924
        unset($sorted_rows[0]);
1925
1926
        return $sorted_rows;
1927
    }
1928
1929
    /**
1930
     * Sort recursively the messages, is used for for nested view messages.
1931
     *
1932
     * @param array  original rows of messages
1933
     * @param array  list recursive of messages
1934
     * @param int   seed for calculate the indent
1935
     * @param int   indent for nested view
1936
     */
1937
    public static function message_recursive_sort(
1938
        $rows,
1939
        &$messages,
1940
        $seed = 0,
1941
        $indent = 0
1942
    ) {
1943
        if ($seed > 0 && isset($rows[$seed]["id"])) {
1944
            $messages[$rows[$seed]["id"]] = $rows[$seed];
1945
            $messages[$rows[$seed]["id"]]["indent_cnt"] = $indent;
1946
            $indent++;
1947
        }
1948
1949
        if (isset($rows[$seed]["children"])) {
1950
            foreach ($rows[$seed]["children"] as $child) {
1951
                self::message_recursive_sort($rows, $messages, $child, $indent);
1952
            }
1953
        }
1954
    }
1955
1956
    /**
1957
     * @param int $messageId
1958
     *
1959
     * @return array
1960
     */
1961
    public static function getAttachmentList($messageId)
1962
    {
1963
        $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1964
        $messageId = (int) $messageId;
1965
1966
        if (empty($messageId)) {
1967
            return [];
1968
        }
1969
1970
        $messageInfo = self::get_message_by_id($messageId);
1971
1972
        if (empty($messageInfo)) {
1973
            return [];
1974
        }
1975
1976
        $attachmentDir = UserManager::getUserPathById($messageInfo['user_receiver_id'], 'system');
1977
        $attachmentDir .= 'message_attachments/';
1978
1979
        $sql = "SELECT * FROM $table
1980
                WHERE message_id = '$messageId'";
1981
        $result = Database::query($sql);
1982
        $files = [];
1983
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1984
            $row['file_source'] = '';
1985
            if (file_exists($attachmentDir.$row['path'])) {
1986
                $row['file_source'] = $attachmentDir.$row['path'];
1987
            }
1988
            $files[] = $row;
1989
        }
1990
1991
        return $files;
1992
    }
1993
1994
    /**
1995
     * Get array of links (download) for message attachment files.
1996
     *
1997
     * @param int    $messageId
1998
     * @param string $type      message list (inbox/outbox)
1999
     *
2000
     * @return array
2001
     */
2002
    public static function getAttachmentLinkList($messageId, $type = '')
2003
    {
2004
        $files = self::getAttachmentList($messageId);
2005
        // get file attachments by message id
2006
        $list = [];
2007
        $totalSize = 0;
2008
2009
        if ($files) {
2010
            $archiveURL = api_get_path(WEB_CODE_PATH).'messages/download.php?type='.$type.'&file=';
2011
            $countFiles = count($files);
2012
2013
            foreach ($files as $row_file) {
2014
                $archiveFile = $row_file['path'];
2015
                $filename = $row_file['filename'];
2016
                $totalSize += $row_file['size'];
2017
                $size = format_file_size($row_file['size']);
2018
                $comment = Security::remove_XSS($row_file['comment']);
2019
                $filename = Security::remove_XSS($filename);
2020
                $type = 'file';
2021
2022
                if ($row_file['comment'] == 'audio_message') {
2023
                    $type = 'audio';
2024
                }
2025
2026
                $listTemp = [
2027
                    'filename' => $filename,
2028
                    'size' => $size,
2029
                    'comment' => $comment,
2030
                    'url' => $archiveURL.$archiveFile,
2031
                    'type' => $type,
2032
                ];
2033
2034
                $list[] = $listTemp;
2035
            }
2036
2037
            return [
2038
                'quantity' => $countFiles,
2039
                'total_size' => format_file_size($totalSize),
2040
                'files' => $list,
2041
            ];
2042
        } else {
2043
            return [];
2044
        }
2045
    }
2046
2047
    /**
2048
     * Get message list by id.
2049
     *
2050
     * @param int $messageId
2051
     *
2052
     * @return array
2053
     */
2054
    public static function get_message_by_id($messageId)
2055
    {
2056
        $table = Database::get_main_table(TABLE_MESSAGE);
2057
        $messageId = (int) $messageId;
2058
        $sql = "SELECT * FROM $table
2059
                WHERE 
2060
                    id = '$messageId' AND 
2061
                    msg_status <> '".MESSAGE_STATUS_DELETED."' ";
2062
        $res = Database::query($sql);
2063
        $item = [];
2064
        if (Database::num_rows($res) > 0) {
2065
            $item = Database::fetch_array($res, 'ASSOC');
2066
        }
2067
2068
        return $item;
2069
    }
2070
2071
    /**
2072
     * @return string
2073
     */
2074
    public static function generate_message_form()
2075
    {
2076
        $form = new FormValidator('send_message');
2077
        $form->addText(
2078
            'subject',
2079
            get_lang('Subject'),
2080
            false,
2081
            ['id' => 'subject_id']
2082
        );
2083
        $form->addTextarea(
2084
            'content',
2085
            get_lang('Message'),
2086
            ['id' => 'content_id', 'rows' => '5']
2087
        );
2088
2089
        return $form->returnForm();
2090
    }
2091
2092
    /**
2093
     * @return string
2094
     */
2095
    public static function generate_invitation_form()
2096
    {
2097
        $form = new FormValidator('send_invitation');
2098
        $form->addTextarea(
2099
            'content',
2100
            get_lang('AddPersonalMessage'),
2101
            ['id' => 'content_invitation_id', 'rows' => 5]
2102
        );
2103
2104
        return $form->returnForm();
2105
    }
2106
2107
    /**
2108
     * @param string $statusList
2109
     * @param array  $keyword
2110
     * @param array  $actions
2111
     * @param string $viewUrl
2112
     *
2113
     * @return string
2114
     */
2115
    public static function getMessageGrid($statusList, $keyword, $actions = [], $viewUrl = '')
2116
    {
2117
        if (empty($statusList)) {
2118
            return '';
2119
        }
2120
        $success = get_lang('SelectedMessagesDeleted');
2121
        $success_read = get_lang('SelectedMessagesRead');
2122
        $success_unread = get_lang('SelectedMessagesUnRead');
2123
        $currentUserId = api_get_user_id();
2124
        $html = '';
2125
2126
        if (isset($_REQUEST['action'])) {
2127
            switch ($_REQUEST['action']) {
2128
                case 'mark_as_unread':
2129
                    if (is_array($_POST['id'])) {
2130
                        foreach ($_POST['id'] as $index => $messageId) {
2131
                            self::update_message_status(
2132
                                $currentUserId,
2133
                                $messageId,
2134
                                MESSAGE_STATUS_UNREAD
2135
                            );
2136
                        }
2137
                    }
2138
                    $html .= Display::return_message(
2139
                        api_xml_http_response_encode($success_unread),
2140
                        'normal',
2141
                        false
2142
                    );
2143
                    break;
2144
                case 'mark_as_read':
2145
                    if (is_array($_POST['id'])) {
2146
                        foreach ($_POST['id'] as $index => $messageId) {
2147
                            self::update_message_status(
2148
                                $currentUserId,
2149
                                $messageId,
2150
                                MESSAGE_STATUS_NEW
2151
                            );
2152
                        }
2153
                    }
2154
                    $html .= Display::return_message(
2155
                        api_xml_http_response_encode($success_read),
2156
                        'normal',
2157
                        false
2158
                    );
2159
                    break;
2160
                case 'delete':
2161
                    foreach ($_POST['id'] as $index => $messageId) {
2162
                        self::delete_message_by_user_receiver($currentUserId, $messageId);
2163
                    }
2164
                    $html .= Display::return_message(
2165
                        api_xml_http_response_encode($success),
2166
                        'normal',
2167
                        false
2168
                    );
2169
                    break;
2170
                case 'deleteone':
2171
                    self::delete_message_by_user_receiver($currentUserId, $_GET['id']);
2172
                    $html .= Display::return_message(
2173
                        api_xml_http_response_encode($success),
2174
                        'confirmation',
2175
                        false
2176
                    );
2177
                    break;
2178
            }
2179
        }
2180
2181
        // display sortable table with messages of the current user
2182
        $table = new SortableTable(
2183
            'message_inbox',
2184
            ['MessageManager', 'getNumberOfMessages'],
2185
            ['MessageManager', 'getMessageData'],
2186
            2,
2187
            20,
2188
            'DESC'
2189
        );
2190
2191
        $table->setDataFunctionParams(
2192
            ['keyword' => $keyword, 'message_status' => $statusList, 'actions' => $actions, 'view_url' => $viewUrl]
2193
        );
2194
        $table->set_header(0, '', false, ['style' => 'width:15px;']);
2195
        $table->set_header(1, get_lang('Messages'), false);
2196
        $table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
2197
        $table->set_header(3, get_lang('Modify'), false, ['style' => 'width:120px;']);
2198
2199
        if (isset($_REQUEST['f']) && $_REQUEST['f'] === 'social') {
2200
            $parameters['f'] = 'social';
2201
            $table->set_additional_parameters($parameters);
2202
        }
2203
2204
        $defaultActions = [
2205
            'delete' => get_lang('DeleteSelectedMessages'),
2206
            'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
2207
            'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
2208
        ];
2209
2210
        if (!in_array('delete', $actions)) {
2211
            unset($defaultActions['delete']);
2212
        }
2213
        if (!in_array('mark_as_unread', $actions)) {
2214
            unset($defaultActions['mark_as_unread']);
2215
        }
2216
        if (!in_array('mark_as_read', $actions)) {
2217
            unset($defaultActions['mark_as_read']);
2218
        }
2219
2220
        $table->set_form_actions($defaultActions);
2221
2222
        $html .= $table->return_table();
2223
2224
        return $html;
2225
    }
2226
2227
    /**
2228
     * @param string $keyword
2229
     *
2230
     * @return string
2231
     */
2232
    public static function inboxDisplay($keyword = '')
2233
    {
2234
        $actions = ['reply', 'mark_as_unread', 'mark_as_read', 'forward', 'delete'];
2235
        $html = self::getMessageGrid([MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD], $keyword, $actions);
2236
2237
        return $html;
2238
    }
2239
2240
    /**
2241
     * @param string $keyword
2242
     *
2243
     * @return string
2244
     */
2245
    public static function getPromotedMessagesGrid($keyword = '')
2246
    {
2247
        //$actions = ['edit', 'delete'];
2248
        $actions = ['delete'];
2249
        $url = api_get_path(WEB_CODE_PATH).'social/view_promoted_message.php';
2250
        $html = self::getMessageGrid([MESSAGE_STATUS_PROMOTED], $keyword, $actions, $url);
2251
2252
        return $html;
2253
    }
2254
2255
    /**
2256
     * @param string $keyword
2257
     *
2258
     * @return string
2259
     */
2260
    public static function outbox_display($keyword = '')
2261
    {
2262
        Session::write('message_sent_search_keyword', $keyword);
2263
        $success = get_lang('SelectedMessagesDeleted').'&nbsp</b><br />
2264
                    <a href="outbox.php">'.get_lang('BackToOutbox').'</a>';
2265
2266
        $html = '';
2267
        if (isset($_REQUEST['action'])) {
2268
            switch ($_REQUEST['action']) {
2269
                case 'delete':
2270
                    $count = count($_POST['id']);
2271
                    if ($count != 0) {
2272
                        foreach ($_POST['id'] as $index => $messageId) {
2273
                            self::delete_message_by_user_receiver(
2274
                                api_get_user_id(),
2275
                                $messageId
2276
                            );
2277
                        }
2278
                    }
2279
                    $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
2280
                    break;
2281
                case 'deleteone':
2282
                    self::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
2283
                    $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
2284
                    $html .= '<br/>';
2285
                    break;
2286
            }
2287
        }
2288
2289
        // display sortable table with messages of the current user
2290
        $table = new SortableTable(
2291
            'message_outbox',
2292
            ['MessageManager', 'getNumberOfMessages'],
2293
            ['MessageManager', 'get_message_data_sent'],
2294
            2,
2295
            20,
2296
            'DESC'
2297
        );
2298
        $table->setDataFunctionParams(
2299
            ['keyword' => $keyword, 'message_status' => [MESSAGE_STATUS_OUTBOX]]
2300
        );
2301
2302
        $table->set_header(0, '', false, ['style' => 'width:15px;']);
2303
        $table->set_header(1, get_lang('Messages'), false);
2304
        $table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
2305
        $table->set_header(3, get_lang('Modify'), false, ['style' => 'width:70px;']);
2306
2307
        $table->set_form_actions(['delete' => get_lang('DeleteSelectedMessages')]);
2308
        $html .= $table->return_table();
2309
2310
        return $html;
2311
    }
2312
2313
    /**
2314
     * Get the count of the last received messages for a user.
2315
     *
2316
     * @param int $userId The user id
2317
     * @param int $lastId The id of the last received message
2318
     *
2319
     * @return int The count of new messages
2320
     */
2321
    public static function countMessagesFromLastReceivedMessage($userId, $lastId = 0)
2322
    {
2323
        $userId = intval($userId);
2324
        $lastId = intval($lastId);
2325
2326
        if (empty($userId)) {
2327
            return 0;
2328
        }
2329
2330
        $messagesTable = Database::get_main_table(TABLE_MESSAGE);
2331
2332
        $conditions = [
2333
            'where' => [
2334
                'user_receiver_id = ?' => $userId,
2335
                'AND msg_status = ?' => MESSAGE_STATUS_UNREAD,
2336
                'AND id > ?' => $lastId,
2337
            ],
2338
        ];
2339
2340
        $result = Database::select('COUNT(1) AS qty', $messagesTable, $conditions);
2341
2342
        if (!empty($result)) {
2343
            $row = current($result);
2344
2345
            return $row['qty'];
2346
        }
2347
2348
        return 0;
2349
    }
2350
2351
    /**
2352
     * Get the data of the last received messages for a user.
2353
     *
2354
     * @deprecated 2.0 Use Chamilo\CoreBundle\Repository\MessageRepository::getFromLastOneReceived
2355
     *
2356
     * @param int $userId The user id
2357
     * @param int $lastId The id of the last received message
2358
     *
2359
     * @return array
2360
     */
2361
    public static function getMessagesFromLastReceivedMessage($userId, $lastId = 0)
2362
    {
2363
        $userId = (int) $userId;
2364
        $lastId = (int) $lastId;
2365
2366
        if (empty($userId)) {
2367
            return [];
2368
        }
2369
2370
        $messagesTable = Database::get_main_table(TABLE_MESSAGE);
2371
        $userTable = Database::get_main_table(TABLE_MAIN_USER);
2372
2373
        $sql = "SELECT m.*, u.user_id, u.lastname, u.firstname
2374
                FROM $messagesTable as m
2375
                INNER JOIN $userTable as u
2376
                ON m.user_sender_id = u.user_id
2377
                WHERE
2378
                    m.user_receiver_id = $userId AND
2379
                    m.msg_status = ".MESSAGE_STATUS_UNREAD."
2380
                    AND m.id > $lastId
2381
                ORDER BY m.send_date DESC";
2382
2383
        $result = Database::query($sql);
2384
2385
        $messages = [];
2386
        if ($result !== false) {
2387
            while ($row = Database::fetch_assoc($result)) {
2388
                $messages[] = $row;
2389
            }
2390
        }
2391
2392
        return $messages;
2393
    }
2394
2395
    /**
2396
     * Check whether a message has attachments.
2397
     *
2398
     * @param int $messageId The message id
2399
     *
2400
     * @return bool Whether the message has attachments return true. Otherwise return false
2401
     */
2402
    public static function hasAttachments($messageId)
2403
    {
2404
        $messageId = (int) $messageId;
2405
2406
        if (empty($messageId)) {
2407
            return false;
2408
        }
2409
2410
        $messageAttachmentTable = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
2411
2412
        $conditions = [
2413
            'where' => [
2414
                'message_id = ?' => $messageId,
2415
            ],
2416
        ];
2417
2418
        $result = Database::select(
2419
            'COUNT(1) AS qty',
2420
            $messageAttachmentTable,
2421
            $conditions,
2422
            'first'
2423
        );
2424
2425
        if (!empty($result)) {
2426
            if ($result['qty'] > 0) {
2427
                return true;
2428
            }
2429
        }
2430
2431
        return false;
2432
    }
2433
2434
    /**
2435
     * @param int $messageId
2436
     *
2437
     * @return array|bool
2438
     */
2439
    public static function getAttachment($messageId)
2440
    {
2441
        $messageId = (int) $messageId;
2442
2443
        if (empty($messageId)) {
2444
            return false;
2445
        }
2446
2447
        $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
2448
2449
        $conditions = [
2450
            'where' => [
2451
                'id = ?' => $messageId,
2452
            ],
2453
        ];
2454
2455
        $result = Database::select(
2456
            '*',
2457
            $table,
2458
            $conditions,
2459
            'first'
2460
        );
2461
2462
        if (!empty($result)) {
2463
            return $result;
2464
        }
2465
2466
        return false;
2467
    }
2468
2469
    /**
2470
     * @param string $url
2471
     *
2472
     * @return FormValidator
2473
     */
2474
    public static function getSearchForm($url)
2475
    {
2476
        $form = new FormValidator(
2477
            'search',
2478
            'post',
2479
            $url,
2480
            null,
2481
            [],
2482
            FormValidator::LAYOUT_INLINE
2483
        );
2484
2485
        $form->addElement(
2486
            'text',
2487
            'keyword',
2488
            false,
2489
            [
2490
                'aria-label' => get_lang('Search'),
2491
            ]
2492
        );
2493
        $form->addButtonSearch(get_lang('Search'));
2494
2495
        return $form;
2496
    }
2497
2498
    /**
2499
     * Send a notification to all admins when a new user is registered.
2500
     *
2501
     * @param User $user
2502
     */
2503
    public static function sendNotificationByRegisteredUser(User $user)
2504
    {
2505
        $tplMailBody = new Template(
2506
            null,
2507
            false,
2508
            false,
2509
            false,
2510
            false,
2511
            false,
2512
            false
2513
        );
2514
        $tplMailBody->assign('user', $user);
2515
        $tplMailBody->assign('is_western_name_order', api_is_western_name_order());
2516
        $tplMailBody->assign(
2517
            'manageUrl',
2518
            api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user->getId()
2519
        );
2520
2521
        $layoutContent = $tplMailBody->get_template('mail/new_user_mail_to_admin.tpl');
2522
2523
        $emailsubject = '['.get_lang('UserRegistered').'] '.$user->getUsername();
2524
        $emailbody = $tplMailBody->fetch($layoutContent);
2525
2526
        $admins = UserManager::get_all_administrators();
2527
2528
        foreach ($admins as $admin_info) {
2529
            self::send_message(
2530
                $admin_info['user_id'],
2531
                $emailsubject,
2532
                $emailbody,
2533
                [],
2534
                [],
2535
                null,
2536
                null,
2537
                null,
2538
                null,
2539
                $user->getId()
2540
            );
2541
        }
2542
    }
2543
2544
    /**
2545
     * Get the error log from failed mailing
2546
     * This assumes a complex setup where you have a cron script regularly copying the mail queue log
2547
     * into app/cache/mail/mailq.
2548
     * This can be done with a cron command like (check the location of your mail log file first):.
2549
     *
2550
     * @example 0,30 * * * * root cp /var/log/exim4/mainlog /var/www/chamilo/app/cache/mail/mailq
2551
     *
2552
     * @return array|bool
2553
     */
2554
    public static function failedSentMailErrors()
2555
    {
2556
        $base = api_get_path(SYS_ARCHIVE_PATH).'mail/';
2557
        $mailq = $base.'mailq';
2558
2559
        if (!file_exists($mailq) || !is_readable($mailq)) {
2560
            return false;
2561
        }
2562
2563
        $file = fopen($mailq, 'r');
2564
        $i = 1;
2565
        while (!feof($file)) {
2566
            $line = fgets($file);
2567
2568
            if (trim($line) == '') {
2569
                continue;
2570
            }
2571
2572
            // Get the mail code, something like 1WBumL-0002xg-FF
2573
            if (preg_match('/(.*)\s((.*)-(.*)-(.*))\s<(.*)$/', $line, $codeMatches)) {
2574
                $mail_queue[$i]['code'] = $codeMatches[2];
2575
            }
2576
2577
            $fullMail = $base.$mail_queue[$i]['code'];
2578
            $mailFile = fopen($fullMail, 'r');
2579
2580
            // Get the reason of mail fail
2581
            $iX = 1;
2582
            while (!feof($mailFile)) {
2583
                $mailLine = fgets($mailFile);
2584
                //if ($iX == 4 && preg_match('/(.*):\s(.*)$/', $mailLine, $matches)) {
2585
                if ($iX == 2 &&
2586
                    preg_match('/(.*)(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s(.*)/', $mailLine, $detailsMatches)
2587
                ) {
2588
                    $mail_queue[$i]['reason'] = $detailsMatches[3];
2589
                }
2590
                $iX++;
2591
            }
2592
2593
            fclose($mailFile);
2594
2595
            // Get the time of mail fail
2596
            if (preg_match('/^\s?(\d+)(\D+)\s+(.*)$/', $line, $timeMatches)) {
2597
                $mail_queue[$i]['time'] = $timeMatches[1].$timeMatches[2];
2598
            } elseif (preg_match('/^(\s+)((.*)@(.*))\s+(.*)$/', $line, $emailMatches)) {
2599
                $mail_queue[$i]['mail'] = $emailMatches[2];
2600
                $i++;
2601
            }
2602
        }
2603
2604
        fclose($file);
2605
2606
        return array_reverse($mail_queue);
2607
    }
2608
2609
    /**
2610
     * @param int $userId
2611
     *
2612
     * @return array
2613
     */
2614
    public static function getUsersThatHadConversationWithUser($userId)
2615
    {
2616
        $messagesTable = Database::get_main_table(TABLE_MESSAGE);
2617
        $userId = (int) $userId;
2618
2619
        $sql = "SELECT DISTINCT
2620
                    user_sender_id
2621
                FROM $messagesTable
2622
                WHERE
2623
                    user_receiver_id = ".$userId;
2624
        $result = Database::query($sql);
2625
        $users = Database::store_result($result);
2626
        $userList = [];
2627
        foreach ($users as $userData) {
2628
            $userId = $userData['user_sender_id'];
2629
            if (empty($userId)) {
2630
                continue;
2631
            }
2632
            $userInfo = api_get_user_info($userId);
2633
            if ($userInfo) {
2634
                $userList[$userId] = $userInfo;
2635
            }
2636
        }
2637
2638
        return $userList;
2639
    }
2640
2641
    /**
2642
     * @param int $userId
2643
     * @param int $otherUserId
2644
     *
2645
     * @return array
2646
     */
2647
    public static function getAllMessagesBetweenStudents($userId, $otherUserId)
2648
    {
2649
        $messagesTable = Database::get_main_table(TABLE_MESSAGE);
2650
        $userId = (int) $userId;
2651
        $otherUserId = (int) $otherUserId;
2652
2653
        if (empty($otherUserId) || empty($userId)) {
2654
            return [];
2655
        }
2656
2657
        $sql = "SELECT DISTINCT * 
2658
                FROM $messagesTable
2659
                WHERE
2660
                    (user_receiver_id = $userId AND user_sender_id = $otherUserId) OR
2661
                    (user_receiver_id = $otherUserId AND user_sender_id = $userId)
2662
                ORDER BY send_date DESC
2663
            ";
2664
        $result = Database::query($sql);
2665
        $messages = Database::store_result($result);
2666
        $list = [];
2667
        foreach ($messages as $message) {
2668
            $list[] = $message;
2669
        }
2670
2671
        return $list;
2672
    }
2673
2674
    /**
2675
     * @param string $subject
2676
     * @param string $message
2677
     * @param array  $courseInfo
2678
     * @param int    $sessionId
2679
     *
2680
     * @return bool
2681
     */
2682
    public static function sendMessageToAllUsersInCourse($subject, $message, $courseInfo, $sessionId = 0)
2683
    {
2684
        if (empty($courseInfo)) {
2685
            return false;
2686
        }
2687
2688
        $senderId = api_get_user_id();
2689
        if (empty($senderId)) {
2690
            return false;
2691
        }
2692
        if (empty($sessionId)) {
2693
            // Course students and teachers
2694
            $users = CourseManager::get_user_list_from_course_code($courseInfo['code']);
2695
        } else {
2696
            // Course-session students and course session coaches
2697
            $users = CourseManager::get_user_list_from_course_code($courseInfo['code'], $sessionId);
2698
        }
2699
2700
        if (empty($users)) {
2701
            return false;
2702
        }
2703
2704
        foreach ($users as $userInfo) {
2705
            self::send_message_simple(
2706
                $userInfo['user_id'],
2707
                $subject,
2708
                $message,
2709
                $senderId,
2710
                false,
2711
                false,
2712
                [],
2713
                false
2714
            );
2715
        }
2716
    }
2717
2718
    /**
2719
     * Clean audio messages already added in the message tool.
2720
     */
2721
    public static function cleanAudioMessage()
2722
    {
2723
        $audioId = Session::read('current_audio_id');
2724
        if (!empty($audioId)) {
2725
            api_remove_uploaded_file_by_id('audio_message', api_get_user_id(), $audioId);
2726
            Session::erase('current_audio_id');
2727
        }
2728
    }
2729
2730
    /**
2731
     * @param int    $senderId
2732
     * @param string $subject
2733
     * @param string $message
2734
     */
2735
    public static function sendMessageToAllAdminUsers(
2736
        $senderId,
2737
        $subject,
2738
        $message
2739
    ) {
2740
        $admins = UserManager::get_all_administrators();
2741
        foreach ($admins as $admin) {
2742
            self::send_message_simple($admin['user_id'], $subject, $message, $senderId);
2743
        }
2744
    }
2745
2746
    /**
2747
     * @param int $messageId
2748
     * @param int $userId
2749
     *
2750
     * @return array
2751
     */
2752
    public static function countLikesAndDislikes($messageId, $userId)
2753
    {
2754
        if (!api_get_configuration_value('social_enable_messages_feedback')) {
2755
            return [];
2756
        }
2757
2758
        $messageId = (int) $messageId;
2759
        $userId = (int) $userId;
2760
2761
        $em = Database::getManager();
2762
        $query = $em
2763
            ->createQuery('
2764
                SELECT SUM(l.liked) AS likes, SUM(l.disliked) AS dislikes FROM ChamiloCoreBundle:MessageFeedback l
2765
                WHERE l.message = :message
2766
            ')
2767
            ->setParameters(['message' => $messageId]);
2768
2769
        try {
2770
            $counts = $query->getSingleResult();
2771
        } catch (Exception $e) {
2772
            $counts = ['likes' => 0, 'dislikes' => 0];
2773
        }
2774
2775
        $userLike = $em
2776
            ->getRepository('ChamiloCoreBundle:MessageFeedback')
2777
            ->findOneBy(['message' => $messageId, 'user' => $userId]);
2778
2779
        return [
2780
            'likes' => (int) $counts['likes'],
2781
            'dislikes' => (int) $counts['dislikes'],
2782
            'user_liked' => $userLike ? $userLike->isLiked() : false,
2783
            'user_disliked' => $userLike ? $userLike->isDisliked() : false,
2784
        ];
2785
    }
2786
2787
    /**
2788
     * @param int $messageId
2789
     * @param int $userId
2790
     * @param int $groupId   Optional.
2791
     *
2792
     * @return string
2793
     */
2794
    public static function getLikesButton($messageId, $userId, $groupId = 0)
2795
    {
2796
        if (!api_get_configuration_value('social_enable_messages_feedback')) {
2797
            return '';
2798
        }
2799
2800
        $countLikes = self::countLikesAndDislikes($messageId, $userId);
2801
2802
        $btnLike = Display::button(
2803
            'like',
2804
            Display::returnFontAwesomeIcon('thumbs-up', '', true)
2805
                .PHP_EOL.'<span>'.$countLikes['likes'].'</span>',
2806
            [
2807
                'title' => get_lang('VoteLike'),
2808
                'class' => 'btn btn-default social-like '.($countLikes['user_liked'] ? 'disabled' : ''),
2809
                'data-status' => 'like',
2810
                'data-message' => $messageId,
2811
                'data-group' => $groupId,
2812
            ]
2813
        );
2814
        $btnDislike = Display::button(
2815
            'like',
2816
            Display::returnFontAwesomeIcon('thumbs-down', '', true)
2817
            .PHP_EOL.'<span>'.$countLikes['dislikes'].'</span>',
2818
            [
2819
                'title' => get_lang('VoteDislike'),
2820
                'class' => 'btn btn-default social-like '.($countLikes['user_disliked'] ? 'disabled' : ''),
2821
                'data-status' => 'dislike',
2822
                'data-message' => $messageId,
2823
                'data-group' => $groupId,
2824
            ]
2825
        );
2826
2827
        return $btnLike.PHP_EOL.$btnDislike;
2828
    }
2829
2830
    /**
2831
     * Execute the SQL necessary to know the number of messages in the database.
2832
     *
2833
     * @param int $userId The user for which we need the unread messages count
2834
     *
2835
     * @return int The number of unread messages in the database for the given user
2836
     */
2837
    public static function getCountNewMessagesFromDB($userId)
2838
    {
2839
        $userId = (int) $userId;
2840
2841
        if (empty($userId)) {
2842
            return 0;
2843
        }
2844
2845
        $table = Database::get_main_table(TABLE_MESSAGE);
2846
        $sql = "SELECT COUNT(id) as count 
2847
                FROM $table
2848
                WHERE
2849
                    user_receiver_id=".$userId." AND
2850
                    msg_status = ".MESSAGE_STATUS_UNREAD;
2851
        $result = Database::query($sql);
2852
        $row = Database::fetch_assoc($result);
2853
2854
        return $row['count'];
2855
    }
2856
}
2857