Passed
Push — master ( f437d8...92f70a )
by Julito
10:14
created

MessageManager::send_message()   F

Complexity

Conditions 35
Paths 7013

Size

Total Lines 266
Code Lines 166

Duplication

Lines 0
Ratio 0 %

Importance

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