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