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