Passed
Push — 1.10.x ( 50e584...7c88bc )
by Angel Fernando Quiroz
40:59
created

MessageManager::get_message_data_sent()   C

Complexity

Conditions 10
Paths 78

Size

Total Lines 69
Code Lines 51

Duplication

Lines 8
Ratio 11.59 %

Importance

Changes 0
Metric Value
cc 10
eloc 51
nc 78
nop 4
dl 8
loc 69
rs 6.0493
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
            // add file attachment additional attributes
367
            foreach ($file_attachments as $index => $file_attach) {
368
                $file_attachments[$index]['path'] = $file_attach['tmp_name'];
369
                $file_attachments[$index]['filename'] = $file_attach['name'];
370
            }
371
372
            if (empty($group_id)) {
373
                $type = Notification::NOTIFICATION_TYPE_MESSAGE;
374
                if ($directMessage) {
375
                    $type = Notification::NOTIFICATION_TYPE_DIRECT_MESSAGE;
376
                }
377
                $notification->save_notification(
378
                    $type,
379
                    array($receiver_user_id),
380
                    $subject,
381
                    $content,
382
                    $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...
383
                    $file_attachments
384
                );
385
            } else {
386
                $usergroup = new UserGroup();
387
                $group_info = $usergroup->get($group_id);
388
                $group_info['topic_id'] = $topic_id;
389
                $group_info['msg_id'] = $inbox_last_id;
390
391
                $user_list = $usergroup->get_users_by_group($group_id, false, array(), 0, 1000);
392
393
                // Adding more sense to the message group
394
                $subject = sprintf(get_lang('ThereIsANewMessageInTheGroupX'), $group_info['name']);
395
396
                $new_user_list = array();
397
                foreach ($user_list as $user_data) {
398
                    $new_user_list[] = $user_data['id'];
399
                }
400
                $group_info = array(
401
                    'group_info' => $group_info,
402
                    'user_info' => $sender_info,
403
                );
404
                $notification->save_notification(
405
                    Notification::NOTIFICATION_TYPE_GROUP,
406
                    $new_user_list,
407
                    $subject,
408
                    $content,
409
                    $group_info,
410
                    $file_attachments
411
                );
412
            }
413
414
            return $inbox_last_id;
415
        }
416
417
        return false;
418
    }
419
420
    /**
421
     * @param int $receiver_user_id
422
     * @param int $subject
423
     * @param string $message
424
     * @param int $sender_id
425
     * @param bool $sendCopyToDrhUsers send copy to related DRH users
426
     * @param bool $directMessage
427
     *
428
     * @return bool
429
     */
430
    public static function send_message_simple(
431
        $receiver_user_id,
432
        $subject,
433
        $message,
434
        $sender_id = null,
435
        $sendCopyToDrhUsers = false,
436
        $directMessage = false
437
    ) {
438
        $result = MessageManager::send_message(
439
            $receiver_user_id,
440
            $subject,
441
            $message,
442
            $_FILES ? $_FILES : [],
443
            [],
444
            null,
445
            null,
446
            null,
447
            null,
448
            $sender_id,
449
            $directMessage
450
        );
451
452
        if ($sendCopyToDrhUsers) {
453
454
            $userInfo = api_get_user_info($receiver_user_id);
455
            $drhList = UserManager::getDrhListFromUser($receiver_user_id);
456
            if (!empty($drhList)) {
457
                foreach ($drhList as $drhInfo) {
458
                    $message = sprintf(
459
                            get_lang('CopyOfMessageSentToXUser'),
460
                            $userInfo['complete_name']
461
                        ).' <br />'.$message;
462
463
                    MessageManager::send_message_simple(
464
                        $drhInfo['user_id'],
465
                        $subject,
466
                        $message,
467
                        $sender_id,
468
                        false,
469
                        $directMessage
470
                    );
471
                }
472
            }
473
        }
474
475
        return $result;
476
    }
477
478
    /**
479
     * Update parent ids for other receiver user from current message in groups
480
     * @author Christian Fasanando Flores
481
     * @param  int	$parent_id
482
     * @param  int	$receiver_user_id
483
     * @param  int	$message_id
484
     * @return void
485
     */
486
    public static function update_parent_ids_from_reply($parent_id, $receiver_user_id, $message_id)
487
    {
488
        $table_message = Database::get_main_table(TABLE_MESSAGE);
489
        $parent_id = intval($parent_id);
490
        $receiver_user_id = intval($receiver_user_id);
491
        $message_id = intval($message_id);
492
        // first get data from message id (parent)
493
        $sql_message = "SELECT * FROM $table_message WHERE id = '$parent_id'";
494
        $rs_message = Database::query($sql_message);
495
        $row_message = Database::fetch_array($rs_message);
496
497
        // get message id from data found early for other receiver user
498
        $sql = "SELECT id FROM $table_message
499
                WHERE
500
                    user_sender_id ='{$row_message['user_sender_id']}' AND
501
                    title='{$row_message['title']}' AND
502
                    content='{$row_message['content']}' AND
503
                    group_id='{$row_message['group_id']}' AND
504
                    user_receiver_id='$receiver_user_id'";
505
        $rs_msg_id = Database::query($sql);
506
        $row = Database::fetch_array($rs_msg_id);
507
508
        // update parent_id for other user receiver
509
        $sql = "UPDATE $table_message SET parent_id = ".$row['id']."
510
                WHERE id = $message_id";
511
        Database::query($sql);
512
    }
513
514
    /**
515
     * @param int $user_receiver_id
516
     * @param int $id
517
     * @return bool|resource
518
     */
519
    public static function delete_message_by_user_receiver($user_receiver_id, $id)
520
    {
521
        $table_message = Database::get_main_table(TABLE_MESSAGE);
522
        if ($id != strval(intval($id)))
523
            return false;
524
        $user_receiver_id = intval($user_receiver_id);
525
        $id = intval($id);
526
        $sql = "SELECT * FROM $table_message
527
                WHERE id=".$id." AND msg_status<>4";
528
        $rs = Database::query($sql);
529
530
        if (Database::num_rows($rs) > 0) {
531
            // delete attachment file
532
            self::delete_message_attachment_file($id, $user_receiver_id);
533
            // delete message
534
            $query = "UPDATE $table_message SET msg_status=3
535
                      WHERE user_receiver_id=".$user_receiver_id." AND id=".$id;
536
            $result = Database::query($query);
537
            return $result;
538
        } else {
539
            return false;
540
        }
541
    }
542
543
    /**
544
     * Set status deleted
545
     * @author Isaac FLores Paz <[email protected]>
546
     * @param  integer
547
     * @param  integer
548
     * @return array
549
     */
550
    public static function delete_message_by_user_sender($user_sender_id, $id)
551
    {
552
        if ($id != strval(intval($id))) {
553
            return false;
554
        }
555
556
        $table_message = Database::get_main_table(TABLE_MESSAGE);
557
558
        $id = intval($id);
559
        $user_sender_id = intval($user_sender_id);
560
561
        $sql = "SELECT * FROM $table_message WHERE id='$id'";
562
        $rs = Database::query($sql);
563
564
        if (Database::num_rows($rs) > 0) {
565
            // delete attachment file
566
            self::delete_message_attachment_file($id, $user_sender_id);
567
            // delete message
568
            $sql = "UPDATE $table_message SET msg_status=3
569
                    WHERE user_sender_id='$user_sender_id' AND id='$id'";
570
            $result = Database::query($sql);
571
572
            return $result;
573
        }
574
575
        return false;
576
    }
577
578
    /**
579
     * Saves a message attachment files
580
     * @param  array 	$file_attach $_FILES['name']
581
     * @param  string  	a comment about the uploaded file
582
     * @param  int		message id
583
     * @param  int		receiver user id (optional)
584
     * @param  int		sender user id (optional)
585
     * @param  int		group id (optional)
586
     * @return void
587
     */
588
    public static function save_message_attachment_file(
589
        $file_attach,
590
        $file_comment,
591
        $message_id,
592
        $receiver_user_id = 0,
593
        $sender_user_id = 0,
594
        $group_id = 0
595
    ) {
596
        $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
597
598
        // Try to add an extension to the file if it hasn't one
599
        $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $file_attach['type']);
600
601
        // user's file name
602
        $file_name = $file_attach['name'];
603
        if (!filter_extension($new_file_name)) {
604
            Display :: display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
605
        } else {
606
            $new_file_name = uniqid('');
607
            if (!empty($receiver_user_id)) {
608
                $message_user_id = $receiver_user_id;
609
            } else {
610
                $message_user_id = $sender_user_id;
611
            }
612
613
            // User-reserved directory where photos have to be placed.*
614
            $userGroup = new UserGroup();
615
616 View Code Duplication
            if (!empty($group_id)) {
617
                $path_user_info = $userGroup->get_group_picture_path_by_id($group_id, 'system', true);
618
            } else {
619
                $path_user_info['dir'] = UserManager::getUserPathById($message_user_id, 'system');
620
            }
621
622
            $path_message_attach = $path_user_info['dir'].'message_attachments/';
623
624
            // If this directory does not exist - we create it.
625
            if (!file_exists($path_message_attach)) {
626
                @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
627
            }
628
            $new_path = $path_message_attach.$new_file_name;
629
            if (is_uploaded_file($file_attach['tmp_name'])) {
630
                @copy($file_attach['tmp_name'], $new_path);
631
            }
632
633
            // Storing the attachments if any
634
            $params = [
635
                'filename' => $file_name,
636
                'comment' => $file_comment,
637
                'path' => $new_file_name,
638
                'message_id' => $message_id,
639
                'size' => $file_attach['size']
640
            ];
641
            Database::insert($tbl_message_attach, $params);
642
        }
643
    }
644
645
    /**
646
     * Delete message attachment files (logically updating the row with a suffix _DELETE_id)
647
     * @param  int	message id
648
     * @param  int	message user id (receiver user id or sender user id)
649
     * @param  int	group id (optional)
650
     * @return void
651
     */
652
    public static function delete_message_attachment_file($message_id, $message_uid, $group_id = 0)
653
    {
654
        $message_id = intval($message_id);
655
        $message_uid = intval($message_uid);
656
        $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
657
658
        $sql = "SELECT * FROM $table_message_attach WHERE message_id = '$message_id'";
659
        $rs = Database::query($sql);
660
        while ($row = Database::fetch_array($rs)) {
661
            $path = $row['path'];
662
            $attach_id = $row['id'];
663
            $new_path = $path.'_DELETED_'.$attach_id;
664
665 View Code Duplication
            if (!empty($group_id)) {
666
                $userGroup = new UserGroup();
667
                $path_user_info = $userGroup->get_group_picture_path_by_id(
668
                    $group_id,
669
                    'system',
670
                    true
671
                );
672
            } else {
673
                $path_user_info['dir'] = UserManager::getUserPathById(
674
                    $message_uid,
675
                    'system'
676
                );
677
            }
678
679
            $path_message_attach = $path_user_info['dir'].'message_attachments/';
680
            if (is_file($path_message_attach.$path)) {
681
                if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
682
                    $sql = "UPDATE $table_message_attach set path='$new_path'
683
                            WHERE id ='$attach_id'";
684
                    Database::query($sql);
685
                }
686
            }
687
        }
688
    }
689
690
    /**
691
     * update messages by user id and message id
692
     * @param  int		$user_id
693
     * @param  int		$message_id
694
     * @return resource
695
     */
696
    public static function update_message($user_id, $message_id)
697
    {
698
        if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id)))
699
            return false;
700
701
        $table_message = Database::get_main_table(TABLE_MESSAGE);
702
        $sql = "UPDATE $table_message SET msg_status = '0'
703
                WHERE
704
                    msg_status<>4 AND
705
                    user_receiver_id=".intval($user_id)." AND
706
                    id='".intval($message_id)."'";
707
        Database::query($sql);
708
    }
709
710
    /**
711
     * @param int $user_id
712
     * @param int $message_id
713
     * @param string $type
714
     * @return bool
715
     */
716 View Code Duplication
    public static function update_message_status($user_id, $message_id,$type)
717
    {
718
        $type = intval($type);
719
        if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id))) {
720
            return false;
721
        }
722
        $table_message = Database::get_main_table(TABLE_MESSAGE);
723
        $sql = "UPDATE $table_message SET
724
                    msg_status = '$type'
725
                WHERE
726
                    user_receiver_id=".intval($user_id)." AND
727
                    id='".intval($message_id)."'";
728
        Database::query($sql);
729
    }
730
731
    /**
732
     * get messages by user id and message id
733
     * @param  int		$user_id
734
     * @param  int		$message_id
735
     * @return array
736
     */
737 View Code Duplication
    public static function get_message_by_user($user_id, $message_id)
738
    {
739
        if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id)))
740
            return false;
741
        $table_message = Database::get_main_table(TABLE_MESSAGE);
742
        $query = "SELECT * FROM $table_message
743
                  WHERE user_receiver_id=".intval($user_id)." AND id='".intval($message_id)."'";
744
        $result = Database::query($query);
745
        return $row = Database::fetch_array($result);
746
    }
747
748
    /**
749
     * get messages by group id
750
     * @param  int		group id
751
     * @return array
752
     */
753
    public static function get_messages_by_group($group_id)
754
    {
755
        if ($group_id != strval(intval($group_id)))
756
            return false;
757
758
        $table_message = Database::get_main_table(TABLE_MESSAGE);
759
        $group_id = intval($group_id);
760
        $sql = "SELECT * FROM $table_message
761
                WHERE
762
                    group_id= $group_id AND
763
                    msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
764
                ORDER BY id";
765
        $rs = Database::query($sql);
766
        $data = array();
767
        if (Database::num_rows($rs) > 0) {
768
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
769
                $data[] = $row;
770
            }
771
        }
772
        return $data;
773
    }
774
775
    /**
776
     * get messages by group id
777
     * @param  int $group_id
778
     * @param int $message_id
779
     * @return array
780
     */
781
    public static function get_messages_by_group_by_message($group_id, $message_id)
782
    {
783
        if ($group_id != strval(intval($group_id)))
784
            return false;
785
        $table_message = Database::get_main_table(TABLE_MESSAGE);
786
        $group_id = intval($group_id);
787
        $sql = "SELECT * FROM $table_message
788
                WHERE
789
                    group_id = $group_id AND
790
                    msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
791
                ORDER BY id ";
792
793
        $rs = Database::query($sql);
794
        $data = array();
795
        $parents = array();
796 View Code Duplication
        if (Database::num_rows($rs) > 0) {
797
            while ($row = Database::fetch_array($rs, 'ASSOC')) {
798
                if ($message_id == $row['parent_id'] || in_array($row['parent_id'], $parents)) {
799
                    $parents[] = $row['id'];
800
                    $data[] = $row;
801
                }
802
            }
803
        }
804
805
        return $data;
806
    }
807
808
    /**
809
     * get messages by parent id optionally with limit
810
     * @param  int		parent id
811
     * @param  int		group id (optional)
812
     * @param  int		offset (optional)
813
     * @param  int		limit (optional)
814
     * @return array
815
     */
816
    public static function get_messages_by_parent($parent_id, $group_id = '', $offset = 0, $limit = 0)
817
    {
818
        if ($parent_id != strval(intval($parent_id))) {
819
            return false;
820
        }
821
        $table_message = Database::get_main_table(TABLE_MESSAGE);
822
        $parent_id = intval($parent_id);
823
824
        $condition_group_id = "";
825
        if ($group_id !== '') {
826
            $group_id = intval($group_id);
827
            $condition_group_id = " AND group_id = '$group_id' ";
828
        }
829
830
        $condition_limit = "";
831
        if ($offset && $limit) {
832
            $offset = ($offset - 1) * $limit;
833
            $condition_limit = " LIMIT $offset,$limit ";
834
        }
835
836
        $sql = "SELECT * FROM $table_message
837
                WHERE
838
                    parent_id='$parent_id' AND
839
                    msg_status <> ".MESSAGE_STATUS_OUTBOX."
840
                    $condition_group_id
841
                ORDER BY send_date DESC $condition_limit ";
842
        $rs = Database::query($sql);
843
        $data = array();
844
        if (Database::num_rows($rs) > 0) {
845
            while ($row = Database::fetch_array($rs)) {
846
                $data[$row['id']] = $row;
847
            }
848
        }
849
850
        return $data;
851
    }
852
853
    /**
854
     * Gets information about if exist messages
855
     * @author Isaac FLores Paz <[email protected]>
856
     * @param  integer
857
     * @param  integer
858
     * @return boolean
859
     */
860
    public static function exist_message($user_id, $id)
861
    {
862
        if ($id != strval(intval($id)) || $user_id != strval(intval($user_id)))
863
            return false;
864
        $table_message = Database::get_main_table(TABLE_MESSAGE);
865
        $query = "SELECT id FROM $table_message
866
                  WHERE
867
                    user_receiver_id = ".intval($user_id)." AND
868
                    id = '".intval($id)."'";
869
        $result = Database::query($query);
870
        $num = Database::num_rows($result);
871
        if ($num > 0) {
872
            return true;
873
        } else {
874
            return false;
875
        }
876
    }
877
878
    /**
879
     * Gets information about messages sent
880
     * @param  integer
881
     * @param  integer
882
     * @param  string
883
     * @return array
884
     */
885
    public static function get_message_data_sent($from, $number_of_items, $column, $direction)
886
    {
887
        $from = intval($from);
888
        $number_of_items = intval($number_of_items);
889 View Code Duplication
        if (!isset($direction)) {
890
            $column = 3;
891
            $direction = 'DESC';
892
        } else {
893
            $column = intval($column);
894
            if (!in_array($direction, array('ASC', 'DESC')))
895
                $direction = 'ASC';
896
        }
897
        $table_message = Database::get_main_table(TABLE_MESSAGE);
898
        $request = api_is_xml_http_request();
899
900
        $keyword = Session::read('message_sent_search_keyword');
901
        $keywordCondition = '';
902
        if (!empty($keyword)) {
903
            $keyword = Database::escape_string($keyword);
904
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
905
        }
906
907
        $sql = "SELECT
908
                    id as col0, user_sender_id as col1, title as col2, send_date as col3, user_receiver_id as col4, msg_status as col5
909
                FROM $table_message
910
                WHERE
911
                    user_sender_id=".api_get_user_id()." AND
912
                    msg_status=".MESSAGE_STATUS_OUTBOX."
913
                    $keywordCondition
914
                ORDER BY col$column $direction
915
                LIMIT $from, $number_of_items";
916
        $sql_result = Database::query($sql);
917
        $i = 0;
918
        $message_list = array();
919
        while ($result = Database::fetch_row($sql_result)) {
920
            if ($request === true) {
921
                $message[0] = '<input type="checkbox" value='.$result[0].' name="out[]">';
922
            } else {
923
                $message[0] = ($result[0]);
924
            }
925
            $class = 'class = "read"';
926
            $result[2] = Security::remove_XSS($result[2]);
927
928
            if ($request === true) {
929
                $message[1] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.GetFullUserName($result[4]).'</a>';
930
                $message[2] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.str_replace("\\", "", $result[2]).'</a>';
931
                $message[3] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
932
933
                $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>';
934
            } else {
935
                $link = '';
936
                if (isset($_GET['f']) && $_GET['f'] == 'social') {
937
                    $link = '&f=social';
938
                }
939
                $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]);
940
                //$message[2] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a>';
941
                $message[2] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
942
                $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>';
943
            }
944
945
            foreach ($message as $key => $value) {
946
                $message[$key] = $value;
947
            }
948
            $message_list[] = $message;
949
            $i++;
950
        }
951
952
        return $message_list;
953
    }
954
955
    /**
956
     * Gets information about number messages sent
957
     * @author Isaac FLores Paz <[email protected]>
958
     * @param void
959
     * @return integer
960
     */
961
    public static function get_number_of_messages_sent()
962
    {
963
        $table_message = Database::get_main_table(TABLE_MESSAGE);
964
965
        $keyword = Session::read('message_sent_search_keyword');
966
        $keywordCondition = '';
967
        if (!empty($keyword)) {
968
            $keyword = Database::escape_string($keyword);
969
            $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
970
        }
971
972
        $sql = "SELECT COUNT(*) as number_messages FROM $table_message
973
                WHERE
974
                  msg_status=".MESSAGE_STATUS_OUTBOX." AND
975
                  user_sender_id=".api_get_user_id()."
976
                  $keywordCondition
977
                ";
978
        $result = Database::query($sql);
979
        $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...
980
981
        return $result['number_messages'];
982
    }
983
984
    /**
985
     * display message box in the inbox
986
     * @param int the message id
987
     * @param string inbox or outbox strings are available
988
     * @todo replace numbers with letters in the $row array pff...
989
     * @return string html with the message content
990
     */
991
    public static function show_message_box($message_id, $source = 'inbox')
992
    {
993
        $table_message = Database::get_main_table(TABLE_MESSAGE);
994
        $message_id = intval($message_id);
995
996
        if ($source == 'outbox') {
997 View Code Duplication
            if (isset($message_id) && is_numeric($message_id)) {
998
                $query = "SELECT * FROM $table_message
999
                          WHERE
1000
                            user_sender_id = ".api_get_user_id()." AND
1001
                            id = ".$message_id." AND
1002
                            msg_status = 4;";
1003
                $result = Database::query($query);
1004
            }
1005
        } else {
1006
            if (is_numeric($message_id) && !empty($message_id)) {
1007
                $query = "UPDATE $table_message SET
1008
                          msg_status = '".MESSAGE_STATUS_NEW."'
1009
                          WHERE
1010
                            user_receiver_id=".api_get_user_id()." AND
1011
                            id='".$message_id."'";
1012
                Database::query($query);
1013
1014
                $query = "SELECT * FROM $table_message
1015
                          WHERE
1016
                            msg_status<>4 AND
1017
                            user_receiver_id=".api_get_user_id()." AND
1018
                            id='".$message_id."'";
1019
                $result = Database::query($query);
1020
            }
1021
        }
1022
        $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...
1023
        $user_sender_id = $row['user_sender_id'];
1024
1025
        // get file attachments by message id
1026
        $files_attachments = self::get_links_message_attachment_files($message_id, $source);
1027
1028
        $user_con = self::users_connected_by_id();
1029
        $band = 0;
1030
        for ($i = 0; $i < count($user_con); $i++) {
1031
            if ($user_sender_id == $user_con[$i]) {
1032
                $band = 1;
1033
            }
1034
        }
1035
1036
        $title = Security::remove_XSS($row['title'], STUDENT, true);
1037
        $content = Security::remove_XSS($row['content'], STUDENT, true);
1038
1039
        $from_user = api_get_user_info($user_sender_id);
1040
        $name = $from_user['complete_name'];
1041
        $user_image = Display::img($from_user['avatar'], $name, array('title' => $name));
1042
1043
        $message_content = Display::page_subheader(str_replace("\\", "", $title));
1044
1045
        if (api_get_setting('allow_social_tool') == 'true') {
1046
            $message_content .= $user_image.' ';
1047
        }
1048
1049
        $receiverUserInfo = api_get_user_info($row['user_receiver_id']);
1050
1051
        $message_content .='<tr>';
1052
        if (api_get_setting('allow_social_tool') == 'true') {
1053
            if ($source == 'outbox') {
1054
                $message_content .= get_lang('From').': <a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a> '.
1055
                    api_strtolower(get_lang('To')).'&nbsp;<b>'.$receiverUserInfo['complete_name'].'</b>';
1056 View Code Duplication
            } else {
1057
                $message_content .= get_lang('From').' <a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a> '.
1058
                    api_strtolower(get_lang('To')).'&nbsp;<b>'.get_lang('Me').'</b>';
1059
            }
1060
        } else {
1061
            if ($source == 'outbox') {
1062
                $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.$receiverUserInfo['complete_name'].'</b>';
1063
            } else {
1064
                $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.get_lang('Me').'</b>';
1065
            }
1066
        }
1067
        $message_content .=' '.get_lang('Date').':  '.api_get_local_time($row['send_date']).'
1068
		        <br />
1069
		        <hr style="color:#ddd" />
1070
		        <table height="209px" width="100%">
1071
		            <tr>
1072
		              <td valign=top class="view-message-content">'.str_replace("\\", "", $content).'</td>
1073
		            </tr>
1074
		        </table>
1075
		        <div id="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>
1076
		        <div style="padding: 15px 0px 5px 0px">';
1077
        $social_link = '';
1078
        if (isset($_GET['f']) && $_GET['f'] == 'social') {
1079
            $social_link = 'f=social';
1080
        }
1081
        if ($source == 'outbox') {
1082
            $message_content .= '<a href="outbox.php?'.$social_link.'">'.
1083
                Display::return_icon('back.png', get_lang('ReturnToOutbox')).'</a> &nbsp';
1084
        } else {
1085
            $message_content .= '<a href="inbox.php?'.$social_link.'">'.
1086
                Display::return_icon('back.png', get_lang('ReturnToInbox')).'</a> &nbsp';
1087
            $message_content .= '<a href="new_message.php?re_id='.$message_id.'&'.$social_link.'">'.
1088
                Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a> &nbsp';
1089
        }
1090
        $message_content .= '<a href="inbox.php?action=deleteone&id='.$message_id.'&'.$social_link.'" >'.
1091
            Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
1092
1093
        $message_content .='</div></td>
1094
		      <td width=10></td>
1095
		    </tr>
1096
		</table>';
1097
        return $message_content;
1098
    }
1099
1100
    /**
1101
     * get user id by user email
1102
     * @param string $user_email
1103
     * @return int user id
1104
     */
1105
    public static function get_user_id_by_email($user_email)
1106
    {
1107
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1108
        $sql = 'SELECT user_id FROM '.$tbl_user.'
1109
                WHERE email="'.Database::escape_string($user_email).'";';
1110
        $rs = Database::query($sql);
1111
        $row = Database::fetch_array($rs, 'ASSOC');
1112
        if (isset($row['user_id'])) {
1113
            return $row['user_id'];
1114
        } else {
1115
            return null;
1116
        }
1117
    }
1118
1119
    /**
1120
     * Displays messages of a group with nested view
1121
     *
1122
     * @param int $group_id
1123
     */
1124
    public static function display_messages_for_group($group_id)
1125
    {
1126
        global $my_group_role;
1127
1128
        $rows = self::get_messages_by_group($group_id);
1129
        $topics_per_page = 10;
1130
        $html_messages = '';
1131
        $query_vars = array('id' => $group_id, 'topics_page_nr' => 0);
1132
1133
        if (is_array($rows) && count($rows) > 0) {
1134
1135
            // prepare array for topics with its items
1136
            $topics = array();
1137
            $x = 0;
1138
            foreach ($rows as $index => $value) {
1139
                if (empty($value['parent_id'])) {
1140
                    $topics[$value['id']] = $value;
1141
                }
1142
            }
1143
1144
            $new_topics = array();
1145
1146
            foreach ($topics as $id => $value) {
1147
                $rows = null;
1148
                $rows = self::get_messages_by_group_by_message($group_id, $value['id']);
1149
                if (!empty($rows)) {
1150
                    $count = count(self::calculate_children($rows, $value['id']));
1151
                } else {
1152
                    $count = 0;
1153
                }
1154
                $value['count'] = $count;
1155
                $new_topics[$id] = $value;
1156
            }
1157
1158
            $array_html = array();
1159
1160
            foreach ($new_topics as $index => $topic) {
1161
                $html = '';
1162
                // topics
1163
                $user_sender_info = api_get_user_info($topic['user_sender_id']);
1164
                $name = $user_sender_info['complete_name'];
1165
1166
                $html .= '<div class="row">';
1167
1168
                $items = $topic['count'];
1169
                $reply_label = ($items == 1) ? get_lang('GroupReply') : get_lang('GroupReplies');
1170
                $label =  Display::label($items.' '.$reply_label);
1171
                $topic['title'] = trim($topic['title']);
1172
1173
                if (empty($topic['title'])) {
1174
                    $topic['title'] = get_lang('Untitled');
1175
                }
1176
1177
                $html .= '<div class="col-md-8">';
1178
                $html .= Display::tag(
1179
                    'h4',
1180
                    Display::url(
1181
                        Security::remove_XSS($topic['title'], STUDENT, true),
1182
                        api_get_path(WEB_CODE_PATH).'social/group_topics.php?id='.$group_id.'&topic_id='.$topic['id']
1183
                    )
1184
                );
1185
                $actions = '';
1186
                if ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
1187
                    $my_group_role == GROUP_USER_PERMISSION_MODERATOR
1188
                ) {
1189
                    $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'));
1190
                }
1191
1192
                $date = '';
1193 View Code Duplication
                if ($topic['send_date'] != $topic['update_date']) {
1194
                    if (!empty($topic['update_date']) &&
1195
                        $topic['update_date'] != '0000-00-00 00:00:00'
1196
                    ) {
1197
                        $date .= '<div class="message-group-date" > <i>'.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']).'</i></div>';
1198
                    }
1199
                } else {
1200
                    $date .= '<div class="message-group-date"> <i>'.get_lang('Created').' '.date_to_str_ago($topic['send_date']).'</i></div>';
1201
                }
1202
                $html .= $date.$label.$actions;
1203
                $html .= '</div>';
1204
1205
                $image = $user_sender_info['avatar'];
1206
1207
                $user_info = '<td valign="top"><a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a>';
1208
                $user_info .= '<div class="message-group-author"><img src="'.$image.'" alt="'.$name.'"  width="32" height="32" title="'.$name.'" /></div>';
1209
                $user_info .= '</td>';
1210
1211
                $html .= '<div class="col-md-2">';
1212
                $html .= $user_info;
1213
                $html .= '</div>';
1214
                $html .= '</div>';
1215
1216
                $array_html[] = array($html);
1217
            }
1218
1219
            // grids for items and topics  with paginations
1220
            $html_messages .= Display::return_sortable_grid(
1221
                'topics',
1222
                array(),
1223
                $array_html,
1224
                array(
1225
                    'hide_navigation' => false,
1226
                    'per_page' => $topics_per_page
1227
                ),
1228
                $query_vars,
1229
                false,
1230
                array(true, true, true, false),
1231
                false
1232
            );
1233
        }
1234
1235
        return $html_messages;
1236
    }
1237
1238
    /**
1239
     * Displays messages of a group with nested view
1240
     * @param $group_id
1241
     * @param $topic_id
1242
     * @param $is_member
1243
     * @param $message_id
1244
     * @return string
1245
     */
1246
    public static function display_message_for_group($group_id, $topic_id, $is_member, $message_id)
1247
    {
1248
        global $my_group_role;
1249
        $main_message = self::get_message_by_id($topic_id);
1250
        if (empty($main_message)) {
1251
            return false;
1252
        }
1253
        $rows = self::get_messages_by_group_by_message($group_id, $topic_id);
1254
        $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...
1255
        $current_user_id = api_get_user_id();
1256
1257
        $items_per_page = 50;
1258
1259
        $query_vars = array('id' => $group_id, 'topic_id' => $topic_id, 'topics_page_nr' => 0);
1260
1261
        // Main message
1262
        $links = '';
1263
        $main_content = '';
1264
1265
        $items_page_nr = null;
1266
1267
        $html = '';
1268
1269
        $delete_button = '';
1270
        if (api_is_platform_admin()) {
1271
            $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);
1272
        }
1273
        $html .= Display::page_subheader(Security::remove_XSS($main_message['title'].$delete_button, STUDENT, true));
1274
1275
        $user_sender_info = api_get_user_info($main_message['user_sender_id']);
1276
        $files_attachments = self::get_links_message_attachment_files($main_message['id']);
1277
        $name = $user_sender_info['complete_name'];
1278
1279
        $topic_page_nr = isset($_GET['topics_page_nr']) ? intval($_GET['topics_page_nr']) : null;
1280
        $links.= '<div id="message-reply-link">';
1281
        if (($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
1282
            $my_group_role == GROUP_USER_PERMISSION_MODERATOR) ||
1283
            $main_message['user_sender_id'] == $current_user_id
1284
        ) {
1285
            $urlEdit = api_get_path(WEB_CODE_PATH);
1286
            $urlEdit .= 'social/message_for_group_form.inc.php?';
1287
            $urlEdit .= http_build_query([
1288
                'user_friend' => $current_user_id,
1289
                'group_id' => $group_id,
1290
                'message_id' => $main_message['id'],
1291
                'action' => 'edit_message_group',
1292
                'anchor_topic' => 'topic_' . $main_message['id'],
1293
                'topics_page_nr' => $topic_page_nr,
1294
                'items_page_nr' => $items_page_nr,
1295
                'topic_id' => $main_message['id']
1296
            ]);
1297
1298
            $links .= Display::url(
1299
                Display::return_icon(
1300
                    'edit.png',
1301
                    get_lang('Edit'),
1302
                    array(),
1303
                    ICON_SIZE_SMALL
1304
                ),
1305
                $urlEdit,
1306
                [
1307
                    'class' => 'ajax btn btn-default',
1308
                    'title' => get_lang('Edit'),
1309
                    'data-title' => get_lang('Edit'),
1310
                    'data-size' => 'lg'
1311
                ]
1312
            );
1313
        }
1314
1315
        $urlReply = api_get_path(WEB_CODE_PATH);
1316
        $urlReply .= 'social/message_for_group_form.inc.php?';
1317
        $urlReply .= http_build_query([
1318
            'user_friend' => api_get_user_id(),
1319
            'group_id' => $group_id,
1320
            'message_id' => $main_message['id'],
1321
            'action' => 'reply_message_group',
1322
            'anchor_topic' => 'topic_' . $main_message['id'],
1323
            'topics_page_nr' => $topic_page_nr,
1324
            'topic_id' => $main_message['id']
1325
        ]);
1326
1327
        $links .= Display::url(
1328
            Display::return_icon('talk.png', get_lang('Reply')),
1329
            $urlReply,
1330
            [
1331
                'class' => 'ajax btn btn-default',
1332
                'title' => get_lang('Reply'),
1333
                'data-title' => get_lang('Reply'),
1334
                'data-size' => 'lg'
1335
            ]
1336
        );
1337
1338
        $links.= '</div>';
1339
1340
        $userPicture = $user_sender_info['avatar'];
1341
        $main_content.= '<div class="message-group-author">
1342
                         <img src="'.$userPicture.'" alt="'.$name.'"  width="32" height="32" title="'.$name.'" /></div>';
1343
        $user_link = '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$main_message['user_sender_id'].'">'.$name.'&nbsp;</a>';
1344
1345
        $date = '';
1346 View Code Duplication
        if ($main_message['send_date'] != $main_message['update_date']) {
1347
            if (!empty($main_message['update_date']) && $main_message['update_date'] != '0000-00-00 00:00:00') {
1348
                $date = '<div class="message-group-date"> '.get_lang('LastUpdate').' '.date_to_str_ago($main_message['update_date']).'</div>';
1349
            }
1350
        } else {
1351
            $date = '<div class="message-group-date"> '.get_lang('Created').' '.date_to_str_ago($main_message['send_date']).'</div>';
1352
        }
1353
        $attachment = '<div class="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>';
1354
        $main_content.= '<div class="message-group-content">'.$links.$user_link.' '.$date.$main_message['content'].$attachment.'</div>';
1355
        $main_content = Security::remove_XSS($main_content, STUDENT, true);
1356
1357
        $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'));
1358
1359
        $topic_id = $main_message['id'];
1360
1361
        if (is_array($rows) && count($rows) > 0) {
1362
            $topics = $rows;
1363
            $array_html_items = array();
1364
            foreach ($topics as $index => $topic) {
1365
                if (empty($topic['id'])) {
1366
                    continue;
1367
                }
1368
                $items_page_nr = isset($_GET['items_'.$topic['id'].'_page_nr']) ? intval($_GET['items_'.$topic['id'].'_page_nr']) : null;
1369
                $links = '';
1370
                $html_items = '';
1371
                $user_sender_info = api_get_user_info($topic['user_sender_id']);
1372
                $files_attachments = self::get_links_message_attachment_files($topic['id']);
1373
                $name = $user_sender_info['complete_name'];
1374
1375
                $links.= '<div id="message-reply-link">';
1376
                if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) || $topic['user_sender_id'] == $current_user_id) {
1377
                    $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').'">'.
1378
                        Display :: return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>';
1379
                }
1380
                $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').'">';
1381
                $links.= Display :: return_icon('talk.png', get_lang('Reply')).'</a>';
1382
                $links.= '</div>';
1383
1384
                $userPicture = $user_sender_info['avatar'];
1385
1386
                $html_items.= '<div class="message-group-author"><img src="'.$userPicture.'" alt="'.$name.'"  width="32" height="32" title="'.$name.'" /></div>';
1387
                $user_link = '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a>';
1388
1389
                $date = '';
1390 View Code Duplication
                if ($topic['send_date'] != $topic['update_date']) {
1391
                    if (!empty($topic['update_date']) && $topic['update_date'] != '0000-00-00 00:00:00') {
1392
                        $date = '<div class="message-group-date"> '.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']).'</div>';
1393
                    }
1394
                } else {
1395
                    $date = '<div class="message-group-date"> '.get_lang('Created').' '.date_to_str_ago($topic['send_date']).'</div>';
1396
                }
1397
                $attachment = '<div class="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>';
1398
                $html_items.= '<div class="message-group-content">'.$links.$user_link.' '.$date.Security::remove_XSS($topic['content'], STUDENT, true).$attachment.'</div>';
1399
1400
                $base_padding = 20;
1401
1402
                if ($topic['indent_cnt'] == 0) {
1403
                    $indent = $base_padding;
1404
                } else {
1405
                    $indent = intval($topic['indent_cnt']) * $base_padding + $base_padding;
1406
                }
1407
                $class = 'group_social_sub_item';
1408
                if (isset($message_id) && $message_id == $topic['id']) {
1409
                    $class .= ' group_social_sub_item_highlight';
1410
                }
1411
1412
                $html_items = Display::div($html_items, array('class' => $class, 'id' => 'msg_'.$topic['id']));
1413
                $html_items = Display::div($html_items, array('class' => '', 'style' => 'margin-left:'.$indent.'px'));
1414
                $array_html_items[] = array($html_items);
1415
            }
1416
            // grids for items with paginations
1417
            $options = array('hide_navigation' => false, 'per_page' => $items_per_page);
1418
            $visibility = array(true, true, true, false);
1419
1420
            $style_class = array(
1421
                'item' => array('class' => 'group_social_item'),
1422
                'main' => array('class' => 'group_social_grid'),
1423
            );
1424
            if (!empty($array_html_items)) {
1425
                $html .= Display::return_sortable_grid(
1426
                    'items_'.$topic['id'],
0 ignored issues
show
Bug introduced by
The variable $topic seems to be defined by a foreach iteration on line 1364. 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...
1427
                    array(),
1428
                    $array_html_items,
1429
                    $options,
1430
                    $query_vars,
1431
                    null,
1432
                    $visibility,
1433
                    false,
1434
                    $style_class
1435
                );
1436
            }
1437
        }
1438
        return $html;
1439
    }
1440
1441
    /**
1442
     * Add children to messages by id is used for nested view messages
1443
     * @param array  $rows rows of messages
1444
     * @return array $first_seed new list adding the item children
1445
     */
1446
    public static function calculate_children($rows, $first_seed)
1447
    {
1448
        $rows_with_children = array();
1449
        foreach ($rows as $row) {
1450
            $rows_with_children[$row["id"]] = $row;
1451
            $rows_with_children[$row["parent_id"]]["children"][] = $row["id"];
1452
        }
1453
        $rows = $rows_with_children;
1454
        $sorted_rows = array(0 => array());
1455
        self::message_recursive_sort($rows, $sorted_rows, $first_seed);
1456
        unset($sorted_rows[0]);
1457
1458
        return $sorted_rows;
1459
    }
1460
1461
    /**
1462
     * Sort recursively the messages, is used for for nested view messages
1463
     * @param array  original rows of messages
1464
     * @param array  list recursive of messages
1465
     * @param int   seed for calculate the indent
1466
     * @param int   indent for nested view
1467
     * @return void
1468
     */
1469
    public static function message_recursive_sort($rows, &$messages, $seed = 0, $indent = 0)
1470
    {
1471
        if ($seed > 0 && isset($rows[$seed]["id"])) {
1472
            $messages[$rows[$seed]["id"]] = $rows[$seed];
1473
            $messages[$rows[$seed]["id"]]["indent_cnt"] = $indent;
1474
            $indent++;
1475
        }
1476
1477
        if (isset($rows[$seed]["children"])) {
1478
            foreach ($rows[$seed]["children"] as $child) {
1479
                self::message_recursive_sort($rows, $messages, $child, $indent);
1480
            }
1481
        }
1482
    }
1483
1484
    /**
1485
     * Sort date by desc from a multi-dimensional array
1486
     * @param array $array1  first array to compare
1487
     * @param array $array2  second array to compare
1488
     * @return bool
1489
     */
1490
    public function order_desc_date($array1, $array2)
1491
    {
1492
        return strcmp($array2['send_date'], $array1['send_date']);
1493
    }
1494
1495
    /**
1496
     * Get array of links (download) for message attachment files
1497
     * @param int  		$message_id
1498
     * @param string	$type message list (inbox/outbox)
1499
     * @return array
1500
     */
1501
    public static function get_links_message_attachment_files($message_id, $type = '')
1502
    {
1503
        $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1504
        $message_id = intval($message_id);
1505
1506
        // get file attachments by message id
1507
        $links_attach_file = array();
1508
        if (!empty($message_id)) {
1509
1510
            $sql = "SELECT * FROM $tbl_message_attach
1511
                    WHERE message_id = '$message_id'";
1512
1513
            $rs_file = Database::query($sql);
1514
            if (Database::num_rows($rs_file) > 0) {
1515
                $attach_icon = Display::return_icon('attachment.gif', '');
1516
                $archiveURL = api_get_path(WEB_CODE_PATH).'messages/download.php?type='.$type.'&file=';
1517
                while ($row_file = Database::fetch_array($rs_file)) {
1518
                    $archiveFile = $row_file['path'];
1519
                    $filename = $row_file['filename'];
1520
                    $filesize = format_file_size($row_file['size']);
1521
                    $filecomment = Security::remove_XSS($row_file['comment']);
1522
                    $filename = Security::remove_XSS($filename);
1523
                    $links_attach_file[] = $attach_icon.'&nbsp;<a href="'.$archiveURL.$archiveFile.'">'.$filename.'</a>&nbsp;('.$filesize.')'.(!empty($filecomment) ? '&nbsp;-&nbsp;<i>'.$filecomment.'</i>' : '');
1524
                }
1525
            }
1526
        }
1527
        return $links_attach_file;
1528
    }
1529
1530
    /**
1531
     * Get message list by id
1532
     * @param int  $message_id
1533
     * @return array
1534
     */
1535
    public static function get_message_by_id($message_id)
1536
    {
1537
        $tbl_message = Database::get_main_table(TABLE_MESSAGE);
1538
        $message_id = intval($message_id);
1539
        $sql = "SELECT * FROM $tbl_message
1540
                WHERE id = '$message_id' AND msg_status <> '".MESSAGE_STATUS_DELETED."' ";
1541
        $res = Database::query($sql);
1542
        $item = array();
1543
        if (Database::num_rows($res) > 0) {
1544
            $item = Database::fetch_array($res, 'ASSOC');
1545
        }
1546
        return $item;
1547
    }
1548
1549
    /**
1550
     * @param $id
1551
     * @param array $params
1552
     * @return string
1553
     */
1554
    public static function generate_message_form($id, $params = array())
1555
    {
1556
        $form = new FormValidator('send_message');
1557
        $form->addText('subject', get_lang('Subject'), false, ['id' => 'subject_id']);
1558
        $form->addTextarea('content', get_lang('Message'), ['id' => 'content_id', 'rows' => '5']);
1559
1560
        return $form->returnForm();
1561
    }
1562
1563
    /**
1564
     * @param $id
1565
     * @param array $params
1566
     * @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...
1567
     * @return string
1568
     */
1569
    public static function generate_invitation_form($id, $params = array())
1570
    {
1571
        $form = new FormValidator('send_invitation');
1572
        $form->addTextarea('content', get_lang('AddPersonalMessage'), ['id' => 'content_invitation_id', 'rows' => 5]);
1573
        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...
1574
    }
1575
1576
    //@todo this functions should be in the message class
1577
1578
    public static function inbox_display($keyword = '')
1579
    {
1580
        $success = get_lang('SelectedMessagesDeleted');
1581
        $success_read = get_lang('SelectedMessagesRead');
1582
        $success_unread = get_lang('SelectedMessagesUnRead');
1583
        $html = '';
1584
1585
        Session::write('message_search_keyword', $keyword);
1586
1587
        if (isset($_REQUEST['action'])) {
1588
            switch ($_REQUEST['action']) {
1589
                 case 'mark_as_unread' :
1590
                    $number_of_selected_messages = count($_POST['id']);
1591
                    if (is_array($_POST['id'])) {
1592
                        foreach ($_POST['id'] as $index => $message_id) {
1593
                            MessageManager::update_message_status(api_get_user_id(), $message_id, MESSAGE_STATUS_UNREAD);
1594
                        }
1595
                    }
1596
                    $html .= Display::return_message(api_xml_http_response_encode($success_unread), 'normal', false);
1597
                    break;
1598
                case 'mark_as_read' :
1599
                    $number_of_selected_messages = count($_POST['id']);
1600
                    if (is_array($_POST['id'])) {
1601
                        foreach ($_POST['id'] as $index => $message_id) {
1602
                            MessageManager::update_message_status(api_get_user_id(), $message_id, MESSAGE_STATUS_NEW);
1603
                        }
1604
                    }
1605
                    $html .= Display::return_message(api_xml_http_response_encode($success_read), 'normal', false);
1606
                    break;
1607 View Code Duplication
                case 'delete' :
1608
                    $number_of_selected_messages = count($_POST['id']);
1609
                    foreach ($_POST['id'] as $index => $message_id) {
1610
                        MessageManager::delete_message_by_user_receiver(api_get_user_id(), $message_id);
1611
                    }
1612
                    $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
1613
                    break;
1614 View Code Duplication
                case 'deleteone' :
1615
                    MessageManager::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
1616
                    $html .= Display::return_message(api_xml_http_response_encode($success), 'confirmation', false);
1617
                    break;
1618
            }
1619
        }
1620
1621
        // display sortable table with messages of the current user
1622
        $table = new SortableTable(
1623
            'message_inbox',
1624
            array('MessageManager', 'get_number_of_messages'),
1625
            array('MessageManager', 'get_message_data'),
1626
            3,
1627
            20,
1628
            'DESC'
1629
        );
1630
        $table->set_header(0, '', false, array('style' => 'width:15px;'));
1631
        $table->set_header(1, get_lang('Messages'), false);
1632
        $table->set_header(2, get_lang('Date'), true, array('style' => 'width:180px;'));
1633
        $table->set_header(3, get_lang('Modify'), false, array('style' => 'width:70px;'));
1634
1635
        if (isset($_REQUEST['f']) && $_REQUEST['f'] == 'social') {
1636
            $parameters['f'] = 'social';
1637
            $table->set_additional_parameters($parameters);
1638
        }
1639
        $table->set_form_actions(
1640
            array(
1641
                'delete' => get_lang('DeleteSelectedMessages'),
1642
                'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
1643
                'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
1644
            )
1645
        );
1646
        $html .= $table->return_table();
1647
1648
        Session::erase('message_search_keyword');
1649
1650
        return $html;
1651
    }
1652
1653
    /**
1654
     * @param string $keyword
1655
     * @return null|string
1656
     */
1657
    public static function outbox_display($keyword = '')
1658
    {
1659
        $social_link = false;
1660
        if (isset($_REQUEST['f']) && $_REQUEST['f'] == 'social') {
1661
            $social_link = 'f=social';
1662
        }
1663
1664
        Session::write('message_sent_search_keyword', $keyword);
1665
1666
        $success = get_lang('SelectedMessagesDeleted').'&nbsp</b><br /><a href="outbox.php?'.$social_link.'">'.get_lang('BackToOutbox').'</a>';
1667
1668
        $html = null;
1669
        if (isset($_REQUEST['action'])) {
1670
            switch ($_REQUEST['action']) {
1671 View Code Duplication
                case 'delete' :
1672
                    $number_of_selected_messages = count($_POST['id']);
1673
                    if ($number_of_selected_messages != 0) {
1674
                        foreach ($_POST['id'] as $index => $message_id) {
1675
                            MessageManager::delete_message_by_user_receiver(api_get_user_id(), $message_id);
1676
                        }
1677
                    }
1678
                    $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
1679
                    break;
1680 View Code Duplication
                case 'deleteone' :
1681
                    MessageManager::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
1682
                    $html .=Display::return_message(api_xml_http_response_encode($success), 'normal', false);
1683
                    $html .= '<br/>';
1684
                    break;
1685
            }
1686
        }
1687
1688
        // display sortable table with messages of the current user
1689
        $table = new SortableTable(
1690
            'message_outbox',
1691
            array('MessageManager', 'get_number_of_messages_sent'),
1692
            array('MessageManager', 'get_message_data_sent'),
1693
            3,
1694
            20,
1695
            'DESC'
1696
        );
1697
1698
        $parameters['f'] = isset($_GET['f']) && $_GET['f'] == 'social' ? 'social' : null;
1699
        $table->set_additional_parameters($parameters);
1700
        $table->set_header(0, '', false, array('style' => 'width:15px;'));
1701
1702
        $table->set_header(1, get_lang('Messages'), false);
1703
        $table->set_header(2, get_lang('Date'), true, array('style' => 'width:160px;'));
1704
        $table->set_header(3, get_lang('Modify'), false, array('style' => 'width:70px;'));
1705
1706
        $table->set_form_actions(array('delete' => get_lang('DeleteSelectedMessages')));
1707
        $html .= $table->return_table();
1708
1709
        Session::erase('message_sent_search_keyword');
1710
1711
        return $html;
1712
    }
1713
1714
    /**
1715
     * Get the count of the last received messages for a user
1716
     * @param int $userId The user id
1717
     * @param int $lastId The id of the last received message
1718
     * @return int The count of new messages
1719
     */
1720
    public static function countMessagesFromLastReceivedMessage($userId, $lastId = 0)
1721
    {
1722
        $userId = intval($userId);
1723
        $lastId = intval($lastId);
1724
1725
        if (empty($userId)) {
1726
            return 0;
1727
        }
1728
1729
        $messagesTable = Database::get_main_table(TABLE_MESSAGE);
1730
1731
        $conditions = array(
1732
            'where' => array(
1733
                'user_receiver_id = ?' => $userId,
1734
                'AND msg_status = ?' => MESSAGE_STATUS_UNREAD,
1735
                'AND id > ?' => $lastId
1736
            )
1737
        );
1738
1739
        $result = Database::select('COUNT(1) AS qty', $messagesTable, $conditions);
1740
1741
        if (!empty($result)) {
1742
            $row = current($result);
1743
1744
            return $row['qty'];
1745
        }
1746
1747
        return 0;
1748
    }
1749
1750
    /**
1751
     * Get the data of the last received messages for a user
1752
     * @param int $userId The user id
1753
     * @param int $lastId The id of the last received message
1754
     * @return int The count of new messages
1755
     */
1756
    public static function getMessagesFromLastReceivedMessage($userId, $lastId = 0)
1757
    {
1758
        $userId = intval($userId);
1759
        $lastId = intval($lastId);
1760
1761
        if (empty($userId)) {
1762
            return 0;
1763
        }
1764
1765
        $messagesTable = Database::get_main_table(TABLE_MESSAGE);
1766
        $userTable = Database::get_main_table(TABLE_MAIN_USER);
1767
1768
        $messages = array();
1769
1770
        $sql = "SELECT m.*, u.user_id, u.lastname, u.firstname
1771
                FROM $messagesTable as m
1772
                INNER JOIN $userTable as u
1773
                ON m.user_sender_id = u.user_id
1774
                WHERE
1775
                    m.user_receiver_id = $userId AND
1776
                    m.msg_status = " . MESSAGE_STATUS_UNREAD . "
1777
                    AND m.id > $lastId
1778
                ORDER BY m.send_date DESC";
1779
1780
        $result = Database::query($sql);
1781
1782
        if ($result !== false) {
1783
            while ($row = Database::fetch_assoc($result)) {
1784
                $messages[] = $row;
1785
            }
1786
        }
1787
1788
        return $messages;
1789
    }
1790
1791
    /**
1792
     * Check whether a message has attachments
1793
     * @param int $messageId The message id
1794
     * @return boolean Whether the message has attachments return true. Otherwise return false
1795
     */
1796
    public static function hasAttachments($messageId)
1797
    {
1798
        $messageId = intval($messageId);
1799
1800
        if (empty($messageId)) {
1801
            return false;
1802
        }
1803
1804
        $messageAttachmentTable = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
1805
1806
        $conditions = array(
1807
            'where' => array(
1808
                'message_id = ?' => $messageId
1809
            )
1810
        );
1811
1812
        $result = Database::select('COUNT(1) AS qty', $messageAttachmentTable, $conditions, 'first');
1813
1814
        if (!empty($result)) {
1815
            if ($result['qty'] > 0) {
1816
                return true;
1817
            }
1818
        }
1819
1820
        return false;
1821
    }
1822
1823
    /**
1824
     * @param string $url
1825
     *
1826
     * @return FormValidator
1827
     */
1828
    public static function getSearchForm($url)
1829
    {
1830
        $form = new FormValidator('search', 'post', $url, null, [], FormValidator::LAYOUT_INLINE);
1831
1832
        $form->addElement('text', 'keyword');
1833
        $form->addButtonSearch(get_lang('Search'));
1834
1835
        return $form;
1836
    }
1837
1838
    /**
1839
     * Send a notification to all amdinistrators when a new user is registered
1840
     * @param \Chamilo\UserBundle\Entity\User $user
1841
     */
1842
    public static function sendNotificationByRegisteredUser(\Chamilo\UserBundle\Entity\User $user)
1843
    {
1844
        $tplMailBody = new Template(null, false, false, false, false, false, false);
1845
        $tplMailBody->assign('user', $user);
1846
        $tplMailBody->assign('is_western_name_order', api_is_western_name_order());
1847
        $tplMailBody->assign('manageUrl', api_get_path(WEB_CODE_PATH) . 'admin/user_edit.php?user_id=' . $user->getId());
1848
1849
        $layoutContent = $tplMailBody->get_template('mail/new_user_mail_to_admin.tpl');
1850
1851
        $emailsubject = '[' . get_lang('UserRegistered') . '] ' . $user->getUsername();
1852
        $emailbody = $tplMailBody->fetch($layoutContent);
1853
1854
        $admins = UserManager::get_all_administrators();
1855
1856 View Code Duplication
        foreach ($admins as $admin_info) {
1857
            MessageManager::send_message(
1858
                $admin_info['user_id'],
1859
                $emailsubject,
1860
                $emailbody,
1861
                [],
1862
                [],
1863
                null,
1864
                null,
1865
                null,
1866
                null,
1867
                $user->getId()
1868
            );
1869
        }
1870
    }
1871
}
1872