Passed
Push — 1.10.x ( 42afde...b1a5c9 )
by
unknown
155:46 queued 107:18
created

MessageManager::get_message_by_user()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 8

Duplication

Lines 10
Ratio 100 %
Metric Value
dl 10
loc 10
rs 9.4285
cc 3
eloc 8
nc 2
nop 2
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * Class MessageManager
8
 *
9
 * This class provides methods for messages management.
10
 * Include/require it in your code to use its features.
11
 *
12
 * @package chamilo.library
13
 */
14
class MessageManager
15
{
16
    /**
17
     * @param int $current_user_id
18
     * @return array
19
     */
20
    public static function get_online_user_list($current_user_id)
21
    {
22
        //@todo this is a bad idea to parse all users online
23
        $count = who_is_online_count();
24
        $userlist = who_is_online(0, $count, null, null, 30, true);
25
        $online_user_list = array();
26
        foreach ($userlist as $user_id) {
0 ignored issues
show
Bug introduced by
The expression $userlist of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
27
            $online_user_list[$user_id] = GetFullUserName($user_id).($current_user_id == $user_id ? ("&nbsp;(".get_lang('Myself').")") : (""));
28
        }
29
30
        return $online_user_list;
31
    }
32
33
    /**
34
     * Displays info stating that the message is sent successfully.
35
     * @deprecated
36
     */
37
    public static function display_success_message($uid)
38
    {
39
        if (isset($_SESSION['social_exist']) &&
40
            $_SESSION['social_exist'] === true
41
        ) {
42
            if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
43
                $success = get_lang('MessageSentTo').
44
                    "&nbsp;<b>".
45
                    GetFullUserName($uid).
46
                    "</b>";
47
            } else {
48
                $success = get_lang('MessageSentTo').
49
                    "&nbsp;<b>".
50
                    GetFullUserName($uid).
51
                    "</b>";
52
            }
53
        } else {
54
            $success = get_lang('MessageSentTo').
55
                "&nbsp;<b>".
56
                GetFullUserName($uid).
57
                "</b>";
58
        }
59
60
        return Display::return_message(api_xml_http_response_encode($success), 'confirmation', false);
61
    }
62
63
    /**
64
     * Get the new messages for the current user from the database.
65
     * @return int
66
     */
67 View Code Duplication
    public static function get_new_messages()
68
    {
69
        $table = Database::get_main_table(TABLE_MESSAGE);
70
        if (!api_get_user_id()) {
71
            return false;
72
        }
73
        $sql = "SELECT * FROM $table
74
                WHERE
75
                    user_receiver_id=".api_get_user_id()." AND
76
                    msg_status=".MESSAGE_STATUS_UNREAD;
77
        $result = Database::query($sql);
78
        $i = Database::num_rows($result);
79
80
        return $i;
81
    }
82
83
    /**
84
     * Get the list of user_ids of users who are online.
85
     */
86
    public static function users_connected_by_id()
87
    {
88
        $count = who_is_online_count();
89
        $user_connect = who_is_online(0, $count, null, null, 30, true);
90
        $user_id_list = array();
91
        for ($i = 0; $i < count($user_connect); $i++) {
92
            $user_id_list[$i] = $user_connect[$i][0];
93
        }
94
95
        return $user_id_list;
96
    }
97
98
    /**
99
     * Gets the total number of messages, used for the inbox sortable table
100
     */
101
    public static function get_number_of_messages($unread = false)
102
    {
103
        $table_message = Database::get_main_table(TABLE_MESSAGE);
104
        if ($unread) {
105
            $condition_msg_status = ' msg_status = '.MESSAGE_STATUS_UNREAD.' ';
106
        } else {
107
            $condition_msg_status = ' msg_status IN('.MESSAGE_STATUS_NEW.','.MESSAGE_STATUS_UNREAD.') ';
108
        }
109
110
        $keyword = Session::read('message_search_keyword');
111
        $keywordCondition = '';
112
        if (!empty($keyword)) {
113
            $keyword = Database::escape_string($keyword);
114
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
115
        }
116
117
        $sql = "SELECT COUNT(*) as number_messages
118
                FROM $table_message
119
                WHERE $condition_msg_status AND
120
                    user_receiver_id=".api_get_user_id()."
121
                    $keywordCondition
122
                ";
123
        $result = Database::query($sql);
124
        $result = Database::fetch_array($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
125
126
        return $result['number_messages'];
127
    }
128
129
    /**
130
     * Gets information about some messages, used for the inbox sortable table
131
     * @param int $from
132
     * @param int $number_of_items
133
     * @param string $direction
134
     */
135
    public static function get_message_data($from, $number_of_items, $column, $direction)
136
    {
137
        $from = intval($from);
138
        $number_of_items = intval($number_of_items);
139
140
        //forcing this order
141 View Code Duplication
        if (!isset($direction)) {
142
            $column = 3;
143
            $direction = 'DESC';
144
        } else {
145
            $column = intval($column);
146
            if (!in_array($direction, array('ASC', 'DESC')))
147
                $direction = 'ASC';
148
        }
149
150
        $keyword = Session::read('message_search_keyword');
151
        $keywordCondition = '';
152
        if (!empty($keyword)) {
153
            $keyword = Database::escape_string($keyword);
154
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
155
        }
156
157
        $table_message = Database::get_main_table(TABLE_MESSAGE);
158
159
        $sql = "SELECT id as col0, user_sender_id as col1, title as col2, send_date as col3, msg_status as col4
160
                FROM $table_message
161
                WHERE
162
                  user_receiver_id=".api_get_user_id()." AND
163
                  msg_status IN (0,1)
164
                  $keywordCondition
165
                ORDER BY col$column $direction
166
                LIMIT $from, $number_of_items";
167
168
        $sql_result = Database::query($sql);
169
        $i = 0;
170
        $message_list = array();
171
172
        while ($result = Database::fetch_row($sql_result)) {
173
            $message[0] = $result[0];
174
            $result[2] = Security::remove_XSS($result[2], STUDENT, true);
175
            $result[2] = cut($result[2], 80, true);
176
177
            if ($result[4] == 1) {
178
                $class = 'class = "unread"';
179
            } else {
180
                $class = 'class = "read"';
181
            }
182
            $link = '';
183
            if (isset($_GET['f']) && $_GET['f'] == 'social') {
184
                $link = '&f=social';
185
            }
186
            $message[1] = '<a '.$class.' href="view_message.php?id='.$result[0].$link.'">'.$result[2].'</a><br />'.GetFullUserName(($result[1]));
187
            $message[3] = '<a href="new_message.php?re_id='.$result[0].$link.'">'.Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a>'.
188
                '&nbsp;&nbsp;<a onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmDeleteMessage')))."'".')) return false;" href="inbox.php?action=deleteone&id='.$result[0].$link.'">'.Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>';
189
190
            $message[2] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
191
            foreach ($message as $key => $value) {
192
                $message[$key] = api_xml_http_response_encode($value);
193
            }
194
            $message_list[] = $message;
195
            $i++;
196
        }
197
198
        return $message_list;
199
    }
200
201
    /**
202
     * Sends a message to a user/group
203
     *
204
     * @param int 	   $receiver_user_id
205
     * @param string  $subject
206
     * @param string  $content
207
     * @param array   $file_attachments files array($_FILES) (optional)
208
     * @param array   $file_comments about attachment files (optional)
209
     * @param int     $group_id (optional)
210
     * @param int     $parent_id (optional)
211
     * @param int 	   $edit_message_id id for updating the message (optional)
212
     * @param int     $topic_id (optional) the default value is the current user_id
213
     * @param int     $sender_id
214
     * @param bool $directMessage
215
     *
216
     * @return bool
217
     */
218
    public static function send_message(
219
        $receiver_user_id,
220
        $subject,
221
        $content,
222
        array $file_attachments = [],
223
        array $file_comments = [],
224
        $group_id = 0,
225
        $parent_id = 0,
226
        $edit_message_id = 0,
227
        $topic_id = 0,
228
        $sender_id = null,
229
        $directMessage = false
230
    ) {
231
        $table_message = Database::get_main_table(TABLE_MESSAGE);
232
        $group_id = intval($group_id);
233
        $receiver_user_id = intval($receiver_user_id);
234
        $parent_id = intval($parent_id);
235
        $edit_message_id = intval($edit_message_id);
236
        $topic_id = intval($topic_id);
237
238
        if (!empty($receiver_user_id)) {
239
            $receiverUserInfo = api_get_user_info($receiver_user_id);
240
241
            // Disabling messages for inactive users.
242
            if ($receiverUserInfo['active'] == 0) {
243
                return false;
244
            }
245
        }
246
247
        if (empty($sender_id)) {
248
            $user_sender_id = api_get_user_id();
249
        } else {
250
            $user_sender_id = intval($sender_id);
251
        }
252
253
        $total_filesize = 0;
254
        if (is_array($file_attachments)) {
255
            foreach ($file_attachments as $file_attach) {
256
                $total_filesize += $file_attach['size'];
257
            }
258
        }
259
260
        // Validating fields
261
        if (empty($subject) && empty($group_id)) {
262
            Display::addFlash(Display::return_message(get_lang('YouShouldWriteASubject'), 'warning'));
263
            return false;
264
        } else if ($total_filesize > intval(api_get_setting('message_max_upload_filesize'))) {
265
            $warning = sprintf(
266
                get_lang("FilesSizeExceedsX"),
267
                format_file_size(api_get_setting('message_max_upload_filesize'))
268
            );
269
270
            Display::addFlash(Display::return_message($warning, 'warning'));
271
272
            return false;
273
        }
274
275
        $inbox_last_id = null;
276
277
        //Just in case we replace the and \n and \n\r while saving in the DB
278
        //$content = str_replace(array("\n", "\n\r"), '<br />', $content);
279
280
        $now = api_get_utc_datetime();
281
        if (!empty($receiver_user_id) || !empty($group_id)) {
282
283
            // message for user friend
284
            $clean_subject = Database::escape_string($subject);
285
            $clean_content = Database::escape_string($content);
286
287
            //message in inbox for user friend
288
            //@todo it's possible to edit a message? yes, only for groups
289
            if ($edit_message_id) {
290
                $query = " UPDATE $table_message SET
291
                                update_date = '".$now."',
292
                                content = '$clean_content'
293
                           WHERE id = '$edit_message_id' ";
294
                Database::query($query);
295
                $inbox_last_id = $edit_message_id;
296
            } else {
297
298
                $params = [
299
                    'user_sender_id' => $user_sender_id,
300
                    'user_receiver_id' => $receiver_user_id,
301
                    'msg_status' => '1',
302
                    'send_date' => $now,
303
                    'title' => $subject,
304
                    'content' => $content,
305
                    'group_id' => $group_id,
306
                    'parent_id' => $parent_id,
307
                    'update_date' => $now
308
                ];
309
                $inbox_last_id = Database::insert($table_message, $params);
310
            }
311
312
            // Save attachment file for inbox messages
313
            if (is_array($file_attachments)) {
314
                $i = 0;
315
                foreach ($file_attachments as $file_attach) {
316
                    if ($file_attach['error'] == 0) {
317
                        self::save_message_attachment_file(
318
                            $file_attach,
319
                            isset($file_comments[$i]) ? $file_comments[$i] : null,
320
                            $inbox_last_id,
321
                            null,
322
                            $receiver_user_id,
323
                            $group_id
324
                        );
325
                    }
326
                    $i++;
327
                }
328
            }
329
330
            if (empty($group_id)) {
331
                // message in outbox for user friend or group
332
                $params = [
333
                    'user_sender_id' => $user_sender_id,
334
                    'user_receiver_id' => $receiver_user_id,
335
                    'msg_status' => '4',
336
                    'send_date' => $now,
337
                    'title' => $subject,
338
                    'content' => $content,
339
                    'group_id' => $group_id,
340
                    'parent_id' => $parent_id,
341
                    'update_date' => $now
342
                ];
343
                $outbox_last_id = Database::insert($table_message, $params);
344
345
                // save attachment file for outbox messages
346
                if (is_array($file_attachments)) {
347
                    $o = 0;
348
                    foreach ($file_attachments as $file_attach) {
349
                        if ($file_attach['error'] == 0) {
350
                            self::save_message_attachment_file(
351
                                $file_attach,
352
                                $file_comments[$o],
353
                                $outbox_last_id,
354
                                $user_sender_id
355
                            );
356
                        }
357
                        $o++;
358
                    }
359
                }
360
            }
361
362
            // Load user settings.
363
            $notification = new Notification();
364
            $sender_info = api_get_user_info($user_sender_id);
365
366
            if (empty($group_id)) {
367
                $type = Notification::NOTIFICATION_TYPE_MESSAGE;
368
                if ($directMessage) {
369
                    $type = Notification::NOTIFICATION_TYPE_DIRECT_MESSAGE;
370
                }
371
                $notification->save_notification(
372
                    $type,
373
                    array($receiver_user_id),
374
                    $subject,
375
                    $content,
376
                    $sender_info
0 ignored issues
show
Security Bug introduced by
It seems like $sender_info defined by api_get_user_info($user_sender_id) on line 364 can also be of type false; however, Notification::save_notification() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
377
                );
378
            } else {
379
                $usergroup = new UserGroup();
380
                $group_info = $usergroup->get($group_id);
381
                $group_info['topic_id'] = $topic_id;
382
                $group_info['msg_id'] = $inbox_last_id;
383
384
                $user_list = $usergroup->get_users_by_group($group_id, false, array(), 0, 1000);
385
386
                // Adding more sense to the message group
387
                $subject = sprintf(get_lang('ThereIsANewMessageInTheGroupX'), $group_info['name']);
388
389
                $new_user_list = array();
390
                foreach ($user_list as $user_data) {
391
                    $new_user_list[] = $user_data['id'];
392
                }
393
                $group_info = array(
394
                    'group_info' => $group_info,
395
                    'user_info' => $sender_info,
396
                );
397
                $notification->save_notification(
398
                    Notification::NOTIFICATION_TYPE_GROUP,
399
                    $new_user_list,
400
                    $subject,
401
                    $content,
402
                    $group_info
403
                );
404
            }
405
406
            return $inbox_last_id;
407
        }
408
409
        return false;
410
    }
411
412
    /**
413
     * @param int $receiver_user_id
414
     * @param int $subject
415
     * @param string $message
416
     * @param int $sender_id
417
     * @param bool $sendCopyToDrhUsers send copy to related DRH users
418
     * @param bool $directMessage
419
     *
420
     * @return bool
421
     */
422
    public static function send_message_simple(
423
        $receiver_user_id,
424
        $subject,
425
        $message,
426
        $sender_id = null,
427
        $sendCopyToDrhUsers = false,
428
        $directMessage = false
429
    ) {
430
        $result = MessageManager::send_message(
431
            $receiver_user_id,
432
            $subject,
433
            $message,
434
            [],
435
            [],
436
            null,
437
            null,
438
            null,
439
            null,
440
            $sender_id,
441
            $directMessage
442
        );
443
444
        if ($sendCopyToDrhUsers) {
445
446
            $userInfo = api_get_user_info($receiver_user_id);
447
            $drhList = UserManager::getDrhListFromUser($receiver_user_id);
448
            if (!empty($drhList)) {
449
                foreach ($drhList as $drhInfo) {
450
                    $message = sprintf(
451
                            get_lang('CopyOfMessageSentToXUser'),
452
                            $userInfo['complete_name']
453
                        ).' <br />'.$message;
454
455
                    MessageManager::send_message_simple(
456
                        $drhInfo['user_id'],
457
                        $subject,
458
                        $message,
459
                        $sender_id,
460
                        false,
461
                        $directMessage
462
                    );
463
                }
464
            }
465
        }
466
467
        return $result;
468
    }
469
470
    /**
471
     * Update parent ids for other receiver user from current message in groups
472
     * @author Christian Fasanando Flores
473
     * @param  int	$parent_id
474
     * @param  int	$receiver_user_id
475
     * @param  int	$message_id
476
     * @return void
477
     */
478
    public static function update_parent_ids_from_reply($parent_id, $receiver_user_id, $message_id)
479
    {
480
        $table_message = Database::get_main_table(TABLE_MESSAGE);
481
        $parent_id = intval($parent_id);
482
        $receiver_user_id = intval($receiver_user_id);
483
        $message_id = intval($message_id);
484
        // first get data from message id (parent)
485
        $sql_message = "SELECT * FROM $table_message WHERE id = '$parent_id'";
486
        $rs_message = Database::query($sql_message);
487
        $row_message = Database::fetch_array($rs_message);
488
489
        // get message id from data found early for other receiver user
490
        $sql = "SELECT id FROM $table_message
491
                WHERE
492
                    user_sender_id ='{$row_message['user_sender_id']}' AND
493
                    title='{$row_message['title']}' AND
494
                    content='{$row_message['content']}' AND
495
                    group_id='{$row_message['group_id']}' AND
496
                    user_receiver_id='$receiver_user_id'";
497
        $rs_msg_id = Database::query($sql);
498
        $row = Database::fetch_array($rs_msg_id);
499
500
        // update parent_id for other user receiver
501
        $sql = "UPDATE $table_message SET parent_id = ".$row['id']."
502
                WHERE id = $message_id";
503
        Database::query($sql);
504
    }
505
506
    /**
507
     * @param int $user_receiver_id
508
     * @param int $id
509
     * @return bool|resource
510
     */
511
    public static function delete_message_by_user_receiver($user_receiver_id, $id)
512
    {
513
        $table_message = Database::get_main_table(TABLE_MESSAGE);
514
        if ($id != strval(intval($id)))
515
            return false;
516
        $user_receiver_id = intval($user_receiver_id);
517
        $id = intval($id);
518
        $sql = "SELECT * FROM $table_message
519
                WHERE id=".$id." AND msg_status<>4";
520
        $rs = Database::query($sql);
521
522
        if (Database::num_rows($rs) > 0) {
523
            // delete attachment file
524
            self::delete_message_attachment_file($id, $user_receiver_id);
525
            // delete message
526
            $query = "UPDATE $table_message SET msg_status=3
527
                      WHERE user_receiver_id=".$user_receiver_id." AND id=".$id;
528
            $result = Database::query($query);
529
            return $result;
530
        } else {
531
            return false;
532
        }
533
    }
534
535
    /**
536
     * Set status deleted
537
     * @author Isaac FLores Paz <[email protected]>
538
     * @param  integer
539
     * @param  integer
540
     * @return array
541
     */
542
    public static function delete_message_by_user_sender($user_sender_id, $id)
543
    {
544
        if ($id != strval(intval($id))) {
545
            return false;
546
        }
547
548
        $table_message = Database::get_main_table(TABLE_MESSAGE);
549
550
        $id = intval($id);
551
        $user_sender_id = intval($user_sender_id);
552
553
        $sql = "SELECT * FROM $table_message WHERE id='$id'";
554
        $rs = Database::query($sql);
555
556
        if (Database::num_rows($rs) > 0) {
557
            // delete attachment file
558
            self::delete_message_attachment_file($id, $user_sender_id);
559
            // delete message
560
            $sql = "UPDATE $table_message SET msg_status=3
561
                    WHERE user_sender_id='$user_sender_id' AND id='$id'";
562
            $result = Database::query($sql);
563
564
            return $result;
565
        }
566
567
        return false;
568
    }
569
570
    /**
571
     * Saves a message attachment files
572
     * @param  array 	$file_attach $_FILES['name']
573
     * @param  string  	a comment about the uploaded file
574
     * @param  int		message id
575
     * @param  int		receiver user id (optional)
576
     * @param  int		sender user id (optional)
577
     * @param  int		group id (optional)
578
     * @return void
579
     */
580
    public static function save_message_attachment_file(
581
        $file_attach,
582
        $file_comment,
583
        $message_id,
584
        $receiver_user_id = 0,
585
        $sender_user_id = 0,
586
        $group_id = 0
587
    ) {
588
        $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
589
590
        // Try to add an extension to the file if it hasn't one
591
        $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $file_attach['type']);
592
593
        // user's file name
594
        $file_name = $file_attach['name'];
595
        if (!filter_extension($new_file_name)) {
596
            Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
597
        } else {
598
            $new_file_name = uniqid('');
599
            if (!empty($receiver_user_id)) {
600
                $message_user_id = $receiver_user_id;
601
            } else {
602
                $message_user_id = $sender_user_id;
603
            }
604
605
            // User-reserved directory where photos have to be placed.*
606
            $userGroup = new UserGroup();
607
608 View Code Duplication
            if (!empty($group_id)) {
609
                $path_user_info = $userGroup->get_group_picture_path_by_id($group_id, 'system', true);
610
            } else {
611
                $path_user_info['dir'] = UserManager::getUserPathById($message_user_id, 'system');
612
            }
613
614
            $path_message_attach = $path_user_info['dir'].'message_attachments/';
615
616
            // If this directory does not exist - we create it.
617
            if (!file_exists($path_message_attach)) {
618
                @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
619
            }
620
            $new_path = $path_message_attach.$new_file_name;
621
            if (is_uploaded_file($file_attach['tmp_name'])) {
622
                @copy($file_attach['tmp_name'], $new_path);
623
            }
624
625
            // Storing the attachments if any
626
            $params = [
627
                'filename' => $file_name,
628
                'comment' => $file_comment,
629
                'path' => $new_file_name,
630
                'message_id' => $message_id,
631
                'size' => $file_attach['size']
632
            ];
633
            Database::insert($tbl_message_attach, $params);
634
        }
635
    }
636
637
    /**
638
     * Delete message attachment files (logically updating the row with a suffix _DELETE_id)
639
     * @param  int	message id
640
     * @param  int	message user id (receiver user id or sender user id)
641
     * @param  int	group id (optional)
642
     * @return void
643
     */
644
    public static function delete_message_attachment_file($message_id, $message_uid, $group_id = 0)
645
    {
646
        $message_id = intval($message_id);
647
        $message_uid = intval($message_uid);
648
        $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
649
650
        $sql = "SELECT * FROM $table_message_attach WHERE message_id = '$message_id'";
651
        $rs = Database::query($sql);
652
        while ($row = Database::fetch_array($rs)) {
653
            $path = $row['path'];
654
            $attach_id = $row['id'];
655
            $new_path = $path.'_DELETED_'.$attach_id;
656
657 View Code Duplication
            if (!empty($group_id)) {
658
                $userGroup = new UserGroup();
659
                $path_user_info = $userGroup->get_group_picture_path_by_id(
660
                    $group_id,
661
                    'system',
662
                    true
663
                );
664
            } else {
665
                $path_user_info['dir'] = UserManager::getUserPathById(
666
                    $message_uid,
667
                    'system'
668
                );
669
            }
670
671
            $path_message_attach = $path_user_info['dir'].'message_attachments/';
672
            if (is_file($path_message_attach.$path)) {
673
                if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
674
                    $sql = "UPDATE $table_message_attach set path='$new_path'
675
                            WHERE id ='$attach_id'";
676
                    Database::query($sql);
677
                }
678
            }
679
        }
680
    }
681
682
    /**
683
     * update messages by user id and message id
684
     * @param  int		$user_id
685
     * @param  int		$message_id
686
     * @return resource
687
     */
688
    public static function update_message($user_id, $message_id)
689
    {
690
        if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id)))
691
            return false;
692
693
        $table_message = Database::get_main_table(TABLE_MESSAGE);
694
        $sql = "UPDATE $table_message SET msg_status = '0'
695
                WHERE
696
                    msg_status<>4 AND
697
                    user_receiver_id=".intval($user_id)." AND
698
                    id='".intval($message_id)."'";
699
        Database::query($sql);
700
    }
701
702
    /**
703
     * @param int $user_id
704
     * @param int $message_id
705
     * @param string $type
706
     * @return bool
707
     */
708 View Code Duplication
    public static function update_message_status($user_id, $message_id,$type)
709
    {
710
        $type = intval($type);
711
        if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id))) {
712
            return false;
713
        }
714
        $table_message = Database::get_main_table(TABLE_MESSAGE);
715
        $sql = "UPDATE $table_message SET
716
                    msg_status = '$type'
717
                WHERE
718
                    user_receiver_id=".intval($user_id)." AND
719
                    id='".intval($message_id)."'";
720
        Database::query($sql);
721
    }
722
723
    /**
724
     * get messages by user id and message id
725
     * @param  int		$user_id
726
     * @param  int		$message_id
727
     * @return array
728
     */
729 View Code Duplication
    public static function get_message_by_user($user_id, $message_id)
730
    {
731
        if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id)))
732
            return false;
733
        $table_message = Database::get_main_table(TABLE_MESSAGE);
734
        $query = "SELECT * FROM $table_message
735
                  WHERE user_receiver_id=".intval($user_id)." AND id='".intval($message_id)."'";
736
        $result = Database::query($query);
737
        return $row = Database::fetch_array($result);
738
    }
739
740
    /**
741
     * get messages by group id
742
     * @param  int		group id
743
     * @return array
744
     */
745
    public static function get_messages_by_group($group_id)
746
    {
747
        if ($group_id != strval(intval($group_id)))
748
            return false;
749
750
        $table_message = Database::get_main_table(TABLE_MESSAGE);
751
        $group_id = intval($group_id);
752
        $sql = "SELECT * FROM $table_message
753
                WHERE
754
                    group_id= $group_id AND
755
                    msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
756
                ORDER BY id";
757
        $rs = Database::query($sql);
758
        $data = array();
759
        if (Database::num_rows($rs) > 0) {
760
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
761
                $data[] = $row;
762
            }
763
        }
764
        return $data;
765
    }
766
767
    /**
768
     * get messages by group id
769
     * @param  int $group_id
770
     * @param int $message_id
771
     * @return array
772
     */
773
    public static function get_messages_by_group_by_message($group_id, $message_id)
774
    {
775
        if ($group_id != strval(intval($group_id)))
776
            return false;
777
        $table_message = Database::get_main_table(TABLE_MESSAGE);
778
        $group_id = intval($group_id);
779
        $sql = "SELECT * FROM $table_message
780
                WHERE
781
                    group_id = $group_id AND
782
                    msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
783
                ORDER BY id ";
784
785
        $rs = Database::query($sql);
786
        $data = array();
787
        $parents = array();
788 View Code Duplication
        if (Database::num_rows($rs) > 0) {
789
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
790
                if ($message_id == $row['parent_id'] || in_array($row['parent_id'], $parents)) {
791
                    $parents[] = $row['id'];
792
                    $data[] = $row;
793
                }
794
            }
795
        }
796
797
        return $data;
798
    }
799
800
    /**
801
     * get messages by parent id optionally with limit
802
     * @param  int		parent id
803
     * @param  int		group id (optional)
804
     * @param  int		offset (optional)
805
     * @param  int		limit (optional)
806
     * @return array
807
     */
808
    public static function get_messages_by_parent($parent_id, $group_id = '', $offset = 0, $limit = 0)
809
    {
810
        if ($parent_id != strval(intval($parent_id))) {
811
            return false;
812
        }
813
        $table_message = Database::get_main_table(TABLE_MESSAGE);
814
        $parent_id = intval($parent_id);
815
816
        $condition_group_id = "";
817
        if ($group_id !== '') {
818
            $group_id = intval($group_id);
819
            $condition_group_id = " AND group_id = '$group_id' ";
820
        }
821
822
        $condition_limit = "";
823
        if ($offset && $limit) {
824
            $offset = ($offset - 1) * $limit;
825
            $condition_limit = " LIMIT $offset,$limit ";
826
        }
827
828
        $sql = "SELECT * FROM $table_message
829
                WHERE
830
                    parent_id='$parent_id' AND
831
                    msg_status <> ".MESSAGE_STATUS_OUTBOX."
832
                    $condition_group_id
833
                ORDER BY send_date DESC $condition_limit ";
834
        $rs = Database::query($sql);
835
        $data = array();
836
        if (Database::num_rows($rs) > 0) {
837
            while ($row = Database::fetch_array($rs)) {
838
                $data[$row['id']] = $row;
839
            }
840
        }
841
842
        return $data;
843
    }
844
845
    /**
846
     * Gets information about if exist messages
847
     * @author Isaac FLores Paz <[email protected]>
848
     * @param  integer
849
     * @param  integer
850
     * @return boolean
851
     */
852
    public static function exist_message($user_id, $id)
853
    {
854
        if ($id != strval(intval($id)) || $user_id != strval(intval($user_id)))
855
            return false;
856
        $table_message = Database::get_main_table(TABLE_MESSAGE);
857
        $query = "SELECT id FROM $table_message
858
                  WHERE
859
                    user_receiver_id = ".intval($user_id)." AND
860
                    id = '".intval($id)."'";
861
        $result = Database::query($query);
862
        $num = Database::num_rows($result);
863
        if ($num > 0) {
864
            return true;
865
        } else {
866
            return false;
867
        }
868
    }
869
870
    /**
871
     * Gets information about messages sent
872
     * @param  integer
873
     * @param  integer
874
     * @param  string
875
     * @return array
876
     */
877
    public static function get_message_data_sent($from, $number_of_items, $column, $direction)
878
    {
879
        $from = intval($from);
880
        $number_of_items = intval($number_of_items);
881 View Code Duplication
        if (!isset($direction)) {
882
            $column = 3;
883
            $direction = 'DESC';
884
        } else {
885
            $column = intval($column);
886
            if (!in_array($direction, array('ASC', 'DESC')))
887
                $direction = 'ASC';
888
        }
889
        $table_message = Database::get_main_table(TABLE_MESSAGE);
890
        $request = api_is_xml_http_request();
891
892
        $keyword = Session::read('message_sent_search_keyword');
893
        $keywordCondition = '';
894
        if (!empty($keyword)) {
895
            $keyword = Database::escape_string($keyword);
896
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
897
        }
898
899
        $sql = "SELECT
900
                    id as col0, user_sender_id as col1, title as col2, send_date as col3, user_receiver_id as col4, msg_status as col5
901
                FROM $table_message
902
                WHERE
903
                    user_sender_id=".api_get_user_id()." AND
904
                    msg_status=".MESSAGE_STATUS_OUTBOX."
905
                    $keywordCondition
906
                ORDER BY col$column $direction
907
                LIMIT $from, $number_of_items";
908
        $sql_result = Database::query($sql);
909
        $i = 0;
910
        $message_list = array();
911
        while ($result = Database::fetch_row($sql_result)) {
912
            if ($request === true) {
913
                $message[0] = '<input type="checkbox" value='.$result[0].' name="out[]">';
914
            } else {
915
                $message[0] = ($result[0]);
916
            }
917
            $class = 'class = "read"';
918
            $result[2] = Security::remove_XSS($result[2]);
919
920
            if ($request === true) {
921
                $message[1] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.GetFullUserName($result[4]).'</a>';
922
                $message[2] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.str_replace("\\", "", $result[2]).'</a>';
923
                $message[3] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
924
925
                $message[4] = '&nbsp;&nbsp;<a onclick="delete_one_message_outbox('.$result[0].')" href="javascript:void(0)"  >'.Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>';
926
            } else {
927
                $link = '';
928
                if (isset($_GET['f']) && $_GET['f'] == 'social') {
929
                    $link = '&f=social';
930
                }
931
                $message[1] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a><br />'.GetFullUserName($result[4]);
932
                //$message[2] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a>';
933
                $message[2] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
934
                $message[3] = '<a href="outbox.php?action=deleteone&id='.$result[0].'&'.$link.'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmDeleteMessage')))."'".')) return false;" >'.Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>';
935
            }
936
937
            foreach ($message as $key => $value) {
938
                $message[$key] = $value;
939
            }
940
            $message_list[] = $message;
941
            $i++;
942
        }
943
944
        return $message_list;
945
    }
946
947
    /**
948
     * Gets information about number messages sent
949
     * @author Isaac FLores Paz <[email protected]>
950
     * @param void
951
     * @return integer
952
     */
953
    public static function get_number_of_messages_sent()
954
    {
955
        $table_message = Database::get_main_table(TABLE_MESSAGE);
956
957
        $keyword = Session::read('message_sent_search_keyword');
958
        $keywordCondition = '';
959
        if (!empty($keyword)) {
960
            $keyword = Database::escape_string($keyword);
961
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
962
        }
963
964
        $sql = "SELECT COUNT(*) as number_messages FROM $table_message
965
                WHERE
966
                  msg_status=".MESSAGE_STATUS_OUTBOX." AND
967
                  user_sender_id=".api_get_user_id()."
968
                  $keywordCondition
969
                ";
970
        $result = Database::query($sql);
971
        $result = Database::fetch_array($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
972
973
        return $result['number_messages'];
974
    }
975
976
    /**
977
     * display message box in the inbox
978
     * @param int the message id
979
     * @param string inbox or outbox strings are available
980
     * @todo replace numbers with letters in the $row array pff...
981
     * @return string html with the message content
982
     */
983
    public static function show_message_box($message_id, $source = 'inbox')
984
    {
985
        $table_message = Database::get_main_table(TABLE_MESSAGE);
986
        $message_id = intval($message_id);
987
988
        if ($source == 'outbox') {
989 View Code Duplication
            if (isset($message_id) && is_numeric($message_id)) {
990
                $query = "SELECT * FROM $table_message
991
                          WHERE
992
                            user_sender_id = ".api_get_user_id()." AND
993
                            id = ".$message_id." AND
994
                            msg_status = 4;";
995
                $result = Database::query($query);
996
            }
997
        } else {
998
            if (is_numeric($message_id) && !empty($message_id)) {
999
                $query = "UPDATE $table_message SET
1000
                          msg_status = '".MESSAGE_STATUS_NEW."'
1001
                          WHERE
1002
                            user_receiver_id=".api_get_user_id()." AND
1003
                            id='".$message_id."'";
1004
                Database::query($query);
1005
1006
                $query = "SELECT * FROM $table_message
1007
                          WHERE
1008
                            msg_status<>4 AND
1009
                            user_receiver_id=".api_get_user_id()." AND
1010
                            id='".$message_id."'";
1011
                $result = Database::query($query);
1012
            }
1013
        }
1014
        $row = Database::fetch_array($result, 'ASSOC');
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_array() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1015
        $user_sender_id = $row['user_sender_id'];
1016
1017
        // get file attachments by message id
1018
        $files_attachments = self::get_links_message_attachment_files($message_id, $source);
1019
1020
        $user_con = self::users_connected_by_id();
1021
        $band = 0;
1022
        for ($i = 0; $i < count($user_con); $i++) {
1023
            if ($user_sender_id == $user_con[$i]) {
1024
                $band = 1;
1025
            }
1026
        }
1027
1028
        $title = Security::remove_XSS($row['title'], STUDENT, true);
1029
        $content = Security::remove_XSS($row['content'], STUDENT, true);
1030
1031
        $from_user = api_get_user_info($user_sender_id);
1032
        $name = $from_user['complete_name'];
1033
        $user_image = Display::img($from_user['avatar'], $name, array('title' => $name));
1034
1035
        $message_content = Display::page_subheader(str_replace("\\", "", $title));
1036
1037
        if (api_get_setting('allow_social_tool') == 'true') {
1038
            $message_content .= $user_image.' ';
1039
        }
1040
1041
        $receiverUserInfo = api_get_user_info($row['user_receiver_id']);
1042
1043
        $message_content .='<tr>';
1044
        if (api_get_setting('allow_social_tool') == 'true') {
1045
            if ($source == 'outbox') {
1046
                $message_content .= get_lang('From').': <a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a> '.
1047
                    api_strtolower(get_lang('To')).'&nbsp;<b>'.$receiverUserInfo['complete_name'].'</b>';
1048 View Code Duplication
            } else {
1049
                $message_content .= get_lang('From').' <a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a> '.
1050
                    api_strtolower(get_lang('To')).'&nbsp;<b>'.get_lang('Me').'</b>';
1051
            }
1052
        } else {
1053
            if ($source == 'outbox') {
1054
                $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.$receiverUserInfo['complete_name'].'</b>';
1055
            } else {
1056
                $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.get_lang('Me').'</b>';
1057
            }
1058
        }
1059
        $message_content .=' '.get_lang('Date').':  '.api_get_local_time($row['send_date']).'
1060
		        <br />
1061
		        <hr style="color:#ddd" />
1062
		        <table height="209px" width="100%">
1063
		            <tr>
1064
		              <td valign=top class="view-message-content">'.str_replace("\\", "", $content).'</td>
1065
		            </tr>
1066
		        </table>
1067
		        <div id="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>
1068
		        <div style="padding: 15px 0px 5px 0px">';
1069
        $social_link = '';
1070
        if (isset($_GET['f']) && $_GET['f'] == 'social') {
1071
            $social_link = 'f=social';
1072
        }
1073
        if ($source == 'outbox') {
1074
            $message_content .= '<a href="outbox.php?'.$social_link.'">'.
1075
                Display::return_icon('back.png', get_lang('ReturnToOutbox')).'</a> &nbsp';
1076
        } else {
1077
            $message_content .= '<a href="inbox.php?'.$social_link.'">'.
1078
                Display::return_icon('back.png', get_lang('ReturnToInbox')).'</a> &nbsp';
1079
            $message_content .= '<a href="new_message.php?re_id='.$message_id.'&'.$social_link.'">'.
1080
                Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a> &nbsp';
1081
        }
1082
        $message_content .= '<a href="inbox.php?action=deleteone&id='.$message_id.'&'.$social_link.'" >'.
1083
            Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
1084
1085
        $message_content .='</div></td>
1086
		      <td width=10></td>
1087
		    </tr>
1088
		</table>';
1089
        return $message_content;
1090
    }
1091
1092
    /**
1093
     * get user id by user email
1094
     * @param string $user_email
1095
     * @return int user id
1096
     */
1097
    public static function get_user_id_by_email($user_email)
1098
    {
1099
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1100
        $sql = 'SELECT user_id FROM '.$tbl_user.'
1101
                WHERE email="'.Database::escape_string($user_email).'";';
1102
        $rs = Database::query($sql);
1103
        $row = Database::fetch_array($rs, 'ASSOC');
1104
        if (isset($row['user_id'])) {
1105
            return $row['user_id'];
1106
        } else {
1107
            return null;
1108
        }
1109
    }
1110
1111
    /**
1112
     * Displays messages of a group with nested view
1113
     *
1114
     * @param int $group_id
1115
     */
1116
    public static function display_messages_for_group($group_id)
1117
    {
1118
        global $my_group_role;
1119
1120
        $rows = self::get_messages_by_group($group_id);
1121
        $topics_per_page = 10;
1122
        $html_messages = '';
1123
        $query_vars = array('id' => $group_id, 'topics_page_nr' => 0);
1124
1125
        if (is_array($rows) && count($rows) > 0) {
1126
1127
            // prepare array for topics with its items
1128
            $topics = array();
1129
            $x = 0;
1130
            foreach ($rows as $index => $value) {
1131
                if (empty($value['parent_id'])) {
1132
                    $topics[$value['id']] = $value;
1133
                }
1134
            }
1135
1136
            $new_topics = array();
1137
1138
            foreach ($topics as $id => $value) {
1139
                $rows = null;
1140
                $rows = self::get_messages_by_group_by_message($group_id, $value['id']);
1141
                if (!empty($rows)) {
1142
                    $count = count(self::calculate_children($rows, $value['id']));
1143
                } else {
1144
                    $count = 0;
1145
                }
1146
                $value['count'] = $count;
1147
                $new_topics[$id] = $value;
1148
            }
1149
1150
            $array_html = array();
1151
1152
            foreach ($new_topics as $index => $topic) {
1153
                $html = '';
1154
                // topics
1155
                $user_sender_info = api_get_user_info($topic['user_sender_id']);
1156
                $name = $user_sender_info['complete_name'];
1157
1158
                $html .= '<div class="row">';
1159
1160
                $items = $topic['count'];
1161
                $reply_label = ($items == 1) ? get_lang('GroupReply') : get_lang('GroupReplies');
1162
                $label =  Display::label($items.' '.$reply_label);
1163
                $topic['title'] = trim($topic['title']);
1164
1165
                if (empty($topic['title'])) {
1166
                    $topic['title'] = get_lang('Untitled');
1167
                }
1168
1169
                $html .= '<div class="col-md-8">';
1170
                $html .= Display::tag(
1171
                    'h4',
1172
                    Display::url(
1173
                        Security::remove_XSS($topic['title'], STUDENT, true),
1174
                        api_get_path(WEB_CODE_PATH).'social/group_topics.php?id='.$group_id.'&topic_id='.$topic['id']
1175
                    )
1176
                );
1177
                $actions = '';
1178
                if ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
1179
                    $my_group_role == GROUP_USER_PERMISSION_MODERATOR
1180
                ) {
1181
                    $actions = '<br />'.Display::url(get_lang('Delete'), api_get_path(WEB_CODE_PATH).'social/group_topics.php?action=delete&id='.$group_id.'&topic_id='.$topic['id'], array('class' => 'btn btn-default'));
1182
                }
1183
1184
                $date = '';
1185 View Code Duplication
                if ($topic['send_date'] != $topic['update_date']) {
1186
                    if (!empty($topic['update_date']) &&
1187
                        $topic['update_date'] != '0000-00-00 00:00:00'
1188
                    ) {
1189
                        $date .= '<div class="message-group-date" > <i>'.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']).'</i></div>';
1190
                    }
1191
                } else {
1192
                    $date .= '<div class="message-group-date"> <i>'.get_lang('Created').' '.date_to_str_ago($topic['send_date']).'</i></div>';
1193
                }
1194
                $html .= $date.$label.$actions;
1195
                $html .= '</div>';
1196
1197
                $image = $user_sender_info['avatar'];
1198
1199
                $user_info = '<td valign="top"><a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a>';
1200
                $user_info .= '<div class="message-group-author"><img src="'.$image.'" alt="'.$name.'"  width="32" height="32" title="'.$name.'" /></div>';
1201
                $user_info .= '</td>';
1202
1203
                $html .= '<div class="col-md-2">';
1204
                $html .= $user_info;
1205
                $html .= '</div>';
1206
                $html .= '</div>';
1207
1208
                $array_html[] = array($html);
1209
            }
1210
1211
            // grids for items and topics  with paginations
1212
            $html_messages .= Display::return_sortable_grid(
1213
                'topics',
1214
                array(),
1215
                $array_html,
1216
                array(
1217
                    'hide_navigation' => false,
1218
                    'per_page' => $topics_per_page
1219
                ),
1220
                $query_vars,
1221
                false,
1222
                array(true, true, true, false),
1223
                false
1224
            );
1225
        }
1226
1227
        return $html_messages;
1228
    }
1229
1230
    /**
1231
     * Displays messages of a group with nested view
1232
     * @param $group_id
1233
     * @param $topic_id
1234
     * @param $is_member
1235
     * @param $message_id
1236
     * @return string
1237
     */
1238
    public static function display_message_for_group($group_id, $topic_id, $is_member, $message_id)
1239
    {
1240
        global $my_group_role;
1241
        $main_message = self::get_message_by_id($topic_id);
1242
        if (empty($main_message)) {
1243
            return false;
1244
        }
1245
        $rows = self::get_messages_by_group_by_message($group_id, $topic_id);
1246
        $rows = self::calculate_children($rows, $topic_id);
0 ignored issues
show
Security Bug introduced by
It seems like $rows can also be of type false; however, MessageManager::calculate_children() does only seem to accept array, did you maybe forget to handle an error condition?
Loading history...
1247
        $current_user_id = api_get_user_id();
1248
1249
        $items_per_page = 50;
1250
1251
        $query_vars = array('id' => $group_id, 'topic_id' => $topic_id, 'topics_page_nr' => 0);
1252
1253
        // Main message
1254
        $links = '';
1255
        $main_content = '';
1256
1257
        $items_page_nr = null;
1258
1259
        $html = '';
1260
1261
        $delete_button = '';
1262
        if (api_is_platform_admin()) {
1263
            $delete_button = Display::url(Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL), 'group_topics.php?action=delete&id='.$group_id.'&topic_id='.$topic_id);
1264
        }
1265
        $html .= Display::page_subheader(Security::remove_XSS($main_message['title'].$delete_button, STUDENT, true));
1266
1267
        $user_sender_info = api_get_user_info($main_message['user_sender_id']);
1268
        $files_attachments = self::get_links_message_attachment_files($main_message['id']);
1269
        $name = $user_sender_info['complete_name'];
1270
1271
        $topic_page_nr = isset($_GET['topics_page_nr']) ? intval($_GET['topics_page_nr']) : null;
1272
        $links.= '<div id="message-reply-link">';
1273
        if (($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
1274
            $my_group_role == GROUP_USER_PERMISSION_MODERATOR) ||
1275
            $main_message['user_sender_id'] == $current_user_id
1276
        ) {
1277
            $urlEdit = api_get_path(WEB_CODE_PATH);
1278
            $urlEdit .= 'social/message_for_group_form.inc.php?';
1279
            $urlEdit .= http_build_query([
1280
                'user_friend' => $current_user_id,
1281
                'group_id' => $group_id,
1282
                'message_id' => $main_message['id'],
1283
                'action' => 'edit_message_group',
1284
                'anchor_topic' => 'topic_' . $main_message['id'],
1285
                'topics_page_nr' => $topic_page_nr,
1286
                'items_page_nr' => $items_page_nr,
1287
                'topic_id' => $main_message['id']
1288
            ]);
1289
1290
            $links .= Display::url(
1291
                Display::return_icon(
1292
                    'edit.png',
1293
                    get_lang('Edit'),
1294
                    array(),
1295
                    ICON_SIZE_SMALL
1296
                ),
1297
                $urlEdit,
1298
                [
1299
                    'class' => 'ajax btn btn-default',
1300
                    'title' => get_lang('Edit'),
1301
                    'data-title' => get_lang('Edit'),
1302
                    'data-size' => 'lg'
1303
                ]
1304
            );
1305
        }
1306
1307
        $urlReply = api_get_path(WEB_CODE_PATH);
1308
        $urlReply .= 'social/message_for_group_form.inc.php?';
1309
        $urlReply .= http_build_query([
1310
            'user_friend' => api_get_user_id(),
1311
            'group_id' => $group_id,
1312
            'message_id' => $main_message['id'],
1313
            'action' => 'reply_message_group',
1314
            'anchor_topic' => 'topic_' . $main_message['id'],
1315
            'topics_page_nr' => $topic_page_nr,
1316
            'topic_id' => $main_message['id']
1317
        ]);
1318
1319
        $links .= Display::url(
1320
            Display::return_icon('talk.png', get_lang('Reply')),
1321
            $urlReply,
1322
            [
1323
                'class' => 'ajax btn btn-default',
1324
                'title' => get_lang('Reply'),
1325
                'data-title' => get_lang('Reply'),
1326
                'data-size' => 'lg'
1327
            ]
1328
        );
1329
1330
        $links.= '</div>';
1331
1332
        $userPicture = $user_sender_info['avatar'];
1333
        $main_content.= '<div class="message-group-author">
1334
                         <img src="'.$userPicture.'" alt="'.$name.'"  width="32" height="32" title="'.$name.'" /></div>';
1335
        $user_link = '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$main_message['user_sender_id'].'">'.$name.'&nbsp;</a>';
1336
1337
        $date = '';
1338 View Code Duplication
        if ($main_message['send_date'] != $main_message['update_date']) {
1339
            if (!empty($main_message['update_date']) && $main_message['update_date'] != '0000-00-00 00:00:00') {
1340
                $date = '<div class="message-group-date"> '.get_lang('LastUpdate').' '.date_to_str_ago($main_message['update_date']).'</div>';
1341
            }
1342
        } else {
1343
            $date = '<div class="message-group-date"> '.get_lang('Created').' '.date_to_str_ago($main_message['send_date']).'</div>';
1344
        }
1345
        $attachment = '<div class="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>';
1346
        $main_content.= '<div class="message-group-content">'.$links.$user_link.' '.$date.$main_message['content'].$attachment.'</div>';
1347
        $main_content = Security::remove_XSS($main_content, STUDENT, true);
1348
1349
        $html .= Display::div(Display::div(Display::div($main_content, array('class' => 'group_social_sub_item', 'style' => 'background-color:#fff;')), array('class' => 'group_social_item')), array('class' => 'group_social_grid'));
1350
1351
        $topic_id = $main_message['id'];
1352
1353
        if (is_array($rows) && count($rows) > 0) {
1354
            $topics = $rows;
1355
            $array_html_items = array();
1356
            foreach ($topics as $index => $topic) {
1357
                if (empty($topic['id'])) {
1358
                    continue;
1359
                }
1360
                $items_page_nr = isset($_GET['items_'.$topic['id'].'_page_nr']) ? intval($_GET['items_'.$topic['id'].'_page_nr']) : null;
1361
                $links = '';
1362
                $html_items = '';
1363
                $user_sender_info = api_get_user_info($topic['user_sender_id']);
1364
                $files_attachments = self::get_links_message_attachment_files($topic['id']);
1365
                $name = $user_sender_info['complete_name'];
1366
1367
                $links.= '<div id="message-reply-link">';
1368
                if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) || $topic['user_sender_id'] == $current_user_id) {
1369
                    $links.= '<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?height=400&width=800&&user_friend='.$current_user_id.'&group_id='.$group_id.'&message_id='.$topic['id'].'&action=edit_message_group&anchor_topic=topic_'.$topic_id.'&topics_page_nr='.$topic_page_nr.'&items_page_nr='.$items_page_nr.'&topic_id='.$topic_id.'" class="ajax btn" data-size="lg" data-title="'.get_lang('Edit').'" title="'.get_lang('Edit').'">'.
1370
                        Display :: return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>';
1371
                }
1372
                $links.= '&nbsp;&nbsp;<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?height=400&width=800&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&message_id='.$topic['id'].'&action=reply_message_group&anchor_topic=topic_'.$topic_id.'&topics_page_nr='.$topic_page_nr.'&items_page_nr='.$items_page_nr.'&topic_id='.$topic_id.'" class="ajax btn" data-size="lg" data-title="'.get_lang('Reply').'" title="'.get_lang('Reply').'">';
1373
                $links.= Display :: return_icon('talk.png', get_lang('Reply')).'</a>';
1374
                $links.= '</div>';
1375
1376
                $userPicture = $user_sender_info['avatar'];
1377
1378
                $html_items.= '<div class="message-group-author"><img src="'.$userPicture.'" alt="'.$name.'"  width="32" height="32" title="'.$name.'" /></div>';
1379
                $user_link = '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a>';
1380
1381
                $date = '';
1382 View Code Duplication
                if ($topic['send_date'] != $topic['update_date']) {
1383
                    if (!empty($topic['update_date']) && $topic['update_date'] != '0000-00-00 00:00:00') {
1384
                        $date = '<div class="message-group-date"> '.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']).'</div>';
1385
                    }
1386
                } else {
1387
                    $date = '<div class="message-group-date"> '.get_lang('Created').' '.date_to_str_ago($topic['send_date']).'</div>';
1388
                }
1389
                $attachment = '<div class="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>';
1390
                $html_items.= '<div class="message-group-content">'.$links.$user_link.' '.$date.Security::remove_XSS($topic['content'], STUDENT, true).$attachment.'</div>';
1391
1392
                $base_padding = 20;
1393
1394
                if ($topic['indent_cnt'] == 0) {
1395
                    $indent = $base_padding;
1396
                } else {
1397
                    $indent = intval($topic['indent_cnt']) * $base_padding + $base_padding;
1398
                }
1399
                $class = 'group_social_sub_item';
1400
                if (isset($message_id) && $message_id == $topic['id']) {
1401
                    $class .= ' group_social_sub_item_highlight';
1402
                }
1403
1404
                $html_items = Display::div($html_items, array('class' => $class, 'id' => 'msg_'.$topic['id']));
1405
                $html_items = Display::div($html_items, array('class' => '', 'style' => 'margin-left:'.$indent.'px'));
1406
                $array_html_items[] = array($html_items);
1407
            }
1408
            // grids for items with paginations
1409
            $options = array('hide_navigation' => false, 'per_page' => $items_per_page);
1410
            $visibility = array(true, true, true, false);
1411
1412
            $style_class = array(
1413
                'item' => array('class' => 'group_social_item'),
1414
                'main' => array('class' => 'group_social_grid'),
1415
            );
1416
            if (!empty($array_html_items)) {
1417
                $html .= Display::return_sortable_grid(
1418
                    'items_'.$topic['id'],
0 ignored issues
show
Bug introduced by
The variable $topic seems to be defined by a foreach iteration on line 1356. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
1419
                    array(),
1420
                    $array_html_items,
1421
                    $options,
1422
                    $query_vars,
1423
                    null,
1424
                    $visibility,
1425
                    false,
1426
                    $style_class
1427
                );
1428
            }
1429
        }
1430
        return $html;
1431
    }
1432
1433
    /**
1434
     * Add children to messages by id is used for nested view messages
1435
     * @param array  $rows rows of messages
1436
     * @return array $first_seed new list adding the item children
1437
     */
1438
    public static function calculate_children($rows, $first_seed)
1439
    {
1440
        $rows_with_children = array();
1441
        foreach ($rows as $row) {
1442
            $rows_with_children[$row["id"]] = $row;
1443
            $rows_with_children[$row["parent_id"]]["children"][] = $row["id"];
1444
        }
1445
        $rows = $rows_with_children;
1446
        $sorted_rows = array(0 => array());
1447
        self::message_recursive_sort($rows, $sorted_rows, $first_seed);
1448
        unset($sorted_rows[0]);
1449
1450
        return $sorted_rows;
1451
    }
1452
1453
    /**
1454
     * Sort recursively the messages, is used for for nested view messages
1455
     * @param array  original rows of messages
1456
     * @param array  list recursive of messages
1457
     * @param int   seed for calculate the indent
1458
     * @param int   indent for nested view
1459
     * @return void
1460
     */
1461
    public static function message_recursive_sort($rows, &$messages, $seed = 0, $indent = 0)
1462
    {
1463
        if ($seed > 0 && isset($rows[$seed]["id"])) {
1464
            $messages[$rows[$seed]["id"]] = $rows[$seed];
1465
            $messages[$rows[$seed]["id"]]["indent_cnt"] = $indent;
1466
            $indent++;
1467
        }
1468
1469
        if (isset($rows[$seed]["children"])) {
1470
            foreach ($rows[$seed]["children"] as $child) {
1471
                self::message_recursive_sort($rows, $messages, $child, $indent);
1472
            }
1473
        }
1474
    }
1475
1476
    /**
1477
     * Sort date by desc from a multi-dimensional array
1478
     * @param array $array1  first array to compare
1479
     * @param array $array2  second array to compare
1480
     * @return bool
1481
     */
1482
    public function order_desc_date($array1, $array2)
1483
    {
1484
        return strcmp($array2['send_date'], $array1['send_date']);
1485
    }
1486
1487
    /**
1488
     * Get array of links (download) for message attachment files
1489
     * @param int  		$message_id
1490
     * @param string	$type message list (inbox/outbox)
1491
     * @return array
1492
     */
1493
    public static function get_links_message_attachment_files($message_id, $type = '')
1494
    {
1495
        $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1496
        $message_id = intval($message_id);
1497
1498
        // get file attachments by message id
1499
        $links_attach_file = array();
1500
        if (!empty($message_id)) {
1501
1502
            $sql = "SELECT * FROM $tbl_message_attach
1503
                    WHERE message_id = '$message_id'";
1504
1505
            $rs_file = Database::query($sql);
1506
            if (Database::num_rows($rs_file) > 0) {
1507
                $attach_icon = Display::return_icon('attachment.gif', '');
1508
                $archiveURL = api_get_path(WEB_CODE_PATH).'messages/download.php?type='.$type.'&file=';
1509
                while ($row_file = Database::fetch_array($rs_file)) {
1510
                    $archiveFile = $row_file['path'];
1511
                    $filename = $row_file['filename'];
1512
                    $filesize = format_file_size($row_file['size']);
1513
                    $filecomment = Security::remove_XSS($row_file['comment']);
1514
                    $filename = Security::remove_XSS($filename);
1515
                    $links_attach_file[] = $attach_icon.'&nbsp;<a href="'.$archiveURL.$archiveFile.'">'.$filename.'</a>&nbsp;('.$filesize.')'.(!empty($filecomment) ? '&nbsp;-&nbsp;<i>'.$filecomment.'</i>' : '');
1516
                }
1517
            }
1518
        }
1519
        return $links_attach_file;
1520
    }
1521
1522
    /**
1523
     * Get message list by id
1524
     * @param int  $message_id
1525
     * @return array
1526
     */
1527
    public static function get_message_by_id($message_id)
1528
    {
1529
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1530
        $message_id = intval($message_id);
1531
        $sql = "SELECT * FROM $tbl_message
1532
                WHERE id = '$message_id' AND msg_status <> '".MESSAGE_STATUS_DELETED."' ";
1533
        $res = Database::query($sql);
1534
        $item = array();
1535
        if (Database::num_rows($res) > 0) {
1536
            $item = Database::fetch_array($res, 'ASSOC');
1537
        }
1538
        return $item;
1539
    }
1540
1541
    /**
1542
     * @param $id
1543
     * @param array $params
1544
     * @return string
1545
     */
1546
    public static function generate_message_form($id, $params = array())
1547
    {
1548
        $form = new FormValidator('send_message');
1549
        $form->addText('subject', get_lang('Subject'), false, ['id' => 'subject_id']);
1550
        $form->addTextarea('content', get_lang('Message'), ['id' => 'content_id', 'rows' => '5']);
1551
1552
        return $form->returnForm();
1553
    }
1554
1555
    /**
1556
     * @param $id
1557
     * @param array $params
1558
     * @param string $display
0 ignored issues
show
Bug introduced by
There is no parameter named $display. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1559
     * @return string
1560
     */
1561
    public static function generate_invitation_form($id, $params = array())
1562
    {
1563
        $form = new FormValidator('send_invitation');
1564
        $form->addTextarea('content', get_lang('AddPersonalMessage'), ['id' => 'content_invitation_id', 'rows' => 5]);
1565
        return $form->return_form();
0 ignored issues
show
Deprecated Code introduced by
The method FormValidator::return_form() has been deprecated with message: use returnForm()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1566
    }
1567
1568
    //@todo this functions should be in the message class
1569
1570
    public static function inbox_display($keyword = '')
1571
    {
1572
        $success = get_lang('SelectedMessagesDeleted');
1573
        $success_read = get_lang('SelectedMessagesRead');
1574
        $success_unread = get_lang('SelectedMessagesUnRead');
1575
        $html = '';
1576
1577
        Session::write('message_search_keyword', $keyword);
1578
1579
        if (isset($_REQUEST['action'])) {
1580
            switch ($_REQUEST['action']) {
1581
                 case 'mark_as_unread' :
1582
                    $number_of_selected_messages = count($_POST['id']);
1583
                    if (is_array($_POST['id'])) {
1584
                        foreach ($_POST['id'] as $index => $message_id) {
1585
                            MessageManager::update_message_status(api_get_user_id(), $message_id, MESSAGE_STATUS_UNREAD);
1586
                        }
1587
                    }
1588
                    $html .= Display::return_message(api_xml_http_response_encode($success_unread), 'normal', false);
1589
                    break;
1590
                case 'mark_as_read' :
1591
                    $number_of_selected_messages = count($_POST['id']);
1592
                    if (is_array($_POST['id'])) {
1593
                        foreach ($_POST['id'] as $index => $message_id) {
1594
                            MessageManager::update_message_status(api_get_user_id(), $message_id, MESSAGE_STATUS_NEW);
1595
                        }
1596
                    }
1597
                    $html .= Display::return_message(api_xml_http_response_encode($success_read), 'normal', false);
1598
                    break;
1599 View Code Duplication
                case 'delete' :
1600
                    $number_of_selected_messages = count($_POST['id']);
1601
                    foreach ($_POST['id'] as $index => $message_id) {
1602
                        MessageManager::delete_message_by_user_receiver(api_get_user_id(), $message_id);
1603
                    }
1604
                    $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
1605
                    break;
1606 View Code Duplication
                case 'deleteone' :
1607
                    MessageManager::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
1608
                    $html .= Display::return_message(api_xml_http_response_encode($success), 'confirmation', false);
1609
                    break;
1610
            }
1611
        }
1612
1613
        // display sortable table with messages of the current user
1614
        $table = new SortableTable(
1615
            'message_inbox',
1616
            array('MessageManager', 'get_number_of_messages'),
1617
            array('MessageManager', 'get_message_data'),
1618
            3,
1619
            20,
1620
            'DESC'
1621
        );
1622
        $table->set_header(0, '', false, array('style' => 'width:15px;'));
1623
        $table->set_header(1, get_lang('Messages'), false);
1624
        $table->set_header(2, get_lang('Date'), true, array('style' => 'width:180px;'));
1625
        $table->set_header(3, get_lang('Modify'), false, array('style' => 'width:70px;'));
1626
1627
        if (isset($_REQUEST['f']) && $_REQUEST['f'] == 'social') {
1628
            $parameters['f'] = 'social';
1629
            $table->set_additional_parameters($parameters);
1630
        }
1631
        $table->set_form_actions(
1632
            array(
1633
                'delete' => get_lang('DeleteSelectedMessages'),
1634
                'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
1635
                'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
1636
            )
1637
        );
1638
        $html .= $table->return_table();
1639
1640
        Session::erase('message_search_keyword');
1641
1642
        return $html;
1643
    }
1644
1645
    /**
1646
     * @param string $keyword
1647
     * @return null|string
1648
     */
1649
    public static function outbox_display($keyword = '')
1650
    {
1651
        $social_link = false;
1652
        if (isset($_REQUEST['f']) && $_REQUEST['f'] == 'social') {
1653
            $social_link = 'f=social';
1654
        }
1655
1656
        Session::write('message_sent_search_keyword', $keyword);
1657
1658
        $success = get_lang('SelectedMessagesDeleted').'&nbsp</b><br /><a href="outbox.php?'.$social_link.'">'.get_lang('BackToOutbox').'</a>';
1659
1660
        $html = null;
1661
        if (isset($_REQUEST['action'])) {
1662
            switch ($_REQUEST['action']) {
1663 View Code Duplication
                case 'delete' :
1664
                    $number_of_selected_messages = count($_POST['id']);
1665
                    if ($number_of_selected_messages != 0) {
1666
                        foreach ($_POST['id'] as $index => $message_id) {
1667
                            MessageManager::delete_message_by_user_receiver(api_get_user_id(), $message_id);
1668
                        }
1669
                    }
1670
                    $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
1671
                    break;
1672 View Code Duplication
                case 'deleteone' :
1673
                    MessageManager::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
1674
                    $html .=Display::return_message(api_xml_http_response_encode($success), 'normal', false);
1675
                    $html .= '<br/>';
1676
                    break;
1677
            }
1678
        }
1679
1680
        // display sortable table with messages of the current user
1681
        $table = new SortableTable(
1682
            'message_outbox',
1683
            array('MessageManager', 'get_number_of_messages_sent'),
1684
            array('MessageManager', 'get_message_data_sent'),
1685
            3,
1686
            20,
1687
            'DESC'
1688
        );
1689
1690
        $parameters['f'] = isset($_GET['f']) && $_GET['f'] == 'social' ? 'social' : null;
1691
        $table->set_additional_parameters($parameters);
1692
        $table->set_header(0, '', false, array('style' => 'width:15px;'));
1693
1694
        $table->set_header(1, get_lang('Messages'), false);
1695
        $table->set_header(2, get_lang('Date'), true, array('style' => 'width:160px;'));
1696
        $table->set_header(3, get_lang('Modify'), false, array('style' => 'width:70px;'));
1697
1698
        $table->set_form_actions(array('delete' => get_lang('DeleteSelectedMessages')));
1699
        $html .= $table->return_table();
1700
1701
        Session::erase('message_sent_search_keyword');
1702
1703
        return $html;
1704
    }
1705
1706
    /**
1707
     * Get the count of the last received messages for a user
1708
     * @param int $userId The user id
1709
     * @param int $lastId The id of the last received message
1710
     * @return int The count of new messages
1711
     */
1712
    public static function countMessagesFromLastReceivedMessage($userId, $lastId = 0)
1713
    {
1714
        $userId = intval($userId);
1715
        $lastId = intval($lastId);
1716
1717
        if (empty($userId)) {
1718
            return 0;
1719
        }
1720
1721
        $messagesTable = Database::get_main_table(TABLE_MESSAGE);
1722
1723
        $conditions = array(
1724
            'where' => array(
1725
                'user_receiver_id = ?' => $userId,
1726
                'AND msg_status = ?' => MESSAGE_STATUS_UNREAD,
1727
                'AND id > ?' => $lastId
1728
            )
1729
        );
1730
1731
        $result = Database::select('COUNT(1) AS qty', $messagesTable, $conditions);
1732
1733
        if (!empty($result)) {
1734
            $row = current($result);
1735
1736
            return $row['qty'];
1737
        }
1738
1739
        return 0;
1740
    }
1741
1742
    /**
1743
     * Get the data of the last received messages for a user
1744
     * @param int $userId The user id
1745
     * @param int $lastId The id of the last received message
1746
     * @return int The count of new messages
1747
     */
1748
    public static function getMessagesFromLastReceivedMessage($userId, $lastId = 0)
1749
    {
1750
        $userId = intval($userId);
1751
        $lastId = intval($lastId);
1752
1753
        if (empty($userId)) {
1754
            return 0;
1755
        }
1756
1757
        $messagesTable = Database::get_main_table(TABLE_MESSAGE);
1758
        $userTable = Database::get_main_table(TABLE_MAIN_USER);
1759
1760
        $messages = array();
1761
1762
        $sql = "SELECT m.*, u.user_id, u.lastname, u.firstname
1763
                FROM $messagesTable as m
1764
                INNER JOIN $userTable as u
1765
                ON m.user_sender_id = u.user_id
1766
                WHERE
1767
                    m.user_receiver_id = $userId AND
1768
                    m.msg_status = " . MESSAGE_STATUS_UNREAD . "
1769
                    AND m.id > $lastId
1770
                ORDER BY m.send_date DESC";
1771
1772
        $result = Database::query($sql);
1773
1774
        if ($result !== false) {
1775
            while ($row = Database::fetch_assoc($result)) {
1776
                $messages[] = $row;
1777
            }
1778
        }
1779
1780
        return $messages;
1781
    }
1782
1783
    /**
1784
     * Check whether a message has attachments
1785
     * @param int $messageId The message id
1786
     * @return boolean Whether the message has attachments return true. Otherwise return false
1787
     */
1788
    public static function hasAttachments($messageId)
1789
    {
1790
        $messageId = intval($messageId);
1791
1792
        if (empty($messageId)) {
1793
            return false;
1794
        }
1795
1796
        $messageAttachmentTable = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1797
1798
        $conditions = array(
1799
            'where' => array(
1800
                'message_id = ?' => $messageId
1801
            )
1802
        );
1803
1804
        $result = Database::select('COUNT(1) AS qty', $messageAttachmentTable, $conditions, 'first');
1805
1806
        if (!empty($result)) {
1807
            if ($result['qty'] > 0) {
1808
                return true;
1809
            }
1810
        }
1811
1812
        return false;
1813
    }
1814
1815
    /**
1816
     * @param string $url
1817
     *
1818
     * @return FormValidator
1819
     */
1820
    public static function getSearchForm($url)
1821
    {
1822
        $form = new FormValidator('search', 'post', $url, null, [], FormValidator::LAYOUT_INLINE);
1823
1824
        $form->addElement('text', 'keyword');
1825
        $form->addButtonSearch(get_lang('Search'));
1826
1827
        return $form;
1828
    }
1829
}
1830