check_header_form()   C
last analyzed

Complexity

Conditions 14
Paths 39

Size

Total Lines 54
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 26
nc 39
nop 0
dl 0
loc 54
rs 6.2666
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
/**
3
 * EGroupware Setup - Manage the EGw config file header.inc.php
4
 *
5
 * @link http://www.egroupware.org
6
 * @package setup
7
 * @author Ralf Becker <RalfBecker-AT-outdoor-training.de>
8
 * @author Miles Lott <[email protected]>
9
 * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
10
 * @version $Id$
11
 */
12
13
use EGroupware\Api;
14
use EGroupware\Api\Framework;
15
16
include('./inc/functions.inc.php');
17
18
require_once('./inc/class.setup_header.inc.php');
19
$GLOBALS['egw_setup']->header = new setup_header();
20
21
$setup_tpl = new Framework\Template('./templates/default', 'keep');	// 'keep' to keep our {hash} prefix of passwords
22
$setup_tpl->set_file(array(
23
	'T_head' => 'head.tpl',
24
	'T_footer' => 'footer.tpl',
25
	'T_alert_msg' => 'msg_alert_msg.tpl',
26
	'T_login_main' => 'login_main.tpl',
27
	'T_login_stage_header' => 'login_stage_header.tpl',
28
	'T_setup_manage' => 'manageheader.tpl'
29
));
30
$setup_tpl->set_block('T_login_stage_header','B_multi_domain','V_multi_domain');
31
$setup_tpl->set_block('T_login_stage_header','B_single_domain','V_single_domain');
32
$setup_tpl->set_block('T_setup_manage','manageheader','manageheader');
33
$setup_tpl->set_block('T_setup_manage','domain','domain');
34
35
$setup_tpl->set_var(array(
36
	'lang_select' => '',
37
	'comment_l' => '',
38
	'comment_r' => '',
39
	'detected' => '',
40
));
41
42
// authentication phase
43
$GLOBALS['egw_info']['setup']['stage']['header'] = $GLOBALS['egw_setup']->detection->check_header();
44
45
if ($GLOBALS['egw_info']['setup']['stage']['header'] > 2 && !$GLOBALS['egw_setup']->auth('Header'))
46
{
47
	$GLOBALS['egw_setup']->html->show_header('Please login',True);
48
	$GLOBALS['egw_setup']->html->login_form();
49
	$GLOBALS['egw_setup']->html->show_footer();
50
	exit;
51
}
52
// Detect current mode
53
switch($GLOBALS['egw_info']['setup']['stage']['header'])
54
{
55
	case '1':
56
		$GLOBALS['egw_info']['setup']['HeaderFormMSG'] = lang('Create your header.inc.php');
57
		$GLOBALS['egw_info']['setup']['PageMSG'] = lang('You have not created your header.inc.php yet!<br /> You can create it now.');
58
		break;
59
	case '2':
60
		$GLOBALS['egw_info']['setup']['HeaderFormMSG'] = $GLOBALS['egw_info']['setup']['PageMSG'] =
61
			lang('Your header admin password is NOT set. Please set it now!');
62
		break;
63
	case '3':
64
		$GLOBALS['egw_info']['setup']['HeaderFormMSG'] = $GLOBALS['egw_info']['setup']['PageMSG'] =
65
			$GLOBALS['egw_info']['setup']['HeaderLoginMSG'] =
66
			lang('You need to add at least one EGroupware domain / database instance.');
67
		break;
68
	case '4':
69
		$GLOBALS['egw_info']['setup']['HeaderFormMSG'] = $GLOBALS['egw_info']['setup']['HeaderLoginMSG'] =
70
			lang('Your header.inc.php needs upgrading.');
71
		$GLOBALS['egw_info']['setup']['PageMSG'] = lang('Your header.inc.php needs upgrading.<br /><blink><b class="msg">WARNING!</b></blink><br /><b>MAKE BACKUPS!</b>');
72
		break;
73
	case '10':
74
		$GLOBALS['egw_info']['setup']['HeaderFormMSG'] = lang('Edit your header.inc.php');
75
		$GLOBALS['egw_info']['setup']['PageMSG'] = lang('Edit your existing header.inc.php');
76
		break;
77
}
78
79
if (!file_exists('../header.inc.php') || filesize('../header.inc.php') < 200 || !is_readable('../header.inc.php') || !defined('EGW_SERVER_ROOT') || EGW_SERVER_ROOT == '..')
80
{
81
	$GLOBALS['egw_setup']->header->defaults();
82
}
83
else
84
{
85
	$GLOBALS['egw_info']['server']['server_root'] = EGW_SERVER_ROOT;
86
}
87
if (isset($_POST['setting']))	// Post of the header-form
88
{
89
	$validation_errors = check_header_form();	// validate the submitted form
90
}
91
if (!isset($_POST['action']) || $validation_errors)	// generate form to edit the header
92
{
93
	show_header_form($validation_errors);
94
}
95
else
96
{
97
	$newheader = $GLOBALS['egw_setup']->header->generate($GLOBALS['egw_info'],$GLOBALS['egw_domain']);
98
99
	$action = @key($_POST['action']);
100
	switch($action)
101
	{
102
		case 'download':
103
			Api\Header\Content::type('header.inc.php','application/octet-stream');
104
			echo $newheader;
105
			break;
106
107
		case 'view':
108
			$GLOBALS['egw_setup']->html->show_header('Generated header.inc.php', False, 'header');
109
			echo '<table width="90%"><tr><td>';
110
			echo '<br />' . lang('Save this text as contents of your header.inc.php') . '<br /><hr />';
111
			echo "<pre>\n";
112
			echo htmlentities($newheader);
113
			echo "\n</pre><hr />\n";
114
			echo '<form action="index.php" method="post">';
115
			echo '<br />' . lang('After retrieving the file, put it into place as the header.inc.php.  Then, click "continue".') . '<br />';
116
			echo '<input type="hidden" name="FormLogout" value="header" />';
117
			echo '<input type="submit" name="junk" value="'.lang('Continue').'" />';
118
			echo '</form>';
119
			echo '</td></tr></table>';
120
			$GLOBALS['egw_setup']->html->show_footer();
121
			break;
122
123
		case 'write':
124
			if ((is_writeable('../header.inc.php') || !file_exists('../header.inc.php') && is_writeable('../')) &&
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (is_writeable('../header.../header.inc.php', 'wb'), Probably Intended Meaning: is_writeable('../header....header.inc.php', 'wb'))
Loading history...
125
				($f = fopen('../header.inc.php','wb')))
126
			{
127
				fwrite($f,$newheader);
128
				fclose($f);
129
				// invalidate OpCache so change have an effect, if scripts are cached and not checked for changes (as in our container installation)
130
				if (function_exists('opcache_is_script_cached') && (opcache_is_script_cached($header= realpath('../header.inc.php'))))
131
				{
132
					opcache_invalidate($header, true);
133
				}
134
				$GLOBALS['egw_setup']->html->show_header('Saved header.inc.php', False, 'header');
135
				echo '<form action="index.php" method="post">';
136
					echo '<br />' . lang('Created header.inc.php!');
137
				echo '<input type="hidden" name="FormLogout" value="header" />';
138
				echo '<input type="submit" name="junk" value="'.lang('Continue').'" />';
139
				echo '</form>';
140
				$GLOBALS['egw_setup']->html->show_footer();
141
				break;
142
			}
143
			else
144
			{
145
				$GLOBALS['egw_setup']->html->show_header('Error generating header.inc.php', False, 'header');
146
				echo lang('Could not open header.inc.php for writing!') . '<br />' . "\n";
147
				echo lang('Please check read/write permissions on directories, or back up and use another option.') . '<br />';
148
				$GLOBALS['egw_setup']->html->show_footer();
149
			}
150
			break;
151
	}
152
}
153
154
/**
155
 * Validate the posted form and place the content again in $GLOBALS['egw_info'] and $GLOBALS['egw_domain']
156
 *
157
 * @return array with validation errors, see setup_header::validation_errors
158
 */
159
function check_header_form()
160
{
161
	// setting the non-domain settings from the posted content
162
	foreach($_POST['setting'] as $name => $value)
163
	{
164
		if (get_magic_quotes_gpc()) $value = stripslashes($value);
165
166
		switch($name)
167
		{
168
			case 'show_domain_selectbox':
169
			case 'mcrypt_enabled':
170
			case 'db_persistent':
171
				$GLOBALS['egw_info']['server'][$name] = $value == 'True';
172
				break;
173
			case 'new_admin_password':
174
				if ($value) $GLOBALS['egw_info']['server']['header_admin_password'] = $value;
175
				break;
176
			default:
177
				$GLOBALS['egw_info']['server'][$name] = $value;
178
				break;
179
		}
180
	}
181
182
	// setting the domain settings from the posted content
183
	foreach($_POST['domains'] as $key => $domain)
184
	{
185
		if ($_POST['deletedomain'][$key])
186
		{
187
			// Need to actually remove the domain.  Drop the DB manually.
188
			unset($GLOBALS['egw_domain'][$domain]);
189
			continue;
190
		}
191
192
		foreach($_POST['setting_'.$key] as $name => $value)
193
		{
194
			if (get_magic_quotes_gpc()) $value = stripslashes($value);
195
196
			if ($name == 'new_config_passwd')
197
			{
198
				if ($value) $GLOBALS['egw_domain'][$domain]['config_passwd'] = $value;
199
				continue;
200
			}
201
			$GLOBALS['egw_domain'][$domain][$name] = $value;
202
		}
203
	}
204
205
	// validate the input and return errors
206
	$validation_errors = $GLOBALS['egw_setup']->header->validation_errors($GLOBALS['egw_info']['server']['server_root']);
207
208
	//echo "egw_info[server]=<pre>".print_r($GLOBALS['egw_info']['server'],true)."</pre>\n";
209
	//echo "egw_domain=<pre>".print_r($GLOBALS['egw_domain'],true)."</pre>\n";
210
	//if ($validation_errors) echo "validation_errors=<pre>".print_r($validation_errors,true)."</pre>\n";
211
212
	return $validation_errors;
213
}
214
215
/**
216
 * Display the form to edit the configuration
217
 *
218
 * @param array $validation_errors to display
219
 */
220
function show_header_form($validation_errors)
221
{
222
	global $setup_tpl;
223
224
	$GLOBALS['egw_setup']->html->show_header($GLOBALS['egw_info']['setup']['HeaderFormMSG'], False, 'header');
225
226
	if(empty($_REQUEST['ConfigLang']))
227
	{
228
		$setup_tpl->set_var('lang_select','<tr><td colspan="2"><form action="manageheader.php" method="post">Please Select your language '.setup_html::lang_select(True,'en')."</form></td></tr>");
229
	}
230
231
	$setup_tpl->set_var('pagemsg',$GLOBALS['egw_info']['setup']['PageMSG']);
232
233
	// checking required PHP version
234
	if ((float) PHP_VERSION < $GLOBALS['egw_setup']->required_php_version)
235
	{
236
		$GLOBALS['egw_setup']->html->show_header($GLOBALS['egw_info']['setup']['header_msg'],True);
237
		$GLOBALS['egw_setup']->html->show_alert_msg('Error',
238
			lang('You are using PHP version %1. EGroupware now requires %2 or later, recommended is PHP %3.',
239
			PHP_VERSION,$GLOBALS['egw_setup']->required_php_version,$GLOBALS['egw_setup']->recommended_php_version));
0 ignored issues
show
Unused Code introduced by
The call to lang() has too many arguments starting with PHP_VERSION. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

239
			/** @scrutinizer ignore-call */ 
240
   lang('You are using PHP version %1. EGroupware now requires %2 or later, recommended is PHP %3.',

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
240
		$GLOBALS['egw_setup']->html->show_footer();
241
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
242
	}
243
	$detected = null;
244
	$supported_db = $GLOBALS['egw_setup']->header->check_db_support($detected);
245
246
	if (!count($supported_db))
247
	{
248
		echo '<p align="center" class="msg"><b>'
249
			. lang('Did not find any valid DB support!')
250
			. "<br />\n"
251
			. lang('Try to configure your php to support one of the above mentioned DBMS, or install EGroupware by hand.')
252
			. '</b></p>';
253
		$GLOBALS['egw_setup']->html->show_footer();
254
		exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
255
	}
256
	$js_default_db_ports = 'var default_db_ports = new Array();'."\n";
257
	foreach($GLOBALS['egw_setup']->header->default_db_ports as $db => $port)
258
	{
259
		$js_default_db_ports .= '  default_db_ports["'.$db.'"]="'.$port.'";'."\n";
260
	}
261
	$setup_tpl->set_var('js_default_db_ports',$js_default_db_ports);
262
263
	if ($validation_errors) $setup_tpl->set_var('detected','<ul><li>'.implode("</li>\n<li>",$validation_errors)."</li>\n</ul>\n");
0 ignored issues
show
Bug Best Practice introduced by
The expression $validation_errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
264
265
	if ($_POST['adddomain'])
266
	{
267
		$GLOBALS['egw_domain'][lang('new')] = $GLOBALS['egw_setup']->header->domain_defaults(
268
			$GLOBALS['egw_info']['server']['header_admin_user'],
269
			$GLOBALS['egw_info']['server']['header_admin_password'],$supported_db);
270
	}
271
	// show the non-domain settings
272
	//echo "<pre>".print_r($GLOBALS['egw_info']['server'],true)."</pre>\n";
273
	foreach($GLOBALS['egw_info']['server'] as $name => $value)
274
	{
275
		switch($name)
276
		{
277
			case 'db_persistent':
278
				if ($GLOBALS['egw_info']['server'][$name] && is_array($GLOBALS['egw_domain']))
279
				{
280
					$GLOBALS['egw_info']['server'][$name] = $GLOBALS['egw_setup']->header->check_db_persistent($GLOBALS['egw_domain']);
281
				}
282
				// fall through
283
			case 'show_domain_selectbox':
284
			case 'mcrypt_enabled':
285
				$setup_tpl->set_var($name.($GLOBALS['egw_info']['server'][$name] ? '_yes' : '_no'),' selected="selected"');
286
				break;
287
			default:
288
				if (!is_array($value)) $setup_tpl->set_var($name,htmlspecialchars($value));
289
				break;
290
		}
291
	}
292
	$supported_session_handler = array(
293
		'egw_session_files' => lang('PHP session handler enabled in php.ini'),
294
	);
295
	if ($GLOBALS['egw_info']['server']['session_handler'] && !isset($supported_session_handler[$GLOBALS['egw_info']['server']['session_handler']]))
296
	{
297
		$supported_session_handler[$GLOBALS['egw_info']['server']['session_handler']] = lang("Custom handler: %1",$GLOBALS['egw_info']['server']['session_handler']);
298
	}
299
	$options = array();
300
	foreach($supported_session_handler as $type => $label)
301
	{
302
		$options[] = '<option ' . ($type == $GLOBALS['egw_info']['server']['session_handler'] ?
303
			'selected="selected" ' : '') . 'value="' . $type . '">' . $label . '</option>';
304
	}
305
	$setup_tpl->set_var('session_options',implode("\n",$options));
306
307
	// showing the settings of all domains
308
	foreach($GLOBALS['egw_domain'] as $domain => $data)
309
	{
310
		$setup_tpl->set_var('db_domain',htmlspecialchars($domain));
311
		foreach($data as $name => $value)
312
		{
313
			if ($name == 'db_port' && !$value)	// Set default here if the admin didn't set a port yet
314
			{
315
				$value = $GLOBALS['egw_setup']->header->default_db_ports[$data['db_type']];
316
			}
317
			$setup_tpl->set_var($name,htmlspecialchars($value));
318
		}
319
		$dbtype_options = '';
320
		foreach($supported_db as $db)
321
		{
322
			$dbtype_options .= '<option ' . ($db == $data['db_type'] ? 'selected="selected" ' : '').
323
				'value="' . $db . '">' . $GLOBALS['egw_setup']->header->db_fullnames[$db] . "</option>\n";
324
		}
325
		$setup_tpl->set_var('dbtype_options',$dbtype_options);
326
327
		$setup_tpl->parse('domains','domain',True);
328
	}
329
	if(is_writeable('../header.inc.php') || !file_exists('../header.inc.php') && is_writeable('../'))
330
	{
331
		$setup_tpl->set_var('actions',lang('%1, %2 or %3 the configuration file.',
332
			'<input type="submit" name="action[write]" value="'.htmlspecialchars(lang('Write')).'" />',
333
			'<input type="submit" name="action[download]" value="'.htmlspecialchars(lang('Download')).'" />',
334
			'<input type="submit" name="action[view]" value="'.htmlspecialchars(lang('View')).'" />'));
335
	}
336
	else
337
	{
338
		$setup_tpl->set_var('actions',lang('Cannot create the header.inc.php due to file permission restrictions.<br /> Instead you can %1 or %2 the file.',
339
			'<input type="submit" name="action[download]" value="'.htmlspecialchars(lang('Download')).'" />',
340
			'<input type="submit" name="action[view]" value="'.htmlspecialchars(lang('View')).'" />'));
341
	}
342
	// set domain and password for the continue button
343
	@reset($GLOBALS['egw_domain']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for reset(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

343
	/** @scrutinizer ignore-unhandled */ @reset($GLOBALS['egw_domain']);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
344
	$firstDomain = @key($GLOBALS['egw_domain']);
345
346
	$setup_tpl->set_var(array(
347
		'FormDomain' => $firstDomain,
348
		'FormUser'   => $GLOBALS['egw_domain'][$firstDomain]['config_user'],
349
		'FormPW'     => $GLOBALS['egw_domain'][$firstDomain]['config_passwd']
350
	));
351
352
	$setup_tpl->set_var(array(
353
		'lang_analysis'        => $validation_errors ? lang('Validation errors') : '',
354
		'lang_settings'        => lang('Settings'),
355
		'lang_domain'          => lang('Database instance (EGw domain)'),
356
		'lang_delete'          => lang('Delete'),
357
		'lang_adddomain'       => lang('Add new database instance (EGw domain)'),
358
		'lang_serverroot'      => lang('Server Root'),
359
		'lang_serverroot_descr'=> lang('Path (not URL!) to your EGroupware installation.'),
360
		'lang_adminuser'       => lang('Header username'),
361
		'lang_adminuser_descr' => lang('Admin user for header manager'),
362
		'lang_adminpass'       => lang('Header password'),
363
		'lang_adminpass_descr' => lang('Admin password to header manager').'.',
364
		'lang_leave_empty'     => lang('Leave empty to keep current.'),
365
		'lang_setup_acl'       => lang('Limit access'),
366
		'lang_setup_acl_descr' => lang('Limit access to setup to the following addresses, networks or hostnames (e.g. 127.0.0.1,10.1.1,myhost.dnydns.org)'),
367
		'lang_dbhost'          => lang('DB Host'),
368
		'lang_dbhostdescr'     => lang('Hostname/IP of database server').'<br />'.
369
			lang('Postgres: Leave it empty to use the prefered unix domain sockets instead of a tcp/ip connection').'<br />'.
370
			lang('ODBC / MaxDB: DSN (data source name) to use'),
371
		'lang_dbport'          => lang('DB Port'),
372
		'lang_dbportdescr'     => lang('TCP port number of database server'),
373
		'lang_dbname'          => lang('DB Name'),
374
		'lang_dbnamedescr'     => lang('Name of database'),
375
		'lang_dbuser'          => lang('DB User'),
376
		'lang_dbuserdescr'     => lang('Name of db user EGroupware uses to connect'),
377
		'lang_dbpass'          => lang('DB Password'),
378
		'lang_dbpassdescr'     => lang('Password of db user'),
379
		'lang_dbtype'          => lang('DB Type'),
380
		'lang_whichdb'         => lang('Which database type do you want to use with EGroupware?'),
381
		'lang_configuser'      => lang('Configuration User'),
382
		'lang_configuser_descr'=> lang('Loginname needed for domain configuration'),
383
		'lang_configpass'      => lang('Configuration Password'),
384
		'lang_passforconfig'   => lang('Password needed for domain configuration.'),
385
		'lang_persist'         => lang('Persistent connections'),
386
		'lang_persistdescr'    => lang('Do you want persistent connections (higher performance, but consumes more resources)'),
387
		'lang_session'         => lang('Sessions Handler'),
388
		'lang_session_descr'   => lang('Session handler class used.'),
389
		'lang_enablemcrypt'    => lang('Enable MCrypt'),
390
		'lang_mcrypt_warning'  => lang('Not all mcrypt algorithms and modes work with EGroupware. If you experience problems try switching it off.'),
391
		'lang_mcryptiv'        => lang('MCrypt initialization vector'),
392
		'lang_mcryptivdescr'   => lang('This should be around 30 bytes in length.<br />Note: The default has been randomly generated.'),
393
		'lang_domselect'       => lang('Domain select box on login'),
394
		'lang_domselect_descr' => lang('Alternatively domains can be accessed by logging in with <i>username@domain</i>.'),
395
		'lang_finaldescr'      => lang('After retrieving the file, put it into place as the header.inc.php.  Then, click "continue".'),
396
		'lang_continue'        => lang('Continue'),
397
		'lang_Yes'             => lang('Yes'),
398
		'lang_No'              => lang('No')
399
	));
400
	$setup_tpl->pfp('out','manageheader');
401
402
	$GLOBALS['egw_setup']->html->show_footer();
403
}
404