Issues (2160)

main/messages/new_message.php (4 issues)

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * This script shows a compose area (wysiwyg editor if supported, otherwise
7
 * a simple textarea) where the user can type a message.
8
 * There are three modes
9
 * - standard: type a message, select a user to send it to, press send
10
 * - reply on message (when pressing reply when viewing a message)
11
 * - send to specific user (when pressing send message in the who is online list).
12
 */
13
$cidReset = true;
14
require_once __DIR__.'/../inc/global.inc.php';
15
16
api_block_anonymous_users();
17
18
if (api_get_setting('allow_message_tool') !== 'true') {
19
    api_not_allowed(true);
20
}
21
22
$logInfo = [
23
    'tool' => 'Messages',
24
    'action' => 'new_message',
25
    'action_details' => isset($_GET['re_id']) ? 're_id' : '',
26
];
27
Event::registerLog($logInfo);
28
29
$allowSocial = api_get_setting('allow_social_tool') === 'true';
30
$nameTools = api_xml_http_response_encode(get_lang('Messages'));
31
32
$htmlHeadXtra[] = '<script>
33
var counter_image = 1;
34
function add_image_form() {
35
    // Multiple filepaths for image form
36
    var filepaths = document.getElementById("file_uploads");
37
    if (document.getElementById("filepath_"+counter_image)) {
38
        counter_image = counter_image + 1;
39
    }  else {
40
        counter_image = counter_image;
41
    }
42
    var elem1 = document.createElement("div");
43
    elem1.setAttribute("id","filepath_"+counter_image);
44
    filepaths.appendChild(elem1);
45
    id_elem1 = "filepath_"+counter_image;
46
    id_elem1 = "\'"+id_elem1+"\'";
47
    document.getElementById("filepath_"+counter_image).innerHTML = "<div class=\"form-group\" ><label class=\"col-sm-4\">'.get_lang('FilesAttachment').'</label><input class=\"col-sm-8\" type=\"file\" name=\"attach_"+counter_image+"\" /></div><div class=\"form-group\" ><label class=\"col-sm-4\">'.get_lang('Description').'</label><div class=\"col-sm-8\"><input style=\"width:100%\" type=\"text\" name=\"legend[]\" /></div></div>";
48
    if (filepaths.childNodes.length == 6) {
49
        var link_attach = document.getElementById("link-more-attach");
50
        if (link_attach) {
51
            link_attach.innerHTML="";
52
        }
53
    }
54
}
55
</script>';
56
$nameTools = get_lang('ComposeMessage');
57
$tpl = new Template(get_lang('ComposeMessage'));
58
59
/**
60
 * Shows the compose area + a list of users to select from.
61
 */
62
function show_compose_to_any($tpl)
63
{
64
    $default['user_list'] = 0;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$default was never initialized. Although not strictly required by PHP, it is generally a good practice to add $default = array(); before regardless.
Loading history...
65
66
    return manageForm($default, null, null, $tpl);
67
}
68
69
function show_compose_reply_to_message($message_id, $receiver_id, $tpl)
70
{
71
    $table = Database::get_main_table(TABLE_MESSAGE);
72
    $receiver_id = (int) $receiver_id;
73
    $message_id = (int) $message_id;
74
75
    $query = "SELECT user_sender_id
76
              FROM $table
77
              WHERE user_receiver_id = ".$receiver_id." AND id = ".$message_id;
78
    $result = Database::query($query);
79
    $row = Database::fetch_array($result, 'ASSOC');
80
    $userInfo = api_get_user_info($row['user_sender_id']);
81
    if (empty($row['user_sender_id']) || empty($userInfo)) {
82
        $html = get_lang('InvalidMessageId');
83
84
        return $html;
85
    }
86
87
    $default['users'] = [$row['user_sender_id']];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$default was never initialized. Although not strictly required by PHP, it is generally a good practice to add $default = array(); before regardless.
Loading history...
88
    $html = manageForm($default, null, $userInfo['complete_name_with_username'], $tpl);
89
90
    return $html;
91
}
92
93
function show_compose_to_user($receiver_id, $tpl)
94
{
95
    $userInfo = api_get_user_info($receiver_id);
96
    $html = get_lang('To').':&nbsp;<strong>'.$userInfo['complete_name'].'</strong>';
97
    $default['title'] = api_xml_http_response_encode(get_lang('EnterTitle'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
$default was never initialized. Although not strictly required by PHP, it is generally a good practice to add $default = array(); before regardless.
Loading history...
98
    $default['users'] = [$receiver_id];
99
    $html .= manageForm($default, null, '', $tpl);
100
101
    return $html;
102
}
103
104
/**
105
 * @param          $default
106
 * @param null     $select_from_user_list
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $select_from_user_list is correct as it would always require null to be passed?
Loading history...
107
 * @param string   $sent_to
108
 * @param Template $tpl
109
 *
110
 * @return string
111
 */
112
function manageForm($default, $select_from_user_list = null, $sent_to = '', $tpl = null)
113
{
114
    $group_id = isset($_REQUEST['group_id']) ? (int) $_REQUEST['group_id'] : null;
115
    $message_id = isset($_GET['message_id']) ? (int) $_GET['message_id'] : null;
116
117
    $onlyTeachers = false;
118
    if (api_get_configuration_value('send_only_messages_to_teachers') && api_is_student()) {
119
        $onlyTeachers = true;
120
    }
121
122
    if (isset($_SESSION['form_values'])) {
123
        $default = $_SESSION['form_values'];
124
    }
125
126
    $form = new FormValidator(
127
        'compose_message',
128
        null,
129
        api_get_self(),
130
        null,
131
        ['enctype' => 'multipart/form-data']
132
    );
133
134
    if (empty($group_id)) {
135
        if (isset($select_from_user_list)) {
136
            $form->addText(
137
                'id_text_name',
138
                get_lang('SendMessageTo'),
139
                true,
140
                [
141
                    'id' => 'id_text_name',
142
                    'onkeyup' => 'send_request_and_search()',
143
                    'autocomplete' => 'off',
144
                ]
145
            );
146
            $form->addRule('id_text_name', get_lang('ThisFieldIsRequired'), 'required');
147
            $form->addElement(
148
                'html',
149
                '<div id="id_div_search" style="padding:0px" class="message-select-box" >&nbsp;</div>'
150
            );
151
            $form->addElement('hidden', 'user_list', 0, ['id' => 'user_list']);
152
        } else {
153
            if (!empty($sent_to)) {
154
                $form->addLabel(get_lang('SendMessageTo'), $sent_to);
155
            }
156
            if (empty($default['users'])) {
157
                if ($onlyTeachers) {
158
                    $courses = CourseManager::get_courses_list_by_user_id(api_get_user_id());
159
                    $teachers = [];
160
                    foreach ($courses as $course) {
161
                        $courseTeachers = CourseManager::getTeachersFromCourse($course['real_id']);
162
                        if ($courseTeachers) {
163
                            foreach ($courseTeachers as $teacher) {
164
                                $teachers[$teacher['id']] = $teacher['fullname'];
165
                            }
166
                        }
167
                    }
168
                    if (!empty($teachers)) {
169
                        asort($teachers);
170
                    }
171
                    $form->addSelect(
172
                        'users',
173
                        get_lang('SendMessageTo'),
174
                        $teachers,
175
                        [
176
                            'multiple' => 'multiple',
177
                        ]
178
                    );
179
                } else {
180
                    $form->addElement(
181
                        'select_ajax',
182
                        'users',
183
                        get_lang('SendMessageTo'),
184
                        [],
185
                        [
186
                            'multiple' => 'multiple',
187
                            'url' => api_get_path(WEB_AJAX_PATH).'message.ajax.php?a=find_users',
188
                        ]
189
                    );
190
                    $form->addRule('users', get_lang('ThisFieldIsRequired'), 'required');
191
                }
192
            } else {
193
                $form->addElement('hidden', 'hidden_user', $default['users'][0], ['id' => 'hidden_user']);
194
            }
195
        }
196
    } else {
197
        $userGroup = new UserGroup();
198
        $group_info = $userGroup->get($group_id);
199
200
        $form->addElement('label', get_lang('ToGroup'), api_xml_http_response_encode($group_info['name']));
201
        $form->addElement('hidden', 'group_id', $group_id);
202
        $form->addElement('hidden', 'parent_id', $message_id);
203
    }
204
205
    $form->addText('title', get_lang('Subject'), true);
206
    $form->addHtmlEditor(
207
        'content',
208
        get_lang('Message'),
209
        false,
210
        true,
211
        ['ToolbarSet' => 'Messages']
212
    );
213
214
    if (isset($_GET['re_id'])) {
215
        $message_reply_info = MessageManager::get_message_by_id($_GET['re_id']);
216
        $default['title'] = get_lang('MailSubjectReplyShort').' '.Security::remove_XSS($message_reply_info['title']);
217
        $form->addHidden('re_id', (int) $_GET['re_id']);
218
        $form->addHidden('save_form', 'save_form');
219
220
        // Adding reply mail
221
        $user_reply_info = api_get_user_info($message_reply_info['user_sender_id']);
222
        $default['content'] = '<p><br/></p>'.sprintf(
223
            get_lang('XWroteY'),
224
            $user_reply_info['complete_name'],
225
            Security::filter_terms($message_reply_info['content'])
226
        );
227
    }
228
229
    if (isset($_GET['forward_id']) && MessageManager::isUserOwner(api_get_user_id(), (int) $_GET['forward_id'])) {
230
        $forwardId = (int) $_GET['forward_id'];
231
        $message_reply_info = MessageManager::get_message_by_id($forwardId);
232
        $attachments = MessageManager::getAttachmentLinkList($forwardId, MessageManager::MESSAGE_TYPE_INBOX);
233
        if (!empty($attachments)) {
234
            $fileListToString = !empty($attachments) ? implode('<br />', $attachments) : '';
235
            $form->addLabel('', $fileListToString);
236
        }
237
        $default['title'] = '['.get_lang('MailSubjectForwardShort').": ".Security::remove_XSS($message_reply_info['title']).']';
238
        $form->addHidden('forward_id', $forwardId);
239
        $form->addHidden('save_form', 'save_form');
240
        $receiverInfo = api_get_user_info($message_reply_info['user_receiver_id']);
241
242
        $forwardMessage = '---------- '.get_lang('ForwardedMessage').' ---------'.'<br />';
243
        $forwardMessage .= get_lang('Date').': '.api_get_local_time($message_reply_info['send_date']).'<br />';
244
        $forwardMessage .= get_lang('Subject').': '.Security::remove_XSS($message_reply_info['title']).'<br />';
245
        $forwardMessage .= get_lang('To').': '.$receiverInfo['complete_name'].' - '.$receiverInfo['email'].' <br />';
246
        $default['content'] = '<p><br/></p>'.$forwardMessage.'<br />'.Security::filter_terms($message_reply_info['content']);
247
    }
248
249
    $extrafield = new ExtraField('message');
250
    $extraHtml = $extrafield->addElements($form);
251
252
    if (empty($group_id)) {
253
        $form->addLabel(
254
            '',
255
            '<div id="file_uploads"><div id="filepath_1">
256
                <div id="filepaths" class="form-horizontal">
257
                    <div id="paths-file" class="form-group">
258
                    <label class="col-sm-4">'.get_lang('FilesAttachment').'</label>
259
                    <input class="col-sm-8" type="file" name="attach_1"/>
260
                    </div>
261
                </div>
262
                <div id="paths-description" class="form-group">
263
                    <label class="col-sm-4">'.get_lang('Description').'</label>
264
                    <div class="col-sm-8">
265
                    <input id="file-descrtiption" class="form-control" type="text" name="legend[]" />
266
                    </div>
267
                </div>
268
            </div>
269
            </div>'
270
        );
271
272
        $form->addLabel(
273
            '',
274
            '<span id="link-more-attach">
275
              <a class="btn btn-default" href="javascript://" onclick="return add_image_form()">'.
276
            get_lang('AddOneMoreFile').'</a></span>&nbsp;('.
277
            sprintf(
278
                get_lang('MaximunFileSizeX'),
279
                getIniMaxFileSizeInBytes(true, true)
280
            ).')'
281
        );
282
    }
283
284
    $form->addLabel(
285
        '',
286
        '<iframe
287
            frameborder="0" height="200" width="100%" scrolling="no"
288
            src="'.api_get_path(WEB_CODE_PATH).'messages/record_audio.php"></iframe>'
289
    );
290
291
    $form->addButtonSend(get_lang('SendMessage'), 'compose');
292
    $form->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>');
293
294
    if (!empty($group_id) && !empty($message_id)) {
295
        $message_info = MessageManager::get_message_by_id($message_id);
296
        $default['title'] = get_lang('MailSubjectReplyShort')." ".$message_info['title'];
297
    }
298
    $form->setDefaults($default);
299
    $html = '';
300
    if ($form->validate()) {
301
        $check = Security::check_token('post');
302
        $disabled = api_get_configuration_value('disable_token_in_new_message');
303
        if ($disabled) {
304
            $check = true;
305
        }
306
307
        if ($check) {
308
            if (isset($_SESSION['form_values'])) {
309
                unset($_SESSION['form_values']);
310
            }
311
312
            $user_list = $default['users'];
313
            $file_comments = $_POST['legend'];
314
            $title = $default['title'];
315
            $content = $default['content'];
316
            $group_id = isset($default['group_id']) ? $default['group_id'] : null;
317
            $parent_id = isset($default['parent_id']) ? $default['parent_id'] : null;
318
            $forwardId = isset($_POST['forward_id']) ? $_POST['forward_id'] : false;
319
320
            if (is_array($user_list) && count($user_list) > 0) {
321
                $extraParams = [];
322
323
                foreach ($form->exportValues() as $key => $value) {
324
                    if (!str_contains($key, 'extra_')) {
325
                        continue;
326
                    }
327
328
                    $extraParams[$key] = $value;
329
                }
330
331
                // All is well, send the message
332
                foreach ($user_list as $userId) {
333
                    $res = MessageManager::send_message(
334
                        $userId,
335
                        $title,
336
                        $content,
337
                        $_FILES,
338
                        $file_comments,
339
                        $group_id,
340
                        $parent_id,
341
                        0,
342
                        0,
343
                        null,
344
                        false,
345
                        $forwardId,
346
                        [],
347
                        true,
348
                        false,
349
                        0,
350
                        $extraParams
351
                    );
352
353
                    if ($res) {
354
                        $userInfo = api_get_user_info($userId);
355
                        Display::addFlash(Display::return_message(
356
                            get_lang('MessageSentTo')."&nbsp;<b>".$userInfo['complete_name_with_username']."</b>",
357
                            'confirmation',
358
                            false
359
                        ));
360
                    } else {
361
                        $_SESSION['form_values'] = $default;
362
                        header('Location: '.api_request_uri());
363
                        exit;
364
                    }
365
                }
366
                MessageManager::cleanAudioMessage();
367
            } else {
368
                Display::addFlash(Display::return_message('ErrorSendingMessage', 'error'));
369
            }
370
        }
371
        Security::clear_token();
372
        header('Location: '.api_get_path(WEB_CODE_PATH).'messages/inbox.php');
373
        exit;
374
    } else {
375
        $token = Security::get_token();
376
        $form->addElement('hidden', 'sec_token');
377
        $form->setConstants(['sec_token' => $token]);
378
        $html .= $form->returnForm();
379
    }
380
381
    $html .= '<script>$(function () { '.$extraHtml['jquery_ready_content'].' });</script>';
382
383
    return $html;
384
}
385
386
if ($allowSocial) {
387
    $this_section = SECTION_SOCIAL;
388
    $interbreadcrumb[] = [
389
        'url' => api_get_path(WEB_CODE_PATH).'social/home.php',
390
        'name' => get_lang('SocialNetwork'),
391
    ];
392
} else {
393
    $this_section = SECTION_MYPROFILE;
394
    $interbreadcrumb[] = [
395
        'url' => api_get_path(WEB_CODE_PATH).'auth/profile.php',
396
        'name' => get_lang('Profile'),
397
    ];
398
}
399
400
$interbreadcrumb[] = [
401
    'url' => api_get_path(WEB_CODE_PATH).'messages/inbox.php',
402
    'name' => get_lang('Messages'),
403
];
404
405
$group_id = isset($_REQUEST['group_id']) ? (int) $_REQUEST['group_id'] : 0;
406
$social_right_content = null;
407
if ($group_id != 0) {
408
    $social_right_content .= '<div class=actions>';
409
    $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'social/group_view.php?id='.$group_id.'">'.
410
        Display::return_icon('back.png', api_xml_http_response_encode(get_lang('ComposeMessage'))).'</a>';
411
    $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/new_message.php?group_id='.$group_id.'">'.
412
        Display::return_icon('message_new.png', api_xml_http_response_encode(get_lang('ComposeMessage'))).'</a>';
413
    $social_right_content .= '</div>';
414
} else {
415
    if ($allowSocial) {
416
    } else {
417
        $social_right_content .= '<div class=actions>';
418
        if (api_get_setting('allow_message_tool') === 'true') {
419
            $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/new_message.php">'.
420
                Display::return_icon('message_new.png', get_lang('ComposeMessage')).'</a>';
421
            $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.
422
                Display::return_icon('inbox.png', get_lang('Inbox')).'</a>';
423
            $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/outbox.php">'.
424
                Display::return_icon('outbox.png', get_lang('Outbox')).'</a>';
425
        }
426
        $social_right_content .= '</div>';
427
    }
428
}
429
430
// LEFT COLUMN
431
$social_left_content = '';
432
if ($allowSocial) {
433
    // Block Social Menu
434
    $social_menu_block = SocialManager::show_social_menu('messages');
435
    $social_right_content .= '<div class="row">';
436
    $social_right_content .= '<div class="col-md-12">';
437
    $social_right_content .= '<div class="actions">';
438
    $social_right_content .= '<a href="'.api_get_path(WEB_CODE_PATH).'messages/inbox.php">'.
439
        Display::return_icon('back.png', get_lang('Back'), [], 32).'</a>';
440
    $social_right_content .= '</div>';
441
    $social_right_content .= '</div>';
442
    $social_right_content .= '<div class="col-md-12">';
443
}
444
445
// MAIN CONTENT
446
if (!isset($_POST['compose'])) {
447
    if (isset($_GET['re_id'])) {
448
        $social_right_content .= show_compose_reply_to_message(
449
            $_GET['re_id'],
450
            api_get_user_id(),
451
            $tpl
452
        );
453
    } elseif (isset($_GET['send_to_user'])) {
454
        $social_right_content .= show_compose_to_user($_GET['send_to_user'], $tpl);
455
    } else {
456
        $social_right_content .= show_compose_to_any($tpl);
457
    }
458
} else {
459
    $restrict = false;
460
    if (isset($_POST['users'])) {
461
        $restrict = true;
462
    } elseif (isset($_POST['group_id'])) {
463
        $restrict = true;
464
    } elseif (isset($_POST['hidden_user'])) {
465
        $restrict = true;
466
    }
467
468
    $default['title'] = $_POST['title'];
469
    $default['content'] = $_POST['content'];
470
471
    // comes from a reply button
472
    if (isset($_GET['re_id']) || isset($_GET['forward_id'])) {
473
        $social_right_content .= manageForm($default, null, null, $tpl);
474
    } else {
475
        // post
476
        if ($restrict) {
477
            if (!isset($_POST['group_id'])) {
478
                $default['users'] = isset($_POST['users']) ? $_POST['users'] : null;
479
            } else {
480
                $default['group_id'] = (int) $_POST['group_id'];
481
            }
482
            if (isset($_POST['hidden_user'])) {
483
                $default['users'] = [$_POST['hidden_user']];
484
            }
485
        } /*else {
486
            $social_right_content .= Display::return_message(get_lang('ErrorSendingMessage'), 'error');
487
        }*/
488
        $social_right_content .= manageForm($default, null, null, $tpl);
489
    }
490
}
491
492
if ($allowSocial) {
493
    $social_right_content .= '</div>';
494
    $social_right_content .= '</div>';
495
}
496
497
// Block Social Avatar
498
SocialManager::setSocialUserBlock($tpl, api_get_user_id(), 'messages');
499
500
MessageManager::cleanAudioMessage();
501
if ($allowSocial) {
502
    $tpl->assign('social_menu_block', $social_menu_block);
503
    $tpl->assign('social_right_content', $social_right_content);
504
    $social_layout = $tpl->get_template('social/inbox.tpl');
505
    $tpl->display($social_layout);
506
} else {
507
    $content = $social_right_content;
508
    $tpl->assign('content', $content);
509
    $tpl->display_one_col_template();
510
}
511