Marius Burkard
2016-05-04 c3189ce6c7301c3ec17878fd3918f31d0d3cb18a
commit | author | age
532ae5 1 <?php
L 2
3 /*
4 Copyright (c) 2007-2010, Till Brehm, projektfarm Gmbh
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without modification,
8 are permitted provided that the following conditions are met:
9
10     * Redistributions of source code must retain the above copyright notice,
11       this list of conditions and the following disclaimer.
12     * Redistributions in binary form must reproduce the above copyright notice,
13       this list of conditions and the following disclaimer in the documentation
14       and/or other materials provided with the distribution.
15     * Neither the name of ISPConfig nor the names of its contributors
16       may be used to endorse or promote products derived from this software without
17       specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
23 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
26 OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
28 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 class installer_base {
32
33     var $wb = array();
34     var $language = 'en';
35     var $db;
36     public $conf;
37     public $install_ispconfig_interface = true;
38     public $is_update = false; // true if it is an update, falsi if it is a new install
cc45ab 39     public $min_php = '5.3.3'; // minimal php-version for update / install
223c56 40     protected $mailman_group = 'list';
532ae5 41
L 42
43     public function __construct() {
44         global $conf; //TODO: maybe $conf  should be passed to constructor
45         //$this->conf = $conf;
46     }
47
48     //: TODO  Implement the translation function and language files for the installer.
49     public function lng($text) {
50         return $text;
51     }
52
53     public function error($msg) {
54         die('ERROR: '.$msg."\n");
55     }
56
57     public function warning($msg) {
b1a6a5 58         echo 'WARNING: '.$msg."\n";
532ae5 59     }
a8ccf6 60
b04e82 61     public function simple_query($query, $answers, $default, $name = '') {
TB 62         global $autoinstall;
532ae5 63         $finished = false;
L 64         do {
b04e82 65             if($name != '' && $autoinstall[$name] != '') {
TB 66                 if($autoinstall[$name] == 'default') {
67                     $input = $default;
68                 } else {
69                     $input = $autoinstall[$name];
70                 }
636822 71             } elseif($name != '' && $autoupdate[$name] != '') {
TB 72                 if($autoupdate[$name] == 'default') {
73                     $input = $default;
74                 } else {
75                     $input = $autoupdate[$name];
76                 }
b04e82 77             } else {
TB 78                 $answers_str = implode(',', $answers);
79                 swrite($this->lng($query).' ('.$answers_str.') ['.$default.']: ');
80                 $input = sread();
81             }
532ae5 82
L 83             //* Stop the installation
84             if($input == 'quit') {
85                 swriteln($this->lng("Installation terminated by user.\n"));
86                 die();
87             }
88
89             //* Select the default
90             if($input == '') {
91                 $answer = $default;
92                 $finished = true;
93             }
94
95             //* Set answer id valid
96             if(in_array($input, $answers)) {
97                 $answer = $input;
98                 $finished = true;
99             }
100
101         } while ($finished == false);
102         swriteln();
103         return $answer;
104     }
105
b04e82 106     public function free_query($query, $default, $name = '') {
TB 107         global $autoinstall;
108         if($name != '' && $autoinstall[$name] != '') {
109             if($autoinstall[$name] == 'default') {
110                 $input = $default;
111             } else {
112                 $input = $autoinstall[$name];
113             }
636822 114         } elseif($name != '' && $autoupdate[$name] != '') {
TB 115             if($autoupdate[$name] == 'default') {
116                 $input = $default;
117             } else {
118                 $input = $autoupdate[$name];
119             }
b04e82 120         } else {
TB 121             swrite($this->lng($query).' ['.$default.']: ');
122             $input = sread();
123         }
532ae5 124
L 125         //* Stop the installation
126         if($input == 'quit') {
127             swriteln($this->lng("Installation terminated by user.\n"));
128             die();
129         }
130
131         $answer =  ($input == '') ? $default : $input;
132         swriteln();
133         return $answer;
134     }
135
136     /*
137     // TODO: this function is not used atmo I think - pedro
138     function request_language(){
a8ccf6 139
532ae5 140         swriteln(lng('Enter your language'));
L 141         swriteln(lng('de, en'));
a8ccf6 142
532ae5 143     }
L 144     */
145
cc45ab 146     //** Detect PHP-Version
FS 147     public function get_php_version() {
de492a 148         if(version_compare(PHP_VERSION, $this->min_php, '<')) return false;
MB 149         else return true;
cc45ab 150     }
FS 151
532ae5 152     //** Detect installed applications
L 153     public function find_installed_apps() {
154         global $conf;
155
156         if(is_installed('mysql') || is_installed('mysqld')) $conf['mysql']['installed'] = true;
157         if(is_installed('postfix')) $conf['postfix']['installed'] = true;
75722e 158         if(is_installed('postgrey')) $conf['postgrey']['installed'] = true;
a75c81 159         if(is_installed('mailman') || is_installed('mmsitepass')) $conf['mailman']['installed'] = true;
e09a27 160         if(is_installed('apache') || is_installed('apache2') || is_installed('httpd') || is_installed('httpd2')) $conf['apache']['installed'] = true;
532ae5 161         if(is_installed('getmail')) $conf['getmail']['installed'] = true;
1ca823 162         if(is_installed('courierlogger')) $conf['courier']['installed'] = true;
532ae5 163         if(is_installed('dovecot')) $conf['dovecot']['installed'] = true;
74d2dc 164         if(is_installed('saslauthd')) $conf['saslauthd']['installed'] = true;
ac28b5 165         if(is_installed('amavisd-new') || is_installed('amavisd')) $conf['amavis']['installed'] = true;
532ae5 166         if(is_installed('clamdscan')) $conf['clamav']['installed'] = true;
L 167         if(is_installed('pure-ftpd') || is_installed('pure-ftpd-wrapper')) $conf['pureftpd']['installed'] = true;
168         if(is_installed('mydns') || is_installed('mydns-ng')) $conf['mydns']['installed'] = true;
169         if(is_installed('jk_chrootsh')) $conf['jailkit']['installed'] = true;
170         if(is_installed('pdns_server') || is_installed('pdns_control')) $conf['powerdns']['installed'] = true;
171         if(is_installed('named') || is_installed('bind') || is_installed('bind9')) $conf['bind']['installed'] = true;
80e3c9 172         if(is_installed('squid')) $conf['squid']['installed'] = true;
T 173         if(is_installed('nginx')) $conf['nginx']['installed'] = true;
bd68aa 174         if(is_installed('iptables') && is_installed('ufw')) $conf['ufw']['installed'] = true;
567aea 175         if(is_installed('iptables') && is_installed('bastille-netfilter')) $conf['firewall']['installed'] = true;
5eb43f 176         if(is_installed('fail2ban-server')) $conf['fail2ban']['installed'] = true;
522ef8 177         if(is_installed('vzctl')) $conf['openvz']['installed'] = true;
a75c81 178         if(is_installed('metronome') && is_installed('metronomectl')) $conf['xmpp']['installed'] = true;
1bed19 179         if(is_installed('spamassassin')) $conf['spamassassin']['installed'] = true;
a75c81 180         if(is_installed('vlogger')) $conf['vlogger']['installed'] = true;
FS 181         if(is_installed('cron')) $conf['cron']['installed'] = true;
a8ccf6 182
d7cfd7 183         if ($conf['services']['web'] && (($conf['apache']['installed'] && is_file($conf['apache']["vhost_conf_enabled_dir"]."/000-ispconfig.vhost")) || ($conf['nginx']['installed'] && is_file($conf['nginx']["vhost_conf_enabled_dir"]."/000-ispconfig.vhost")))) $this->ispconfig_interface_installed = true;
532ae5 184     }
L 185
bedf79 186     public function force_configure_app($service, $enable_force=true) {
a75c81 187         $force = false;
32dcc8 188         if($enable_force == true) {
TB 189             swriteln("[WARN] autodetect for $service failed");
190         } else {
191             swriteln("[INFO] service $service not detected");
192         }
bedf79 193         if($enable_force) {
FS 194             if(strtolower($this->simple_query("Force configure $service", array('y', 'n'), 'n') ) == 'y') {
195                 $force = true;
196             } else swriteln("Skipping $service\n");
197         }
a75c81 198         return $force;
FS 199     }
200
418f62 201     public function reconfigure_app($service, $reconfigure_services_answer) {
FS 202         $reconfigure = false;
203         if ($reconfigure_services_answer != 'selected') {
204             $reconfigure = true;
205         } else {
206             if(strtolower($this->simple_query("Reconfigure $service", array('y', 'n'), 'y') ) == 'y') {
207                 $reconfigure = true;
208             } else {
209                 swriteln("Skip reconfigure $service\n");
210             }
211         }
212         return $reconfigure;
213     }
a75c81 214
532ae5 215     /** Create the database for ISPConfig */
b1a6a5 216
MC 217
532ae5 218     public function configure_database() {
L 219         global $conf;
220
670d37 221         //* check sql-mode
FS 222         $check_sql_mode = $this->db->queryOneRecord("SELECT @@sql_mode");
223
2b3b4c 224         if ($check_sql_mode['@@sql_mode'] != '' && $check_sql_mode['@@sql_mode'] != 'NO_ENGINE_SUBSTITUTION') {
FS 225             echo "Wrong SQL-mode. You should use NO_ENGINE_SUBSTITUTION. Add\n\n";
226             echo "    sql-mode=\"NO_ENGINE_SUBSTITUTION\"\n\n";
227             echo"to the mysqld-section in /etc/mysql/my.cnf and restart mysqld afterwards\n";
228             die();
229         }
670d37 230
532ae5 231         //** Create the database
2af58c 232         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS ?? DEFAULT CHARACTER SET ?', $conf['mysql']['database'], $conf['mysql']['charset'])) {
532ae5 233             $this->error('Unable to create MySQL database: '.$conf['mysql']['database'].'.');
L 234         }
235
236         //* Set the database name in the DB library
305dda 237         $this->db->setDBName($conf['mysql']['database']);
532ae5 238
L 239         //* Load the database dump into the database, if database contains no tables
240         $db_tables = $this->db->getTables();
241         if(count($db_tables) > 0) {
242             $this->error('Stopped: Database already contains some tables.');
243         } else {
244             if($conf['mysql']['admin_password'] == '') {
02bf99 245                 caselog("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." ".escapeshellarg($conf['mysql']['database'])." < '".ISPC_INSTALL_ROOT."/install/sql/ispconfig3.sql' &> /dev/null",
b1a6a5 246                     __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql');
532ae5 247             } else {
02bf99 248                 caselog("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -p".escapeshellarg($conf['mysql']['admin_password'])." ".escapeshellarg($conf['mysql']['database'])." < '".ISPC_INSTALL_ROOT."/install/sql/ispconfig3.sql' &> /dev/null",
b1a6a5 249                     __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql');
532ae5 250             }
L 251             $db_tables = $this->db->getTables();
252             if(count($db_tables) == 0) {
253                 $this->error('Unable to load SQL-Dump into database table.');
254             }
255
256             //* Load system.ini into the sys_ini table
2af58c 257             $system_ini = rf('tpl/system.ini.master');
MC 258             $this->db->query("UPDATE sys_ini SET config = ? WHERE sysini_id = 1", $system_ini);
532ae5 259
L 260         }
261     }
262
263     //** Create the server record in the database
264     public function add_database_server_record() {
265
266         global $conf;
267
268         if($conf['mysql']['host'] == 'localhost') {
269             $from_host = 'localhost';
270         } else {
271             $from_host = $conf['hostname'];
272         }
273
274         // Delete ISPConfig user in the local database, in case that it exists
9c87a0 275         $this->db->query("DROP USER ?@?", $conf['mysql']['ispconfig_user'], $from_host);
3dded7 276         $this->db->query("DROP DATABASE IF EXISTS ?", $conf['mysql']['database']);
532ae5 277
L 278         //* Create the ISPConfig database user in the local database
2af58c 279         $query = 'GRANT SELECT, INSERT, UPDATE, DELETE ON ?? TO ?@? IDENTIFIED BY ?';
MC 280         if(!$this->db->query($query, $conf['mysql']['database'] . ".*", $conf['mysql']['ispconfig_user'], $from_host, $conf['mysql']['ispconfig_password'])) {
532ae5 281             $this->error('Unable to create database user: '.$conf['mysql']['ispconfig_user'].' Error: '.$this->db->errorMessage);
L 282         }
283
284         //* Set the database name in the DB library
305dda 285         $this->db->setDBName($conf['mysql']['database']);
532ae5 286
L 287         $tpl_ini_array = ini_to_array(rf('tpl/server.ini.master'));
288
289         //* Update further distribution specific parameters for server config here
290         //* HINT: Every line added here has to be added in update.lib.php too!!
291         $tpl_ini_array['web']['vhost_conf_dir'] = $conf['apache']['vhost_conf_dir'];
292         $tpl_ini_array['web']['vhost_conf_enabled_dir'] = $conf['apache']['vhost_conf_enabled_dir'];
293         $tpl_ini_array['jailkit']['jailkit_chroot_app_programs'] = $conf['jailkit']['jailkit_chroot_app_programs'];
294         $tpl_ini_array['fastcgi']['fastcgi_phpini_path'] = $conf['fastcgi']['fastcgi_phpini_path'];
295         $tpl_ini_array['fastcgi']['fastcgi_starter_path'] = $conf['fastcgi']['fastcgi_starter_path'];
526b99 296         $tpl_ini_array['fastcgi']['fastcgi_bin'] = $conf['fastcgi']['fastcgi_bin'];
532ae5 297         $tpl_ini_array['server']['hostname'] = $conf['hostname'];
L 298         $tpl_ini_array['server']['ip_address'] = @gethostbyname($conf['hostname']);
299         $tpl_ini_array['web']['website_basedir'] = $conf['web']['website_basedir'];
300         $tpl_ini_array['web']['website_path'] = $conf['web']['website_path'];
301         $tpl_ini_array['web']['website_symlinks'] = $conf['web']['website_symlinks'];
302         $tpl_ini_array['cron']['crontab_dir'] = $conf['cron']['crontab_dir'];
303         $tpl_ini_array['web']['security_level'] = 20;
304         $tpl_ini_array['web']['user'] = $conf['apache']['user'];
305         $tpl_ini_array['web']['group'] = $conf['apache']['group'];
306         $tpl_ini_array['web']['php_ini_path_apache'] = $conf['apache']['php_ini_path_apache'];
307         $tpl_ini_array['web']['php_ini_path_cgi'] = $conf['apache']['php_ini_path_cgi'];
308         $tpl_ini_array['mail']['pop3_imap_daemon'] = ($conf['dovecot']['installed'] == true)?'dovecot':'courier';
309         $tpl_ini_array['mail']['mail_filter_syntax'] = ($conf['dovecot']['installed'] == true)?'sieve':'maildrop';
310         $tpl_ini_array['dns']['bind_user'] = $conf['bind']['bind_user'];
311         $tpl_ini_array['dns']['bind_group'] = $conf['bind']['bind_group'];
312         $tpl_ini_array['dns']['bind_zonefiles_dir'] = $conf['bind']['bind_zonefiles_dir'];
313         $tpl_ini_array['dns']['named_conf_path'] = $conf['bind']['named_conf_path'];
314         $tpl_ini_array['dns']['named_conf_local_path'] = $conf['bind']['named_conf_local_path'];
a8ccf6 315
dba68f 316         $tpl_ini_array['web']['nginx_vhost_conf_dir'] = $conf['nginx']['vhost_conf_dir'];
T 317         $tpl_ini_array['web']['nginx_vhost_conf_enabled_dir'] = $conf['nginx']['vhost_conf_enabled_dir'];
318         $tpl_ini_array['web']['nginx_user'] = $conf['nginx']['user'];
319         $tpl_ini_array['web']['nginx_group'] = $conf['nginx']['group'];
320         $tpl_ini_array['web']['nginx_cgi_socket'] = $conf['nginx']['cgi_socket'];
321         $tpl_ini_array['web']['php_fpm_init_script'] = $conf['nginx']['php_fpm_init_script'];
322         $tpl_ini_array['web']['php_fpm_ini_path'] = $conf['nginx']['php_fpm_ini_path'];
323         $tpl_ini_array['web']['php_fpm_pool_dir'] = $conf['nginx']['php_fpm_pool_dir'];
324         $tpl_ini_array['web']['php_fpm_start_port'] = $conf['nginx']['php_fpm_start_port'];
325         $tpl_ini_array['web']['php_fpm_socket_dir'] = $conf['nginx']['php_fpm_socket_dir'];
a8ccf6 326
80e3c9 327         if ($conf['nginx']['installed'] == true) {
4ffb51 328             $tpl_ini_array['web']['server_type'] = 'nginx';
F 329             $tpl_ini_array['global']['webserver'] = 'nginx';
80e3c9 330         }
a8ccf6 331
532ae5 332         if (array_key_exists('awstats', $conf)) {
L 333             foreach ($conf['awstats'] as $aw_sett => $aw_value) {
334                 $tpl_ini_array['web']['awstats_'.$aw_sett] = $aw_value;
335             }
336         }
337
338         $server_ini_content = array_to_ini($tpl_ini_array);
075732 339         
532ae5 340         $mail_server_enabled = ($conf['services']['mail'])?1:0;
L 341         $web_server_enabled = ($conf['services']['web'])?1:0;
342         $dns_server_enabled = ($conf['services']['dns'])?1:0;
343         $file_server_enabled = ($conf['services']['file'])?1:0;
344         $db_server_enabled = ($conf['services']['db'])?1:0;
522ef8 345         $vserver_server_enabled = ($conf['openvz']['installed'])?1:0;
c91bdc 346         $proxy_server_enabled = (isset($conf['services']['proxy']) && $conf['services']['proxy'])?1:0;
T 347         $firewall_server_enabled = (isset($conf['services']['firewall']) && $conf['services']['firewall'])?1:0;
a8ccf6 348
532ae5 349         //** Get the database version number based on the patchfiles
L 350         $found = true;
351         $current_db_version = 1;
352         while($found == true) {
353             $next_db_version = intval($current_db_version + 1);
354             $patch_filename = realpath(dirname(__FILE__).'/../').'/sql/incremental/upd_'.str_pad($next_db_version, 4, '0', STR_PAD_LEFT).'.sql';
355             if(is_file($patch_filename)) {
356                 $current_db_version = $next_db_version;
357             } else {
358                 $found = false;
359             }
360         }
361         $current_db_version = intval($current_db_version);
362
363
364         if($conf['mysql']['master_slave_setup'] == 'y') {
365
366             //* Insert the server record in master DB
2af58c 367             $sql = "INSERT INTO `server` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (1, 1, 'riud', 'riud', 'r', ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, ?, ?, ?);";
MC 368             $this->dbmaster->query($sql, $conf['hostname'], $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $server_ini_content, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);
532ae5 369             $conf['server_id'] = $this->dbmaster->insertID();
L 370             $conf['server_id'] = $conf['server_id'];
371
372             //* Insert the same record in the local DB
061295 373             $sql = "INSERT INTO `server` (`server_id`, `sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (?,1, 1, 'riud', 'riud', 'r', ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, ?, ?, ?);";
2af58c 374             $this->db->query($sql, $conf['server_id'], $conf['hostname'], $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $server_ini_content, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);
532ae5 375
L 376             //* username for the ispconfig user
377             $conf['mysql']['master_ispconfig_user'] = 'ispcsrv'.$conf['server_id'];
378
379             $this->grant_master_database_rights();
380
381         } else {
382             //* Insert the server, if its not a mster / slave setup
2af58c 383             $sql = "INSERT INTO `server` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (1, 1, 'riud', 'riud', 'r', ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, ?, ?, ?);";
MC 384             $this->db->query($sql, $conf['hostname'], $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $server_ini_content, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);
532ae5 385             $conf['server_id'] = $this->db->insertID();
L 386             $conf['server_id'] = $conf['server_id'];
387         }
388
389
390     }
d22277 391     
MB 392     public function detect_ips(){
393         global $conf;
394
395         exec("ip addr show | awk '/global/ { print $2 }' | cut -d '/' -f 1", $output, $retval);
396         
397         if($retval == 0){
398             if(is_array($output) && !empty($output)){
399                 foreach($output as $line){
400                     $line = trim($line);
401                     $ip_type = '';
402                     if (filter_var($line, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
403                         $ip_type = 'IPv4';
404                     }
405                     if (filter_var($line, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
406                         $ip_type = 'IPv6';
407                     }
408                     if($ip_type == '') continue;
409                     if($this->db->dbHost != $this->dbmaster->dbHost){
410                         $this->dbmaster->query('INSERT INTO server_ip (
411                             sys_userid, sys_groupid, sys_perm_user, sys_perm_group,
412                             sys_perm_other, server_id, client_id, ip_type, ip_address,
413                             virtualhost, virtualhost_port
414                         ) VALUES (
415                             1,
416                             1,
417                             "riud",
418                             "riud",
419                             "",
18093f 420                             ?,
d22277 421                             0,
18093f 422                             ?,
MB 423                             ?,
d22277 424                             "y",
MB 425                             "80,443"
18093f 426                         )', $conf['server_id'], $ip_type, $line);
d22277 427                         $server_ip_id = $this->dbmaster->insertID();
MB 428                         $this->db->query('INSERT INTO server_ip (
429                             server_php_id, sys_userid, sys_groupid, sys_perm_user, sys_perm_group,
430                             sys_perm_other, server_id, client_id, ip_type, ip_address,
431                             virtualhost, virtualhost_port
432                         ) VALUES (
18093f 433                             ?,
d22277 434                             1,
MB 435                             1,
436                             "riud",
437                             "riud",
438                             "",
18093f 439                             ?,
d22277 440                             0,
18093f 441                             ?,
MB 442                             ?,
d22277 443                             "y",
MB 444                             "80,443"
18093f 445                         )', $server_ip_id, $conf['server_id'], $ip_type, $line);
d22277 446                     } else {
MB 447                         $this->db->query('INSERT INTO server_ip (
448                             sys_userid, sys_groupid, sys_perm_user, sys_perm_group,
449                             sys_perm_other, server_id, client_id, ip_type, ip_address,
450                             virtualhost, virtualhost_port
451                         ) VALUES (
452                             1,
453                             1,
454                             "riud",
455                             "riud",
456                             "",
18093f 457                             ?,
d22277 458                             0,
18093f 459                             ?,
MB 460                             ?,
d22277 461                             "y",
MB 462                             "80,443"
18093f 463                         )', $conf['server_id'], $ip_type, $line);
d22277 464                     }
MB 465                 }
466             }
467         }
468     }
532ae5 469
100d41 470     public function grant_master_database_rights($verbose = false) {
532ae5 471         global $conf;
L 472
473         /*
474          * The following code is a little bit tricky:
475          * * If we HAVE a master-slave - Setup then the client has to grant the rights for himself
476          *   at the master.
477          * * If we DO NOT have a master-slave - Setup then we have two possibilities
478          *   1) it is a single server
479          *   2) it is the MASTER of n clients
480         */
481         $hosts = array();
a8ccf6 482
532ae5 483         if($conf['mysql']['master_slave_setup'] == 'y') {
L 484             /*
485              * it is a master-slave - Setup so the slave has to grant its rights in the master
486              * database
487              */
488
489             //* insert the ispconfig user in the remote server
490             $from_host = $conf['hostname'];
491             $from_ip = gethostbyname($conf['hostname']);
a8ccf6 492
532ae5 493             $hosts[$from_host]['user'] = $conf['mysql']['master_ispconfig_user'];
L 494             $hosts[$from_host]['db'] = $conf['mysql']['master_database'];
495             $hosts[$from_host]['pwd'] = $conf['mysql']['master_ispconfig_password'];
496
497             $hosts[$from_ip]['user'] = $conf['mysql']['master_ispconfig_user'];
498             $hosts[$from_ip]['db'] = $conf['mysql']['master_database'];
499             $hosts[$from_ip]['pwd'] = $conf['mysql']['master_ispconfig_password'];
500         } else{
501             /*
502              * it is NOT a master-slave - Setup so we have to find out all clients and their
503              * host
504              */
505             $query = "SELECT Host, User FROM mysql.user WHERE User like 'ispcsrv%' ORDER BY User, Host";
506             $data = $this->dbmaster->queryAllRecords($query);
507             if($data === false) {
508                 $this->error('Unable to get the user rights: '.$value['db'].' Error: '.$this->dbmaster->errorMessage);
509             }
510             foreach ($data as $item){
511                 $hosts[$item['Host']]['user'] = $item['User'];
512                 $hosts[$item['Host']]['db'] = $conf['mysql']['master_database'];
513                 $hosts[$item['Host']]['pwd'] = ''; // the user already exists, so we need no pwd!
514             }
515         }
a8ccf6 516
532ae5 517         if(count($hosts) > 0) {
b1a6a5 518             foreach($hosts as $host => $value) {
MC 519                 /*
532ae5 520              * If a pwd exists, this means, we have to add the new user (and his pwd).
L 521              * if not, the user already exists and we do not need the pwd
522              */
b1a6a5 523                 if ($value['pwd'] != ''){
2af58c 524                     $query = "CREATE USER ?@? IDENTIFIED BY ?";
b1a6a5 525                     if ($verbose){
MC 526                         echo "\n\n" . $query ."\n";
527                     }
2af58c 528                     $this->dbmaster->query($query, $value['user'], $host, $value['pwd']); // ignore the error
b1a6a5 529                 }
MC 530
531                 /*
532              *  Try to delete all rights of the user in case that it exists.
533              *  In Case that it will not exist, do nothing (ignore the error!)
534              */
2af58c 535                 $query = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM ?@?";
100d41 536                 if ($verbose){
V 537                     echo "\n\n" . $query ."\n";
538                 }
2af58c 539                 $this->dbmaster->query($query, $value['user'], $host); // ignore the error
b1a6a5 540
MC 541                 //* Create the ISPConfig database user in the remote database
2af58c 542                 $query = "GRANT SELECT ON ?? TO ?@?";
b1a6a5 543                 if ($verbose){
MC 544                     echo $query ."\n";
545                 }
2af58c 546                 if(!$this->dbmaster->query($query, $value['db'] . '.server', $value['user'], $host)) {
b1a6a5 547                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 548                 }
549
2af58c 550                 $query = "GRANT SELECT, INSERT ON ?? TO ?@?";
b1a6a5 551                 if ($verbose){
MC 552                     echo $query ."\n";
553                 }
2af58c 554                 if(!$this->dbmaster->query($query, $value['db'] . '.sys_log', $value['user'], $host)) {
b1a6a5 555                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 556                 }
557
2af58c 558                 $query = "GRANT SELECT, UPDATE(`status`, `error`) ON ?? TO ?@?";
b1a6a5 559                 if ($verbose){
MC 560                     echo $query ."\n";
561                 }
2af58c 562                 if(!$this->dbmaster->query($query, $value['db'] . '.sys_datalog', $value['user'], $host)) {
b1a6a5 563                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 564                 }
565
2af58c 566                 $query = "GRANT SELECT, UPDATE(`status`) ON ?? TO ?@?";
b1a6a5 567                 if ($verbose){
MC 568                     echo $query ."\n";
569                 }
2af58c 570                 if(!$this->dbmaster->query($query, $value['db'] . '.software_update_inst', $value['user'], $host)) {
b1a6a5 571                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 572                 }
573
2af58c 574                 $query = "GRANT SELECT, UPDATE(`updated`) ON ?? TO ?@?";
b1a6a5 575                 if ($verbose){
MC 576                     echo $query ."\n";
577                 }
2af58c 578                 if(!$this->dbmaster->query($query, $value['db'] . '.server', $value['user'], $host)) {
b1a6a5 579                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 580                 }
581
2af58c 582                 $query = "GRANT SELECT, UPDATE (`ssl_request`, `ssl_cert`, `ssl_action`, `ssl_key`) ON ?? TO ?@?";
b1a6a5 583                 if ($verbose){
MC 584                     echo $query ."\n";
585                 }
2af58c 586                 if(!$this->dbmaster->query($query, $value['db'] . '.web_domain', $value['user'], $host)) {
b1a6a5 587                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 588                 }
589
2af58c 590                 $query = "GRANT SELECT ON ?? TO ?@?";
b1a6a5 591                 if ($verbose){
MC 592                     echo $query ."\n";
593                 }
2af58c 594                 if(!$this->dbmaster->query($query, $value['db'] . '.sys_group', $value['user'], $host)) {
b1a6a5 595                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 596                 }
597
2af58c 598                 $query = "GRANT SELECT, UPDATE (`action_state`, `response`) ON ?? TO ?@?";
b1a6a5 599                 if ($verbose){
MC 600                     echo $query ."\n";
601                 }
2af58c 602                 if(!$this->dbmaster->query($query, $value['db'] . '.sys_remoteaction', $value['user'], $host)) {
b1a6a5 603                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 604                 }
605
2af58c 606                 $query = "GRANT SELECT, INSERT , DELETE ON ?? TO ?@?";
b1a6a5 607                 if ($verbose){
MC 608                     echo $query ."\n";
609                 }
2af58c 610                 if(!$this->dbmaster->query($query, $value['db'] . '.monitor_data', $value['user'], $host)) {
b1a6a5 611                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 612                 }
613
2af58c 614                 $query = "GRANT SELECT, INSERT, UPDATE ON ?? TO ?@?";
b1a6a5 615                 if ($verbose){
MC 616                     echo $query ."\n";
617                 }
2af58c 618                 if(!$this->dbmaster->query($query, $value['db'] . '.mail_traffic', $value['user'], $host)) {
b1a6a5 619                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 620                 }
621
2af58c 622                 $query = "GRANT SELECT, INSERT, UPDATE ON ?? TO ?@?";
b1a6a5 623                 if ($verbose){
MC 624                     echo $query ."\n";
625                 }
2af58c 626                 if(!$this->dbmaster->query($query, $value['db'] . '.web_traffic', $value['user'], $host)) {
b1a6a5 627                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 628                 }
629
2af58c 630                 $query = "GRANT SELECT, UPDATE, DELETE ON ?? TO ?@?";
e92eda 631                 if ($verbose){
TB 632                     echo $query ."\n";
633                 }
2af58c 634                 if(!$this->dbmaster->query($query, $value['db'] . '.aps_instances', $value['user'], $host)) {
e92eda 635                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
TB 636                 }
637                 
2af58c 638                 $query = "GRANT SELECT, DELETE ON ?? TO ?@?";
b1a6a5 639                 if ($verbose){
MC 640                     echo $query ."\n";
641                 }
2af58c 642                 if(!$this->dbmaster->query($query, $value['db'] . '.aps_instances_settings', $value['user'], $host)) {
b1a6a5 643                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 644                 }
645
2af58c 646                 $query = "GRANT SELECT, INSERT, DELETE ON ?? TO ?@?";
b1a6a5 647                 if ($verbose){
MC 648                     echo $query ."\n";
649                 }
2af58c 650                 if(!$this->dbmaster->query($query, $value['db'] . '.web_backup', $value['user'], $host)) {
b1a6a5 651                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
MC 652                 }
653
2af58c 654                 $query = "GRANT SELECT, INSERT, DELETE ON ?? TO ?@?";
2dc842 655                 if ($verbose){
FS 656                     echo $query ."\n";
657                 }
2af58c 658                 if(!$this->dbmaster->query($query, $value['db'] . '.mail_backup', $value['user'], $host)) {
2dc842 659                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
FS 660                 }
9af8f6 661                 
994f32 662                 $query = "GRANT SELECT, UPDATE(`dnssec_initialized`, `dnssec_info`, `dnssec_last_signed`) ON ?? TO ?@?";
9af8f6 663                 if ($verbose){
AT 664                     echo $query ."\n";
665                 }
666                 if(!$this->dbmaster->query($query, $value['db'] . '.dns_soa', $value['user'], $host)) {
667                     $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
668                 }
669
532ae5 670             }
L 671
672         }
673
674     }
675
676     //** writes postfix configuration files
677     public function process_postfix_config($configfile) {
678         global $conf;
679
680         $config_dir = $conf['postfix']['config_dir'].'/';
681         $full_file_name = $config_dir.$configfile;
682         //* Backup exiting file
683         if(is_file($full_file_name)) {
684             copy($full_file_name, $config_dir.$configfile.'~');
685         }
615a0a 686         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 687         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 688         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
689         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
690         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
691         $content = str_replace('{server_id}', $conf['server_id'], $content);
692         wf($full_file_name, $content);
693     }
694
695     public function configure_jailkit() {
696         global $conf;
697
698         $cf = $conf['jailkit'];
699         $config_dir = $cf['config_dir'];
700         $jk_init = $cf['jk_init'];
701         $jk_chrootsh = $cf['jk_chrootsh'];
702
703         if (is_dir($config_dir)) {
704             if(is_file($config_dir.'/'.$jk_init)) copy($config_dir.'/'.$jk_init, $config_dir.'/'.$jk_init.'~');
705             if(is_file($config_dir.'/'.$jk_chrootsh.'.master')) copy($config_dir.'/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh.'~');
b1a6a5 706
MC 707             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master')) {
708                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master', $config_dir.'/'.$jk_init);
709             } else {
710                 copy('tpl/'.$jk_init.'.master', $config_dir.'/'.$jk_init);
711             }
712             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master')) {
713                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh);
714             } else {
715                 copy('tpl/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh);
716             }
532ae5 717         }
a8ccf6 718
edf806 719         //* help jailkit fo find its ini files
T 720         if(!is_link('/usr/jk_socketd.ini')) exec('ln -s /etc/jailkit/jk_socketd.ini /usr/jk_socketd.ini');
721         if(!is_link('/usr/jk_init.ini')) exec('ln -s /etc/jailkit/jk_init.ini /usr/jk_init.ini');
532ae5 722
L 723     }
a8ccf6 724
532ae5 725     public function configure_mailman($status = 'insert') {
L 726         global $conf;
727
728         $config_dir = $conf['mailman']['config_dir'].'/';
729         $full_file_name = $config_dir.'mm_cfg.py';
730         //* Backup exiting file
731         if(is_file($full_file_name)) {
732             copy($full_file_name, $config_dir.'mm_cfg.py~');
733         }
a8ccf6 734
532ae5 735         // load files
615a0a 736         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mm_cfg.py.master', 'tpl/mm_cfg.py.master');
532ae5 737         $old_file = rf($full_file_name);
a8ccf6 738
532ae5 739         $old_options = array();
a8ccf6 740         $lines = explode("\n", $old_file);
532ae5 741         foreach ($lines as $line)
L 742         {
8fe9ab 743             if (trim($line) != '' && substr($line, 0, 1) != '#')
532ae5 744             {
8fe9ab 745                 @list($key, $value) = @explode("=", $line);
86e699 746                 if (isset($value) && $value !== '')
532ae5 747                 {
L 748                     $key = rtrim($key);
749                     $old_options[$key] = trim($value);
750                 }
751             }
752         }
a8ccf6 753
532ae5 754         $virtual_domains = '';
L 755         if($status == 'update')
756         {
757             // create virtual_domains list
758             $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain");
a8ccf6 759
8fe9ab 760             if(is_array($domainAll)) {
b1a6a5 761                 foreach($domainAll as $domain)
MC 762                 {
763                     if ($domainAll[0]['domain'] == $domain['domain'])
764                         $virtual_domains .= "'".$domain['domain']."'";
765                     else
766                         $virtual_domains .= ", '".$domain['domain']."'";
767                 }
8fe9ab 768             }
532ae5 769         }
L 770         else
771             $virtual_domains = "' '";
a8ccf6 772
532ae5 773         $content = str_replace('{hostname}', $conf['hostname'], $content);
46c775 774         if(!isset($old_options['DEFAULT_SERVER_LANGUAGE'])) $old_options['DEFAULT_SERVER_LANGUAGE'] = '';
532ae5 775         $content = str_replace('{default_language}', $old_options['DEFAULT_SERVER_LANGUAGE'], $content);
L 776         $content = str_replace('{virtual_domains}', $virtual_domains, $content);
b1a6a5 777
532ae5 778         wf($full_file_name, $content);
b1a6a5 779
cc6568 780         //* Write virtual_to_transport.sh script
H 781         $config_dir = $conf['mailman']['config_dir'].'/';
782         $full_file_name = $config_dir.'virtual_to_transport.sh';
b1a6a5 783
cc6568 784         //* Backup exiting virtual_to_transport.sh script
H 785         if(is_file($full_file_name)) {
786             copy($full_file_name, $config_dir.'virtual_to_transport.sh~');
787         }
b1a6a5 788
cc6568 789         if(is_dir('/etc/mailman')) {
615a0a 790             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) {
b1a6a5 791                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name);
MC 792             } else {
793                 copy('tpl/mailman-virtual_to_transport.sh', $full_file_name);
794             }
223c56 795             chgrp($full_file_name, $this->mailman_group);
d22542 796             chmod($full_file_name, 0755);
cc6568 797         }
b1a6a5 798
cc6568 799         //* Create aliasaes
H 800         exec('/usr/lib/mailman/bin/genaliases 2>/dev/null');
b1a6a5 801
223c56 802         if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman');
MC 803         exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman');
532ae5 804     }
L 805
9c6782 806     public function get_postfix_service($service, $type) {
FS 807         global $conf;
808
809         exec("postconf -M", $out, $ret);
810
811         if ($ret === 0) { //* with postfix >= 2.9 we can detect configured services with postconf
812             unset($out);
813             exec ("postconf -M $service/$type 2> /dev/null", $out, $ret); //* Postfix >= 2.11
814             if (!isset($out[0])) { //* try Postfix 2.9
815                 exec ("postconf -M $service.$type 2> /dev/null", $out, $ret);
816             }
817             $postfix_service = @($out[0]=='')?false:true;
818         } else { //* fallback - Postfix < 2.9
819             rf($conf['postfix']['config_dir'].'/master.cf');
820             $regex = '/[^#]'.$service.'.*.'.$type.'.*/';
821             $postfix_service = @(!preg_match($regex, $content))?true:false;
822         }
823
824         return $postfix_service;
bd5d26 825     }
FS 826
532ae5 827     public function configure_postfix($options = '') {
b04e82 828         global $conf,$autoinstall;
532ae5 829         $cf = $conf['postfix'];
L 830         $config_dir = $cf['config_dir'];
831
832         if(!is_dir($config_dir)) {
833             $this->error("The postfix configuration directory '$config_dir' does not exist.");
834         }
835
836         //* mysql-virtual_domains.cf
837         $this->process_postfix_config('mysql-virtual_domains.cf');
838
839         //* mysql-virtual_forwardings.cf
840         $this->process_postfix_config('mysql-virtual_forwardings.cf');
841
842         //* mysql-virtual_mailboxes.cf
843         $this->process_postfix_config('mysql-virtual_mailboxes.cf');
844
845         //* mysql-virtual_email2email.cf
846         $this->process_postfix_config('mysql-virtual_email2email.cf');
847
848         //* mysql-virtual_transports.cf
849         $this->process_postfix_config('mysql-virtual_transports.cf');
850
851         //* mysql-virtual_recipient.cf
852         $this->process_postfix_config('mysql-virtual_recipient.cf');
853
854         //* mysql-virtual_sender.cf
855         $this->process_postfix_config('mysql-virtual_sender.cf');
856
03b633 857         //* mysql-virtual_sender_login_maps.cf
D 858         $this->process_postfix_config('mysql-virtual_sender_login_maps.cf');
859
532ae5 860         //* mysql-virtual_client.cf
L 861         $this->process_postfix_config('mysql-virtual_client.cf');
862
863         //* mysql-virtual_relaydomains.cf
864         $this->process_postfix_config('mysql-virtual_relaydomains.cf');
865
866         //* mysql-virtual_relayrecipientmaps.cf
867         $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf');
3361d7 868         
R 869         //* mysql-virtual_outgoing_bcc.cf
870         $this->process_postfix_config('mysql-virtual_outgoing_bcc.cf');
532ae5 871
75722e 872                 //* mysql-virtual_policy_greylist.cf
D 873                 $this->process_postfix_config('mysql-virtual_policy_greylist.cf');
874
ec5716 875         //* postfix-dkim
T 876         $full_file_name=$config_dir.'/tag_as_originating.re';
ae3cf8 877         if(is_file($full_file_name)) copy($full_file_name, $full_file_name.'~');
b1a6a5 878         wf($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10026');
ec5716 879
T 880         $full_file_name=$config_dir.'/tag_as_foreign.re';
ae3cf8 881         if(is_file($full_file_name)) copy($full_file_name, $full_file_name.'~');
b1a6a5 882         wf($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10024');
ec5716 883
532ae5 884         //* Changing mode and group of the new created config files.
L 885         caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
b1a6a5 886             __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed');
532ae5 887         caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
b1a6a5 888             __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed');
532ae5 889
L 890         //* Creating virtual mail user and group
891         $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname'];
892         if(!is_group($cf['vmail_groupname'])) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
893
894         $command = 'useradd -g '.$cf['vmail_groupname'].' -u '.$cf['vmail_userid'].' '.$cf['vmail_username'].' -d '.$cf['vmail_mailbox_base'].' -m';
895         if(!is_user($cf['vmail_username'])) caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a8ccf6 896
b67344 897         //* These postconf commands will be executed on installation and update
2af58c 898         $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . '.server', $conf['server_id']);
a296ae 899         $server_ini_array = ini_to_array(stripslashes($server_ini_rec['config']));
M 900         unset($server_ini_rec);
901
902         //* If there are RBL's defined, format the list and add them to smtp_recipient_restrictions to prevent removeal after an update
903         $rbl_list = '';
6882ab 904         if (@isset($server_ini_array['mail']['realtime_blackhole_list']) && $server_ini_array['mail']['realtime_blackhole_list'] != '') {
b1a6a5 905             $rbl_hosts = explode(",", str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list']));
a296ae 906             foreach ($rbl_hosts as $key => $value) {
M 907                 $rbl_list .= ", reject_rbl_client ". $value;
908             }
909         }
910         unset($rbl_hosts);
b1a6a5 911
75722e 912         //* If Postgrey is installed, configure it
D 913         $greylisting = '';
914         if($conf['postgrey']['installed'] == true) {
20f478 915             $greylisting = ', check_recipient_access mysql:/etc/postfix/mysql-virtual_policy_greylist.cf';
75722e 916         }
20f478 917         
D 918         $reject_sender_login_mismatch = '';
919         if(isset($server_ini_array['mail']['reject_sender_login_mismatch']) && ($server_ini_array['mail']['reject_sender_login_mismatch'] == 'y')) {
920             $reject_sender_login_mismatch = ', reject_authenticated_sender_login_mismatch';
921         }
922         unset($server_ini_array);
75722e 923         
c757ee 924         $tmp = str_replace('.','\.',$conf['hostname']);
JN 925
b1a6a5 926         $postconf_placeholders = array('{config_dir}' => $config_dir,
MC 927             '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'],
928             '{vmail_userid}' => $cf['vmail_userid'],
929             '{vmail_groupid}' => $cf['vmail_groupid'],
75722e 930             '{rbl_list}' => $rbl_list,
D 931             '{greylisting}' => $greylisting,
20f478 932             '{reject_slm}' => $reject_sender_login_mismatch,
c757ee 933             '{myhostname}' => $tmp,
75722e 934         );
b1a6a5 935
MC 936         $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_postfix.conf.master', 'tpl/debian_postfix.conf.master');
937         $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders);
938         $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines
a8ccf6 939
b67344 940         //* These postconf commands will be executed on installation only
T 941         if($this->is_update == false) {
b1a6a5 942             $postconf_commands = array_merge($postconf_commands, array(
MC 943                     'myhostname = '.$conf['hostname'],
944                     'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain',
945                     'mynetworks = 127.0.0.0/8 [::1]/128'
946                 ));
b67344 947         }
532ae5 948
L 949         //* Create the header and body check files
950         touch($config_dir.'/header_checks');
951         touch($config_dir.'/mime_header_checks');
952         touch($config_dir.'/nested_header_checks');
953         touch($config_dir.'/body_checks');
a8ccf6 954
532ae5 955         //* Create the mailman files
cc6568 956         if(!is_dir('/var/lib/mailman/data')) exec('mkdir -p /var/lib/mailman/data');
5378e9 957         if(!is_file('/var/lib/mailman/data/aliases')) touch('/var/lib/mailman/data/aliases');
T 958         exec('postalias /var/lib/mailman/data/aliases');
959         if(!is_file('/var/lib/mailman/data/virtual-mailman')) touch('/var/lib/mailman/data/virtual-mailman');
d4d965 960         exec('postmap /var/lib/mailman/data/virtual-mailman');
cc6568 961         if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman');
H 962         exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman');
532ae5 963
709aed 964         //* Create auxillary postfix conf files
JN 965         $configfile = 'helo_access';
966         if(is_file($config_dir.'/'.$configfile)) {
967             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
c757ee 968             chmod($config_dir.'/'.$configfile.'~', 0400);
709aed 969         }
JN 970         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
971         $content = strtr($content, $postconf_placeholders);
972         # todo: look up this server's ip addrs and loop through each
973         # todo: look up domains hosted on this server and loop through each
974         wf($config_dir.'/'.$configfile, $content);
975
976         $configfile = 'blacklist_helo';
977         if(is_file($config_dir.'/'.$configfile)) {
978             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
c757ee 979             chmod($config_dir.'/'.$configfile.'~', 0400);
709aed 980         }
JN 981         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
982         $content = strtr($content, $postconf_placeholders);
983         wf($config_dir.'/'.$configfile, $content);
532ae5 984
L 985         //* Make a backup copy of the main.cf file
986         copy($config_dir.'/main.cf', $config_dir.'/main.cf~');
987
988         //* Executing the postconf commands
989         foreach($postconf_commands as $cmd) {
990             $command = "postconf -e '$cmd'";
991             caselog($command." &> /dev/null", __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
992         }
993
b1a6a5 994         if(!stristr($options, 'dont-create-certs')) {
532ae5 995             //* Create the SSL certificate
b04e82 996             if(AUTOINSTALL){
bcd725 997                 $command = 'cd '.$config_dir.'; '
b04e82 998                     ."openssl req -new -subj '/C=".escapeshellcmd($autoinstall['ssl_cert_country'])."/ST=".escapeshellcmd($autoinstall['ssl_cert_state'])."/L=".escapeshellcmd($autoinstall['ssl_cert_locality'])."/O=".escapeshellcmd($autoinstall['ssl_cert_organisation'])."/OU=".escapeshellcmd($autoinstall['ssl_cert_organisation_unit'])."/CN=".escapeshellcmd($autoinstall['ssl_cert_common_name'])."' -outform PEM -out smtpd.cert -newkey rsa:4096 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509";
bcd725 999             } else {
FT 1000                 $command = 'cd '.$config_dir.'; '
1001                     .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:4096 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509';
1002             }
532ae5 1003             exec($command);
L 1004
1005             $command = 'chmod o= '.$config_dir.'/smtpd.key';
1006             caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
1007         }
1008
1009         //** We have to change the permissions of the courier authdaemon directory to make it accessible for maildrop.
1010         $command = 'chmod 755  /var/run/courier/authdaemon/';
1011         if(is_file('/var/run/courier/authdaemon/')) caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
1012
bd5d26 1013         //* Check maildrop service in posfix master.cf
FS 1014         $regex = "/^maildrop   unix.*pipe flags=DRhu user=vmail argv=\\/usr\\/bin\\/maildrop -d ".$cf['vmail_username']." \\$\{extension} \\$\{recipient} \\$\{user} \\$\{nexthop} \\$\{sender}/";
532ae5 1015         $configfile = $config_dir.'/master.cf';
9c6782 1016         if($this->get_postfix_service('maildrop', 'unix')) {
f652c5 1017             exec ("postconf -M maildrop.unix &> /dev/null", $out, $ret);
bd5d26 1018             $change_maildrop_flags = @(preg_match($regex, $out[0]) && $out[0] !='')?false:true;
9c6782 1019         } else {
bd5d26 1020             $change_maildrop_flags = @(preg_match($regex, $configfile))?false:true;
FS 1021         }
1022         if ($change_maildrop_flags) {
1023             //* Change maildrop service in posfix master.cf
1024             if(is_file($config_dir.'/master.cf')) {
1025                 copy($config_dir.'/master.cf', $config_dir.'/master.cf~');
1026             }
1027             if(is_file($config_dir.'/master.cf~')) {
1028                 chmod($config_dir.'/master.cf~', 0400);
1029              }
1030             $configfile = $config_dir.'/master.cf';
1031             $content = rf($configfile);
1032             $content =    str_replace('flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}',
1033                         'flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d '.$cf['vmail_username'].' ${extension} ${recipient} ${user} ${nexthop} ${sender}',
1034                         $content);
1035             wf($configfile, $content);
1036         }
532ae5 1037
L 1038         //* Writing the Maildrop mailfilter file
1039         $configfile = 'mailfilter';
1040         if(is_file($cf['vmail_mailbox_base'].'/.'.$configfile)) {
1041             copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~');
1042         }
615a0a 1043         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1044         $content = str_replace('{dist_postfix_vmail_mailbox_base}', $cf['vmail_mailbox_base'], $content);
L 1045         wf($cf['vmail_mailbox_base'].'/.'.$configfile, $content);
1046
1047         //* Create the directory for the custom mailfilters
1048         if(!is_dir($cf['vmail_mailbox_base'].'/mailfilters')) {
1049             $command = 'mkdir '.$cf['vmail_mailbox_base'].'/mailfilters';
1050             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1051         }
1052
1053         //* Chmod and chown the .mailfilter file
419eb7 1054         $command = 'chown '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 1055         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 1056
419eb7 1057         $command = 'chmod 600 '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 1058         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 1059
1060     }
75722e 1061     
532ae5 1062     public function configure_saslauthd() {
L 1063         global $conf;
a8ccf6 1064
26c0fc 1065         //* Get saslsauthd version
b1a6a5 1066         exec('saslauthd -v 2>&1', $out);
MC 1067         $parts = explode(' ', $out[0]);
26c0fc 1068         $saslversion = $parts[1];
T 1069         unset($parts);
1070         unset($out);
532ae5 1071
0adcbb 1072         if(version_compare($saslversion , '2.1.23', '<=')) {
26c0fc 1073             //* Configfile for saslauthd versions up to 2.1.23
T 1074             $configfile = 'sasl_smtpd.conf';
0adcbb 1075         } else {
FS 1076             //* Configfile for saslauthd versions 2.1.24 and newer
1077             $configfile = 'sasl_smtpd2.conf';
26c0fc 1078         }
a8ccf6 1079
b1a6a5 1080         if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf')) copy($conf['postfix']['config_dir'].'/sasl/smtpd.conf', $conf['postfix']['config_dir'].'/sasl/smtpd.conf~');
532ae5 1081         if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf~')) chmod($conf['postfix']['config_dir'].'/sasl/smtpd.conf~', 0400);
615a0a 1082         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
b1a6a5 1083         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1084         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1085         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1086         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1087         wf($conf['postfix']['config_dir'].'/sasl/smtpd.conf', $content);
532ae5 1088
L 1089         // TODO: Chmod and chown on the config file
1090
1091
1092         // Recursively create the spool directory
1093         if(!@is_dir('/var/spool/postfix/var/run/saslauthd')) mkdir('/var/spool/postfix/var/run/saslauthd', 0755, true);
1094
1095         // Edit the file /etc/default/saslauthd
1096         $configfile = $conf['saslauthd']['config'];
b1a6a5 1097         if(is_file($configfile)) copy($configfile, $configfile.'~');
532ae5 1098         if(is_file($configfile.'~')) chmod($configfile.'~', 0400);
L 1099         $content = rf($configfile);
b1a6a5 1100         $content = str_replace('START=no', 'START=yes', $content);
532ae5 1101         // Debian
b1a6a5 1102         $content = str_replace('OPTIONS="-c"', 'OPTIONS="-m /var/spool/postfix/var/run/saslauthd -r"', $content);
532ae5 1103         // Ubuntu
b1a6a5 1104         $content = str_replace('OPTIONS="-c -m /var/run/saslauthd"', 'OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"', $content);
MC 1105         wf($configfile, $content);
532ae5 1106
L 1107         // Edit the file /etc/init.d/saslauthd
1108         $configfile = $conf['init_scripts'].'/'.$conf['saslauthd']['init_script'];
1109         $content = rf($configfile);
b1a6a5 1110         $content = str_replace('PIDFILE=$RUN_DIR/saslauthd.pid', 'PIDFILE="/var/spool/postfix/var/run/${NAME}/saslauthd.pid"', $content);
MC 1111         wf($configfile, $content);
532ae5 1112
L 1113         // add the postfix user to the sasl group (at least necessary for Ubuntu 8.04 and most likely Debian Lenny as well.
1114         exec('adduser postfix sasl');
1115
1116
1117     }
1118
1119     public function configure_pam() {
1120         global $conf;
1121         $pam = $conf['pam'];
1122         //* configure pam for SMTP authentication agains the ispconfig database
1123         $configfile = 'pamd_smtp';
1124         if(is_file($pam.'/smtp'))    copy($pam.'/smtp', $pam.'/smtp~');
1125         if(is_file($pam.'/smtp~'))   chmod($pam.'/smtp~', 0400);
1126
615a0a 1127         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1128         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 1129         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1130         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1131         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1132         wf($pam.'/smtp', $content);
1133         // On some OSes smtp is world readable which allows for reading database information.  Removing world readable rights should have no effect.
1134         if(is_file($pam.'/smtp'))    exec("chmod o= $pam/smtp");
1135         chmod($pam.'/smtp', 0660);
1136         chown($pam.'/smtp', 'daemon');
1137         chgrp($pam.'/smtp', 'daemon');
1138
1139     }
1140
1141     public function configure_courier() {
1142         global $conf;
1143         $config_dir = $conf['courier']['config_dir'];
1144         //* authmysqlrc
1145         $configfile = 'authmysqlrc';
1146         if(is_file($config_dir.'/'.$configfile)) {
1147             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1148         }
1149         chmod($config_dir.'/'.$configfile.'~', 0400);
615a0a 1150         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
b1a6a5 1151         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1152         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1153         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1154         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
82e9b9 1155         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
532ae5 1156         wf($config_dir.'/'.$configfile, $content);
L 1157
1158         chmod($config_dir.'/'.$configfile, 0660);
1159         chown($config_dir.'/'.$configfile, 'daemon');
1160         chgrp($config_dir.'/'.$configfile, 'daemon');
1161
1162         //* authdaemonrc
1163         $configfile = $config_dir.'/authdaemonrc';
1164         if(is_file($configfile)) {
1165             copy($configfile, $configfile.'~');
1166         }
1167         if(is_file($configfile.'~')) {
1168             chmod($configfile.'~', 0400);
1169         }
1170         $content = rf($configfile);
1171         $content = str_replace('authmodulelist="authpam"', 'authmodulelist="authmysql"', $content);
1172         wf($configfile, $content);
1173     }
1174
1175     public function configure_dovecot() {
1176         global $conf;
59baa4 1177         
DM 1178         $virtual_transport = 'dovecot';
8b23f8 1179
FS 1180         $configure_lmtp = false;
59baa4 1181         
DM 1182         // check if virtual_transport must be changed
1183         if ($this->is_update) {
2af58c 1184             $tmp = $this->db->queryOneRecord("SELECT * FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . ".server", $conf['server_id']);
59baa4 1185             $ini_array = ini_to_array(stripslashes($tmp['config']));
DM 1186             // ini_array needs not to be checked, because already done in update.php -> updateDbAndIni()
1187             
1188             if(isset($ini_array['mail']['mailbox_virtual_uidgid_maps']) && $ini_array['mail']['mailbox_virtual_uidgid_maps'] == 'y') {
1189                 $virtual_transport = 'lmtp:unix:private/dovecot-lmtp';
8b23f8 1190                 $configure_lmtp = true;
59baa4 1191             }
DM 1192         }
532ae5 1193
bd5d26 1194         $config_dir = $conf['postfix']['config_dir'];
9c6782 1195
532ae5 1196         //* Configure master.cf and add a line for deliver
9c6782 1197         if(!$this->get_postfix_service('dovecot', 'unix')) {
bd5d26 1198              //* backup
FS 1199             if(is_file($config_dir.'/master.cf')){
1200                 copy($config_dir.'/master.cf', $config_dir.'/master.cf~2');
1201             }
1202             if(is_file($config_dir.'/master.cf~')){
1203                 chmod($config_dir.'/master.cf~2', 0400);
1204             }
1205             //* Configure master.cf and add a line for deliver
1206             $content = rf($conf["postfix"]["config_dir"].'/master.cf');
9c6782 1207             $deliver_content = 'dovecot   unix  -       n       n       -       -       pipe'."\n".'  flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}'."\n";
bd5d26 1208             af($config_dir.'/master.cf', $deliver_content);
FS 1209             unset($content);
1210             unset($deliver_content);
532ae5 1211         }
L 1212
1213         //* Reconfigure postfix to use dovecot authentication
1214         // Adding the amavisd commands to the postfix configuration
1215         $postconf_commands = array (
b1a6a5 1216             'dovecot_destination_recipient_limit = 1',
59baa4 1217             'virtual_transport = '.$virtual_transport,
b1a6a5 1218             'smtpd_sasl_type = dovecot',
MC 1219             'smtpd_sasl_path = private/auth'
532ae5 1220         );
L 1221
1222         // Make a backup copy of the main.cf file
b1a6a5 1223         copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~3');
532ae5 1224
L 1225         // Executing the postconf commands
1226         foreach($postconf_commands as $cmd) {
1227             $command = "postconf -e '$cmd'";
1228             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1229         }
1230
31e0d1 1231         //* backup dovecot.conf
bd5d26 1232         $config_dir = $conf['dovecot']['config_dir'];
532ae5 1233         $configfile = 'dovecot.conf';
L 1234         if(is_file($config_dir.'/'.$configfile)) {
1235             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1236         }
a8ccf6 1237
31e0d1 1238         //* Get the dovecot version
b1a6a5 1239         exec('dovecot --version', $tmp);
1fc360 1240         $dovecot_version = $tmp[0];
31e0d1 1241         unset($tmp);
a8ccf6 1242
31e0d1 1243         //* Copy dovecot configuration file
0adcbb 1244         if(version_compare($dovecot_version,1, '<=')) {    //* Dovecot 1.x
FS 1245             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master')) {
1246                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master', $config_dir.'/'.$configfile);
1247             } else {
1248                 copy('tpl/debian_dovecot.conf.master', $config_dir.'/'.$configfile);
1249             }
1250         } else {    //* Dovecot 2.x
b1a6a5 1251             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master')) {
MC 1252                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master', $config_dir.'/'.$configfile);
1253             } else {
1254                 copy('tpl/debian_dovecot2.conf.master', $config_dir.'/'.$configfile);
1255             }
65576f 1256             replaceLine($config_dir.'/'.$configfile, 'postmaster_address = postmaster@example.com', 'postmaster_address = postmaster@'.$conf['hostname'], 1, 0);
0adcbb 1257             if(version_compare($dovecot_version, 2.1, '<')) {
1fc360 1258                 removeLine($config_dir.'/'.$configfile, 'ssl_protocols =');
b1a6a5 1259             }
31e0d1 1260         }
532ae5 1261
8b23f8 1262         //* dovecot-lmtpd
FS 1263         if($configure_lmtp) {
1264             replaceLine($config_dir.'/'.$configfile, 'protocols = imap pop3', 'protocols = imap pop3 lmtp', 1, 0);
1265         }
1266
532ae5 1267         //* dovecot-sql.conf
L 1268         $configfile = 'dovecot-sql.conf';
1269         if(is_file($config_dir.'/'.$configfile)) {
1270             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1271         }
edf806 1272         if(is_file($config_dir.'/'.$configfile.'~')) chmod($config_dir.'/'.$configfile.'~', 0400);
615a0a 1273         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot-sql.conf.master', 'tpl/debian_dovecot-sql.conf.master');
b1a6a5 1274         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1275         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1276         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1277         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
82e9b9 1278         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
032b86 1279         $content = str_replace('{server_id}', $conf['server_id'], $content);
532ae5 1280         wf($config_dir.'/'.$configfile, $content);
L 1281
1282         chmod($config_dir.'/'.$configfile, 0600);
1283         chown($config_dir.'/'.$configfile, 'root');
1284         chgrp($config_dir.'/'.$configfile, 'root');
5e7306 1285         
TB 1286         // Dovecot shall ignore mounts in website directory
7db4cd 1287         if(is_installed('doveadm')) exec("doveadm mount add '/var/www/*' ignore > /dev/null 2> /dev/null");
532ae5 1288
L 1289     }
1290
1291     public function configure_amavis() {
1292         global $conf;
1293
1294         // amavisd user config file
1295         $configfile = 'amavisd_user_config';
b1a6a5 1296         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user')) copy($conf['amavis']['config_dir'].'/conf.d/50-user', $conf['amavis']['config_dir'].'/50-user~');
c83951 1297         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user~')) chmod($conf['amavis']['config_dir'].'/50-user~', 0400);
615a0a 1298         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
b1a6a5 1299         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1300         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1301         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1302         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
1303         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1304         wf($conf['amavis']['config_dir'].'/conf.d/50-user', $content);
c83951 1305         chmod($conf['amavis']['config_dir'].'/conf.d/50-user', 0640);
532ae5 1306
L 1307         // TODO: chmod and chown on the config file
1308
1309
1310         // Adding the amavisd commands to the postfix configuration
864ee2 1311         // Add array for no error in foreach and maybe future options
X 1312         $postconf_commands = array ();
a8ccf6 1313
864ee2 1314         // Check for amavisd -> pure webserver with postfix for mailing without antispam
ac28b5 1315         if ($conf['amavis']['installed']) {
864ee2 1316             $postconf_commands[] = 'content_filter = amavis:[127.0.0.1]:10024';
X 1317             $postconf_commands[] = 'receive_override_options = no_address_mappings';
1318         }
532ae5 1319
L 1320         // Make a backup copy of the main.cf file
b1a6a5 1321         copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~2');
532ae5 1322
L 1323         // Executing the postconf commands
1324         foreach($postconf_commands as $cmd) {
1325             $command = "postconf -e '$cmd'";
1326             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1327         }
1328
9c6782 1329         $config_dir = $conf['postfix']['config_dir'];
bd5d26 1330
FS 1331         // Adding amavis-services to the master.cf file if the service does not already exists
9c6782 1332         $add_amavis = !$this->get_postfix_service('amavis','unix');
FS 1333         $add_amavis_10025 = !$this->get_postfix_service('127.0.0.1:10025','inet');
1334         $add_amavis_10027 = !$this->get_postfix_service('127.0.0.1:10027','inet');
bd5d26 1335
FS 1336         if ($add_amavis || $add_amavis_10025 || $add_amavis_10027) {
1337             //* backup master.cf
1338             if(is_file($config_dir.'/master.cf')) copy($config_dir.'/master.cf', $config_dir.'/master.cf~');
1339             // adjust amavis-config
1340             if($add_amavis) {
1341                 $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', 'tpl/master_cf_amavis.master');
1342                 af($config_dir.'/master.cf', $content);
1343                 unset($content);
1344             }
1345             if ($add_amavis_10025) {
1346                 $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis10025.master', 'tpl/master_cf_amavis10025.master');
1347                 af($config_dir.'/master.cf', $content);
1348                 unset($content);
1349             }
1350             if ($add_amavis_10027) {
1351                 $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis10027.master', 'tpl/master_cf_amavis10027.master');
1352                 af($config_dir.'/master.cf', $content);
1353                 unset($content);
1354             }
44ae08 1355         }
532ae5 1356
L 1357         // Add the clamav user to the amavis group
1358         exec('adduser clamav amavis');
1359
535a69 1360         // Create the director for DKIM-Keys
be6237 1361         if(!is_dir('/var/lib/amavis/dkim')) mkdir('/var/lib/amavis/dkim', 0750, true);
535a69 1362         // get shell-user for amavis
T 1363         $amavis_user=exec('grep -o "^amavis:\|^vscan:" /etc/passwd');
1364         if(!empty($amavis_user)) {
b1a6a5 1365             $amavis_user=rtrim($amavis_user, ":");
44ae08 1366             exec('chown '.$amavis_user.' /var/lib/amavis/dkim');
535a69 1367         }
T 1368         // get shell-group for amavis
1369         $amavis_group=exec('grep -o "^amavis:\|^vscan:" /etc/group');
1370         if(!empty($amavis_group)) {
b1a6a5 1371             $amavis_group=rtrim($amavis_group, ":");
44ae08 1372             exec('chgrp '.$amavis_group.' /var/lib/amavis/dkim');
535a69 1373         }
532ae5 1374     }
L 1375
1376     public function configure_spamassassin() {
1377         global $conf;
1378
1379         //* Enable spamasasssin on debian and ubuntu
1380         $configfile = '/etc/default/spamassassin';
1381         if(is_file($configfile)) {
1382             copy($configfile, $configfile.'~');
1383         }
1384         $content = rf($configfile);
1385         $content = str_replace('ENABLED=0', 'ENABLED=1', $content);
1386         wf($configfile, $content);
1387     }
1388
1389     public function configure_getmail() {
1390         global $conf;
1391
1392         $config_dir = $conf['getmail']['config_dir'];
1393
1394         if(!@is_dir($config_dir)) mkdir(escapeshellcmd($config_dir), 0700, true);
1395
1396         $command = 'useradd -d '.$config_dir.' getmail';
1397         if(!is_user('getmail')) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1398
1399         $command = "chown -R getmail $config_dir";
1400         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1401
1402         $command = "chmod -R 700 $config_dir";
1403         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1404     }
1405
1406
1407     public function configure_pureftpd() {
1408         global $conf;
1409
1410         $config_dir = $conf['pureftpd']['config_dir'];
1411
1412         //* configure pure-ftpd for MySQL authentication against the ispconfig database
1413         $configfile = 'db/mysql.conf';
1414         if(is_file($config_dir.'/'.$configfile)) {
1415             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1416         }
1417         if(is_file($config_dir.'/'.$configfile.'~')) {
1418             chmod($config_dir.'/'.$configfile.'~', 0400);
1419         }
615a0a 1420         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/pureftpd_mysql.conf.master', 'tpl/pureftpd_mysql.conf.master');
532ae5 1421         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 1422         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1423         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1424         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1425         $content = str_replace('{server_id}', $conf['server_id'], $content);
1426         wf($config_dir.'/'.$configfile, $content);
1427         chmod($config_dir.'/'.$configfile, 0600);
1428         chown($config_dir.'/'.$configfile, 'root');
1429         chgrp($config_dir.'/'.$configfile, 'root');
1430         // **enable chrooting
1431         //exec('mkdir -p '.$config_dir.'/conf/ChrootEveryone');
1432         exec('echo "yes" > '.$config_dir.'/conf/ChrootEveryone');
1433         exec('echo "yes" > '.$config_dir.'/conf/BrokenClientsCompatibility');
1434         exec('echo "yes" > '.$config_dir.'/conf/DisplayDotFiles');
1435
1436         if(is_file('/etc/default/pure-ftpd-common')) {
b1a6a5 1437             replaceLine('/etc/default/pure-ftpd-common', 'STANDALONE_OR_INETD=inetd', 'STANDALONE_OR_INETD=standalone', 1, 0);
MC 1438             replaceLine('/etc/default/pure-ftpd-common', 'VIRTUALCHROOT=false', 'VIRTUALCHROOT=true', 1, 0);
532ae5 1439         }
L 1440
1441         if(is_file('/etc/inetd.conf')) {
b1a6a5 1442             replaceLine('/etc/inetd.conf', '/usr/sbin/pure-ftpd-wrapper', '#ftp     stream  tcp     nowait  root    /usr/sbin/tcpd /usr/sbin/pure-ftpd-wrapper', 0, 0);
acdd7a 1443             exec($this->getinitcommand('openbsd-inetd', 'restart'));
33bcd0 1444             //if(is_file($conf['init_scripts'].'/'.'openbsd-inetd')) exec($conf['init_scripts'].'/'.'openbsd-inetd restart');
532ae5 1445         }
L 1446
1447         if(!is_file('/etc/pure-ftpd/conf/DontResolve')) exec('echo "yes" > /etc/pure-ftpd/conf/DontResolve');
1448     }
1449
1450     public function configure_mydns() {
1451         global $conf;
1452
1453         // configure pam for SMTP authentication agains the ispconfig database
1454         $configfile = 'mydns.conf';
b1a6a5 1455         if(is_file($conf['mydns']['config_dir'].'/'.$configfile)) copy($conf['mydns']['config_dir'].'/'.$configfile, $conf['mydns']['config_dir'].'/'.$configfile.'~');
532ae5 1456         if(is_file($conf['mydns']['config_dir'].'/'.$configfile.'~')) chmod($conf['mydns']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1457         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
b1a6a5 1458         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1459         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1460         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1461         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
82e9b9 1462         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
b1a6a5 1463         $content = str_replace('{server_id}', $conf['server_id'], $content);
MC 1464         wf($conf['mydns']['config_dir'].'/'.$configfile, $content);
532ae5 1465         chmod($conf['mydns']['config_dir'].'/'.$configfile, 0600);
L 1466         chown($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1467         chgrp($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1468
1469     }
1470
1471     public function configure_powerdns() {
1472         global $conf;
1473
1474         //* Create the database
2af58c 1475         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS ?? DEFAULT CHARACTER SET ?', $conf['powerdns']['database'], $conf['mysql']['charset'])) {
532ae5 1476             $this->error('Unable to create MySQL database: '.$conf['powerdns']['database'].'.');
L 1477         }
1478
1479         //* Create the ISPConfig database user in the local database
2af58c 1480         $query = "GRANT ALL ON ?? TO ?@'localhost'";
MC 1481         if(!$this->db->query($query, $conf['powerdns']['database'] . '.*', $conf['mysql']['ispconfig_user'])) {
532ae5 1482             $this->error('Unable to create user for powerdns database Error: '.$this->db->errorMessage);
L 1483         }
1484
1485         //* load the powerdns databse dump
1486         if($conf['mysql']['admin_password'] == '') {
1487             caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null",
b1a6a5 1488                 __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
532ae5 1489         } else {
L 1490             caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' -p'".$conf['mysql']['admin_password']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null",
b1a6a5 1491                 __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
532ae5 1492         }
L 1493
1494         //* Create the powerdns config file
1495         $configfile = 'pdns.local';
b1a6a5 1496         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile)) copy($conf['powerdns']['config_dir'].'/'.$configfile, $conf['powerdns']['config_dir'].'/'.$configfile.'~');
532ae5 1497         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile.'~')) chmod($conf['powerdns']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1498         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
b1a6a5 1499         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1500         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1501         $content = str_replace('{powerdns_database}', $conf['powerdns']['database'], $content);
1502         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
82e9b9 1503         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
b1a6a5 1504         wf($conf['powerdns']['config_dir'].'/'.$configfile, $content);
532ae5 1505         chmod($conf['powerdns']['config_dir'].'/'.$configfile, 0600);
L 1506         chown($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1507         chgrp($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1508
1509
1510     }
6a25ac 1511     
AT 1512     //** writes bind configuration files
1513     public function process_bind_file($configfile, $target='/', $absolute=false) {
1514         global $conf;
1515
1516         if ($absolute) $full_file_name = $target.$configfile;
1517         else $full_file_name = $conf['ispconfig_install_dir'].$target.$configfile;
1518         
1519         //* Backup exiting file
1520         if(is_file($full_file_name)) {
1521             copy($full_file_name, $config_dir.$configfile.'~');
1522         }
1523         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
1524         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
1525         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1526         $content = str_replace('{mysql_server_ispconfig_database}', $conf['mysql']['database'], $content);
1527         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1528         $content = str_replace('{ispconfig_install_dir}', $conf['ispconfig_install_dir'], $content);
1529         $content = str_replace('{dnssec_conffile}', $conf['ispconfig_install_dir'].'/server/scripts/dnssec-config.sh', $content);
1530         wf($full_file_name, $content);
1531     }
532ae5 1532
L 1533     public function configure_bind() {
1534         global $conf;
1535
b1a6a5 1536         //* Check if the zonefile directory has a slash at the end
MC 1537         $content=$conf['bind']['bind_zonefiles_dir'];
1538         if(substr($content, -1, 1) != '/') {
1539             $content .= '/';
532ae5 1540         }
L 1541
1542         //* Create the slave subdirectory
b1a6a5 1543         $content .= 'slave';
f66404 1544         if(!@is_dir($content)) mkdir($content, 02770, true);
532ae5 1545
b1a6a5 1546         //* Chown the slave subdirectory to $conf['bind']['bind_user']
MC 1547         chown($content, $conf['bind']['bind_user']);
1548         chgrp($content, $conf['bind']['bind_group']);
f66404 1549         chmod($content, 02770);
6a25ac 1550         
AT 1551         //* Install scripts for dnssec implementation
c5f49d 1552         $this->process_bind_file('named.conf.options', '/etc/bind/', true); //TODO replace hardcoded path
532ae5 1553     }
L 1554
1555
fbe2d6 1556     public function configure_xmpp($options = '') {
9f94a1 1557         global $conf;
MF 1558
1559         if($conf['xmpp']['installed'] == false) return;
1560         //* Create the logging directory for xmpp server
1561         if(!@is_dir('/var/log/metronome')) mkdir('/var/log/metronome', 0755, true);
1562         chown('/var/log/metronome', 'metronome');
1563         if(!@is_dir('/var/run/metronome')) mkdir('/var/run/metronome', 0755, true);
1564         chown('/var/run/metronome', 'metronome');
1565         if(!@is_dir('/var/lib/metronome')) mkdir('/var/lib/metronome', 0755, true);
1566         chown('/var/lib/metronome', 'metronome');
1567         if(!@is_dir('/etc/metronome/hosts')) mkdir('/etc/metronome/hosts', 0755, true);
1568         if(!@is_dir('/etc/metronome/status')) mkdir('/etc/metronome/status', 0755, true);
1569         unlink('/etc/metronome/metronome.cfg.lua');
1570
2af58c 1571         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ?", $conf["server_id"]);
9f94a1 1572         $server_name = $row["server_name"];
MF 1573
1574         $tpl = new tpl('metronome_conf_main.master');
1575         wf('/etc/metronome/metronome.cfg.lua', $tpl->grab());
1576         unset($tpl);
1577
1578         $tpl = new tpl('metronome_conf_global.master');
1579         $tpl->setVar('xmpp_admins','');
1580         wf('/etc/metronome/global.cfg.lua', $tpl->grab());
1581         unset($tpl);
1582
1583         // Copy isp libs
1584         if(!@is_dir('/usr/lib/metronome/isp-modules')) mkdir('/usr/lib/metronome/isp-modules', 0755, true);
1585         caselog('cp -rf apps/metronome_libs/* /usr/lib/metronome/isp-modules/', __FILE__, __LINE__);
3e994a 1586         // Process db config
MF 1587         $full_file_name = '/usr/lib/metronome/isp-modules/mod_auth_external/db_conf.inc.php';
1588         $content = rf($full_file_name);
1589         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
1590         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1591         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1592         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1593         $content = str_replace('{server_id}', $conf['server_id'], $content);
1594         wf($full_file_name, $content);
1595
fbe2d6 1596         if(!stristr($options, 'dont-create-certs')){
MF 1597             // Create SSL Certificate for localhost
1598             echo "writing new private key to 'localhost.key'\n-----\n";
1599             $ssl_country = $this->free_query('Country Name (2 letter code)', 'AU');
1600             $ssl_locality = $this->free_query('Locality Name (eg, city)', '');
1601             $ssl_organisation = $this->free_query('Organization Name (eg, company)', 'Internet Widgits Pty Ltd');
1602             $ssl_organisation_unit = $this->free_query('Organizational Unit Name (eg, section)', '');
1603             $ssl_domain = $this->free_query('Common Name (e.g. server FQDN or YOUR name)', $conf['hostname']);
1604             $ssl_email = $this->free_query('Email Address', '');
6886b5 1605
fbe2d6 1606             $tpl = new tpl('metronome_conf_ssl.master');
MF 1607             $tpl->setVar('ssl_country',$ssl_country);
1608             $tpl->setVar('ssl_locality',$ssl_locality);
1609             $tpl->setVar('ssl_organisation',$ssl_organisation);
1610             $tpl->setVar('ssl_organisation_unit',$ssl_organisation_unit);
1611             $tpl->setVar('domain',$ssl_domain);
1612             $tpl->setVar('ssl_email',$ssl_email);
1613             wf('/etc/metronome/certs/localhost.cnf', $tpl->grab());
1614             unset($tpl);
1615             // Generate new key, csr and cert
1616             exec("(cd /etc/metronome/certs && make localhost.key)");
1617             exec("(cd /etc/metronome/certs && make localhost.csr)");
1618             exec("(cd /etc/metronome/certs && make localhost.cert)");
1619             exec('chmod 0400 /etc/metronome/certs/localhost.key');
1620             exec('chown metronome /etc/metronome/certs/localhost.key');
1621         }else{
1622             echo "-----\n";
1623             echo "Metronome XMPP SSL server certificate is not renewed. Run the following command manual as root to recreate it:\n";
1624             echo "# (cd /etc/metronome/certs && make localhost.key && make localhost.csr && make localhost.cert && chmod 0400 localhost.key && chown metronome localhost.key)\n";
1625             echo "-----\n";
1626         }
9f94a1 1627
MF 1628         // Copy init script
1629         caselog('cp -f apps/metronome-init /etc/init.d/metronome', __FILE__, __LINE__);
1630         caselog('chmod u+x /etc/init.d/metronome', __FILE__, __LINE__);
fa79b7 1631         caselog('update-rc.d metronome defaults', __FILE__, __LINE__);
9f94a1 1632
8b608c 1633         exec($this->getinitcommand($conf['xmpp']['init_script'], 'restart'));
9f94a1 1634
6886b5 1635 /*
MF 1636 writing new private key to 'smtpd.key'
1637 -----
1638 You are about to be asked to enter information that will be incorporated
1639 into your certificate request.
1640 What you are about to enter is what is called a Distinguished Name or a DN.
1641 There are quite a few fields but you can leave some blank
1642 For some fields there will be a default value,
1643 If you enter '.', the field will be left blank.
1644 -----
1645 Country Name (2 letter code) [AU]:
1646 State or Province Name (full name) [Some-State]:
1647 Locality Name (eg, city) []:
1648 Organization Name (eg, company) [Internet Widgits Pty Ltd]:
1649 Organizational Unit Name (eg, section) []:
1650 Common Name (e.g. server FQDN or YOUR name) []:
1651 Email Address []:
1652  * */
9f94a1 1653
MF 1654         /*// Dont just copy over the virtualhost template but add some custom settings
1655         $tpl = new tpl('apache_apps.vhost.master');
1656
1657         $tpl->setVar('apps_vhost_port',$conf['web']['apps_vhost_port']);
1658         $tpl->setVar('apps_vhost_dir',$conf['web']['website_basedir'].'/apps');
1659         $tpl->setVar('apps_vhost_basedir',$conf['web']['website_basedir']);
1660         $tpl->setVar('apps_vhost_servername',$apps_vhost_servername);
1661         $tpl->setVar('apache_version',getapacheversion());
1662
1663
1664         // comment out the listen directive if port is 80 or 443
1665         if($conf['web']['apps_vhost_ip'] == 80 or $conf['web']['apps_vhost_ip'] == 443) {
1666             $tpl->setVar('vhost_port_listen','#');
1667         } else {
1668             $tpl->setVar('vhost_port_listen','');
1669         }
1670
1671         wf($vhost_conf_dir.'/apps.vhost', $tpl->grab());
1672         unset($tpl);*/
1673     }
1674
532ae5 1675
L 1676     public function configure_apache() {
1677         global $conf;
1678
4ffb51 1679         if($conf['apache']['installed'] == false) return;
532ae5 1680         //* Create the logging directory for the vhost logfiles
L 1681         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1682
1683         if(is_file('/etc/suphp/suphp.conf')) {
b1a6a5 1684             replaceLine('/etc/suphp/suphp.conf', 'php=php:/usr/bin', 'x-httpd-suphp="php:/usr/bin/php-cgi"', 0);
532ae5 1685             //replaceLine('/etc/suphp/suphp.conf','docroot=','docroot=/var/clients',0);
b1a6a5 1686             replaceLine('/etc/suphp/suphp.conf', 'umask=0077', 'umask=0022', 0);
532ae5 1687         }
L 1688
1689         if(is_file('/etc/apache2/sites-enabled/000-default')) {
b1a6a5 1690             replaceLine('/etc/apache2/sites-available/000-default', 'NameVirtualHost *', 'NameVirtualHost *:80', 1, 0);
MC 1691             replaceLine('/etc/apache2/sites-available/000-default', '<VirtualHost *>', '<VirtualHost *:80>', 1, 0);
532ae5 1692         }
L 1693
1694         if(is_file('/etc/apache2/ports.conf')) {
1695             // add a line "Listen 443" to ports conf if line does not exist
b1a6a5 1696             replaceLine('/etc/apache2/ports.conf', 'Listen 443', 'Listen 443', 1);
14001d 1697             
TB 1698             // Comment out the namevirtualhost lines, as they were added by ispconfig in ispconfig.conf file again
1699             replaceLine('/etc/apache2/ports.conf', 'NameVirtualHost *:80', '# NameVirtualHost *:80', 1);
1700             replaceLine('/etc/apache2/ports.conf', 'NameVirtualHost *:443', '# NameVirtualHost *:443', 1);
532ae5 1701         }
ef561f 1702         
TB 1703         if(is_file('/etc/apache2/mods-available/fcgid.conf')) {
1704             // add or modify the parameters for fcgid.conf
1705             replaceLine('/etc/apache2/mods-available/fcgid.conf','MaxRequestLen','MaxRequestLen 15728640',1);
1706         }
532ae5 1707
8eca28 1708         if(is_file('/etc/apache2/apache.conf')) {
MC 1709             if(hasLine('/etc/apache2/apache.conf', 'Include sites-enabled/', 1) == false) {
39e5f0 1710                 if(hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.conf', 1) == false && hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/', 1) == false) {
8eca28 1711                     replaceLine('/etc/apache2/apache.conf', 'Include sites-enabled/', 'Include sites-enabled/', 1, 1);
MC 1712                 } elseif(hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.vhost', 1) == false) {
39e5f0 1713                     replaceLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.vhost', 'IncludeOptional sites-enabled/', 1, 1);
TB 1714                 }
1715             }
1716         }
1717         
1718         if(is_file('/etc/apache2/apache2.conf')) {
1719             if(hasLine('/etc/apache2/apache2.conf', 'Include sites-enabled/', 1) == false && hasLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/', 1) == false) {
d10d15 1720                 if(hasLine('/etc/apache2/apache2.conf', 'Include sites-enabled/*.conf', 1) == true) {
TB 1721                     replaceLine('/etc/apache2/apache2.conf', 'Include sites-enabled/*.conf', 'Include sites-enabled/', 1, 1);
39e5f0 1722                 } elseif(hasLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/*.conf', 1) == true) {
TB 1723                     replaceLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/*.conf', 'IncludeOptional sites-enabled/', 1, 1);
8eca28 1724                 }
MC 1725             }
1726         }
532ae5 1727
L 1728         //* Copy the ISPConfig configuration include
1729         $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1730         $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1731
ccbf14 1732         $tpl = new tpl('apache_ispconfig.conf.master');
TB 1733         $tpl->setVar('apache_version',getapacheversion());
1734         
2af58c 1735         $records = $this->db->queryAllRecords("SELECT * FROM ?? WHERE server_id = ? AND virtualhost = 'y'", $conf['mysql']['master_database'] . '.server_ip', $conf['server_id']);
ccbf14 1736         $ip_addresses = array();
TB 1737         
532ae5 1738         if(is_array($records) && count($records) > 0) {
L 1739             foreach($records as $rec) {
a2156e 1740                 if($rec['ip_type'] == 'IPv6') {
T 1741                     $ip_address = '['.$rec['ip_address'].']';
1742                 } else {
1743                     $ip_address = $rec['ip_address'];
1744                 }
b1a6a5 1745                 $ports = explode(',', $rec['virtualhost_port']);
a2156e 1746                 if(is_array($ports)) {
T 1747                     foreach($ports as $port) {
1748                         $port = intval($port);
1749                         if($port > 0 && $port < 65536 && $ip_address != '') {
ccbf14 1750                             $ip_addresses[] = array('ip_address' => $ip_address, 'port' => $port);
a2156e 1751                         }
T 1752                     }
1753                 }
532ae5 1754             }
L 1755         }
855547 1756         
3de838 1757         if(count($ip_addresses) > 0) $tpl->setLoop('ip_adresses',$ip_addresses);
855547 1758         
ccbf14 1759         wf($vhost_conf_dir.'/ispconfig.conf', $tpl->grab());
TB 1760         unset($tpl);
532ae5 1761
L 1762         if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.conf')) {
b1a6a5 1763             symlink($vhost_conf_dir.'/ispconfig.conf', $vhost_conf_enabled_dir.'/000-ispconfig.conf');
532ae5 1764         }
L 1765
1766         //* make sure that webalizer finds its config file when it is directly in /etc
1767         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1768             mkdir('/etc/webalizer');
b1a6a5 1769             symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf');
532ae5 1770         }
L 1771
1772         if(is_file('/etc/webalizer/webalizer.conf')) {
1773             // Change webalizer mode to incremental
b1a6a5 1774             replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0);
MC 1775             replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental     yes', 0, 0);
1776             replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName     webalizer.hist', 0, 0);
532ae5 1777         }
a8ccf6 1778
532ae5 1779         // Check the awsatst script
L 1780         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
b1a6a5 1781         if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl', '/usr/share/awstats/tools/awstats_buildstaticpages.pl');
MC 1782         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1);
a8ccf6 1783
532ae5 1784         //* add a sshusers group
L 1785         $command = 'groupadd sshusers';
1786         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1787
1788     }
a8ccf6 1789
4ffb51 1790     public function configure_nginx(){
80e3c9 1791         global $conf;
a8ccf6 1792
4ffb51 1793         if($conf['nginx']['installed'] == false) return;
F 1794         //* Create the logging directory for the vhost logfiles
1795         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1796
1797         //* make sure that webalizer finds its config file when it is directly in /etc
1798         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1799             mkdir('/etc/webalizer');
b1a6a5 1800             symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf');
4ffb51 1801         }
F 1802
1803         if(is_file('/etc/webalizer/webalizer.conf')) {
1804             // Change webalizer mode to incremental
b1a6a5 1805             replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0);
MC 1806             replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental     yes', 0, 0);
1807             replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName     webalizer.hist', 0, 0);
4ffb51 1808         }
a8ccf6 1809
4ffb51 1810         // Check the awsatst script
F 1811         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
b1a6a5 1812         if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl', '/usr/share/awstats/tools/awstats_buildstaticpages.pl');
MC 1813         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1);
a8ccf6 1814
4ffb51 1815         //* add a sshusers group
F 1816         $command = 'groupadd sshusers';
1817         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
80e3c9 1818     }
a8ccf6 1819
d083f2 1820     public function configure_fail2ban() {
b1a6a5 1821         // To Do
MC 1822     }
a8ccf6 1823
80e3c9 1824     public function configure_squid()
T 1825     {
1826         global $conf;
2af58c 1827         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ?", $conf["server_id"]);
80e3c9 1828         $ip_address = gethostbyname($row["server_name"]);
T 1829         $server_name = $row["server_name"];
a8ccf6 1830
80e3c9 1831         $configfile = 'squid.conf';
b1a6a5 1832         if(is_file($conf["squid"]["config_dir"].'/'.$configfile)) copy($conf["squid"]["config_dir"].'/'.$configfile, $conf["squid"]["config_dir"].'/'.$configfile.'~');
80e3c9 1833         if(is_file($conf["squid"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["squid"]["config_dir"].'/'.$configfile.'~');
615a0a 1834         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master");
b1a6a5 1835         $content = str_replace('{server_name}', $server_name, $content);
MC 1836         $content = str_replace('{ip_address}', $ip_address, $content);
1837         $content = str_replace('{config_dir}', $conf['squid']['config_dir'], $content);
1838         wf($conf["squid"]["config_dir"].'/'.$configfile, $content);
80e3c9 1839         exec('chmod 600 '.$conf["squid"]["config_dir"].'/'.$configfile);
T 1840         exec('chown root:root '.$conf["squid"]["config_dir"].'/'.$configfile);
1841     }
a8ccf6 1842
80e3c9 1843     public function configure_ufw_firewall()
T 1844     {
8e5493 1845         if($this->is_update == false) {
TB 1846             $configfile = 'ufw.conf';
1847             if(is_file('/etc/ufw/ufw.conf')) copy('/etc/ufw/ufw.conf', '/etc/ufw/ufw.conf~');
1848             $content = rf("tpl/".$configfile.".master");
1849             wf('/etc/ufw/ufw.conf', $content);
1850             exec('chmod 600 /etc/ufw/ufw.conf');
1851             exec('chown root:root /etc/ufw/ufw.conf');
1852         }
80e3c9 1853     }
532ae5 1854
bd68aa 1855     public function configure_bastille_firewall() {
532ae5 1856         global $conf;
L 1857
1858         $dist_init_scripts = $conf['init_scripts'];
1859
1860         if(is_dir('/etc/Bastille.backup')) caselog('rm -rf /etc/Bastille.backup', __FILE__, __LINE__);
1861         if(is_dir('/etc/Bastille')) caselog('mv -f /etc/Bastille /etc/Bastille.backup', __FILE__, __LINE__);
1862         @mkdir('/etc/Bastille', 0700);
1863         if(is_dir('/etc/Bastille.backup/firewall.d')) caselog('cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/', __FILE__, __LINE__);
615a0a 1864         if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) {
b1a6a5 1865             caselog('cp -f ' . $conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
MC 1866         } else {
1867             caselog('cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
1868         }
532ae5 1869         caselog('chmod 644 /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
L 1870         $content = rf('/etc/Bastille/bastille-firewall.cfg');
1871         $content = str_replace('{DNS_SERVERS}', '', $content);
1872
1873         $tcp_public_services = '';
1874         $udp_public_services = '';
1875
2af58c 1876         $row = $this->db->queryOneRecord('SELECT * FROM ?? WHERE server_id = ?', $conf["mysql"]["database"] . '.firewall', $conf['server_id']);
532ae5 1877
L 1878         if(trim($row['tcp_port']) != '' || trim($row['udp_port']) != '') {
b1a6a5 1879             $tcp_public_services = trim(str_replace(',', ' ', $row['tcp_port']));
MC 1880             $udp_public_services = trim(str_replace(',', ' ', $row['udp_port']));
532ae5 1881         } else {
L 1882             $tcp_public_services = '21 22 25 53 80 110 143 443 3306 8080 10000';
1883             $udp_public_services = '53';
1884         }
1885
1886         if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
1887             $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
2af58c 1888             if($row['tcp_port'] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ? WHERE server_id = ?", ',' . intval($conf['apache']['vhost_port']), $conf['server_id']);
532ae5 1889         }
L 1890
1891         $content = str_replace('{TCP_PUBLIC_SERVICES}', $tcp_public_services, $content);
1892         $content = str_replace('{UDP_PUBLIC_SERVICES}', $udp_public_services, $content);
1893
1894         wf('/etc/Bastille/bastille-firewall.cfg', $content);
1895
1896         if(is_file($dist_init_scripts.'/bastille-firewall')) caselog('mv -f '.$dist_init_scripts.'/bastille-firewall '.$dist_init_scripts.'/bastille-firewall.backup', __FILE__, __LINE__);
1897         caselog('cp -f apps/bastille-firewall '.$dist_init_scripts, __FILE__, __LINE__);
1898         caselog('chmod 700 '.$dist_init_scripts.'/bastille-firewall', __FILE__, __LINE__);
1899
1900         if(is_file('/sbin/bastille-ipchains')) caselog('mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup', __FILE__, __LINE__);
1901         caselog('cp -f apps/bastille-ipchains /sbin', __FILE__, __LINE__);
1902         caselog('chmod 700 /sbin/bastille-ipchains', __FILE__, __LINE__);
1903
1904         if(is_file('/sbin/bastille-netfilter')) caselog('mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup', __FILE__, __LINE__);
1905         caselog('cp -f apps/bastille-netfilter /sbin', __FILE__, __LINE__);
1906         caselog('chmod 700 /sbin/bastille-netfilter', __FILE__, __LINE__);
1907
1908         if(!@is_dir('/var/lock/subsys')) caselog('mkdir /var/lock/subsys', __FILE__, __LINE__);
1909
1910         exec('which ipchains &> /dev/null', $ipchains_location, $ret_val);
1911         if(!is_file('/sbin/ipchains') && !is_link('/sbin/ipchains') && $ret_val == 0) phpcaselog(@symlink(shell_exec('which ipchains'), '/sbin/ipchains'), 'create symlink', __FILE__, __LINE__);
1912         unset($ipchains_location);
1913         exec('which iptables &> /dev/null', $iptables_location, $ret_val);
1914         if(!is_file('/sbin/iptables') && !is_link('/sbin/iptables') && $ret_val == 0) phpcaselog(@symlink(trim(shell_exec('which iptables')), '/sbin/iptables'), 'create symlink', __FILE__, __LINE__);
1915         unset($iptables_location);
1916
1917     }
1918
1919     public function configure_vlogger() {
1920         global $conf;
1921
1922         //** Configure vlogger to use traffic logging to mysql (master) db
1923         $configfile = 'vlogger-dbi.conf';
b1a6a5 1924         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile)) copy($conf['vlogger']['config_dir'].'/'.$configfile, $conf['vlogger']['config_dir'].'/'.$configfile.'~');
532ae5 1925         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile.'~')) chmod($conf['vlogger']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1926         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1927         if($conf['mysql']['master_slave_setup'] == 'y') {
b1a6a5 1928             $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
MC 1929             $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1930             $content = str_replace('{mysql_server_database}', $conf['mysql']['master_database'], $content);
1931             $content = str_replace('{mysql_server_ip}', $conf['mysql']['master_host'], $content);
532ae5 1932         } else {
b1a6a5 1933             $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1934             $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1935             $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1936             $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
532ae5 1937         }
b1a6a5 1938         wf($conf['vlogger']['config_dir'].'/'.$configfile, $content);
532ae5 1939         chmod($conf['vlogger']['config_dir'].'/'.$configfile, 0600);
L 1940         chown($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1941         chgrp($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1942
1943     }
1944
1945     public function configure_apps_vhost() {
1946         global $conf;
1947
1948         //* Create the ispconfig apps vhost user and group
165152 1949         if($conf['apache']['installed'] == true){
4ffb51 1950             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
F 1951             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1952             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1953
4ffb51 1954             $command = 'groupadd '.$apps_vhost_user;
F 1955             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1956
4ffb51 1957             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
F 1958             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1959
L 1960
5edf40 1961             //$command = 'adduser '.$conf['apache']['user'].' '.$apps_vhost_group;
TB 1962             $command = 'usermod -a -G '.$apps_vhost_group.' '.$conf['apache']['user'];
4ffb51 1963             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1964
99b55b 1965             if(!@is_dir($install_dir)){
F 1966                 mkdir($install_dir, 0755, true);
1967             } else {
1968                 chmod($install_dir, 0755);
1969             }
4ffb51 1970             chown($install_dir, $apps_vhost_user);
F 1971             chgrp($install_dir, $apps_vhost_group);
532ae5 1972
4ffb51 1973             //* Copy the apps vhost file
F 1974             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1975             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1976             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'':'ServerName '.$conf['web']['apps_vhost_servername'];
d0356f 1977             
TB 1978             //* Get the apps vhost port
1979             if($this->is_update == true) {
1980                 $conf['web']['apps_vhost_port'] = get_apps_vhost_port_number();
1981             }
532ae5 1982
4ffb51 1983             // Dont just copy over the virtualhost template but add some custom settings
ccbf14 1984             $tpl = new tpl('apache_apps.vhost.master');
TB 1985             $tpl->setVar('apps_vhost_ip',$conf['web']['apps_vhost_ip']);
1986             $tpl->setVar('apps_vhost_port',$conf['web']['apps_vhost_port']);
1987             $tpl->setVar('apps_vhost_dir',$conf['web']['website_basedir'].'/apps');
1988             $tpl->setVar('apps_vhost_basedir',$conf['web']['website_basedir']);
1989             $tpl->setVar('apps_vhost_servername',$apps_vhost_servername);
1990             $tpl->setVar('apache_version',getapacheversion());
532ae5 1991
L 1992
4ffb51 1993             // comment out the listen directive if port is 80 or 443
F 1994             if($conf['web']['apps_vhost_ip'] == 80 or $conf['web']['apps_vhost_ip'] == 443) {
ccbf14 1995                 $tpl->setVar('vhost_port_listen','#');
4ffb51 1996             } else {
ccbf14 1997                 $tpl->setVar('vhost_port_listen','');
4ffb51 1998             }
532ae5 1999
ccbf14 2000             wf($vhost_conf_dir.'/apps.vhost', $tpl->grab());
TB 2001             unset($tpl);
532ae5 2002
4ffb51 2003             //copy('tpl/apache_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
F 2004             //* and create the symlink
7e1cfb 2005             if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
F 2006             if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
b1a6a5 2007                 symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost');
4ffb51 2008             }
a8ccf6 2009
4ffb51 2010             if(!is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter')) {
615a0a 2011                 $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_apps_fcgi_starter.master', 'tpl/apache_apps_fcgi_starter.master');
526b99 2012                 $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content);
T 2013                 $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content);
4ffb51 2014                 mkdir($conf['web']['website_basedir'].'/php-fcgi-scripts/apps', 0755, true);
526b99 2015                 //copy('tpl/apache_apps_fcgi_starter.master',$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
T 2016                 wf($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter', $content);
4ffb51 2017                 exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
F 2018                 exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps');
2019
b1a6a5 2020             }
532ae5 2021         }
165152 2022         if($conf['nginx']['installed'] == true){
4ffb51 2023             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
F 2024             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
2025             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 2026
4ffb51 2027             $command = 'groupadd '.$apps_vhost_user;
F 2028             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2029
2030             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
2031             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2032
2033
11f2ad 2034             //$command = 'adduser '.$conf['nginx']['user'].' '.$apps_vhost_group;
TB 2035             $command = 'usermod -a -G '.$apps_vhost_group.' '.$conf['nginx']['user'];
4ffb51 2036             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
F 2037
6e2d48 2038             if(!@is_dir($install_dir)){
F 2039                 mkdir($install_dir, 0755, true);
2040             } else {
2041                 chmod($install_dir, 0755);
2042             }
4ffb51 2043             chown($install_dir, $apps_vhost_user);
F 2044             chgrp($install_dir, $apps_vhost_group);
2045
2046             //* Copy the apps vhost file
2047             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
2048             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
2049             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'_':$conf['web']['apps_vhost_servername'];
2050
2051             // Dont just copy over the virtualhost template but add some custom settings
615a0a 2052             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_apps.vhost.master', 'tpl/nginx_apps.vhost.master');
a8ccf6 2053
4ffb51 2054             if($conf['web']['apps_vhost_ip'] == '_default_'){
F 2055                 $apps_vhost_ip = '';
2056             } else {
2057                 $apps_vhost_ip = $conf['web']['apps_vhost_ip'].':';
2058             }
a8ccf6 2059
ca0b77 2060             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
b1a6a5 2061             if(substr($socket_dir, -1) != '/') $socket_dir .= '/';
ca0b77 2062             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
F 2063             $fpm_socket = $socket_dir.'apps.sock';
8ab3cd 2064             $cgi_socket = escapeshellcmd($conf['nginx']['cgi_socket']);
4ffb51 2065
F 2066             $content = str_replace('{apps_vhost_ip}', $apps_vhost_ip, $content);
2067             $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content);
2068             $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content);
2069             $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content);
ca0b77 2070             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 2071             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
8ab3cd 2072             $content = str_replace('{cgi_socket}', $cgi_socket, $content);
b1a6a5 2073
183c47 2074             if(file_exists('/var/run/php5-fpm.sock')){
F 2075                 $use_tcp = '#';
2076                 $use_socket = '';
2077             } else {
2078                 $use_tcp = '';
2079                 $use_socket = '#';
2080             }
2081             $content = str_replace('{use_tcp}', $use_tcp, $content);
2082             $content = str_replace('{use_socket}', $use_socket, $content);
134721 2083             
TB 2084             // SSL in apps vhost is off by default. Might change later.
2085             $content = str_replace('{ssl_on}', 'off', $content);
2086             $content = str_replace('{ssl_comment}', '#', $content);
4ffb51 2087
F 2088             wf($vhost_conf_dir.'/apps.vhost', $content);
a8ccf6 2089
fbb24a 2090             // PHP-FPM
F 2091             // Dont just copy over the php-fpm pool template but add some custom settings
615a0a 2092             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apps_php_fpm_pool.conf.master', 'tpl/apps_php_fpm_pool.conf.master');
fbb24a 2093             $content = str_replace('{fpm_pool}', 'apps', $content);
ca0b77 2094             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 2095             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
fbb24a 2096             $content = str_replace('{fpm_user}', $apps_vhost_user, $content);
F 2097             $content = str_replace('{fpm_group}', $apps_vhost_group, $content);
2098             wf($conf['nginx']['php_fpm_pool_dir'].'/apps.conf', $content);
4ffb51 2099
F 2100             //copy('tpl/nginx_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
2101             //* and create the symlink
7e1cfb 2102             if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
F 2103             if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
b1a6a5 2104                 symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost');
4ffb51 2105             }
a8ccf6 2106
532ae5 2107         }
L 2108     }
a8ccf6 2109
532ae5 2110     public function make_ispconfig_ssl_cert() {
b04e82 2111         global $conf,$autoinstall;
532ae5 2112
L 2113         $install_dir = $conf['ispconfig_install_dir'];
a8ccf6 2114
532ae5 2115         $ssl_crt_file = $install_dir.'/interface/ssl/ispserver.crt';
L 2116         $ssl_csr_file = $install_dir.'/interface/ssl/ispserver.csr';
2117         $ssl_key_file = $install_dir.'/interface/ssl/ispserver.key';
a8ccf6 2118
532ae5 2119         if(!@is_dir($install_dir.'/interface/ssl')) mkdir($install_dir.'/interface/ssl', 0755, true);
a8ccf6 2120
b1a6a5 2121         $ssl_pw = substr(md5(mt_rand()), 0, 6);
532ae5 2122         exec("openssl genrsa -des3 -passout pass:$ssl_pw -out $ssl_key_file 4096");
b04e82 2123         if(AUTOINSTALL){
TB 2124             exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -subj '/C=".escapeshellcmd($autoinstall['ssl_cert_country'])."/ST=".escapeshellcmd($autoinstall['ssl_cert_state'])."/L=".escapeshellcmd($autoinstall['ssl_cert_locality'])."/O=".escapeshellcmd($autoinstall['ssl_cert_organisation'])."/OU=".escapeshellcmd($autoinstall['ssl_cert_organisation_unit'])."/CN=".escapeshellcmd($autoinstall['ssl_cert_common_name'])."' -key $ssl_key_file -out $ssl_csr_file");
bcd725 2125         } else {
FT 2126             exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -out $ssl_csr_file");
2127         }
532ae5 2128         exec("openssl req -x509 -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -in $ssl_csr_file -out $ssl_crt_file -days 3650");
L 2129         exec("openssl rsa -passin pass:$ssl_pw -in $ssl_key_file -out $ssl_key_file.insecure");
b1a6a5 2130         rename($ssl_key_file, $ssl_key_file.'.secure');
MC 2131         rename($ssl_key_file.'.insecure', $ssl_key_file);
980485 2132         
TB 2133         exec('chown -R root:root /usr/local/ispconfig/interface/ssl');
a8ccf6 2134
532ae5 2135     }
L 2136
2137     public function install_ispconfig() {
2138         global $conf;
2139
2140         $install_dir = $conf['ispconfig_install_dir'];
2141
2142         //* Create the ISPConfig installation directory
2143         if(!@is_dir($install_dir)) {
2144             $command = "mkdir $install_dir";
2145             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2146         }
2147
2148         //* Create a ISPConfig user and group
2149         $command = 'groupadd ispconfig';
2150         if(!is_group('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2151
2152         $command = 'useradd -g ispconfig -d '.$install_dir.' ispconfig';
2153         if(!is_user('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2154
2155         //* copy the ISPConfig interface part
2156         $command = 'cp -rf ../interface '.$install_dir;
2157         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2158
2159         //* copy the ISPConfig server part
2160         $command = 'cp -rf ../server '.$install_dir;
2161         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a13af2 2162         
fb6c56 2163         //* Make a backup of the security settings
TB 2164         if(is_file('/usr/local/ispconfig/security/security_settings.ini')) copy('/usr/local/ispconfig/security/security_settings.ini','/usr/local/ispconfig/security/security_settings.ini~');
2165         
a13af2 2166         //* copy the ISPConfig security part
TB 2167         $command = 'cp -rf ../security '.$install_dir;
2168         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
fb6c56 2169         
TB 2170         //* Apply changed security_settings.ini values to new security_settings.ini file
2171         if(is_file('/usr/local/ispconfig/security/security_settings.ini~')) {
2172             $security_settings_old = ini_to_array(file_get_contents('/usr/local/ispconfig/security/security_settings.ini~'));
2173             $security_settings_new = ini_to_array(file_get_contents('/usr/local/ispconfig/security/security_settings.ini'));
2174             if(is_array($security_settings_new) && is_array($security_settings_old)) {
2175                 foreach($security_settings_new as $section => $sval) {
2176                     if(is_array($sval)) {
2177                         foreach($sval as $key => $val) {
2178                             if(isset($security_settings_old[$section]) && isset($security_settings_old[$section][$key])) {
2179                                 $security_settings_new[$section][$key] = $security_settings_old[$section][$key];
2180                             }
2181                         }
2182                     }
2183                 }
2184                 file_put_contents('/usr/local/ispconfig/security/security_settings.ini',array_to_ini($security_settings_new));
2185             }
2186         }
532ae5 2187
L 2188         //* Create a symlink, so ISPConfig is accessible via web
2189         // Replaced by a separate vhost definition for port 8080
2190         // $command = "ln -s $install_dir/interface/web/ /var/www/ispconfig";
2191         // caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2192
2193         //* Create the config file for ISPConfig interface
2194         $configfile = 'config.inc.php';
2195         if(is_file($install_dir.'/interface/lib/'.$configfile)) {
2196             copy($install_dir.'/interface/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
2197         }
615a0a 2198         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 2199         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
b1a6a5 2200         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
532ae5 2201         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
L 2202         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
82e9b9 2203         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
532ae5 2204
L 2205         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
2206         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
2207         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
2208         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
82e9b9 2209         $content = str_replace('{mysql_master_server_port}', $conf['mysql']['master_port'], $content);
532ae5 2210
L 2211         $content = str_replace('{server_id}', $conf['server_id'], $content);
2212         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
b63764 2213         $content = str_replace('{language}', $conf['language'], $content);
8cf78b 2214         $content = str_replace('{timezone}', $conf['timezone'], $content);
f598b0 2215         $content = str_replace('{theme}', $conf['theme'], $content);
992797 2216         $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content);
b63764 2217
532ae5 2218         wf($install_dir.'/interface/lib/'.$configfile, $content);
L 2219
2220         //* Create the config file for ISPConfig server
2221         $configfile = 'config.inc.php';
2222         if(is_file($install_dir.'/server/lib/'.$configfile)) {
2223             copy($install_dir.'/server/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
2224         }
615a0a 2225         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 2226         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 2227         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
2228         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
2229         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
82e9b9 2230         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
532ae5 2231
L 2232         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
2233         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
2234         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
2235         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
82e9b9 2236         $content = str_replace('{mysql_master_server_port}', $conf['mysql']['master_port'], $content);
532ae5 2237
L 2238         $content = str_replace('{server_id}', $conf['server_id'], $content);
2239         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
2240         $content = str_replace('{language}', $conf['language'], $content);
8cf78b 2241         $content = str_replace('{timezone}', $conf['timezone'], $content);
f598b0 2242         $content = str_replace('{theme}', $conf['theme'], $content);
992797 2243         $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content);
532ae5 2244
L 2245         wf($install_dir.'/server/lib/'.$configfile, $content);
2246
2247         //* Create the config file for remote-actions (but only, if it does not exist, because
2248         //  the value is a autoinc-value and so changed by the remoteaction_core_module
2249         if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) {
2250             $content = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
2251             wf($install_dir.'/server/lib/remote_action.inc.php', $content);
2252         }
2253
2254         //* Enable the server modules and plugins.
2255         // TODO: Implement a selector which modules and plugins shall be enabled.
2256         $dir = $install_dir.'/server/mods-available/';
2257         if (is_dir($dir)) {
2258             if ($dh = opendir($dir)) {
2259                 while (($file = readdir($dh)) !== false) {
b1a6a5 2260                     if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') {
MC 2261                         include_once $install_dir.'/server/mods-available/'.$file;
2262                         $module_name = substr($file, 0, -8);
532ae5 2263                         $tmp = new $module_name;
L 2264                         if($tmp->onInstall()) {
2265                             if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) {
2266                                 @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-enabled/'.$file);
2267                                 // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-enabled/'.$file);
2268                             }
2269                             if (strpos($file, '_core_module') !== false) {
2270                                 if(!@is_link($install_dir.'/server/mods-core/'.$file)) {
2271                                     @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-core/'.$file);
2272                                     // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-core/'.$file);
2273                                 }
2274                             }
2275                         }
2276                         unset($tmp);
2277                     }
2278                 }
2279                 closedir($dh);
2280             }
2281         }
2282
2283         $dir = $install_dir.'/server/plugins-available/';
2284         if (is_dir($dir)) {
2285             if ($dh = opendir($dir)) {
2286                 while (($file = readdir($dh)) !== false) {
4ffb51 2287                     if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue;
F 2288                     if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue;
b1a6a5 2289                     if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') {
MC 2290                         include_once $install_dir.'/server/plugins-available/'.$file;
2291                         $plugin_name = substr($file, 0, -8);
532ae5 2292                         $tmp = new $plugin_name;
b1a6a5 2293                         if(method_exists($tmp, 'onInstall') && $tmp->onInstall()) {
532ae5 2294                             if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) {
L 2295                                 @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file);
2296                                 //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-enabled/'.$file);
2297                             }
2298                             if (strpos($file, '_core_plugin') !== false) {
2299                                 if(!@is_link($install_dir.'/server/plugins-core/'.$file)) {
2300                                     @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-core/'.$file);
2301                                     //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-core/'.$file);
2302                                 }
2303                             }
2304                         }
2305                         unset($tmp);
2306                     }
2307                 }
2308                 closedir($dh);
2309             }
2310         }
2311
2312         // Update the server config
2313         $mail_server_enabled = ($conf['services']['mail'])?1:0;
2314         $web_server_enabled = ($conf['services']['web'])?1:0;
2315         $dns_server_enabled = ($conf['services']['dns'])?1:0;
2316         $file_server_enabled = ($conf['services']['file'])?1:0;
2317         $db_server_enabled = ($conf['services']['db'])?1:0;
8cf955 2318         $vserver_server_enabled = ($conf['openvz']['installed'])?1:0;
80e3c9 2319         $proxy_server_enabled = ($conf['services']['proxy'])?1:0;
T 2320         $firewall_server_enabled = ($conf['services']['firewall'])?1:0;
9f94a1 2321         $xmpp_server_enabled = ($conf['services']['xmpp'])?1:0;
532ae5 2322
2af58c 2323         $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled', proxy_server = '$proxy_server_enabled', firewall_server = '$firewall_server_enabled', xmpp_server = '.$xmpp_server_enabled.' WHERE server_id = ?";
532ae5 2324
2af58c 2325         $this->db->query($sql, $conf['server_id']);
532ae5 2326         if($conf['mysql']['master_slave_setup'] == 'y') {
2af58c 2327             $this->dbmaster->query($sql, $conf['server_id']);
532ae5 2328         }
L 2329
2330
3e0fc8 2331         // chown install dir to root and chmod 755
TB 2332         $command = 'chown root:root '.$install_dir;
2333         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2334         $command = 'chmod 755 '.$install_dir;
532ae5 2335         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 2336
fa029b 2337         //* Chmod the files and directories in the install dir
3e0fc8 2338         $command = 'chmod -R 750 '.$install_dir.'/*';
TB 2339         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2340
2341         //* chown the interface files to the ispconfig user and group
2342         $command = 'chown -R ispconfig:ispconfig '.$install_dir.'/interface';
2343         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2344         
2345         //* chown the server files to the root user and group
2346         $command = 'chown -R root:root '.$install_dir.'/server';
532ae5 2347         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
fa029b 2348         
TB 2349         //* chown the security files to the root user and group
2350         $command = 'chown -R root:root '.$install_dir.'/security';
2351         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2352         
2353         //* chown the security directory and security_settings.ini to root:ispconfig
2354         $command = 'chown root:ispconfig '.$install_dir.'/security/security_settings.ini';
2355         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2356         $command = 'chown root:ispconfig '.$install_dir.'/security';
2357         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
cb1221 2358         $command = 'chown root:ispconfig '.$install_dir.'/security/ids.whitelist';
TB 2359         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2360         $command = 'chown root:ispconfig '.$install_dir.'/security/ids.htmlfield';
2361         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2362         $command = 'chown root:ispconfig '.$install_dir.'/security/apache_directives.blacklist';
532ae5 2363         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 2364
2365         //* Make the global language file directory group writable
2366         exec("chmod -R 770 $install_dir/interface/lib/lang");
2367
2368         //* Make the temp directory for language file exports writable
2369         if(is_dir($install_dir.'/interface/web/temp')) exec("chmod -R 770 $install_dir/interface/web/temp");
2370
2371         //* Make all interface language file directories group writable
2372         $handle = @opendir($install_dir.'/interface/web');
b1a6a5 2373         while ($file = @readdir($handle)) {
532ae5 2374             if ($file != '.' && $file != '..') {
L 2375                 if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) {
2376                     $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang');
b1a6a5 2377                     chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang', 0770);
MC 2378                     while ($lang_file = @readdir($handle2)) {
532ae5 2379                         if ($lang_file != '.' && $lang_file != '..') {
b1a6a5 2380                             chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file, 0770);
532ae5 2381                         }
L 2382                     }
2383                 }
2384             }
2385         }
a8ccf6 2386
477d4e 2387         //* Make the APS directories group writable
T 2388         exec("chmod -R 770 $install_dir/interface/web/sites/aps_meta_packages");
2389         exec("chmod -R 770 $install_dir/server/aps_packages");
532ae5 2390
L 2391         //* make sure that the server config file (not the interface one) is only readable by the root user
bfcdef 2392         chmod($install_dir.'/server/lib/config.inc.php', 0600);
T 2393         chown($install_dir.'/server/lib/config.inc.php', 'root');
2394         chgrp($install_dir.'/server/lib/config.inc.php', 'root');
b1a6a5 2395
bfcdef 2396         //* Make sure thet the interface config file is readable by user ispconfig only
T 2397         chmod($install_dir.'/interface/lib/config.inc.php', 0600);
2398         chown($install_dir.'/interface/lib/config.inc.php', 'ispconfig');
2399         chgrp($install_dir.'/interface/lib/config.inc.php', 'ispconfig');
532ae5 2400
L 2401         chmod($install_dir.'/server/lib/remote_action.inc.php', 0600);
2402         chown($install_dir.'/server/lib/remote_action.inc.php', 'root');
2403         chgrp($install_dir.'/server/lib/remote_action.inc.php', 'root');
2404
2405         if(@is_file($install_dir.'/server/lib/mysql_clientdb.conf')) {
2406             chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
2407             chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
2408             chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
2409         }
a8ccf6 2410
8cf78b 2411         if(is_dir($install_dir.'/interface/invoices')) {
e94a9f 2412             exec('chmod -R 770 '.escapeshellarg($install_dir.'/interface/invoices'));
T 2413             exec('chown -R ispconfig:ispconfig '.escapeshellarg($install_dir.'/interface/invoices'));
edf806 2414         }
980485 2415         
TB 2416         exec('chown -R root:root /usr/local/ispconfig/interface/ssl');
532ae5 2417
L 2418         // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing
2419         // and must be fixed as this will allow the apache user to read the ispconfig files.
2420         // Later this must run as own apache server or via suexec!
63b369 2421         if($conf['apache']['installed'] == true){
F 2422             $command = 'adduser '.$conf['apache']['user'].' ispconfig';
2423             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 2424             if(is_group('ispapps')){
F 2425                 $command = 'adduser '.$conf['apache']['user'].' ispapps';
2426                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2427             }
63b369 2428         }
F 2429         if($conf['nginx']['installed'] == true){
2430             $command = 'adduser '.$conf['nginx']['user'].' ispconfig';
2431             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 2432             if(is_group('ispapps')){
F 2433                 $command = 'adduser '.$conf['nginx']['user'].' ispapps';
2434                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2435             }
63b369 2436         }
532ae5 2437
L 2438         //* Make the shell scripts executable
2439         $command = "chmod +x $install_dir/server/scripts/*.sh";
2440         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2441
55cb02 2442         if ($this->install_ispconfig_interface == true && isset($conf['interface_password']) && $conf['interface_password']!='admin') {
FS 2443             $sql = "UPDATE sys_user SET passwort = md5(?) WHERE username = 'admin';";
2444             $this->db->query($sql, $conf['interface_password']);
2445         }
2446
7e1cfb 2447         if($conf['apache']['installed'] == true && $this->install_ispconfig_interface == true){
4ffb51 2448             //* Copy the ISPConfig vhost for the controlpanel
F 2449             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
2450             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
532ae5 2451
4ffb51 2452             // Dont just copy over the virtualhost template but add some custom settings
ccbf14 2453             $tpl = new tpl('apache_ispconfig.vhost.master');
TB 2454             $tpl->setVar('vhost_port',$conf['apache']['vhost_port']);
532ae5 2455
4ffb51 2456             // comment out the listen directive if port is 80 or 443
F 2457             if($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) {
ccbf14 2458                 $tpl->setVar('vhost_port_listen','#');
4ffb51 2459             } else {
ccbf14 2460                 $tpl->setVar('vhost_port_listen','');
4ffb51 2461             }
a8ccf6 2462
4ffb51 2463             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
ccbf14 2464                 $tpl->setVar('ssl_comment','');
4ffb51 2465             } else {
ccbf14 2466                 $tpl->setVar('ssl_comment','#');
4ffb51 2467             }
10b4c8 2468             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key') && is_file($install_dir.'/interface/ssl/ispserver.bundle')) {
ccbf14 2469                 $tpl->setVar('ssl_bundle_comment','');
10b4c8 2470             } else {
ccbf14 2471                 $tpl->setVar('ssl_bundle_comment','#');
10b4c8 2472             }
ccbf14 2473             
TB 2474             $tpl->setVar('apache_version',getapacheversion());
532ae5 2475
ccbf14 2476             wf($vhost_conf_dir.'/ispconfig.vhost', $tpl->grab());
532ae5 2477
4ffb51 2478             //* and create the symlink
7e1cfb 2479             if($this->is_update == false) {
4ffb51 2480                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
F 2481                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
b1a6a5 2482                     symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost');
4ffb51 2483                 }
F 2484             }
cc6568 2485             //if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) {
b1a6a5 2486             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master');
MC 2487             $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content);
2488             $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content);
2489             @mkdir('/var/www/php-fcgi-scripts/ispconfig', 0755, true);
2490             wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content);
2491             exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter');
2492             @symlink($install_dir.'/interface/web', '/var/www/ispconfig');
2493             exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig');
cc6568 2494             //}
532ae5 2495         }
a8ccf6 2496
7e1cfb 2497         if($conf['nginx']['installed'] == true && $this->install_ispconfig_interface == true){
4ffb51 2498             //* Copy the ISPConfig vhost for the controlpanel
F 2499             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
2500             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
532ae5 2501
4ffb51 2502             // Dont just copy over the virtualhost template but add some custom settings
615a0a 2503             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_ispconfig.vhost.master', 'tpl/nginx_ispconfig.vhost.master');
4ffb51 2504             $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content);
a8ccf6 2505
4ffb51 2506             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
f9b8d0 2507                 $content = str_replace('{ssl_on}', 'on', $content);
4ffb51 2508                 $content = str_replace('{ssl_comment}', '', $content);
F 2509                 $content = str_replace('{fastcgi_ssl}', 'on', $content);
2510             } else {
f9b8d0 2511                 $content = str_replace('{ssl_on}', 'off', $content);
4ffb51 2512                 $content = str_replace('{ssl_comment}', '#', $content);
F 2513                 $content = str_replace('{fastcgi_ssl}', 'off', $content);
2514             }
a8ccf6 2515
ca0b77 2516             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
b1a6a5 2517             if(substr($socket_dir, -1) != '/') $socket_dir .= '/';
ca0b77 2518             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
F 2519             $fpm_socket = $socket_dir.'ispconfig.sock';
a8ccf6 2520
ca0b77 2521             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 2522             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
a8ccf6 2523
4ffb51 2524             wf($vhost_conf_dir.'/ispconfig.vhost', $content);
a8ccf6 2525
4ffb51 2526             unset($content);
a8ccf6 2527
4ffb51 2528             // PHP-FPM
F 2529             // Dont just copy over the php-fpm pool template but add some custom settings
615a0a 2530             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/php_fpm_pool.conf.master', 'tpl/php_fpm_pool.conf.master');
4ffb51 2531             $content = str_replace('{fpm_pool}', 'ispconfig', $content);
ca0b77 2532             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 2533             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
4ffb51 2534             $content = str_replace('{fpm_user}', 'ispconfig', $content);
F 2535             $content = str_replace('{fpm_group}', 'ispconfig', $content);
2536             wf($conf['nginx']['php_fpm_pool_dir'].'/ispconfig.conf', $content);
2537
2538             //copy('tpl/nginx_ispconfig.vhost.master', $vhost_conf_dir.'/ispconfig.vhost');
2539             //* and create the symlink
7e1cfb 2540             if($this->is_update == false) {
4ffb51 2541                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
F 2542                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
b1a6a5 2543                     symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost');
4ffb51 2544                 }
F 2545             }
532ae5 2546         }
L 2547
2548         //* Install the update script
b34f99 2549         if(is_file('/usr/local/bin/ispconfig_update_from_dev.sh')) unlink('/usr/local/bin/ispconfig_update_from_dev.sh');
MC 2550         chown($install_dir.'/server/scripts/update_from_dev.sh', 'root');
2551         chmod($install_dir.'/server/scripts/update_from_dev.sh', 0700);
532ae5 2552         chown($install_dir.'/server/scripts/update_from_tgz.sh', 'root');
L 2553         chmod($install_dir.'/server/scripts/update_from_tgz.sh', 0700);
2554         chown($install_dir.'/server/scripts/ispconfig_update.sh', 'root');
2555         chmod($install_dir.'/server/scripts/ispconfig_update.sh', 0700);
b34f99 2556         if(!is_link('/usr/local/bin/ispconfig_update_from_dev.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update_from_dev.sh');
b1a6a5 2557         if(!is_link('/usr/local/bin/ispconfig_update.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update.sh');
532ae5 2558
L 2559         //* Make the logs readable for the ispconfig user
2560         if(@is_file('/var/log/mail.log')) exec('chmod +r /var/log/mail.log');
2561         if(@is_file('/var/log/mail.warn')) exec('chmod +r /var/log/mail.warn');
2562         if(@is_file('/var/log/mail.err')) exec('chmod +r /var/log/mail.err');
2563         if(@is_file('/var/log/messages')) exec('chmod +r /var/log/messages');
2564         if(@is_file('/var/log/clamav/clamav.log')) exec('chmod +r /var/log/clamav/clamav.log');
2565         if(@is_file('/var/log/clamav/freshclam.log')) exec('chmod +r /var/log/clamav/freshclam.log');
2566
2567         //* Create the ispconfig log file and directory
2568         if(!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) {
2569             if(!is_dir($conf['ispconfig_log_dir'])) mkdir($conf['ispconfig_log_dir'], 0755);
2570             touch($conf['ispconfig_log_dir'].'/ispconfig.log');
2571         }
a8ccf6 2572
99c89b 2573         //* Create the ispconfig auth log file and set uid/gid
a8ccf6 2574         if(!is_file($conf['ispconfig_log_dir'].'/auth.log')) {
99c89b 2575             touch($conf['ispconfig_log_dir'].'/auth.log');
a8ccf6 2576         }
0799f8 2577         exec('chown ispconfig:ispconfig '. $conf['ispconfig_log_dir'].'/auth.log');
T 2578         exec('chmod 660 '. $conf['ispconfig_log_dir'].'/auth.log');
a8ccf6 2579
0c5b42 2580         if(is_user('getmail')) {
b1a6a5 2581             rename($install_dir.'/server/scripts/run-getmail.sh', '/usr/local/bin/run-getmail.sh');
0c5b42 2582             if(is_user('getmail')) chown('/usr/local/bin/run-getmail.sh', 'getmail');
T 2583             chmod('/usr/local/bin/run-getmail.sh', 0744);
2584         }
532ae5 2585
L 2586         //* Add Log-Rotation
2587         if (is_dir('/etc/logrotate.d')) {
2588             @unlink('/etc/logrotate.d/logispc3'); // ignore, if the file is not there
2589             /* We rotate these logs in cron_daily.php
2590             $fh = fopen('/etc/logrotate.d/logispc3', 'w');
2591             fwrite($fh,
2592                     "$conf['ispconfig_log_dir']/ispconfig.log { \n" .
2593                     "    weekly \n" .
2594                     "    missingok \n" .
2595                     "    rotate 4 \n" .
2596                     "    compress \n" .
2597                     "    delaycompress \n" .
2598                     "} \n" .
2599                     "$conf['ispconfig_log_dir']/cron.log { \n" .
2600                     "    weekly \n" .
2601                     "    missingok \n" .
2602                     "    rotate 4 \n" .
2603                     "    compress \n" .
2604                     "    delaycompress \n" .
2605                     "}");
2606             fclose($fh);
2607             */
2608         }
b1a6a5 2609
d71bae 2610         //* Remove Domain module as its functions are available in the client module now
T 2611         if(@is_dir('/usr/local/ispconfig/interface/web/domain')) exec('rm -rf /usr/local/ispconfig/interface/web/domain');
f30628 2612         
TB 2613         //* Disable rkhunter run and update in debian cronjob as ispconfig is running and updating rkhunter
2614         if(is_file('/etc/default/rkhunter')) {
2615             replaceLine('/etc/default/rkhunter', 'CRON_DAILY_RUN="yes"', 'CRON_DAILY_RUN="no"', 1, 0);
2616             replaceLine('/etc/default/rkhunter', 'CRON_DB_UPDATE="yes"', 'CRON_DB_UPDATE="no"', 1, 0);
2617         }
2618         
021aec 2619         // Add symlink for patch tool
TB 2620         if(!is_link('/usr/local/bin/ispconfig_patch')) exec('ln -s /usr/local/ispconfig/server/scripts/ispconfig_patch /usr/local/bin/ispconfig_patch');
5b3f25 2621         
c83951 2622         // Change mode of a few files from amavisd
TB 2623         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user')) chmod($conf['amavis']['config_dir'].'/conf.d/50-user', 0640);
2624         if(is_file($conf['amavis']['config_dir'].'/50-user~')) chmod($conf['amavis']['config_dir'].'/50-user~', 0400);
2625         if(is_file($conf['amavis']['config_dir'].'/amavisd.conf')) chmod($conf['amavis']['config_dir'].'/amavisd.conf', 0640);
2626         if(is_file($conf['amavis']['config_dir'].'/amavisd.conf~')) chmod($conf['amavis']['config_dir'].'/amavisd.conf~', 0400);
532ae5 2627     }
L 2628
2629     public function configure_dbserver() {
2630         global $conf;
2631
2632         //* If this server shall act as database server for client DB's, we configure this here
2633         $install_dir = $conf['ispconfig_install_dir'];
2634
2635         // Create a file with the database login details which
2636         // are used to create the client databases.
2637
2638         if(!is_dir($install_dir.'/server/lib')) {
2639             $command = "mkdir $install_dir/server/lib";
2640             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2641         }
2642
615a0a 2643         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mysql_clientdb.conf.master', 'tpl/mysql_clientdb.conf.master');
b1a6a5 2644         $content = str_replace('{hostname}', $conf['mysql']['host'], $content);
MC 2645         $content = str_replace('{username}', $conf['mysql']['admin_user'], $content);
67fede 2646         $content = str_replace('{password}', addslashes($conf['mysql']['admin_password']), $content);
b1a6a5 2647         wf($install_dir.'/server/lib/mysql_clientdb.conf', $content);
532ae5 2648         chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
L 2649         chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
a8ccf6 2650         chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
532ae5 2651
L 2652     }
2653
2654     public function install_crontab() {
2655         global $conf;
2656
2657         $install_dir = $conf['ispconfig_install_dir'];
2658
2659         //* Root Crontab
2660         exec('crontab -u root -l > crontab.txt');
2661         $existing_root_cron_jobs = file('crontab.txt');
2662
2663         // remove existing ispconfig cronjobs, in case the syntax has changed
2664         foreach($existing_root_cron_jobs as $key => $val) {
b1a6a5 2665             if(stristr($val, $install_dir)) unset($existing_root_cron_jobs[$key]);
532ae5 2666         }
L 2667
2668         $root_cron_jobs = array(
ad90a3 2669             "* * * * * ".$install_dir."/server/server.sh 2>&1 | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done",
MC 2670             "* * * * * ".$install_dir."/server/cron.sh 2>&1 | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done"
532ae5 2671         );
a8ccf6 2672
b6a10a 2673         if ($conf['nginx']['installed'] == true) {
F 2674             $root_cron_jobs[] = "0 0 * * * ".$install_dir."/server/scripts/create_daily_nginx_access_logs.sh &> /dev/null";
2675         }
a8ccf6 2676
532ae5 2677         foreach($root_cron_jobs as $cron_job) {
L 2678             if(!in_array($cron_job."\n", $existing_root_cron_jobs)) {
2679                 $existing_root_cron_jobs[] = $cron_job."\n";
2680             }
2681         }
2682         file_put_contents('crontab.txt', $existing_root_cron_jobs);
2683         exec('crontab -u root crontab.txt &> /dev/null');
2684         unlink('crontab.txt');
2685
2686         //* Getmail crontab
2687         if(is_user('getmail')) {
2688             $cf = $conf['getmail'];
2689             exec('crontab -u getmail -l > crontab.txt');
2690             $existing_cron_jobs = file('crontab.txt');
2691
2692             $cron_jobs = array(
b1a6a5 2693                 '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null'
532ae5 2694             );
L 2695
2696             // remove existing ispconfig cronjobs, in case the syntax has changed
2697             foreach($existing_cron_jobs as $key => $val) {
b1a6a5 2698                 if(stristr($val, 'getmail')) unset($existing_cron_jobs[$key]);
532ae5 2699             }
L 2700
2701             foreach($cron_jobs as $cron_job) {
2702                 if(!in_array($cron_job."\n", $existing_cron_jobs)) {
2703                     $existing_cron_jobs[] = $cron_job."\n";
2704                 }
2705             }
2706             file_put_contents('crontab.txt', $existing_cron_jobs);
2707             exec('crontab -u getmail crontab.txt &> /dev/null');
2708             unlink('crontab.txt');
2709         }
2710
2711         touch($conf['ispconfig_log_dir'].'/cron.log');
cc6568 2712         chmod($conf['ispconfig_log_dir'].'/cron.log', 0660);
532ae5 2713
L 2714     }
5b3f25 2715     
d5f2d5 2716     public function create_mount_script(){
MC 2717         global $app, $conf;
2718         $mount_script = '/usr/local/ispconfig/server/scripts/backup_dir_mount.sh';
2719         $mount_command = '';
2720         
2721         if(is_file($mount_script)) return;
2722         if(is_file('/etc/rc.local')){
2723             $rc_local = file('/etc/rc.local');
2724             if(is_array($rc_local) && !empty($rc_local)){
2725                 foreach($rc_local as $line){
2726                     $line = trim($line);
2727                     if(substr($line, 0, 1) == '#') continue;
2728                     if(strpos($line, 'sshfs') !== false && strpos($line, '/var/backup') !== false){
2729                         $mount_command = "#!/bin/sh\n\n";
2730                         $mount_command .= $line."\n\n";
2731                         file_put_contents($mount_script, $mount_command);
2732                         chmod($mount_script, 0755);
2733                         chown($mount_script, 'root');
2734                         chgrp($mount_script, 'root');
2735                         break;
2736                     }
2737                 }
2738             }
2739         }
2740     }
2741     
5b3f25 2742     // This function is called at the end of the update process and contains code to clean up parts of old ISPCONfig releases
TB 2743     public function cleanup_ispconfig() {
2744         global $app,$conf;
2745         
2746         // Remove directories recursively
2747         if(is_dir('/usr/local/ispconfig/interface/web/designer')) exec('rm -rf /usr/local/ispconfig/interface/web/designer');
4c3fcd 2748         if(is_dir('/usr/local/ispconfig/interface/web/themes/default-304')) exec('rm -rf /usr/local/ispconfig/interface/web/themes/default-304');
5b3f25 2749         
TB 2750         // Remove files
2751         if(is_file('/usr/local/ispconfig/interface/lib/classes/db_firebird.inc.php')) unlink('/usr/local/ispconfig/interface/lib/classes/db_firebird.inc.php');
2752         if(is_file('/usr/local/ispconfig/interface/lib/classes/form.inc.php')) unlink('/usr/local/ispconfig/interface/lib/classes/form.inc.php');
2753         
86bc65 2754         // Change mode of a few files from amavisd
MC 2755         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user')) chmod($conf['amavis']['config_dir'].'/conf.d/50-user', 0640);
2756         if(is_file($conf['amavis']['config_dir'].'/50-user~')) chmod($conf['amavis']['config_dir'].'/50-user~', 0400);
2757         if(is_file($conf['amavis']['config_dir'].'/amavisd.conf')) chmod($conf['amavis']['config_dir'].'/amavisd.conf', 0640);
2758         if(is_file($conf['amavis']['config_dir'].'/amavisd.conf~')) chmod($conf['amavis']['config_dir'].'/amavisd.conf~', 0400);
5b3f25 2759         
TB 2760     }
b1a6a5 2761
33bcd0 2762     public function getinitcommand($servicename, $action, $init_script_directory = ''){
FT 2763         global $conf;
2764         // upstart
2765         if(is_executable('/sbin/initctl')){
2766             exec('/sbin/initctl version 2>/dev/null | /bin/grep -q upstart', $retval['output'], $retval['retval']);
2767             if(intval($retval['retval']) == 0) return 'service '.$servicename.' '.$action;
2768         }
bc04c3 2769         // systemd
TB 2770         if(is_executable('/bin/systemd') || is_executable('/usr/bin/systemctl')){
2771             return 'systemctl '.$action.' '.$servicename.'.service';
2772         }
33bcd0 2773         // sysvinit
FT 2774         if($init_script_directory == '') $init_script_directory = $conf['init_scripts'];
2775         if(substr($init_script_directory, -1) === '/') $init_script_directory = substr($init_script_directory, 0, -1);
2776         return $init_script_directory.'/'.$servicename.' '.$action;
2777     }
532ae5 2778
L 2779     /**
2780      * Helper function - get the path to a template file based on
2781      * the local part of the filename. Checks first for the existence
2782      * of a distribution specific file and if not found looks in the
2783      * base template folder. Optionally the behaviour can be changed
2784      * by setting the 2nd parameter which will fetch the contents
2785      * of the template file and return it instead of the path. The 3rd
2786      * parameter further extends this behaviour by filtering the contents
2787      * by inserting the ispconfig database credentials using the {} placeholders.
2788      *
2789      * @param string $tLocal local part of filename
2790      * @param bool $tRf
2791      * @param bool $tDBCred
2792      * @return string Relative path to the chosen template file
2793      */
2794     protected function get_template_file($tLocal, $tRf=false, $tDBCred=false) {
2795         global $conf, $dist;
2796
2797         $final_path = '';
b1a6a5 2798         $dist_template = $conf['ispconfig_install_dir'] . '/server/conf-custom/install/' . $tLocal . '.master';
MC 2799         if (file_exists($dist_template)) {
532ae5 2800             $final_path = $dist_template;
L 2801         } else {
b1a6a5 2802             $dist_template = 'dist/tpl/'.strtolower($dist['name'])."/$tLocal.master";
MC 2803             if (file_exists($dist_template)) {
2804                 $final_path = $dist_template;
2805             } else {
2806                 $final_path = "tpl/$tLocal.master";
2807             }
2808         }
532ae5 2809
L 2810         if (!$tRf) {
2811             return $final_path;
2812         } else {
2813             return (!$tDBCred) ? rf($final_path) : $this->insert_db_credentials(rf($final_path));
2814         }
2815     }
2816
2817     /**
2818      * Helper function - writes the contents to a config file
2819      * and performs a backup if the file exist. Additionally
2820      * if the file exists the new file will be given the
2821      * same rights and ownership as the original. Optionally the
2822      * rights and/or ownership can be overriden by appending umask,
2823      * user and group to the parameters. Providing only uid and gid
2824      * values will result in only a chown.
2825      *
2826      * @param $tConf
2827      * @param $tContents
2828      * @return bool
2829      */
2830     protected function write_config_file($tConf, $tContents) {
2831         // Backup config file before writing new contents and stat file
2832         if ( is_file($tConf) ) {
2833             $stat = exec('stat -c \'%a %U %G\' '.escapeshellarg($tConf), $output, $res);
2834             if ($res == 0) { // stat successfull
8cddcd 2835                 list($access, $user, $group) = explode(" ", $stat);
532ae5 2836             }
L 2837
2838             if ( copy($tConf, $tConf.'~') ) {
2839                 chmod($tConf.'~', 0400);
2840             }
2841         }
2842
2843         wf($tConf, $tContents); // write file
2844
2845         if (func_num_args() >= 4) // override rights and/or ownership
b1a6a5 2846             {
532ae5 2847             $args = func_get_args();
L 2848             $output = array_slice($args, 2);
2849
2850             switch (sizeof($output)) {
b1a6a5 2851             case 3:
MC 2852                 $umask = array_shift($output);
2853                 if (is_numeric($umask) && preg_match('/^0?[0-7]{3}$/', $umask)) {
2854                     $access = $umask;
2855                 }
2856             case 2:
2857                 if (is_user($output[0]) && is_group($output[1])) {
2858                     list($user, $group) = $output;
2859                 }
2860                 break;
532ae5 2861             }
L 2862         }
2863
2864         if (!empty($user) && !empty($group)) {
2865             chown($tConf, $user);
2866             chgrp($tConf, $group);
2867         }
2868
2869         if (!empty($access)) {
2870             exec("chmod $access $tConf");
2871         }
2872     }
2873
2874     /**
2875      * Helper function - filter the contents of a config
2876      * file by inserting the common ispconfig database
2877      * credentials.
2878      *
2879      * @param $tContents
2880      * @return string
2881      */
2882     protected function insert_db_credentials($tContents) {
2883         global $conf;
2884
2885         $tContents = str_replace('{mysql_server_ispconfig_user}', $conf["mysql"]["ispconfig_user"], $tContents);
2886         $tContents = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $tContents);
2887         $tContents = str_replace('{mysql_server_database}', $conf["mysql"]["database"], $tContents);
2888         $tContents = str_replace('{mysql_server_ip}', $conf["mysql"]["ip"], $tContents);
b1a6a5 2889         $tContents = str_replace('{mysql_server_host}', $conf['mysql']['host'], $tContents);
82e9b9 2890         $tContents = str_replace('{mysql_server_port}', $conf['mysql']['port'], $tContents);
b1a6a5 2891         $tContents = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $tContents);
532ae5 2892
L 2893         return $tContents;
2894     }
b1a6a5 2895
532ae5 2896 }
L 2897
f66404 2898 ?>