Completed
Push — master ( b0d47a...a8d5c3 )
by Ralf
20:19
created

fix_perms()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 7
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 16
rs 8.8333
1
#!/usr/bin/env php
2
<?php
3
/**
4
 * EGroupware - RPM post install: automatic install or update EGroupware
5
 *
6
 * @link http://www.egroupware.org
7
 * @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
8
 * @author [email protected]
9
 */
10
11
if (php_sapi_name() !== 'cli')	// security precaution: forbit calling post_install as web-page
12
{
13
	die('<h1>post_install.php must NOT be called as web-page --> exiting !!!</h1>');
14
}
15
$verbose = false;
16
$config = array(
17
	'php'         => PHP_BINARY,
18
	'source_dir'  => realpath(__DIR__.'/../..'),
19
	'data_dir'    => '/var/lib/egroupware',
20
	'header'      => '$data_dir/header.inc.php',	// symlinked to source_dir by rpm
21
	'setup-cli'   => '$source_dir/setup/setup-cli.php',
22
	'domain'      => 'default',
23
	'config_user' => 'admin',
24
	'config_passwd'   => randomstring(),
25
	'db_type'     => 'mysqli',
26
	'db_host'     => 'localhost',
27
	'db_port'     => 3306,
28
	'db_name'     => 'egroupware',
29
	'db_user'     => 'egroupware',
30
	'db_pass'     => randomstring(),
31
	'db_grant_host' => 'localhost',
32
	'db_root'     => 'root',	// mysql root user/pw to create database
33
	'db_root_pw'  => '',
34
	'backup'      => '',
35
	'admin_user'  => 'sysop',
36
	'admin_passwd'=> randomstring(),
37
	'admin_email' => '',
38
	'lang'        => 'en',	// languages for admin user and extra lang to install
39
	'charset'     => 'utf-8',
40
	'start_db'    => '/sbin/service mysqld',
41
	'autostart_db' => '/sbin/chkconfig --level 345 mysqld on',
42
	'start_webserver' => '/sbin/service httpd',
43
	'autostart_webserver' => '/sbin/chkconfig --level 345 httpd on',
44
	'distro'      => 'rh',
45
	'account-auth'  => 'sql',
46
	'account_min_id' => '',
47
	'ldap_suffix'   => 'dc=local',
48
	'ldap_host'     => 'localhost',
49
	'ldap_admin'    => 'cn=admin,$suffix',
50
	'ldap_admin_pw' => '',
51
	'ldap_base'     => 'o=$domain,$suffix',
52
	'ldap_root_dn'  => 'cn=admin,$base',
53
	'ldap_root_pw'  => randomstring(),
54
	'ldap_context'  => 'ou=accounts,$base',
55
	'ldap_search_filter' => '(uid=%user)',
56
	'ldap_group_context' => 'ou=groups,$base',
57
	'ldap_encryption_type' => '',
58
	'sambaadmin/sambasid'=> '',	// SID for sambaadmin
59
	'mailserver'    => '',
60
	'smtpserver'    => 'localhost,25',
61
	'smtp'          => '',	// see setup-cli.php --help config
62
	'imap'          => '',
63
	'sieve'         => '',
64
	'folder'        => '',
65
	'install-update-app' => '',	// install or update a single (non-default) app
66
	'webserver_user'=> 'apache',	// required to fix permissions
67
	'apache_config'   => '/etc/httpd/conf.d/egroupware.conf',
68
	'php5enmod'     => '',
69
);
70
71
// read language from LANG enviroment variable
72
if (($lang = isset($_ENV['LANG']) ? $_ENV['LANG'] : (isset($_SERVER['LANG']) ? $_SERVER['LANG'] : null)))
73
{
74
	@list($lang,$nat) = preg_split('/[_.]/',$lang);
75
	if (in_array($lang.'-'.strtolower($nat),array('es-es','pt-br','zh-tw')))
76
	{
77
		$lang .= '-'.strtolower($nat);
78
	}
79
	$config['lang'] = $lang;
80
}
81
$config['source_dir'] = dirname(dirname(dirname(__FILE__)));
82
83
/**
84
 * Set distribution spezific defaults
85
 *
86
 * @param string $distro =null default autodetect
87
 */
88
function set_distro_defaults($distro=null)
89
{
90
	global $config;
91
	if (is_null($distro))
92
	{
93
		$matches = null;
94
		// check for ID in /etc/os-release and use it
95
		if (file_exists('/etc/os-release') && preg_match('/^ID="?([^"=]+)"?$/m', $os_release=file_get_contents('/etc/os-release'), $matches))
96
		{
97
			$distro = $matches[1];
98
		}
99
		// old detections based on distro specific /etc/*release files
100
		else
101
		{
102
			$distro = file_exists('/etc/SuSE-release') ? 'suse' :
103
				(file_exists('/etc/mandriva-release') ? 'mandriva' :
104
				(file_exists('/etc/lsb-release') && preg_match('/^DISTRIB_ID="?Univention"?$/mi',
105
					file_get_contents('/etc/lsb-release')) ? 'univention' :
106
				(file_exists('/etc/debian_version') ? 'debian' : 'rh')));
107
		}
108
	}
109
	switch (($config['distro'] = $distro))
110
	{
111
		case 'suse': case 'opensuse-leap': case 'opensuse':
112
			// openSUSE 12.1+ no longer uses php5
113
			if (file_exists('/usr/bin/php5')) $config['php'] = '/usr/bin/php5';
114
			if (file_exists('/usr/bin/php7')) $config['php'] = '/usr/bin/php7';
115
			$config['start_db'] = '/sbin/service mysql';
116
			$config['autostart_db'] = '/sbin/chkconfig --level 345 mysql on';
117
			$config['start_webserver'] = '/sbin/service apache2';
118
			$config['autostart_webserver'] = '/sbin/chkconfig --level 345 apache2 on';
119
			$config['ldap_suffix'] = 'dc=site';
120
			$config['ldap_admin'] = $config['ldap_root_dn'] = 'cn=Administrator,$suffix';
121
			$config['ldap_root_pw'] = '$admin_pw';
122
			$config['ldap_base'] = '$suffix';
123
			$config['ldap_context'] = 'ou=people,$base';
124
			$config['ldap_group_context'] = 'ou=group,$base';
125
			$config['webserver_user'] = 'wwwrun';
126
			$config['apache_config'] = '/etc/apache2/conf.d/egroupware.conf';
127
			break;
128
		case 'debian': case 'ubuntu':
129
			// service not in Debian5, only newer Ubuntu, which complains about /etc/init.d/xx
130
			if (file_exists('/usr/sbin/service'))
131
			{
132
				$config['start_db'] = '/usr/sbin/service mysql';
133
				$config['start_webserver'] = '/usr/sbin/service apache2';
134
			}
135
			else
136
			{
137
				$config['start_db'] = '/etc/init.d/mysql';
138
				$config['start_webserver'] = '/etc/init.d/apache2';
139
			}
140
			$config['autostart_db'] = '/usr/sbin/update-rc.d mysql defaults';
141
			$config['autostart_webserver'] = '/usr/sbin/update-rc.d apache2 defaults';
142
			$config['webserver_user'] = 'www-data';
143
			$config['apache_config'] = '/etc/egroupware/apache.conf';
144
			break;
145
		case 'mandriva':
146
			$config['ldap_suffix'] = 'dc=site';
147
			$config['ldap_admin'] = $config['ldap_root_dn'] = 'uid=LDAP Admin,ou=System Accounts,$suffix';
148
			$config['ldap_root_pw'] = '$admin_pw';
149
			$config['ldap_base'] = '$suffix';
150
			$config['ldap_context'] = 'ou=People,$base';
151
			$config['ldap_group_context'] = 'ou=Group,$base';
152
			$config['apache_config'] = '/etc/apache2/conf.d/egroupware.conf';
153
			break;
154
		case 'univention':
155
			set_univention_defaults();
156
			break;
157
		default:
158
			// if we dont support ID from os-release, look for first one in ID_LIKE
159
			if (!empty($os_release) && preg_match('/^ID_LIKE="?([^"=]+)"?$/m', $os_release, $matches))
160
			{
161
				list($distro) = explode(' ', $matches[1]);
162
				return set_distro_defaults($distro);
0 ignored issues
show
Bug introduced by
Are you sure the usage of set_distro_defaults($distro) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
163
			}
164
			// old default: rh
165
			$config['distro'] = 'rh';
166
			// fall through
167
		case 'rh': case 'rhel': case 'centos': case 'fedora':
168
			// some MySQL packages (mysql.com, MariaDB, ...) use "mysql" as service name instead of RH default "mysqld"
169
			if (file_exists('/usr/bin/systemctl'))	// RHEL 7
170
			{
171
				$config['start_db'] = '/usr/bin/systemctl %s mariadb';
172
				$config['autostart_db'] = build_cmd('start_db', 'enable');
173
				$config['start_webserver'] = '/usr/bin/systemctl %s httpd';
174
				$config['autostart_webserver'] = build_cmd('start_webserver', 'enable');
175
			}
176
			elseif (!file_exists('/etc/init.d/mysqld') && file_exists('/etc/init.d/mysql'))
177
			{
178
				foreach(array('start_db','autostart_db') as $name)
179
				{
180
					$config[$name] = str_replace('mysqld','mysql',$config[$name]);
181
				}
182
			}
183
			break;
184
	}
185
}
186
set_distro_defaults();
187
188
// read config from command line
189
$argv = str_replace(array("''", '""'), '', $_SERVER['argv']);
190
$prog = array_shift($argv);
191
192
// check if we have EGW_POST_INSTALL set and prepend it to the command line (command line has precedence)
193
if (($config_set = isset($_ENV['EGW_POST_INSTALL']) ? $_ENV['EGW_POST_INSTALL'] : @$_SERVER['EGW_POST_INSTALL']))
194
{
195
	$conf = array();
196
	$config_set = preg_split('/[ \t]+/',trim($config_set));
197
	while($config_set)
198
	{
199
		$val = array_shift($config_set);
200
		if (($quote = $val[0]) == "'" || $quote == '"')	// arguments might be quoted with ' or "
201
		{
202
			while (substr($val,-1) != $quote)
203
			{
204
				if (!$config_set) throw new Exception('Invalid EGW_POST_INSTALL enviroment variable!');
205
				$val .= ' '.array_shift($config_set);
206
			}
207
			$val = substr($val,1,-1);
208
		}
209
		$conf[] = $val;
210
	}
211
	$argv = array_merge($conf,$argv);
212
}
213
214
$auth_type_given = false;
215
while(($arg = array_shift($argv)))
216
{
217
	if ($arg == '-v' || $arg == '--verbose')
218
	{
219
		$verbose = true;
220
	}
221
	elseif($arg == '-h' || $arg == '--help')
222
	{
223
		usage();
224
	}
225
	elseif($arg == '--suse')
226
	{
227
		set_distro_defaults('suse');
228
	}
229
	elseif($arg == '--distro')
230
	{
231
		set_distro_defaults(array_shift($argv));
232
	}
233
	elseif(substr($arg,0,2) == '--' && isset($config[$name=substr($arg,2)]))
234
	{
235
		$config[$name] = array_shift($argv);
236
237
		switch($name)
238
		{
239
			case 'auth_type':
240
				$auth_type_given = true;
241
				break;
242
243
			case 'account_repository':	// auth-type defaults to account-repository
244
				if (!$auth_type_given)
245
				{
246
					$config['auth_type'] = $config[$name];
247
				}
248
				break;
249
		}
250
	}
251
	else
252
	{
253
		usage("Unknown argument '$arg'!");
254
	}
255
}
256
257
$replace = array();
258
foreach($config as $name => $value)
259
{
260
	$replace['$'.$name] = $value;
261
	if (strpos($value,'$') !== false)
262
	{
263
		$config[$name] = strtr($value,$replace);
264
	}
265
}
266
// basic config checks
267
foreach(array('php','source_dir','data_dir','setup-cli') as $name)
268
{
269
	if (!file_exists($config[$name])) bail_out(1,$config[$name].' not found!');
270
}
271
272
// fix important php.ini and conf.d/*.ini settings
273
check_fix_php_apc_ini();
274
275
// not limiting memory, as backups might fail with limit we set
276
$setup_cli = $config['php'].' -d memory_limit=-1 '.$config['setup-cli'];
277
278
// if we have a header, include it
279
if (file_exists($config['header']) && filesize($config['header']) >= 200)	// default header redirecting to setup is 147 bytes
280
{
281
	$GLOBALS['egw_info'] = array(
282
		'flags' => array(
283
			'noapi' => true,
284
			'currentapp' => 'login',	// stop PHP Notice: Undefined index "currentapp" in pre 16.1 header
285
		)
286
	);
287
	include $config['header'];
288
289
	// get user from header and replace password, as we dont know it
290
	$old_password = patch_header($config['header'],$config['config_user'],$config['config_passwd']);
291
	// register a shutdown function to put old password back in any case
292
	register_shutdown_function(function() use (&$config, $old_password)
293
	{
294
		patch_header($config['header'], $config['config_user'], $old_password);
295
	});
296
}
297
// new header or does not include requested domain (!= "default") --> new install
298
if (!isset($GLOBALS['egw_domain']) ||  $config['domain'] !== 'default' && !isset($GLOBALS['egw_domain'][$config['domain']]))
299
{
300
	// --> new install
301
	$extra_config = '';
302
303
	// check for localhost if database server is started and start it (permanent) if not
304
	if ($config['db_host'] == 'localhost' && $config['start_db'])
305
	{
306
		exec(build_cmd('start_db', 'status'), $dummy, $ret);
307
		if ($ret)
308
		{
309
			system(build_cmd('start_db', 'start'));
310
			if (!empty($config['autostart_db'])) system($config['autostart_db']);
311
		}
312
	}
313
	// create database
314
	$setup_db = $setup_cli.' --setup-cmd-database sub_command=create_db';
315
	foreach(array('domain','db_type','db_host','db_port','db_name','db_user','db_pass','db_root','db_root_pw','db_grant_host') as $name)
316
	{
317
		$setup_db .= ' '.escapeshellarg($name.'='.$config[$name]);
318
	}
319
	run_cmd($setup_db);
0 ignored issues
show
Bug introduced by
The call to run_cmd() has too few arguments starting with name. ( Ignorable by Annotation )

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

319
	/** @scrutinizer ignore-call */ 
320
 run_cmd($setup_db);

This check compares calls to functions or methods with their respective definitions. If the call has less 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...
320
321
	// check if ldap is required and initialise it
322
	// we need to specify account_repository and auth_type to --install as extra config, otherwise install happens for sql!
323
	@list($config['account_repository'],$config['auth_type'],$rest) = explode(',',$config['account-auth'],3);
324
	$extra_config .= ' '.escapeshellarg('account_repository='.$config['account_repository']);
325
	$extra_config .= ' '.escapeshellarg('auth_type='.(empty($config['auth_type']) ? $config['account_repository'] : $config['auth_type']));
326
	if (empty($rest)) unset($config['account-auth']);
327
	if (array_intersect(array($config['account_repository'], $config['auth_type']), array('ldap', 'univention')))
328
	{
329
		// set account_min_id to 1100 if not specified to NOT clash with system accounts
330
		$extra_config .= ' '.escapeshellarg('account_min_id='.(!empty($config['account_min_id']) ? $config['account_min_id'] : 1100));
331
332
		$setup_ldap = $setup_cli.' --setup-cmd-ldap sub_command='.
333
			($config['account_repository'] == 'ldap' ? 'create_ldap' : 'test_ldap');
334
		foreach(array(
335
			'domain','ldap_suffix','ldap_host','ldap_admin','ldap_admin_pw',	// non-egw params: only used for create
336
			'ldap_base','ldap_root_dn','ldap_root_pw','ldap_context','ldap_search_filter','ldap_group_context',	// egw params
337
			'ldap_encryption_type', 'sambaadmin/sambasid',
338
		) as $name)
339
		{
340
			if (strpos($value=$config[$name],'$') !== false)
341
			{
342
				$config[$name] = $value = strtr($value,array(
343
					'$suffix' => $config['ldap_suffix'],
344
					'$base' => $config['ldap_base'],
345
					'$admin_pw' => $config['ldap_admin_pw'],
346
				));
347
			}
348
			$setup_ldap .= ' '.escapeshellarg($name.'='.$value);
349
350
			if (!in_array($name,array('domain','ldap_suffix','ldap_admin','ldap_admin_pw')))
351
			{
352
				$extra_config .= ' '.escapeshellarg($name.'='.$value);
353
			}
354
		}
355
		run_cmd($setup_ldap);
356
	}
357
	// enable mcrypt extension eg. for Ubuntu 14.04+
358
	if (!empty($config['php5enmod']))
359
	{
360
		run_cmd($config['php5enmod']);
361
	}
362
363
	// create or edit header header
364
	$setup_header = $setup_cli.(isset($GLOBALS['egw_domain']) ? ' --edit-header ' : ' --create-header ').
365
		escapeshellarg($config['config_passwd'].','.$config['config_user']).
366
		' --domain '.escapeshellarg($config['domain'].','.$config['db_name'].','.$config['db_user'].','.$config['db_pass'].
367
			','.$config['db_type'].','.$config['db_host'].','.$config['db_port']);
368
	run_cmd($setup_header);
369
370
	// install egroupware
371
	$setup_install = $setup_cli.' --install '.escapeshellarg($config['domain'].','.$config['config_user'].','.$config['config_passwd'].','.$config['backup'].','.$config['charset'].','.$config['lang'])
372
		.$extra_config;
373
	run_cmd($setup_install);
374
375
	if ($config['data_dir'] != '/var/lib/egroupware')
376
	{
377
		// set files dir different from default
378
		$setup_config = $setup_cli.' --config '.escapeshellarg($config['domain'].','.$config['config_user'].','.$config['config_passwd']).
379
			' --files-dir '.escapeshellarg($config['data_dir'].'/files').' --backup-dir '.escapeshellarg($config['data_dir'].'/backup');
380
		run_cmd($setup_config);
381
	}
382
	// create mailserver config (fmail requires at least minimal config given as default, otherwise fatal error)
383
	$setup_mailserver = $setup_cli.' --config '.escapeshellarg($config['domain'].','.$config['config_user'].','.$config['config_passwd']);
384
	foreach(array('account-auth','smtpserver','smtp','postfix','mailserver','imap','cyrus','sieve','folder') as $name)
385
	{
386
		if (!empty($config[$name])) $setup_mailserver .= ' --'.$name.' '.escapeshellarg($config[$name]);
387
	}
388
	run_cmd($setup_mailserver);
389
390
	// create first user
391
	$setup_admin = $setup_cli.' --admin '.escapeshellarg($config['domain'].','.$config['config_user'].','.$config['config_passwd'].','.
392
		$config['admin_user'].','.$config['admin_passwd'].',,,'.$config['admin_email'].','.$config['lang']);
393
	run_cmd($setup_admin);
394
395
	// check if webserver is started and start it (permanent) if not
396
	if ($config['start_webserver'])
397
	{
398
		exec(build_cmd('start_webserver', 'status'),$dummy,$ret);
399
		if ($ret)
400
		{
401
			system(build_cmd('start_webserver', 'start'));
402
			if (!empty($config['autostart_webserver'])) system($config['autostart_webserver']);
403
		}
404
		else
405
		{
406
			system(build_cmd('start_webserver', 'reload'));
407
		}
408
	}
409
	// fix egw_cache evtl. created by root, stoping webserver from accessing it
410
	fix_perms();
411
412
	echo "\n";
413
	echo "EGroupware successful installed\n";
414
	echo "===============================\n";
415
	echo "\n";
416
	echo "Please note the following user names and passwords:\n";
417
	echo "\n";
418
	echo "Setup username:      $config[config_user]\n";
419
	echo "      password:      $config[config_passwd]\n";
420
	echo "\n";
421
	echo "EGroupware username: $config[admin_user]\n";
422
	echo "           password: $config[admin_passwd]\n";
423
	echo "\n";
424
	echo "You can log into EGroupware by pointing your browser to http://localhost/egroupware/\n";
425
	echo "Please replace localhost with the appropriate hostname, if you connect remote.\n\n";
426
427
	if (empty($config['db_root_pw']))
428
	{
429
		echo "*** Database has no root password set, please fix that immediatly".
430
			(substr($config['db_type'], 0, 5) === 'mysql' ? ": mysqladmin -u root password NEWPASSWORD\n\n" : "!\n\n");
431
	}
432
}
433
else
434
{
435
	// --> existing install --> update
436
437
	// update egroupware, or single app(s), in later case skip backup
438
	$setup_update = $setup_cli.' --update '.escapeshellarg('all,'.$config['config_user'].','.$config['config_passwd'].
439
		(empty($config['install-update-app']) ? '' : ',no,'.$config['install-update-app']));
440
	$ret = run_cmd($setup_update,$output,array(4,15));
0 ignored issues
show
Unused Code introduced by
The call to run_cmd() has too many arguments starting with array(4, 15). ( Ignorable by Annotation )

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

440
	$ret = /** @scrutinizer ignore-call */ run_cmd($setup_update,$output,array(4,15));

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...
441
442
	switch($ret)
443
	{
444
		case 4:		// header needs an update
445
			$header_update = $setup_cli.' --update-header '.escapeshellarg($config['config_passwd'].','.$config['config_user']);
446
			run_cmd($header_update);
447
			$ret = run_cmd($setup_update,$output,15);
448
			if ($ret != 15) break;
449
			// fall through
450
		case 15:	// missing configuration (eg. mailserver)
451
			if (!$verbose) echo implode("\n",(array)$output)."\n";
452
			break;
453
454
		case 0:
455
			echo "\nEGroupware successful updated\n";
456
			break;
457
	}
458
	// fix egw_cache evtl. created by root, stoping webserver from accessing it
459
	fix_perms();
460
461
	if (!empty($config['start_webserver']))
462
	{
463
		// restart running Apache, to force APC to update changed sources and/or Apache configuration
464
		$output = array();
465
		run_cmd(build_cmd('start_webserver', 'status').' && '.build_cmd('start_webserver', 'restart'), $output, true);
466
	}
467
	exit($ret);
468
}
469
470
/**
471
 * Build command to execute
472
 *
473
 * @param string $cmd command or index into $config, which either incl. %s for arg or arg with be appended
474
 * @param string $arg argument
475
 * @return string
476
 */
477
function build_cmd($cmd, $arg)
478
{
479
	global $config;
480
481
	if (isset($config[$cmd])) $cmd = $config[$cmd];
482
483
	if (strpos($cmd, '%s')) return str_replace('%s', $arg, $cmd);
484
485
	return $cmd.' '.$arg;
486
}
487
488
/**
489
 * Patches a given password (for header admin) into the EGroupware header.inc.php and returns the old one
490
 *
491
 * @param string $filename
492
 * @param string &$user username on return(!)
493
 * @param string $password new password
494
 * @return string old password
495
 */
496
function patch_header($filename,&$user,$password)
497
{
498
	$header = file_get_contents($filename);
499
500
	$umatches = $pmatches = null;
501
	if (!preg_match('/'.preg_quote("\$GLOBALS['egw_info']['server']['header_admin_user'] = '", '/')."([^']+)';/m",$header,$umatches) ||
502
		!preg_match('/'.preg_quote("\$GLOBALS['egw_info']['server']['header_admin_password'] = '", '/')."([^']*)';/m",$header,$pmatches))
503
	{
504
		bail_out(99,"$filename is no regular EGroupware header.inc.php!");
505
	}
506
	file_put_contents($filename,preg_replace('/'.preg_quote("\$GLOBALS['egw_info']['server']['header_admin_password'] = '", '/')."([^']*)';/m",
507
		"\$GLOBALS['egw_info']['server']['header_admin_password'] = '".$password."';",$header));
508
509
	$user = $umatches[1];
510
511
	return $pmatches[1];
512
}
513
514
/**
515
 * Runs given shell command, exists with error-code after echoing the output of the failed command (if not already running verbose)
516
 *
517
 * @param string $cmd
518
 * @param array &$output=null $output of command
519
 * @param int|array|true $no_bailout =null exit code(s) to NOT bail out, or true to never bail out
520
 * @return int exit code of $cmd
521
 */
522
function run_cmd($cmd,array &$output=null,$no_bailout=null)
523
{
524
	global $verbose;
525
526
	if ($verbose)
527
	{
528
		echo $cmd."\n";
529
		$ret = null;
530
		system($cmd,$ret);
531
	}
532
	else
533
	{
534
		$output[] = $cmd;
535
		exec($cmd,$output,$ret);
536
	}
537
	if ($ret && $no_bailout !== true && !in_array($ret,(array)$no_bailout))
538
	{
539
		bail_out($ret,$verbose?null:$output);
540
	}
541
	return $ret;
542
}
543
544
/**
545
 * Stop programm execution with a given exit code and optional extra message
546
 *
547
 * @param int $ret =1
548
 * @param array|string $output line(s) to output before temination notice
549
 */
550
function bail_out($ret=1,$output=null)
551
{
552
	if ($output) echo implode("\n",(array)$output);
553
	echo "\n\nInstallation failed --> exiting!\n\n";
554
	exit($ret);
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...
555
}
556
557
/**
558
 * Return a rand string, eg. to generate passwords
559
 *
560
 * @param int $len =16
561
 * @return string
562
 */
563
function randomstring($len=16)
564
{
565
	static $usedchars = array(
566
		'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f',
567
		'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
568
		'w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L',
569
		'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
570
		'@','!','&','(',')','=','?',';',':','#','_','-','<',
571
		'>','|','[',']','}',	// dont add %, /\,'"{ as we have problems dealing with them
572
	);
573
574
	// use cryptographically secure random_int available in PHP 7+
575
	$func = function_exists('random_int') ? 'random_int' : 'mt_rand';
576
577
	$str = '';
578
	for($i=0; $i < $len; $i++)
579
	{
580
		$str .= $usedchars[$func(0,count($usedchars)-1)];
581
	}
582
	return $str;
583
}
584
585
/**
586
 * Give usage information and an optional error-message, before stoping program execution with exit-code 90 or 0
587
 *
588
 * @param string $error =null optional error-message
589
 */
590
function usage($error=null)
591
{
592
	global $prog,$config;
593
594
	echo "Usage: $prog [-h|--help] [-v|--verbose] [--distro=(suse|rh|debian)] [options, ...]\n\n";
595
	echo "options and their defaults:\n";
596
	foreach($config as $name => $default)
597
	{
598
		if (in_array($name, array('postfix','cyrus'))) continue;	// do NOT report deprecated options
599
		if (in_array($name,array('config_passwd','db_pass','admin_passwd','ldap_root_pw')) && strlen($config[$name]) == 16)
600
		{
601
			$default = '<16 char random string>';
602
		}
603
		echo '--'.str_pad($name,20).$default."\n";
604
	}
605
	if ($error)
606
	{
607
		echo "$error\n\n";
608
		exit(90);
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...
609
	}
610
	exit(0);
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...
611
}
612
613
/**
614
 * fix egw_cache and files_dir perms evtl. created by root, stoping webserver from accessing it
615
 */
616
function fix_perms()
617
{
618
	global $config;
619
620
	// chown only works as root (uid=0)
621
	if (function_exists('posix_getuid') && posix_geteuid()) return;
622
623
	if (file_exists('/tmp/egw_cache') && !empty($config['webserver_user']))
624
	{
625
		system('/bin/chown -R '.$config['webserver_user'].' /tmp/egw_cache');
626
		system('/bin/chmod 700 /tmp/egw_cache');
627
	}
628
	// in case update changes something in filesystem
629
	if (file_exists($config['data_dir']) && !empty($config['webserver_user']))
630
	{
631
		@system('/bin/chown -R '.$config['webserver_user'].' '.$config['data_dir'].'/*/files/sqlfs');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for system(). 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

631
		/** @scrutinizer ignore-unhandled */ @system('/bin/chown -R '.$config['webserver_user'].' '.$config['data_dir'].'/*/files/sqlfs');

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...
632
	}
633
}
634
635
/**
636
 * Set Univention UCS specific defaults
637
 *
638
 * Defaults are read from ucr registry and /etc/*.secret files
639
 *
640
 * There are 4 types of Univention servers:
641
 * - master DC: /etc/machine.secret, /etc/ldap.secret, ldap/server/type=master
642
 * - backup DC: /etc/machine.secret, /etc/ldap.secret, /etc/ldap-backup.secret, ldap/server/type=slave (not backup!)
643
 * - slave:     /etc/machine.secret, /etc/ldap-backup.secret, ldap/server/type=slave
644
 * - member:    /etc/machine.secret, no ldap/server/type
645
 *
646
 * univention-ldapsearch works on all 4 types.
647
 *
648
 * ucr get ldap/server/(ip|port) points to local ldap (not member).
649
 * ucr get ldap/master(/port) ldap/base points to master (on all servers)
650
 *
651
 * @todo slave and member have no /etc/ldap.secret
652
 */
653
function set_univention_defaults()
654
{
655
	global $config;
656
657
	set_distro_defaults('debian');
658
	$config['distro'] = 'univention';
659
660
	// set lang from ucr locale, as cloud-config at least never has anything but EN set in enviroment
661
	@list($lang,$nat) = preg_split('/[_.]/', _ucr_get('locale/default'));
662
	if (in_array($lang.'-'.strtolower($nat),array('es-es','pt-br','zh-tw')))
663
	{
664
		$lang .= '-'.strtolower($nat);
665
	}
666
	$config['lang'] = $lang;
667
668
	// mysql settings
669
	$config['db_root_pw'] = _ucr_secret('mysql');
670
671
	// check if ucs ldap server is configured
672
	if (_ucr_get('ldap/server/ip'))
673
	{
674
		// ldap settings, see http://docs.univention.de/developer-reference.html#join:secret
675
		$config['ldap_suffix'] = $config['ldap_base'] = _ucr_get('ldap/base');
676
		// port is ldap allowing starttls (zertificate/CA is correctly set in /etc/ldap/ldap.conf)
677
		$config['ldap_host'] = 'tls://'._ucr_get('ldap/master').':'._ucr_get('ldap/master/port');
678
		$config['ldap_admin'] = $config['ldap_root'] = 'cn=admin,$suffix';
679
		$config['ldap_admin_pw'] = $config['ldap_root_pw'] = _ucr_secret('ldap');
680
		$config['ldap_context'] = 'cn=users,$base';
681
		$config['ldap_group_context'] = 'cn=groups,$base';
682
		$config['ldap_search_filter'] = '(uid=%user)';
683
684
		// ldap password hash (our default blowfish_crypt seems not to work)
685
		$config['ldap_encryption_type'] = 'sha512_crypt';
686
687
		$config['account_min_id'] = 1200;	// UCS use 11xx for internal users/groups
688
689
		$config['account-auth'] = 'univention,univention';
690
691
		// set sambaadmin sambaSID
692
		$config['sambaadmin/sambasid'] = exec('/usr/bin/univention-ldapsearch -x "(objectclass=sambadomain)" sambaSID|sed -n "s/sambaSID: \(.*\)/\1/p"');
693
694
		// mailserver, see setup-cli.php --help config
695
		if (($mailserver = exec('/usr/bin/univention-ldapsearch -x "(univentionAppID=mailserver_*)" univentionAppInstalledOnServer|sed -n "s/univentionAppInstalledOnServer: \(.*\)/\1/p"')) &&
696
			// only set on host mailserver app is installed: _ucr_get('mail/cyrus/imap') == 'yes' &&
697
			($domains=_ucr_get('mail/hosteddomains')))
698
		{
699
			if (!is_array($domains)) $domains = explode("\n", $domains);
0 ignored issues
show
introduced by
The condition is_array($domains) is always false.
Loading history...
700
			$domain = array_shift($domains);
701
			// set "use auth with session credentials",tls,"not user editable","further identities"
702
			$config['smtpserver'] = "$mailserver,465,,,yes,tls,no,yes";
703
			$config['smtp'] = ',Smtp\\Univention';
704
			$config['mailserver'] = "$mailserver,993,$domain,email,tls";
705
			if (_ucr_get('mail/dovecot') == 'yes')
706
			{
707
				$matches = null;
708
				if (file_exists('/etc/dovecot/master-users') &&
709
					preg_match('/^([^:]+):{PLAIN}([^:]+):/i', file_get_contents('/etc/dovecot/master-users'), $matches))
710
				{
711
					$config['imap'] = $matches[1].','.$matches[2].',Imap\\Dovecot';
712
				}
713
				else
714
				{
715
					$config['imap'] = ',,Imap\\Dovecot';
716
				}
717
				// default with sieve port to 4190, as config is only available on host mailserver app is installed
718
				if (!($sieve_port = _ucr_get('mail/dovecot/sieve/port'))) $sieve_port = 4190;
719
			}
720
			else
721
			{
722
				$config['imap'] = /*'cyrus,'._ucr_secret('cyrus')*/','.',Imap\\Cyrus';
723
				// default with sieve port to 4190, as config is only available on host mailserver app is installed
724
				if (!($sieve_port = _ucr_get('mail/cyrus/sieve/port'))) $sieve_port = 4190;
725
			}
726
			// set folders so mail creates them on first login, UCS does not automatic
727
			$config['folder'] = 'INBOX/Sent,INBOX/Trash,INBOX/Drafts,INBOX/Templates,Spam,,Ham';
728
			$config['sieve'] = "$mailserver,$sieve_port,starttls";
729
			// set an email address for sysop user so mail works right away
730
			$config['admin_email'] = '$admin_user@'.$domain;
731
		}
732
		$config['apache_config'] = '/etc/egroupware/apache-univention.conf';
733
	}
734
}
735
736
/**
737
 * Get a value from Univention registry
738
 *
739
 * @param string $name
740
 * @return string
741
 */
742
function _ucr_get($name)
743
{
744
	static $values=null;
745
	if (!isset($values))
746
	{
747
		$output = $matches = null;
748
		exec('/usr/sbin/ucr dump', $output);
749
		foreach($output as $line)
750
		{
751
			if (preg_match("/^([^:]+): (.*)\n?$/", $line, $matches))
752
			{
753
				$values[$matches[1]] = $matches[2];
754
			}
755
		}
756
	}
757
	return $values[$name];
758
}
759
760
/**
761
 * Read one Univention secret/password eg. _ucr_secret('mysql')
762
 *
763
 * @param string $name
764
 * @return string|boolean
765
 */
766
function _ucr_secret($name)
767
{
768
	if (!file_exists($filename = '/etc/'.basename($name).'.secret'))
769
	{
770
		return false;
771
	}
772
	return trim(file_get_contents($filename));
773
}
774
775
/**
776
 * Check and evtl. fix APC(u) shared memory size (apc.shm_segments * apc.shm_size) >= 64M
777
 *
778
 * We check for < 64M to allow to use that for small installs manually, but set 128M by default.
779
 */
780
function check_fix_php_apc_ini()
781
{
782
	if (extension_loaded('apc') || extension_loaded('apcu'))
783
	{
784
		$shm_size = ini_get('apc.shm_size');
785
		$shm_segments = ini_get('apc.shm_segments');
786
		// ancent APC (3.1.3) in Debian 6/Squezze has size in MB without a unit
787
		if (($numeric_size = is_numeric($shm_size) && $shm_size <= 1048576)) $shm_size .= 'M';
788
789
		$size = _size_with_unit($shm_size) * $shm_segments;
790
		//echo "shm_size=$shm_size, shm_segments=$shm_segments --> $size, numeric_size=$numeric_size\n";
791
792
		// check if we have less then 64MB (eg. default 32M) --> set it to 128MB
793
		if ($size < _size_with_unit('64M'))
794
		{
795
			ob_start();
796
			phpinfo();
797
			$phpinfo = ob_get_clean();
798
			$matches = null;
799
			if (preg_match('#(/[a-z0-9./-]+apcu?.ini)(,| |$)#mi', $phpinfo, $matches) &&
800
				file_exists($path = $matches[1]) && ($apc_ini = file_get_contents($path)))
801
			{
802
				$new_shm_size = 128 / $shm_segments;
803
				if (!$numeric_size) $new_shm_size .= 'M';
804
				if (preg_match('|^apc.shm_size\s*=\s*(\d+[KMG]?)$|m', $apc_ini))
805
				{
806
					file_put_contents($path, preg_replace('|^apc.shm_size\s*=\s*(\d+[KMG]?)$|m', 'apc.shm_size='.$new_shm_size, $apc_ini));
807
				}
808
				else
809
				{
810
					file_put_contents($path, $apc_ini."\napc.shm_size=$new_shm_size\n");
811
				}
812
				echo "Fix APC(u) configuration, set apc.shm_size=$new_shm_size in $path\n";
813
			}
814
		}
815
	}
816
}
817
818
/**
819
 * Check if CA certificates are added to open_basedir to be accessible
820
 *
821
 * Different distros use different CA directories:
822
 * - Debian/Ubuntu: /usr/lib/ssl/certs with files symlinked from /usr/share/ca-certificates
823
 * - RHEL/CentOS: /etc/pki/tls/certs with files symlinks from /etc/pki/ca-trust
824
 * - openSUSE/SLES: /var/lib/ca-certificates/openssl
825
 */
826
function check_fix_open_basedir_certs()
827
{
828
	global $config;
829
830
	if (extension_loaded('openssl') && function_exists('openssl_get_cert_locations') &&
831
		($locations = openssl_get_cert_locations()) &&
832
		file_exists($default_cert_dir = $locations['default_cert_dir']))
833
	{
834
		$check_dirs = array($default_cert_dir);
835
		foreach(scandir($default_cert_dir) as $cert)
836
		{
837
			$cert = $default_cert_dir.'/'.$cert;
838
			if (is_link($cert) && ($link = readlink($cert)) &&
839
				dirname($link) != '.' && !in_array(dirname($link), $check_dirs))
840
			{
841
				$check_dirs[] = dirname($link);
842
			}
843
		}
844
		//echo "Checking if OpenSSL CA dirs are included in open_basedir: ".implode(', ', $check_dirs)."\n";
845
		$matches = null;
846
		if (($content = file_get_contents($config['apache_config'])) &&
847
			preg_match('/^\s*php_admin_value\s+open_basedir\s+(.*)$/m', $content, $matches))
848
		{
849
			//echo "$config[apache_config] contains open_basedir $matches[1]\n";
850
			$open_basedirs = explode(':', $matches[1]);
851
			$need_adding = array();
852
			foreach($check_dirs as $dir)
853
			{
854
				if (!in_array($dir, $open_basedirs)) $need_adding[] = $dir;
855
			}
856
			if ($need_adding)
857
			{
858
				$content = preg_replace('/^\s*php_admin_value\s+open_basedir\s+(.*)$/m',
859
					'\\0:'.implode(':', $need_adding), $content);
860
				if (file_put_contents($config['apache_config'], $content))
861
				{
862
					echo "Added OpenSSL CA directories ".implode(', ', $need_adding)." to Apache config $config[apache_config].\n";
863
				}
864
				else
865
				{
866
					echo "Failed to add OpenSSL CA directories ".implode(', ', $need_adding)." to Apache config $config[apache_config]!\n";
867
				}
868
			}
869
		}
870
	}
871
}
872
873
/**
874
 * Convert a size with unit eg. 32M to a number
875
 * @param int|string $_size
876
 * @return int
877
 */
878
function _size_with_unit($_size)
879
{
880
	$size = (int)$_size;
881
	switch(strtoupper(substr($_size, -1)))
882
	{
883
		case 'G':
884
			$size *= 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
885
		case 'M':
886
			$size *= 1024;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
887
		case 'K':
888
			$size *= 1024;
889
	}
890
	return $size;
891
}
892