Passed
Push — 1.11.x ( 220ec2...a18d33 )
by Angel Fernando Quiroz
10:53
created

MessageManager::getMessagesCountForUser()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 19
nc 6
nop 1
dl 0
loc 34
rs 9.6333
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Message;
6
use Chamilo\UserBundle\Entity\User;
7
use ChamiloSession as Session;
8
9
/**
10
 * Class MessageManager.
11
 *
12
 * This class provides methods for messages management.
13
 * Include/require it in your code to use its features.
14
 */
15
class MessageManager
16
{
17
    const MESSAGE_TYPE_INBOX = 1;
18
    const MESSAGE_TYPE_OUTBOX = 2;
19
    const MESSAGE_TYPE_PROMOTED = 3;
20
21
    /**
22
     * Get count new messages for the current user from the database.
23
     *
24
     * @return int
25
     */
26
    public static function getCountNewMessages()
27
    {
28
        $userId = api_get_user_id();
29
        if (empty($userId)) {
30
            return false;
31
        }
32
33
        static $count;
34
        if (!isset($count)) {
35
            $cacheAvailable = api_get_configuration_value('apc');
36
            if ($cacheAvailable === true) {
37
                $var = api_get_configuration_value('apc_prefix').'social_messages_unread_u_'.$userId;
38
                if (apcu_exists($var)) {
39
                    $count = apcu_fetch($var);
40
                } else {
41
                    $count = self::getCountNewMessagesFromDB($userId);
42
                    apcu_store($var, $count, 60);
43
                }
44
            } else {
45
                $count = self::getCountNewMessagesFromDB($userId);
46
            }
47
        }
48
49
        return $count;
50
    }
51
52
    /**
53
     * Gets the total number of messages, used for the inbox sortable table.
54
     *
55
     * @param array $params
56
     *
57
     * @return int
58
     */
59
    public static function getNumberOfMessages($params)
60
    {
61
        $table = Database::get_main_table(TABLE_MESSAGE);
62
        $conditions = self::getWhereConditions($params);
63
64
        $sql = "SELECT COUNT(id) as number_messages
65
                FROM $table
66
                WHERE
67
                    $conditions
68
                ";
69
        $result = Database::query($sql);
70
        $result = Database::fetch_array($result);
71
72
        if ($result) {
73
            return (int) $result['number_messages'];
74
        }
75
76
        return 0;
77
    }
78
79
    /**
80
     * @param array $extraParams
81
     *
82
     * @return string
83
     */
84
    public static function getWhereConditions($extraParams)
85
    {
86
        $userId = api_get_user_id();
87
88
        $keyword = isset($extraParams['keyword']) && !empty($extraParams['keyword']) ? $extraParams['keyword'] : '';
89
        $type = isset($extraParams['type']) && !empty($extraParams['type']) ? $extraParams['type'] : '';
90
91
        if (empty($type)) {
92
            return '';
93
        }
94
95
        switch ($type) {
96
            case self::MESSAGE_TYPE_INBOX:
97
                $statusList = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
98
                $userCondition = " user_receiver_id = $userId AND";
99
                break;
100
            case self::MESSAGE_TYPE_OUTBOX:
101
                $statusList = [MESSAGE_STATUS_OUTBOX];
102
                $userCondition = " user_sender_id = $userId AND";
103
                break;
104
            case self::MESSAGE_TYPE_PROMOTED:
105
                $statusList = [MESSAGE_STATUS_PROMOTED];
106
                $userCondition = " user_receiver_id = $userId AND";
107
                break;
108
        }
109
110
        if (empty($statusList)) {
111
            return '';
112
        }
113
114
        $keywordCondition = '';
115
        if (!empty($keyword)) {
116
            $keyword = Database::escape_string($keyword);
117
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
118
        }
119
        $messageStatusCondition = implode("','", $statusList);
120
121
        return " $userCondition
122
                 msg_status IN ('$messageStatusCondition')
123
                 $keywordCondition";
124
    }
125
126
    /**
127
     * Gets information about some messages, used for the inbox sortable table.
128
     *
129
     * @param int    $from
130
     * @param int    $numberOfItems
131
     * @param int    $column
132
     * @param string $direction
133
     * @param array  $extraParams
134
     *
135
     * @return array
136
     */
137
    public static function getMessageData(
138
        $from,
139
        $numberOfItems,
140
        $column,
141
        $direction,
142
        $extraParams = []
143
    ) {
144
        $from = (int) $from;
145
        $numberOfItems = (int) $numberOfItems;
146
        // Forcing this order.
147
        if (!isset($direction)) {
148
            $column = 2;
149
            $direction = 'DESC';
150
        } else {
151
            $column = (int) $column;
152
            if (!in_array($direction, ['ASC', 'DESC'])) {
153
                $direction = 'ASC';
154
            }
155
        }
156
157
        if (!in_array($column, [0, 1, 2])) {
158
            $column = 2;
159
        }
160
161
        $type = isset($extraParams['type']) && !empty($extraParams['type']) ? $extraParams['type'] : '';
162
163
        if (empty($type)) {
164
            return [];
165
        }
166
167
        $viewUrl = '';
168
        switch ($type) {
169
            case self::MESSAGE_TYPE_OUTBOX:
170
            case self::MESSAGE_TYPE_INBOX:
171
                $viewUrl = api_get_path(WEB_CODE_PATH).'messages/view_message.php';
172
                break;
173
            case self::MESSAGE_TYPE_PROMOTED:
174
                $viewUrl = api_get_path(WEB_CODE_PATH).'social/view_promoted_message.php';
175
                break;
176
        }
177
        $viewUrl .= '?type='.$type;
178
179
        $whereConditions = self::getWhereConditions($extraParams);
180
181
        if (empty($whereConditions)) {
182
            return [];
183
        }
184
185
        $table = Database::get_main_table(TABLE_MESSAGE);
186
        $sql = "SELECT
187
                    id as col0,
188
                    title as col1,
189
                    send_date as col2,
190
                    msg_status as col3,
191
                    user_sender_id,
192
                    user_receiver_id
193
                FROM $table
194
                WHERE
195
                    $whereConditions
196
                ORDER BY col$column $direction
197
                LIMIT $from, $numberOfItems";
198
199
        $result = Database::query($sql);
200
        $messageList = [];
201
        $newMessageLink = api_get_path(WEB_CODE_PATH).'messages/new_message.php';
202
203
        $actions = $extraParams['actions'];
204
        $url = api_get_self();
205
        while ($row = Database::fetch_array($result, 'ASSOC')) {
206
            $messageId = $row['col0'];
207
            $title = $row['col1'];
208
            $sendDate = $row['col2'];
209
            $status = $row['col3'];
210
            $senderId = $row['user_sender_id'];
211
            $receiverId = $row['user_receiver_id'];
212
213
            $title = Security::remove_XSS($title, STUDENT, true);
214
            $title = cut($title, 80, true);
215
216
            $class = 'class = "read"';
217
            if (1 == $status) {
218
                $class = 'class = "unread"';
219
            }
220
221
            $userInfo = api_get_user_info($senderId);
222
            if ($type == self::MESSAGE_TYPE_OUTBOX) {
223
                $userInfo = api_get_user_info($receiverId);
224
            }
225
            $message[3] = '';
226
            if (!empty($senderId) && !empty($userInfo)) {
227
                $message[1] = '<a '.$class.' href="'.$viewUrl.'&id='.$messageId.'">'.$title.'</a><br />';
228
                $message[1] .= $userInfo['complete_name_with_username'];
229
                if (in_array('reply', $actions)) {
230
                    $message[3] =
231
                        Display::url(
232
                            Display::returnFontAwesomeIcon('reply', 2),
233
                            $newMessageLink.'?re_id='.$messageId,
234
                            ['title' => get_lang('ReplyToMessage')]
235
                        );
236
                }
237
            } else {
238
                $message[1] = '<a '.$class.' href="'.$viewUrl.'&id='.$messageId.'">'.$title.'</a><br />';
239
                $message[1] .= get_lang('UnknownUser');
240
                if (in_array('reply', $actions)) {
241
                    $message[3] =
242
                        Display::url(
243
                            Display::returnFontAwesomeIcon('reply', 2),
244
                            '#',
245
                            ['title' => get_lang('ReplyToMessage')]
246
                        );
247
                }
248
            }
249
250
            $message[0] = $messageId;
251
            $message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
252
253
            // Actions
254
            if (in_array('edit', $actions)) {
255
                $message[3] .=
256
                    '&nbsp;&nbsp;'.
257
                    Display::url(
258
                        Display::returnFontAwesomeIcon('pencil', 2),
259
                        $newMessageLink.'?action=edit&id='.$messageId,
260
                        ['title' => get_lang('ForwardMessage')]
261
                    );
262
            }
263
264
            // Actions
265
            if (in_array('forward', $actions)) {
266
                $message[3] .=
267
                    '&nbsp;&nbsp;'.
268
                    Display::url(
269
                        Display::returnFontAwesomeIcon('share', 2),
270
                        $newMessageLink.'?forward_id='.$messageId,
271
                        ['title' => get_lang('ForwardMessage')]
272
                    );
273
            }
274
275
            if (in_array('delete', $actions)) {
276
                $message[3] .= '&nbsp;&nbsp;<a title="'.addslashes(
277
                    get_lang('DeleteMessage')
278
                ).'" onclick="javascript:if(!confirm('."'".addslashes(
279
                    api_htmlentities(get_lang('ConfirmDeleteMessage'))
280
                )."'".')) return false;" href="'.$url.'?action=deleteone&id='.$messageId.'">'.
281
                Display::returnFontAwesomeIcon('trash', 2).'</a>';
282
            }
283
284
            foreach ($message as $key => $value) {
285
                $message[$key] = api_xml_http_response_encode($value);
286
            }
287
            $messageList[] = $message;
288
        }
289
290
        return $messageList;
291
    }
292
293
    /**
294
     * @param array  $aboutUserInfo
295
     * @param array  $fromUserInfo
296
     * @param string $subject
297
     * @param string $content
298
     *
299
     * @return bool
300
     */
301
    public static function sendMessageAboutUser(
302
        $aboutUserInfo,
303
        $fromUserInfo,
304
        $subject,
305
        $content
306
    ) {
307
        if (empty($aboutUserInfo) || empty($fromUserInfo)) {
308
            return false;
309
        }
310
311
        if (empty($fromUserInfo['id']) || empty($aboutUserInfo['id'])) {
312
            return false;
313
        }
314
315
        $table = Database::get_main_table(TABLE_MESSAGE);
316
        $now = api_get_utc_datetime();
317
        $params = [
318
            'user_sender_id' => $fromUserInfo['id'],
319
            'user_receiver_id' => $aboutUserInfo['id'],
320
            'msg_status' => MESSAGE_STATUS_CONVERSATION,
321
            'send_date' => $now,
322
            'title' => $subject,
323
            'content' => $content,
324
            'group_id' => 0,
325
            'parent_id' => 0,
326
            'update_date' => $now,
327
        ];
328
        $id = Database::insert($table, $params);
329
330
        if ($id) {
331
            return true;
332
        }
333
334
        return false;
335
    }
336
337
    /**
338
     * @param array $aboutUserInfo
339
     *
340
     * @return array
341
     */
342
    public static function getMessagesAboutUser($aboutUserInfo)
343
    {
344
        if (!empty($aboutUserInfo)) {
345
            $table = Database::get_main_table(TABLE_MESSAGE);
346
            $sql = 'SELECT id FROM '.$table.'
347
                    WHERE
348
                      user_receiver_id = '.$aboutUserInfo['id'].' AND
349
                      msg_status = '.MESSAGE_STATUS_CONVERSATION.'
350
                    ';
351
            $result = Database::query($sql);
352
            $messages = [];
353
            $repo = Database::getManager()->getRepository('ChamiloCoreBundle:Message');
354
            while ($row = Database::fetch_array($result)) {
355
                $message = $repo->find($row['id']);
356
                $messages[] = $message;
357
            }
358
359
            return $messages;
360
        }
361
362
        return [];
363
    }
364
365
    /**
366
     * @param array $userInfo
367
     *
368
     * @return string
369
     */
370
    public static function getMessagesAboutUserToString($userInfo)
371
    {
372
        $messages = self::getMessagesAboutUser($userInfo);
373
        $html = '';
374
        if (!empty($messages)) {
375
            /** @var Message $message */
376
            foreach ($messages as $message) {
377
                $tag = 'message_'.$message->getId();
378
                $tagAccordion = 'accordion_'.$message->getId();
379
                $tagCollapse = 'collapse_'.$message->getId();
380
                $date = Display::dateToStringAgoAndLongDate(
381
                    $message->getSendDate()
382
                );
383
                $localTime = api_get_local_time(
384
                    $message->getSendDate(),
385
                    null,
386
                    null,
387
                    false,
388
                    false
389
                );
390
                $senderId = $message->getUserSenderId();
391
                $senderInfo = api_get_user_info($senderId);
392
                $html .= Display::panelCollapse(
393
                    $localTime.' '.$senderInfo['complete_name'].' '.$message->getTitle(),
394
                    $message->getContent().'<br />'.$date.'<br />'.get_lang(
395
                        'Author'
396
                    ).': '.$senderInfo['complete_name_with_message_link'],
397
                    $tag,
398
                    null,
399
                    $tagAccordion,
400
                    $tagCollapse,
401
                    false
402
                );
403
            }
404
        }
405
406
        return $html;
407
    }
408
409
    /**
410
     * @param int    $senderId
411
     * @param int    $receiverId
412
     * @param string $subject
413
     * @param string $message
414
     *
415
     * @return bool
416
     */
417
    public static function messageWasAlreadySent($senderId, $receiverId, $subject, $message)
418
    {
419
        $table = Database::get_main_table(TABLE_MESSAGE);
420
        $senderId = (int) $senderId;
421
        $receiverId = (int) $receiverId;
422
        $subject = Database::escape_string($subject);
423
        $message = Database::escape_string($message);
424
425
        $sql = "SELECT * FROM $table
426
                WHERE
427
                    user_sender_id = $senderId AND
428
                    user_receiver_id = $receiverId AND
429
                    title = '$subject' AND
430
                    content = '$message' AND
431
                    (msg_status = ".MESSAGE_STATUS_UNREAD." OR msg_status = ".MESSAGE_STATUS_NEW.")
432
                ";
433
        $result = Database::query($sql);
434
435
        return Database::num_rows($result) > 0;
436
    }
437
438
    /**
439
     * Sends a message to a user/group.
440
     *
441
     * @param int    $receiverUserId
442
     * @param string $subject
443
     * @param string $content
444
     * @param array  $attachments                files array($_FILES) (optional)
445
     * @param array  $fileCommentList            about attachment files (optional)
446
     * @param int    $group_id                   (optional)
447
     * @param int    $parent_id                  (optional)
448
     * @param int    $editMessageId              id for updating the message (optional)
449
     * @param int    $topic_id                   (optional) the default value is the current user_id
450
     * @param int    $sender_id
451
     * @param bool   $directMessage
452
     * @param int    $forwardId
453
     * @param array  $smsParameters
454
     * @param bool   $checkCurrentAudioId
455
     * @param bool   $forceTitleWhenSendingEmail force the use of $title as subject instead of "You have a new message"
456
     * @param int    $status                     Message status
457
     *
458
     * @return bool
459
     */
460
    public static function send_message(
461
        $receiverUserId,
462
        $subject,
463
        $content,
464
        array $attachments = [],
465
        array $fileCommentList = [],
466
        $group_id = 0,
467
        $parent_id = 0,
468
        $editMessageId = 0,
469
        $topic_id = 0,
470
        $sender_id = 0,
471
        $directMessage = false,
472
        $forwardId = 0,
473
        $smsParameters = [],
474
        $checkCurrentAudioId = false,
475
        $forceTitleWhenSendingEmail = false,
476
        $status = 0
477
    ) {
478
        $group_id = (int) $group_id;
479
        $receiverUserId = (int) $receiverUserId;
480
        $parent_id = (int) $parent_id;
481
        $editMessageId = (int) $editMessageId;
482
        $topic_id = (int) $topic_id;
483
        $status = empty($status) ? MESSAGE_STATUS_UNREAD : (int) $status;
484
485
        $sendEmail = true;
486
        if (!empty($receiverUserId)) {
487
            $receiverUserInfo = api_get_user_info($receiverUserId);
488
            if (empty($receiverUserInfo)) {
489
                return false;
490
            }
491
492
            // Disabling messages for inactive users.
493
            if (0 == $receiverUserInfo['active']) {
494
                return false;
495
            }
496
497
            // Disabling messages depending the pausetraining plugin.
498
            $allowPauseFormation =
499
                'true' === api_get_plugin_setting('pausetraining', 'tool_enable') &&
500
                'true' === api_get_plugin_setting('pausetraining', 'allow_users_to_edit_pause_formation');
501
502
            if ($allowPauseFormation) {
503
                $extraFieldValue = new ExtraFieldValue('user');
504
                $disableEmails = $extraFieldValue->get_values_by_handler_and_field_variable(
505
                    $receiverUserId,
506
                    'disable_emails'
507
                );
508
509
                // User doesn't want email notifications but chamilo inbox still available.
510
                if (!empty($disableEmails) &&
511
                    isset($disableEmails['value']) && 1 === (int) $disableEmails['value']
512
                ) {
513
                    $sendEmail = false;
514
                }
515
516
                if ($sendEmail) {
517
                    // Check if user pause his formation.
518
                    $pause = $extraFieldValue->get_values_by_handler_and_field_variable(
519
                        $receiverUserId,
520
                        'pause_formation'
521
                    );
522
                    if (!empty($pause) && isset($pause['value']) && 1 === (int) $pause['value']) {
523
                        $startDate = $extraFieldValue->get_values_by_handler_and_field_variable(
524
                            $receiverUserInfo['user_id'],
525
                            'start_pause_date'
526
                        );
527
                        $endDate = $extraFieldValue->get_values_by_handler_and_field_variable(
528
                            $receiverUserInfo['user_id'],
529
                            'end_pause_date'
530
                        );
531
532
                        if (
533
                            !empty($startDate) && isset($startDate['value']) && !empty($startDate['value']) &&
534
                            !empty($endDate) && isset($endDate['value']) && !empty($endDate['value'])
535
                        ) {
536
                            $now = time();
537
                            $start = api_strtotime($startDate['value']);
538
                            $end = api_strtotime($endDate['value']);
539
540
                            if ($now > $start && $now < $end) {
541
                                $sendEmail = false;
542
                            }
543
                        }
544
                    }
545
                }
546
            }
547
        }
548
549
        $user_sender_id = empty($sender_id) ? api_get_user_id() : (int) $sender_id;
550
        if (empty($user_sender_id)) {
551
            Display::addFlash(Display::return_message(get_lang('UserDoesNotExist'), 'warning'));
552
553
            return false;
554
        }
555
556
        $totalFileSize = 0;
557
        $attachmentList = [];
558
        if (is_array($attachments)) {
559
            $counter = 0;
560
            foreach ($attachments as $attachment) {
561
                $attachment['comment'] = isset($fileCommentList[$counter]) ? $fileCommentList[$counter] : '';
562
                $fileSize = isset($attachment['size']) ? $attachment['size'] : 0;
563
                if (is_array($fileSize)) {
564
                    foreach ($fileSize as $size) {
565
                        $totalFileSize += $size;
566
                    }
567
                } else {
568
                    $totalFileSize += $fileSize;
569
                }
570
                $attachmentList[] = $attachment;
571
                $counter++;
572
            }
573
        }
574
575
        if ($checkCurrentAudioId) {
576
            // Add the audio file as an attachment
577
            $audioId = Session::read('current_audio_id');
578
            if (!empty($audioId)) {
579
                $file = api_get_uploaded_file('audio_message', api_get_user_id(), $audioId);
580
                if (!empty($file)) {
581
                    $audioAttachment = [
582
                        'name' => basename($file),
583
                        'comment' => 'audio_message',
584
                        'size' => filesize($file),
585
                        'tmp_name' => $file,
586
                        'error' => 0,
587
                        'type' => DocumentManager::file_get_mime_type(basename($file)),
588
                    ];
589
                    // create attachment from audio message
590
                    $attachmentList[] = $audioAttachment;
591
                }
592
            }
593
        }
594
595
        // Validating fields
596
        if (empty($subject) && empty($group_id)) {
597
            Display::addFlash(
598
                Display::return_message(
599
                    get_lang('YouShouldWriteASubject'),
600
                    'warning'
601
                )
602
            );
603
604
            return false;
605
        } elseif ($totalFileSize > (int) api_get_setting('message_max_upload_filesize')) {
606
            $warning = sprintf(
607
                get_lang('FilesSizeExceedsX'),
608
                format_file_size(api_get_setting('message_max_upload_filesize'))
609
            );
610
611
            Display::addFlash(Display::return_message($warning, 'warning'));
612
613
            return false;
614
        }
615
616
        $now = api_get_utc_datetime();
617
        $table = Database::get_main_table(TABLE_MESSAGE);
618
619
        if (!empty($receiverUserId) || !empty($group_id)) {
620
            // message for user friend
621
            //@todo it's possible to edit a message? yes, only for groups
622
            if (!empty($editMessageId)) {
623
                $query = " UPDATE $table SET
624
                              update_date = '".$now."',
625
                              content = '".Database::escape_string($content)."'
626
                           WHERE id = '$editMessageId' ";
627
                Database::query($query);
628
                $messageId = $editMessageId;
629
            } else {
630
                $params = [
631
                    'user_sender_id' => $user_sender_id,
632
                    'user_receiver_id' => $receiverUserId,
633
                    'msg_status' => $status,
634
                    'send_date' => $now,
635
                    'title' => $subject,
636
                    'content' => $content,
637
                    'group_id' => $group_id,
638
                    'parent_id' => $parent_id,
639
                    'update_date' => $now,
640
                ];
641
                $messageId = Database::insert($table, $params);
642
            }
643
644
            // Forward also message attachments
645
            if (!empty($forwardId)) {
646
                $attachments = self::getAttachmentList($forwardId);
647
                foreach ($attachments as $attachment) {
648
                    if (!empty($attachment['file_source'])) {
649
                        $file = [
650
                            'name' => $attachment['filename'],
651
                            'tmp_name' => $attachment['file_source'],
652
                            'size' => $attachment['size'],
653
                            'error' => 0,
654
                            'comment' => $attachment['comment'],
655
                        ];
656
657
                        // Inject this array so files can be added when sending and email with the mailer
658
                        $attachmentList[] = $file;
659
                    }
660
                }
661
            }
662
663
            // Save attachment file for inbox messages
664
            if (is_array($attachmentList)) {
665
                foreach ($attachmentList as $attachment) {
666
                    if (0 == $attachment['error']) {
667
                        $comment = $attachment['comment'];
668
                        self::saveMessageAttachmentFile(
669
                            $attachment,
670
                            $comment,
671
                            $messageId,
672
                            null,
673
                            $receiverUserId,
674
                            $group_id
675
                        );
676
                    }
677
                }
678
            }
679
680
            // Save message in the outbox for user friend or group.
681
            if (empty($group_id) && MESSAGE_STATUS_UNREAD == $status) {
682
                $params = [
683
                    'user_sender_id' => $user_sender_id,
684
                    'user_receiver_id' => $receiverUserId,
685
                    'msg_status' => MESSAGE_STATUS_OUTBOX,
686
                    'send_date' => $now,
687
                    'title' => $subject,
688
                    'content' => $content,
689
                    'group_id' => $group_id,
690
                    'parent_id' => $parent_id,
691
                    'update_date' => $now,
692
                ];
693
                $outbox_last_id = Database::insert($table, $params);
694
695
                // save attachment file for outbox messages
696
                if (is_array($attachmentList)) {
697
                    foreach ($attachmentList as $attachment) {
698
                        if (0 == $attachment['error']) {
699
                            $comment = $attachment['comment'];
700
                            self::saveMessageAttachmentFile(
701
                                $attachment,
702
                                $comment,
703
                                $outbox_last_id,
704
                                $user_sender_id
705
                            );
706
                        }
707
                    }
708
                }
709
            }
710
711
            if ($sendEmail) {
712
                $notification = new Notification();
713
                $sender_info = api_get_user_info($user_sender_id);
714
715
                // add file attachment additional attributes
716
                $attachmentAddedByMail = [];
717
                foreach ($attachmentList as $attachment) {
718
                    $attachmentAddedByMail[] = [
719
                        'path' => $attachment['tmp_name'],
720
                        'filename' => $attachment['name'],
721
                    ];
722
                }
723
724
                if (empty($group_id)) {
725
                    $type = Notification::NOTIFICATION_TYPE_MESSAGE;
726
                    if ($directMessage) {
727
                        $type = Notification::NOTIFICATION_TYPE_DIRECT_MESSAGE;
728
                    }
729
                    $notification->saveNotification(
730
                        $messageId,
731
                        $type,
732
                        [$receiverUserId],
733
                        $subject,
734
                        $content,
735
                        $sender_info,
736
                        $attachmentAddedByMail,
737
                        $smsParameters,
738
                        $forceTitleWhenSendingEmail
739
                    );
740
                } else {
741
                    $usergroup = new UserGroup();
742
                    $group_info = $usergroup->get($group_id);
743
                    $group_info['topic_id'] = $topic_id;
744
                    $group_info['msg_id'] = $messageId;
745
746
                    $user_list = $usergroup->get_users_by_group(
747
                        $group_id,
748
                        false,
749
                        [],
750
                        0,
751
                        1000
752
                    );
753
754
                    // Adding more sense to the message group
755
                    $subject = sprintf(get_lang('ThereIsANewMessageInTheGroupX'), $group_info['name']);
756
                    $new_user_list = [];
757
                    foreach ($user_list as $user_data) {
758
                        $new_user_list[] = $user_data['id'];
759
                    }
760
                    $group_info = [
761
                        'group_info' => $group_info,
762
                        'user_info' => $sender_info,
763
                    ];
764
                    $notification->saveNotification(
765
                        $messageId,
766
                        Notification::NOTIFICATION_TYPE_GROUP,
767
                        $new_user_list,
768
                        $subject,
769
                        $content,
770
                        $group_info,
771
                        $attachmentAddedByMail,
772
                        $smsParameters
773
                    );
774
                }
775
            }
776
777
            return $messageId;
778
        }
779
780
        return false;
781
    }
782
783
    /**
784
     * @param int    $receiverUserId
785
     * @param int    $subject
786
     * @param string $message
787
     * @param int    $sender_id
788
     * @param bool   $sendCopyToDrhUsers send copy to related DRH users
789
     * @param bool   $directMessage
790
     * @param array  $smsParameters
791
     * @param bool   $uploadFiles        Do not upload files using the MessageManager class
792
     * @param array  $attachmentList
793
     *
794
     * @return bool
795
     */
796
    public static function send_message_simple(
797
        $receiverUserId,
798
        $subject,
799
        $message,
800
        $sender_id = 0,
801
        $sendCopyToDrhUsers = false,
802
        $directMessage = false,
803
        $smsParameters = [],
804
        $uploadFiles = true,
805
        $attachmentList = []
806
    ) {
807
        $files = $_FILES ? $_FILES : [];
808
        if (false === $uploadFiles) {
809
            $files = [];
810
        }
811
        // $attachmentList must have: tmp_name, name, size keys
812
        if (!empty($attachmentList)) {
813
            $files = $attachmentList;
814
        }
815
        $result = self::send_message(
816
            $receiverUserId,
817
            $subject,
818
            $message,
819
            $files,
820
            [],
821
            null,
822
            null,
823
            null,
824
            null,
825
            $sender_id,
826
            $directMessage,
827
            0,
828
            $smsParameters
829
        );
830
831
        if ($sendCopyToDrhUsers) {
832
            $userInfo = api_get_user_info($receiverUserId);
833
            $drhList = UserManager::getDrhListFromUser($receiverUserId);
834
            if (!empty($drhList)) {
835
                foreach ($drhList as $drhInfo) {
836
                    $message = sprintf(
837
                        get_lang('CopyOfMessageSentToXUser'),
838
                        $userInfo['complete_name']
839
                    ).' <br />'.$message;
840
841
                    self::send_message_simple(
842
                        $drhInfo['id'],
843
                        $subject,
844
                        $message,
845
                        $sender_id,
846
                        false,
847
                        $directMessage
848
                    );
849
                }
850
            }
851
        }
852
853
        return $result;
854
    }
855
856
    /**
857
     * @param int $user_receiver_id
858
     * @param int $id
859
     *
860
     * @return bool
861
     */
862
    public static function delete_message_by_user_receiver($user_receiver_id, $id)
863
    {
864
        $table = Database::get_main_table(TABLE_MESSAGE);
865
        $id = (int) $id;
866
        $user_receiver_id = (int) $user_receiver_id;
867
868
        if (empty($id) || empty($user_receiver_id)) {
869
            return false;
870
        }
871
872
        $sql = "SELECT * FROM $table
873
                WHERE
874
                    id = $id AND
875
                    user_receiver_id = $user_receiver_id AND
876
                    msg_status <> ".MESSAGE_STATUS_OUTBOX;
877
        $rs = Database::query($sql);
878
879
        if (Database::num_rows($rs) > 0) {
880
            // Delete attachment file.
881
            self::delete_message_attachment_file($id, $user_receiver_id);
882
            // Soft delete message.
883
            $query = "UPDATE $table
884
                      SET msg_status = ".MESSAGE_STATUS_DELETED."
885
                      WHERE
886
                        id = $id AND
887
                        user_receiver_id = $user_receiver_id ";
888
            Database::query($query);
889
890
            return true;
891
        }
892
893
        return false;
894
    }
895
896
    /**
897
     * Set status deleted.
898
     *
899
     * @author Isaac FLores Paz <[email protected]>
900
     *
901
     * @param  int
902
     * @param  int
903
     *
904
     * @return bool
905
     */
906
    public static function delete_message_by_user_sender($user_sender_id, $id)
907
    {
908
        $user_sender_id = (int) $user_sender_id;
909
        $id = (int) $id;
910
911
        if (empty($id) || empty($user_sender_id)) {
912
            return false;
913
        }
914
915
        $table = Database::get_main_table(TABLE_MESSAGE);
916
917
        $sql = "SELECT * FROM $table WHERE id = $id AND user_sender_id= $user_sender_id";
918
        $rs = Database::query($sql);
919
920
        if (Database::num_rows($rs) > 0) {
921
            // delete attachment file
922
            self::delete_message_attachment_file($id, $user_sender_id);
923
            // delete message
924
            $sql = "UPDATE $table
925
                    SET msg_status = '".MESSAGE_STATUS_DELETED."'
926
                    WHERE user_sender_id= $user_sender_id AND id= $id";
927
            Database::query($sql);
928
929
            return true;
930
        }
931
932
        return false;
933
    }
934
935
    /**
936
     * Saves a message attachment files.
937
     *
938
     * @param array $file_attach $_FILES['name']
939
     * @param  string    a comment about the uploaded file
940
     * @param  int        message id
941
     * @param  int        receiver user id (optional)
942
     * @param  int        sender user id (optional)
943
     * @param  int        group id (optional)
944
     */
945
    public static function saveMessageAttachmentFile(
946
        $file_attach,
947
        $file_comment,
948
        $message_id,
949
        $receiver_user_id = 0,
950
        $sender_user_id = 0,
951
        $group_id = 0
952
    ) {
953
        $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
954
955
        // Try to add an extension to the file if it hasn't one
956
        $type = isset($file_attach['type']) ? $file_attach['type'] : '';
957
        if (empty($type)) {
958
            $type = DocumentManager::file_get_mime_type($file_attach['name']);
959
        }
960
        $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $type);
961
962
        // user's file name
963
        $file_name = $file_attach['name'];
964
        if (!filter_extension($new_file_name)) {
965
            Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
966
        } else {
967
            $new_file_name = uniqid('');
968
            if (!empty($receiver_user_id)) {
969
                $message_user_id = $receiver_user_id;
970
            } else {
971
                $message_user_id = $sender_user_id;
972
            }
973
974
            // User-reserved directory where photos have to be placed.*
975
            $userGroup = new UserGroup();
976
            if (!empty($group_id)) {
977
                $path_user_info = $userGroup->get_group_picture_path_by_id(
978
                    $group_id,
979
                    'system',
980
                    true
981
                );
982
            } else {
983
                $path_user_info['dir'] = UserManager::getUserPathById($message_user_id, 'system');
984
            }
985
986
            $path_message_attach = $path_user_info['dir'].'message_attachments/';
987
            // If this directory does not exist - we create it.
988
            if (!file_exists($path_message_attach)) {
989
                @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
990
            }
991
992
            $new_path = $path_message_attach.$new_file_name;
993
            $fileCopied = false;
994
            if (isset($file_attach['tmp_name']) && !empty($file_attach['tmp_name'])) {
995
                if (is_uploaded_file($file_attach['tmp_name'])) {
996
                    @copy($file_attach['tmp_name'], $new_path);
997
                    $fileCopied = true;
998
                } else {
999
                    // 'tmp_name' can be set by the ticket or when forwarding a message
1000
                    if (file_exists($file_attach['tmp_name'])) {
1001
                        @copy($file_attach['tmp_name'], $new_path);
1002
                        $fileCopied = true;
1003
                    }
1004
                }
1005
            }
1006
1007
            if ($fileCopied) {
1008
                // Storing the attachments if any
1009
                $params = [
1010
                    'filename' => $file_name,
1011
                    'comment' => $file_comment,
1012
                    'path' => $new_file_name,
1013
                    'message_id' => $message_id,
1014
                    'size' => $file_attach['size'],
1015
                ];
1016
1017
                return Database::insert($table, $params);
1018
            }
1019
        }
1020
1021
        return false;
1022
    }
1023
1024
    /**
1025
     * Delete message attachment files (logically updating the row with a suffix _DELETE_id).
1026
     *
1027
     * @param  int    message id
1028
     * @param  int    message user id (receiver user id or sender user id)
1029
     * @param  int    group id (optional)
1030
     */
1031
    public static function delete_message_attachment_file(
1032
        $message_id,
1033
        $message_uid,
1034
        $group_id = 0
1035
    ) {
1036
        $message_id = (int) $message_id;
1037
        $message_uid = (int) $message_uid;
1038
        $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1039
1040
        $sql = "SELECT * FROM $table_message_attach
1041
                WHERE message_id = '$message_id'";
1042
        $rs = Database::query($sql);
1043
        while ($row = Database::fetch_array($rs)) {
1044
            $path = $row['path'];
1045
            $attach_id = (int) $row['id'];
1046
            $new_path = $path.'_DELETED_'.$attach_id;
1047
1048
            if (!empty($group_id)) {
1049
                $userGroup = new UserGroup();
1050
                $path_user_info = $userGroup->get_group_picture_path_by_id(
1051
                    $group_id,
1052
                    'system',
1053
                    true
1054
                );
1055
            } else {
1056
                $path_user_info['dir'] = UserManager::getUserPathById(
1057
                    $message_uid,
1058
                    'system'
1059
                );
1060
            }
1061
1062
            $path_message_attach = $path_user_info['dir'].'message_attachments/';
1063
            if (is_file($path_message_attach.$path)) {
1064
                if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
1065
                    $sql = "UPDATE $table_message_attach
1066
                            SET path = '$new_path'
1067
                            WHERE id = $attach_id ";
1068
                    Database::query($sql);
1069
                }
1070
            }
1071
        }
1072
    }
1073
1074
    /**
1075
     * @param int $user_id
1076
     * @param int $message_id
1077
     * @param int $type
1078
     *
1079
     * @return bool
1080
     */
1081
    public static function update_message_status($user_id, $message_id, $type)
1082
    {
1083
        $user_id = (int) $user_id;
1084
        $message_id = (int) $message_id;
1085
        $type = (int) $type;
1086
1087
        if (empty($user_id) || empty($message_id)) {
1088
            return false;
1089
        }
1090
1091
        $table_message = Database::get_main_table(TABLE_MESSAGE);
1092
        $sql = "UPDATE $table_message SET
1093
                    msg_status = '$type'
1094
                WHERE
1095
                    user_receiver_id = ".$user_id." AND
1096
                    id = '".$message_id."'";
1097
        $result = Database::query($sql);
1098
1099
        return Database::affected_rows($result) > 0;
1100
    }
1101
1102
    /**
1103
     * get messages by group id.
1104
     *
1105
     * @param int $group_id group id
1106
     *
1107
     * @return array
1108
     */
1109
    public static function get_messages_by_group($group_id)
1110
    {
1111
        $group_id = (int) $group_id;
1112
1113
        if (empty($group_id)) {
1114
            return false;
1115
        }
1116
1117
        $table = Database::get_main_table(TABLE_MESSAGE);
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
        $rs = Database::query($sql);
1124
        $data = [];
1125
        if (Database::num_rows($rs) > 0) {
1126
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1127
                $data[] = $row;
1128
            }
1129
        }
1130
1131
        return $data;
1132
    }
1133
1134
    /**
1135
     * get messages by group id.
1136
     *
1137
     * @param int $group_id
1138
     * @param int $message_id
1139
     *
1140
     * @return array
1141
     */
1142
    public static function get_messages_by_group_by_message($group_id, $message_id)
1143
    {
1144
        $group_id = (int) $group_id;
1145
1146
        if (empty($group_id)) {
1147
            return false;
1148
        }
1149
1150
        $table = Database::get_main_table(TABLE_MESSAGE);
1151
        $sql = "SELECT * FROM $table
1152
                WHERE
1153
                    group_id = $group_id AND
1154
                    msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
1155
                ORDER BY id ";
1156
1157
        $rs = Database::query($sql);
1158
        $data = [];
1159
        $parents = [];
1160
        if (Database::num_rows($rs) > 0) {
1161
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
1162
                if ($message_id == $row['parent_id'] || in_array($row['parent_id'], $parents)) {
1163
                    $parents[] = $row['id'];
1164
                    $data[] = $row;
1165
                }
1166
            }
1167
        }
1168
1169
        return $data;
1170
    }
1171
1172
    /**
1173
     * Get messages by parent id optionally with limit.
1174
     *
1175
     * @param  int        parent id
1176
     * @param  int        group id (optional)
1177
     * @param  int        offset (optional)
1178
     * @param  int        limit (optional)
1179
     *
1180
     * @return array
1181
     */
1182
    public static function getMessagesByParent($parentId, $groupId = 0, $offset = 0, $limit = 0)
1183
    {
1184
        $table = Database::get_main_table(TABLE_MESSAGE);
1185
        $parentId = (int) $parentId;
1186
1187
        if (empty($parentId)) {
1188
            return [];
1189
        }
1190
1191
        $condition_group_id = '';
1192
        if (!empty($groupId)) {
1193
            $groupId = (int) $groupId;
1194
            $condition_group_id = " AND group_id = '$groupId' ";
1195
        }
1196