Completed
Push — 1.10.x ( ba0bf0...97c0d2 )
by Angel Fernando Quiroz
44:06
created

new_message.php ➔ manage_form()   F

Complexity

Conditions 21
Paths 7680

Size

Total Lines 138
Code Lines 96

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 21
eloc 96
nc 7680
nop 3
dl 0
loc 138
rs 2

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
*	@package chamilo.messages
5
*/
6
7
/**
8
* This script shows a compose area (wysiwyg editor if supported, otherwise
9
* a simple textarea) where the user can type a message.
10
* There are three modes
11
* - standard: type a message, select a user to send it to, press send
12
* - reply on message (when pressing reply when viewing a message)
13
* - send to specific user (when pressing send message in the who is online list)
14
*/
15
$cidReset	= true;
16
require_once '../inc/global.inc.php';
17
18
api_block_anonymous_users();
19
20
if (api_get_setting('allow_message_tool') !='true') {
21
    api_not_allowed();
22
}
23
24
$nameTools = api_xml_http_response_encode(get_lang('Messages'));
25
/*	Constants and variables */
26
27
$htmlHeadXtra[]='
28
<script language="javascript">
29
function validate(form, list) {
30
	if(list.selectedIndex<0) {
31
    	alert("Please select someone to send the message to.")
32
    	return false
33
	} else {
34
    	return true
35
    }
36
}
37
38
</script>';
39
40
$htmlHeadXtra[] = '<script>
41
var counter_image = 1;
42
/*
43
function remove_image_form(id_elem1) {
44
	var elem1 = document.getElementById(id_elem1);
45
	elem1.parentNode.removeChild(elem1);
46
}
47
*/
48
function add_image_form() {
49
	// Multiple filepaths for image form
50
	var filepaths = document.getElementById("filepaths");
51
	if (document.getElementById("filepath_"+counter_image)) {
52
		counter_image = counter_image + 1;
53
	}  else {
54
		counter_image = counter_image;
55
	}
56
	var elem1 = document.createElement("div");
57
	elem1.setAttribute("id","filepath_"+counter_image);
58
	filepaths.appendChild(elem1);
59
	id_elem1 = "filepath_"+counter_image;
60
	id_elem1 = "\'"+id_elem1+"\'";
61
	document.getElementById("filepath_"+counter_image).innerHTML = "<input type=\"file\" name=\"attach_"+counter_image+"\" />&nbsp; <br />'.get_lang('Description').'&nbsp;&nbsp;<input type=\"text\" name=\"legend[]\"  /><br /><br />";
62
	if (filepaths.childNodes.length == 6) {
63
		var link_attach = document.getElementById("link-more-attach");
64
		if (link_attach) {
65
			link_attach.innerHTML="";
66
		}
67
	}
68
}
69
</script>';
70
$nameTools = get_lang('ComposeMessage');
71
/*		FUNCTIONS  */
72
73
/**
74
* Shows the compose area + a list of users to select from.
75
*/
76
function show_compose_to_any($user_id) {
77
	$online_user_list = MessageManager::get_online_user_list($user_id);
78
	$default['user_list'] = 0;
79
	$online_user_list=null;
80
	$html = manage_form($default, $online_user_list);
81
    return $html;
82
}
83
84
function show_compose_reply_to_message($message_id, $receiver_id)
85
{
86
	$table_message = Database::get_main_table(TABLE_MESSAGE);
87
	$query = "SELECT user_sender_id FROM $table_message
88
			  WHERE user_receiver_id=".intval($receiver_id)." AND id='".intval($message_id)."';";
89
	$result = Database::query($query);
90
	$row = Database::fetch_array($result,'ASSOC');
91
	if (!isset($row['user_sender_id'])) {
92
		$html = get_lang('InvalidMessageId');
93
94
		return $html;
95
	}
96
	$userInfo = api_get_user_info($row['user_sender_id']);
97
	$default['users'] = array($row['user_sender_id']);
98
	$html = manage_form($default, null, $userInfo['complete_name']);
99
100
    return $html;
101
}
102
103
function show_compose_to_user ($receiver_id) {
104
	$html = get_lang('To').':&nbsp;<strong>'.GetFullUserName($receiver_id).'</strong>';
105
	$default['title'] = api_xml_http_response_encode(get_lang('EnterTitle'));
106
	$default['users'] = array($receiver_id);
107
	$html .= manage_form($default);
108
    return $html;
109
}
110
111
function manage_form($default, $select_from_user_list = null, $sent_to = null)
112
{
113
    $group_id = isset($_REQUEST['group_id']) ? intval($_REQUEST['group_id']) : null;
114
    $message_id = isset($_GET['message_id'])  ?  intval($_GET['message_id']) : null;
115
    $param_f = isset($_GET['f']) && $_GET['f'] == 'social' ? 'social' : null;
116
117
    $form = new FormValidator('compose_message', null, api_get_self().'?f='.$param_f, null, array('enctype'=>'multipart/form-data'));
118
    if (empty($group_id)) {
119
        if (isset($select_from_user_list)) {
120
            $form->addText(
121
                'id_text_name',
122
                get_lang('SendMessageTo'),
123
                true,
124
                array(
125
                    'id'=>'id_text_name',
126
                    'onkeyup'=>'send_request_and_search()',
127
                    'autocomplete'=>'off'
128
                )
129
            );
130
            $form->addRule('id_text_name', get_lang('ThisFieldIsRequired'), 'required');
131
            $form->addElement('html','<div id="id_div_search" style="padding:0px" class="message-select-box" >&nbsp;</div>');
132
            $form->addElement('hidden','user_list', 0, array('id'=>'user_list'));
133
        } else {
134
            if (!empty($sent_to)) {
135
                $form->addLabel(get_lang('SendMessageTo'), $sent_to);
136
            }
137
            if (empty($default['users'])) {
138
                //fb select
139
                $form->addElement(
140
                    'select_ajax',
141
                    'users',
142
                    get_lang('SendMessageTo'),
143
                    array(),
144
                    [
145
                        'multiple' => 'multiple',
146
                        'url' => api_get_path(WEB_AJAX_PATH) . 'message.ajax.php?a=find_users'
147
                    ]
148
                );
149
            } else {
150
                $form->addElement('hidden','hidden_user',$default['users'][0],array('id'=>'hidden_user'));
151
            }
152
        }
153
    } else {
154
        $userGroup = new UserGroup();
155
        $group_info = $userGroup->get($group_id);
156
157
        $form->addElement('label', get_lang('ToGroup'), api_xml_http_response_encode($group_info['name']));
158
        $form->addElement('hidden','group_id',$group_id);
159
        $form->addElement('hidden','parent_id',$message_id);
160
    }
161
162
    $form->addText('title', get_lang('Subject'), true);
163
    $form->addHtmlEditor(
164
        'content',
165
        get_lang('Message'),
166
        false,
167
        false,
168
        array('ToolbarSet' => 'Messages', 'Width' => '100%', 'Height' => '250')
169
    );
170
171
    if (isset($_GET['re_id'])) {
172
        $message_reply_info = MessageManager::get_message_by_id($_GET['re_id']);
173
        $default['title'] = get_lang('MailSubjectReplyShort')." ".$message_reply_info['title'];
174
        $form->addElement('hidden','re_id', intval($_GET['re_id']));
175
        $form->addElement('hidden','save_form','save_form');
176
177
        //adding reply mail
178
        $user_reply_info = api_get_user_info($message_reply_info['user_sender_id']);
179
        $default['content'] = '<p><br/></p>'.sprintf(
180
            get_lang('XWroteY'),
181
            $user_reply_info['complete_name'],
182
            Security::filter_terms($message_reply_info['content'])
183
        );
184
    }
185
186
    if (empty($group_id)) {
187
188
        $form->addElement('label', '', '<div  id="filepaths" class="form-group">
189
                    <div id="filepath_1">
190
                    <label>'.get_lang('FilesAttachment').'</label>
191
                    <input type="file" name="attach_1"/>
192
                    <label>'.get_lang('Description').'</label>
193
                    <input id="file-descrtiption" type="text" name="legend[]" class="form-control"/>
194
                    </div>
195
                </div>'
196
        );
197
198
        $form->addElement('label', '', '<span id="link-more-attach"><a href="javascript://" onclick="return add_image_form()">'.get_lang('AddOneMoreFile').'</a></span>&nbsp;('.sprintf(get_lang('MaximunFileSizeX'),format_file_size(api_get_setting('message_max_upload_filesize'))).')');
199
    }
200
201
    $form->addButtonSend(get_lang('SendMessage'), 'compose');
202
    $form->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>');
203
204
    if (!empty($group_id) && !empty($message_id)) {
205
        $message_info = MessageManager::get_message_by_id($message_id);
206
        $default['title'] = get_lang('MailSubjectReplyShort')." ".$message_info['title'];
207
    }
208
    $form->setDefaults($default);
209
    $html = '';
210
    if ($form->validate()) {
211
        $check = Security::check_token('post');
212
        if ($check) {
213
            $user_list = $default['users'];
214
            $file_comments = $_POST['legend'];
215
            $title = $default['title'];
216
            $content = $default['content'];
217
            $group_id = isset($default['group_id']) ? $default['group_id'] : null;
218
            $parent_id = isset($default['parent_id']) ? $default['parent_id'] : null;
219
            if (is_array($user_list) && count($user_list)> 0) {
220
                //all is well, send the message
221
                foreach ($user_list as $user) {
222
                    $res = MessageManager::send_message(
223
                        $user,
224
                        $title,
225
                        $content,
226
                        $_FILES,
227
                        $file_comments,
228
                        $group_id,
229
                        $parent_id
230
                    );
231
                    if ($res) {
232
                        $html .= MessageManager::display_success_message($user);
0 ignored issues
show
Deprecated Code introduced by
The method MessageManager::display_success_message() has been deprecated.

This method has been deprecated.

Loading history...
233
                    }
234
                }
235
            } else {
236
                Display::display_error_message('ErrorSendingMessage');
237
            }
238
        }
239
        Security::clear_token();
240
    } else {
241
        $token = Security::get_token();
242
        $form->addElement('hidden','sec_token');
243
        $form->setConstants(array('sec_token' => $token));
244
        $html .= $form->returnForm();
245
    }
246
247
    return $html;
248
}
249
250
$socialToolIsActive = isset($_GET['f']) && $_GET['f'] == 'social';
251
252
/* MAIN SECTION */
253
if ($socialToolIsActive) {
254
	$this_section = SECTION_SOCIAL;
255
    $interbreadcrumb[] = array(
256
        'url' => api_get_path(WEB_PATH).'main/social/home.php',
257
        'name' => get_lang('SocialNetwork'),
258
    );
259
} else {
260
	$this_section = SECTION_MYPROFILE;
261
    $interbreadcrumb[] = array(
262
        'url' => api_get_path(WEB_PATH).'main/auth/profile.php',
263
        'name' => get_lang('Profile'),
264
    );
265
}
266
267
$group_id = isset($_REQUEST['group_id']) ? intval($_REQUEST['group_id']) : null;
268
$social_right_content = null;
269
if ($group_id != 0) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $group_id of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
270
	$social_right_content .= '<div class=actions>';
271
	$social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/social/group_view.php?id='.$group_id.'">'.
272
		Display::return_icon('back.png',api_xml_http_response_encode(get_lang('ComposeMessage'))).'</a>';
273
	$social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php?group_id='.$group_id.'">'.
274
		Display::return_icon('message_new.png',api_xml_http_response_encode(get_lang('ComposeMessage'))).'</a>';
275
	$social_right_content .= '</div>';
276 View Code Duplication
} else {
277
	if ($socialToolIsActive) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
278
	} else {
279
		$social_right_content .= '<div class=actions>';
280
		if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
281
			$social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.
282
                Display::return_icon('shared_profile.png', get_lang('ViewSharedProfile')).'</a>';
283
		}
284
		if (api_get_setting('allow_message_tool') == 'true') {
285
			$social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/new_message.php">'.
286
                Display::return_icon('message_new.png',get_lang('ComposeMessage')).'</a>';
287
			$social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.
288
                Display::return_icon('inbox.png',get_lang('Inbox')).'</a>';
289
            $social_right_content .= '<a href="'.api_get_path(WEB_PATH).'main/messages/outbox.php">'.
290
                Display::return_icon('outbox.png',get_lang('Outbox')).'</a>';
291
		}
292
		$social_right_content .= '</div>';
293
	}
294
}
295
296
// LEFT COLUMN
297
$social_left_content = null;
298
if (api_get_setting('allow_social_tool') == 'true') {
299
    //Block Social Menu
300
    $social_menu_block = SocialManager::show_social_menu('messages');
301
    $social_right_content .= '<div class="row">';
302
    $social_right_content .= '<div class="col-md-12">';
303
    $social_right_content .= '<div class="actions">';
304
    $social_right_content .=  '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php?f=social">'.
305
        Display::return_icon('back.png', get_lang('Back'), array(), 32).'</a>';
306
    $social_right_content .=  '</div>';
307
    $social_right_content .=  '</div>';
308
    $social_right_content .= '<div class="col-md-12">';
309
}
310
311
// MAIN CONTENT
312
if (!isset($_POST['compose'])) {
313
    if(isset($_GET['re_id'])) {
314
        $social_right_content .= show_compose_reply_to_message(
315
            $_GET['re_id'],
316
            api_get_user_id()
317
        );
318
    } elseif(isset($_GET['send_to_user'])) {
319
        $social_right_content .= show_compose_to_user($_GET['send_to_user']);
320
    } else {
321
        $social_right_content .= show_compose_to_any(api_get_user_id());
322
    }
323
} else {
324
    $restrict = false;
325
    if (isset($_POST['users'])) {
326
        $restrict = true;
327
    } elseif (isset($_POST['group_id'])) {
328
        $restrict = true;
329
    } elseif(isset($_POST['hidden_user'])) {
330
        $restrict = true;
331
    }
332
333
    $default['title'] = $_POST['title'];
334
    $default['content'] = $_POST['content'];
335
336
    // comes from a reply button
337
    if (isset($_GET['re_id'])) {
338
        $social_right_content .= manage_form($default);
339
    } else {
340
        // post
341
        if ($restrict) {
342
            if (!isset($_POST['group_id'])) {
343
                $default['users'] = isset($_POST['users']) ? $_POST['users'] : null;
344
            } else {
345
                $default['group_id'] = $_POST['group_id'];
346
            }
347
            if (isset($_POST['hidden_user'])) {
348
                $default['users']	 = array($_POST['hidden_user']);
349
            }
350
            $social_right_content .= manage_form($default);
351
        } else {
352
            $social_right_content .= Display::return_message(get_lang('ErrorSendingMessage'),'error');
353
        }
354
    }
355
}
356
if (api_get_setting('allow_social_tool') == 'true') {
357
    $social_right_content .=  '</div>';
358
    $social_right_content .=  '</div>';
359
}
360
361
$tpl = new Template(get_lang('ComposeMessage'));
362
// Block Social Avatar
363
SocialManager::setSocialUserBlock($tpl, $user_id, 'messages');
364
365 View Code Duplication
if (api_get_setting('allow_social_tool') == 'true') {
366
    $tpl->assign('social_menu_block', $social_menu_block);
367
    $tpl->assign('social_right_content', $social_right_content);
368
    $social_layout = $tpl->get_template('social/inbox.tpl');
369
    $tpl->display($social_layout);
370
} else {
371
    $content = $social_right_content;
372
    //$tpl->assign('actions', $actions);
373
    //$tpl->assign('message', $show_message);
374
    $tpl->assign('content', $content);
375
    $tpl->display_one_col_template();
376
}
377