Till Brehm
2014-09-24 6061d5f84726eb7f93eceff24de63bb471c9d029
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) {
7fe908 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;
992797 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 */
7fe908 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",
7fe908 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",
7fe908 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'].".* "
7fe908 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) {
7fe908 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              */
7fe908 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
7fe908 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."' ";
7fe908 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
532ae5 519             }
L 520
521             /*
522          * It is all done. Relod the rights...
523          */
7fe908 524             $this->dbmaster->query('FLUSH PRIVILEGES;');
532ae5 525         }
L 526
527     }
528
529     //** writes postfix configuration files
530     public function process_postfix_config($configfile) {
531         global $conf;
532
533         $config_dir = $conf['postfix']['config_dir'].'/';
534         $full_file_name = $config_dir.$configfile;
535         //* Backup exiting file
536         if(is_file($full_file_name)) {
537             copy($full_file_name, $config_dir.$configfile.'~');
538         }
615a0a 539         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 540         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 541         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
542         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
543         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
544         $content = str_replace('{server_id}', $conf['server_id'], $content);
545         wf($full_file_name, $content);
546     }
547
548     public function configure_jailkit() {
549         global $conf;
550
551         $cf = $conf['jailkit'];
552         $config_dir = $cf['config_dir'];
553         $jk_init = $cf['jk_init'];
554         $jk_chrootsh = $cf['jk_chrootsh'];
555
556         if (is_dir($config_dir)) {
557             if(is_file($config_dir.'/'.$jk_init)) copy($config_dir.'/'.$jk_init, $config_dir.'/'.$jk_init.'~');
558             if(is_file($config_dir.'/'.$jk_chrootsh.'.master')) copy($config_dir.'/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh.'~');
7fe908 559
MC 560             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master')) {
561                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master', $config_dir.'/'.$jk_init);
562             } else {
563                 copy('tpl/'.$jk_init.'.master', $config_dir.'/'.$jk_init);
564             }
565             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master')) {
566                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh);
567             } else {
568                 copy('tpl/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh);
569             }
532ae5 570         }
a8ccf6 571
edf806 572         //* help jailkit fo find its ini files
T 573         if(!is_link('/usr/jk_socketd.ini')) exec('ln -s /etc/jailkit/jk_socketd.ini /usr/jk_socketd.ini');
574         if(!is_link('/usr/jk_init.ini')) exec('ln -s /etc/jailkit/jk_init.ini /usr/jk_init.ini');
532ae5 575
L 576     }
a8ccf6 577
532ae5 578     public function configure_mailman($status = 'insert') {
L 579         global $conf;
580
581         $config_dir = $conf['mailman']['config_dir'].'/';
582         $full_file_name = $config_dir.'mm_cfg.py';
583         //* Backup exiting file
584         if(is_file($full_file_name)) {
585             copy($full_file_name, $config_dir.'mm_cfg.py~');
586         }
a8ccf6 587
532ae5 588         // load files
615a0a 589         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mm_cfg.py.master', 'tpl/mm_cfg.py.master');
532ae5 590         $old_file = rf($full_file_name);
a8ccf6 591
532ae5 592         $old_options = array();
a8ccf6 593         $lines = explode("\n", $old_file);
532ae5 594         foreach ($lines as $line)
L 595         {
8fe9ab 596             if (trim($line) != '' && substr($line, 0, 1) != '#')
532ae5 597             {
8fe9ab 598                 @list($key, $value) = @explode("=", $line);
532ae5 599                 if (!empty($value))
L 600                 {
601                     $key = rtrim($key);
602                     $old_options[$key] = trim($value);
603                 }
604             }
605         }
a8ccf6 606
532ae5 607         $virtual_domains = '';
L 608         if($status == 'update')
609         {
610             // create virtual_domains list
611             $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain");
a8ccf6 612
8fe9ab 613             if(is_array($domainAll)) {
7fe908 614                 foreach($domainAll as $domain)
MC 615                 {
616                     if ($domainAll[0]['domain'] == $domain['domain'])
617                         $virtual_domains .= "'".$domain['domain']."'";
618                     else
619                         $virtual_domains .= ", '".$domain['domain']."'";
620                 }
8fe9ab 621             }
532ae5 622         }
L 623         else
624             $virtual_domains = "' '";
a8ccf6 625
532ae5 626         $content = str_replace('{hostname}', $conf['hostname'], $content);
46c775 627         if(!isset($old_options['DEFAULT_SERVER_LANGUAGE'])) $old_options['DEFAULT_SERVER_LANGUAGE'] = '';
532ae5 628         $content = str_replace('{default_language}', $old_options['DEFAULT_SERVER_LANGUAGE'], $content);
L 629         $content = str_replace('{virtual_domains}', $virtual_domains, $content);
7fe908 630
532ae5 631         wf($full_file_name, $content);
7fe908 632
cc6568 633         //* Write virtual_to_transport.sh script
H 634         $config_dir = $conf['mailman']['config_dir'].'/';
635         $full_file_name = $config_dir.'virtual_to_transport.sh';
7fe908 636
cc6568 637         //* Backup exiting virtual_to_transport.sh script
H 638         if(is_file($full_file_name)) {
639             copy($full_file_name, $config_dir.'virtual_to_transport.sh~');
640         }
7fe908 641
cc6568 642         if(is_dir('/etc/mailman')) {
615a0a 643             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) {
7fe908 644                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name);
MC 645             } else {
646                 copy('tpl/mailman-virtual_to_transport.sh', $full_file_name);
647             }
648             chgrp($full_file_name, 'list');
d22542 649             chmod($full_file_name, 0755);
cc6568 650         }
7fe908 651
cc6568 652         //* Create aliasaes
H 653         exec('/usr/lib/mailman/bin/genaliases 2>/dev/null');
5afa9d 654         if(is_file('/var/lib/mailman/data/virtual-mailman')) exec('postmap /var/lib/mailman/data/virtual-mailman');
7fe908 655
532ae5 656     }
L 657
658     public function configure_postfix($options = '') {
b04e82 659         global $conf,$autoinstall;
532ae5 660         $cf = $conf['postfix'];
L 661         $config_dir = $cf['config_dir'];
662
663         if(!is_dir($config_dir)) {
664             $this->error("The postfix configuration directory '$config_dir' does not exist.");
665         }
666
667         //* mysql-virtual_domains.cf
668         $this->process_postfix_config('mysql-virtual_domains.cf');
669
670         //* mysql-virtual_forwardings.cf
671         $this->process_postfix_config('mysql-virtual_forwardings.cf');
672
673         //* mysql-virtual_mailboxes.cf
674         $this->process_postfix_config('mysql-virtual_mailboxes.cf');
675
676         //* mysql-virtual_email2email.cf
677         $this->process_postfix_config('mysql-virtual_email2email.cf');
678
679         //* mysql-virtual_transports.cf
680         $this->process_postfix_config('mysql-virtual_transports.cf');
681
682         //* mysql-virtual_recipient.cf
683         $this->process_postfix_config('mysql-virtual_recipient.cf');
684
685         //* mysql-virtual_sender.cf
686         $this->process_postfix_config('mysql-virtual_sender.cf');
687
688         //* mysql-virtual_client.cf
689         $this->process_postfix_config('mysql-virtual_client.cf');
690
691         //* mysql-virtual_relaydomains.cf
692         $this->process_postfix_config('mysql-virtual_relaydomains.cf');
693
694         //* mysql-virtual_relayrecipientmaps.cf
695         $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf');
696
697         //* Changing mode and group of the new created config files.
698         caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
7fe908 699             __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed');
532ae5 700         caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null',
7fe908 701             __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed');
532ae5 702
L 703         //* Creating virtual mail user and group
704         $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname'];
705         if(!is_group($cf['vmail_groupname'])) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
706
707         $command = 'useradd -g '.$cf['vmail_groupname'].' -u '.$cf['vmail_userid'].' '.$cf['vmail_username'].' -d '.$cf['vmail_mailbox_base'].' -m';
708         if(!is_user($cf['vmail_username'])) caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a8ccf6 709
b67344 710         //* These postconf commands will be executed on installation and update
4ed035 711         $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM `" . $this->db->quote($conf["mysql"]["database"]) . "`.`server` WHERE server_id = ".$conf['server_id']);
a296ae 712         $server_ini_array = ini_to_array(stripslashes($server_ini_rec['config']));
M 713         unset($server_ini_rec);
714
715         //* If there are RBL's defined, format the list and add them to smtp_recipient_restrictions to prevent removeal after an update
716         $rbl_list = '';
6882ab 717         if (@isset($server_ini_array['mail']['realtime_blackhole_list']) && $server_ini_array['mail']['realtime_blackhole_list'] != '') {
7fe908 718             $rbl_hosts = explode(",", str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list']));
a296ae 719             foreach ($rbl_hosts as $key => $value) {
M 720                 $rbl_list .= ", reject_rbl_client ". $value;
721             }
722         }
723         unset($rbl_hosts);
724         unset($server_ini_array);
7fe908 725
MC 726         $postconf_placeholders = array('{config_dir}' => $config_dir,
727             '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'],
728             '{vmail_userid}' => $cf['vmail_userid'],
729             '{vmail_groupid}' => $cf['vmail_groupid'],
730             '{rbl_list}' => $rbl_list);
731
732         $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_postfix.conf.master', 'tpl/debian_postfix.conf.master');
733         $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders);
734         $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines
a8ccf6 735
b67344 736         //* These postconf commands will be executed on installation only
T 737         if($this->is_update == false) {
7fe908 738             $postconf_commands = array_merge($postconf_commands, array(
MC 739                     'myhostname = '.$conf['hostname'],
740                     'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain',
741                     'mynetworks = 127.0.0.0/8 [::1]/128'
742                 ));
b67344 743         }
532ae5 744
L 745         //* Create the header and body check files
746         touch($config_dir.'/header_checks');
747         touch($config_dir.'/mime_header_checks');
748         touch($config_dir.'/nested_header_checks');
749         touch($config_dir.'/body_checks');
a8ccf6 750
532ae5 751         //* Create the mailman files
cc6568 752         if(!is_dir('/var/lib/mailman/data')) exec('mkdir -p /var/lib/mailman/data');
5378e9 753         if(!is_file('/var/lib/mailman/data/aliases')) touch('/var/lib/mailman/data/aliases');
T 754         exec('postalias /var/lib/mailman/data/aliases');
755         if(!is_file('/var/lib/mailman/data/virtual-mailman')) touch('/var/lib/mailman/data/virtual-mailman');
d4d965 756         exec('postmap /var/lib/mailman/data/virtual-mailman');
cc6568 757         if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman');
H 758         exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman');
532ae5 759
L 760         //* Make a backup copy of the main.cf file
761         copy($config_dir.'/main.cf', $config_dir.'/main.cf~');
762
763         //* Executing the postconf commands
764         foreach($postconf_commands as $cmd) {
765             $command = "postconf -e '$cmd'";
766             caselog($command." &> /dev/null", __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
767         }
768
7fe908 769         if(!stristr($options, 'dont-create-certs')) {
532ae5 770             //* Create the SSL certificate
b04e82 771             if(AUTOINSTALL){
bcd725 772                 $command = 'cd '.$config_dir.'; '
b04e82 773                     ."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 774             } else {
FT 775                 $command = 'cd '.$config_dir.'; '
776                     .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:4096 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509';
777             }
532ae5 778             exec($command);
L 779
780             $command = 'chmod o= '.$config_dir.'/smtpd.key';
781             caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
782         }
783
784         //** We have to change the permissions of the courier authdaemon directory to make it accessible for maildrop.
785         $command = 'chmod 755  /var/run/courier/authdaemon/';
786         if(is_file('/var/run/courier/authdaemon/')) caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command);
787
788         //* Changing maildrop lines in posfix master.cf
789         if(is_file($config_dir.'/master.cf')) {
790             copy($config_dir.'/master.cf', $config_dir.'/master.cf~');
791         }
792         if(is_file($config_dir.'/master.cf~')) {
793             chmod($config_dir.'/master.cf~', 0400);
794         }
795         $configfile = $config_dir.'/master.cf';
796         $content = rf($configfile);
797         $content = str_replace('flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}',
7fe908 798             'flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d '.$cf['vmail_username'].' ${extension} ${recipient} ${user} ${nexthop} ${sender}',
MC 799             $content);
532ae5 800         wf($configfile, $content);
L 801
802         //* Writing the Maildrop mailfilter file
803         $configfile = 'mailfilter';
804         if(is_file($cf['vmail_mailbox_base'].'/.'.$configfile)) {
805             copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~');
806         }
615a0a 807         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 808         $content = str_replace('{dist_postfix_vmail_mailbox_base}', $cf['vmail_mailbox_base'], $content);
L 809         wf($cf['vmail_mailbox_base'].'/.'.$configfile, $content);
810
811         //* Create the directory for the custom mailfilters
812         if(!is_dir($cf['vmail_mailbox_base'].'/mailfilters')) {
813             $command = 'mkdir '.$cf['vmail_mailbox_base'].'/mailfilters';
814             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
815         }
816
817         //* Chmod and chown the .mailfilter file
419eb7 818         $command = 'chown '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 819         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 820
419eb7 821         $command = 'chmod 600 '.$cf['vmail_mailbox_base'].'/.mailfilter';
532ae5 822         caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 823
824     }
825
826     public function configure_saslauthd() {
827         global $conf;
a8ccf6 828
26c0fc 829         //* Get saslsauthd version
7fe908 830         exec('saslauthd -v 2>&1', $out);
MC 831         $parts = explode(' ', $out[0]);
26c0fc 832         $saslversion = $parts[1];
T 833         unset($parts);
834         unset($out);
532ae5 835
26c0fc 836         if(version_compare($saslversion , '2.1.23') > 0) {
T 837             //* Configfile for saslauthd versions 2.1.24 and newer
838             $configfile = 'sasl_smtpd2.conf';
839         } else {
840             //* Configfile for saslauthd versions up to 2.1.23
841             $configfile = 'sasl_smtpd.conf';
842         }
a8ccf6 843
7fe908 844         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 845         if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf~')) chmod($conf['postfix']['config_dir'].'/sasl/smtpd.conf~', 0400);
615a0a 846         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 847         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 848         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
849         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
850         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
851         wf($conf['postfix']['config_dir'].'/sasl/smtpd.conf', $content);
532ae5 852
L 853         // TODO: Chmod and chown on the config file
854
855
856         // Recursively create the spool directory
857         if(!@is_dir('/var/spool/postfix/var/run/saslauthd')) mkdir('/var/spool/postfix/var/run/saslauthd', 0755, true);
858
859         // Edit the file /etc/default/saslauthd
860         $configfile = $conf['saslauthd']['config'];
7fe908 861         if(is_file($configfile)) copy($configfile, $configfile.'~');
532ae5 862         if(is_file($configfile.'~')) chmod($configfile.'~', 0400);
L 863         $content = rf($configfile);
7fe908 864         $content = str_replace('START=no', 'START=yes', $content);
532ae5 865         // Debian
7fe908 866         $content = str_replace('OPTIONS="-c"', 'OPTIONS="-m /var/spool/postfix/var/run/saslauthd -r"', $content);
532ae5 867         // Ubuntu
7fe908 868         $content = str_replace('OPTIONS="-c -m /var/run/saslauthd"', 'OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"', $content);
MC 869         wf($configfile, $content);
532ae5 870
L 871         // Edit the file /etc/init.d/saslauthd
872         $configfile = $conf['init_scripts'].'/'.$conf['saslauthd']['init_script'];
873         $content = rf($configfile);
7fe908 874         $content = str_replace('PIDFILE=$RUN_DIR/saslauthd.pid', 'PIDFILE="/var/spool/postfix/var/run/${NAME}/saslauthd.pid"', $content);
MC 875         wf($configfile, $content);
532ae5 876
L 877         // add the postfix user to the sasl group (at least necessary for Ubuntu 8.04 and most likely Debian Lenny as well.
878         exec('adduser postfix sasl');
879
880
881     }
882
883     public function configure_pam() {
884         global $conf;
885         $pam = $conf['pam'];
886         //* configure pam for SMTP authentication agains the ispconfig database
887         $configfile = 'pamd_smtp';
888         if(is_file($pam.'/smtp'))    copy($pam.'/smtp', $pam.'/smtp~');
889         if(is_file($pam.'/smtp~'))   chmod($pam.'/smtp~', 0400);
890
615a0a 891         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 892         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 893         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
894         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
895         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
896         wf($pam.'/smtp', $content);
897         // On some OSes smtp is world readable which allows for reading database information.  Removing world readable rights should have no effect.
898         if(is_file($pam.'/smtp'))    exec("chmod o= $pam/smtp");
899         chmod($pam.'/smtp', 0660);
900         chown($pam.'/smtp', 'daemon');
901         chgrp($pam.'/smtp', 'daemon');
902
903     }
904
905     public function configure_courier() {
906         global $conf;
907         $config_dir = $conf['courier']['config_dir'];
908         //* authmysqlrc
909         $configfile = 'authmysqlrc';
910         if(is_file($config_dir.'/'.$configfile)) {
911             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
912         }
913         chmod($config_dir.'/'.$configfile.'~', 0400);
615a0a 914         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 915         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 916         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
917         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
918         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
532ae5 919         wf($config_dir.'/'.$configfile, $content);
L 920
921         chmod($config_dir.'/'.$configfile, 0660);
922         chown($config_dir.'/'.$configfile, 'daemon');
923         chgrp($config_dir.'/'.$configfile, 'daemon');
924
925         //* authdaemonrc
926         $configfile = $config_dir.'/authdaemonrc';
927         if(is_file($configfile)) {
928             copy($configfile, $configfile.'~');
929         }
930         if(is_file($configfile.'~')) {
931             chmod($configfile.'~', 0400);
932         }
933         $content = rf($configfile);
934         $content = str_replace('authmodulelist="authpam"', 'authmodulelist="authmysql"', $content);
935         wf($configfile, $content);
936     }
937
938     public function configure_dovecot() {
939         global $conf;
940
941         $config_dir = $conf['dovecot']['config_dir'];
942
943         //* Configure master.cf and add a line for deliver
944         if(is_file($conf['postfix']['config_dir'].'/master.cf')) {
945             copy($conf['postfix']['config_dir'].'/master.cf', $conf['postfix']['config_dir'].'/master.cf~2');
946         }
947         if(is_file($conf['postfix']['config_dir'].'/master.cf~')) {
948             chmod($conf['postfix']['config_dir'].'/master.cf~2', 0400);
949         }
950         $content = rf($conf['postfix']['config_dir'].'/master.cf');
951         // Only add the content if we had not addded it before
7fe908 952         if(!stristr($content, 'dovecot/deliver')) {
013ae4 953             $deliver_content = 'dovecot   unix  -       n       n       -       -       pipe'."\n".'  flags=DROhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}';
7fe908 954             af($conf['postfix']['config_dir'].'/master.cf', $deliver_content);
532ae5 955         }
L 956         unset($content);
957         unset($deliver_content);
958
959
960         //* Reconfigure postfix to use dovecot authentication
961         // Adding the amavisd commands to the postfix configuration
962         $postconf_commands = array (
7fe908 963             'dovecot_destination_recipient_limit = 1',
MC 964             'virtual_transport = dovecot',
965             'smtpd_sasl_type = dovecot',
966             'smtpd_sasl_path = private/auth'
532ae5 967         );
L 968
969         // Make a backup copy of the main.cf file
7fe908 970         copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~3');
532ae5 971
L 972         // Executing the postconf commands
973         foreach($postconf_commands as $cmd) {
974             $command = "postconf -e '$cmd'";
975             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
976         }
977
31e0d1 978         //* backup dovecot.conf
532ae5 979         $configfile = 'dovecot.conf';
L 980         if(is_file($config_dir.'/'.$configfile)) {
981             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
982         }
a8ccf6 983
31e0d1 984         //* Get the dovecot version
7fe908 985         exec('dovecot --version', $tmp);
MC 986         $parts = explode('.', trim($tmp[0]));
31e0d1 987         $dovecot_version = $parts[0];
T 988         unset($tmp);
989         unset($parts);
a8ccf6 990
31e0d1 991         //* Copy dovecot configuration file
T 992         if($dovecot_version == 2) {
7fe908 993             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master')) {
MC 994                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master', $config_dir.'/'.$configfile);
995             } else {
996                 copy('tpl/debian_dovecot2.conf.master', $config_dir.'/'.$configfile);
997             }
65576f 998             replaceLine($config_dir.'/'.$configfile, 'postmaster_address = postmaster@example.com', 'postmaster_address = postmaster@'.$conf['hostname'], 1, 0);
31e0d1 999         } else {
7fe908 1000             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master')) {
MC 1001                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master', $config_dir.'/'.$configfile);
1002             } else {
1003                 copy('tpl/debian_dovecot.conf.master', $config_dir.'/'.$configfile);
1004             }
31e0d1 1005         }
532ae5 1006
L 1007         //* dovecot-sql.conf
1008         $configfile = 'dovecot-sql.conf';
1009         if(is_file($config_dir.'/'.$configfile)) {
1010             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1011         }
edf806 1012         if(is_file($config_dir.'/'.$configfile.'~')) chmod($config_dir.'/'.$configfile.'~', 0400);
615a0a 1013         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot-sql.conf.master', 'tpl/debian_dovecot-sql.conf.master');
7fe908 1014         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1015         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1016         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1017         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
032b86 1018         $content = str_replace('{server_id}', $conf['server_id'], $content);
532ae5 1019         wf($config_dir.'/'.$configfile, $content);
L 1020
1021         chmod($config_dir.'/'.$configfile, 0600);
1022         chown($config_dir.'/'.$configfile, 'root');
1023         chgrp($config_dir.'/'.$configfile, 'root');
5e7306 1024         
TB 1025         // Dovecot shall ignore mounts in website directory
7db4cd 1026         if(is_installed('doveadm')) exec("doveadm mount add '/var/www/*' ignore > /dev/null 2> /dev/null");
532ae5 1027
L 1028     }
1029
1030     public function configure_amavis() {
1031         global $conf;
1032
1033         // amavisd user config file
1034         $configfile = 'amavisd_user_config';
7fe908 1035         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 1036         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user~')) chmod($conf['amavis']['config_dir'].'/conf.d/50-user~', 0400);
615a0a 1037         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1038         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1039         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1040         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1041         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
1042         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1043         wf($conf['amavis']['config_dir'].'/conf.d/50-user', $content);
532ae5 1044
L 1045         // TODO: chmod and chown on the config file
1046
1047
1048         // Adding the amavisd commands to the postfix configuration
864ee2 1049         // Add array for no error in foreach and maybe future options
X 1050         $postconf_commands = array ();
a8ccf6 1051
864ee2 1052         // Check for amavisd -> pure webserver with postfix for mailing without antispam
ac28b5 1053         if ($conf['amavis']['installed']) {
864ee2 1054             $postconf_commands[] = 'content_filter = amavis:[127.0.0.1]:10024';
X 1055             $postconf_commands[] = 'receive_override_options = no_address_mappings';
1056         }
532ae5 1057
L 1058         // Make a backup copy of the main.cf file
7fe908 1059         copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~2');
532ae5 1060
L 1061         // Executing the postconf commands
1062         foreach($postconf_commands as $cmd) {
1063             $command = "postconf -e '$cmd'";
1064             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1065         }
1066
1067         // Append the configuration for amavisd to the master.cf file
7fe908 1068         if(is_file($conf['postfix']['config_dir'].'/master.cf')) copy($conf['postfix']['config_dir'].'/master.cf', $conf['postfix']['config_dir'].'/master.cf~');
532ae5 1069         $content = rf($conf['postfix']['config_dir'].'/master.cf');
L 1070         // Only add the content if we had not addded it before
7fe908 1071         if(!stristr($content, '127.0.0.1:10025')) {
532ae5 1072             unset($content);
615a0a 1073             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', 'tpl/master_cf_amavis.master');
7fe908 1074             af($conf['postfix']['config_dir'].'/master.cf', $content);
532ae5 1075         }
L 1076         unset($content);
1077
1078         // Add the clamav user to the amavis group
1079         exec('adduser clamav amavis');
1080
1081
1082     }
1083
1084     public function configure_spamassassin() {
1085         global $conf;
1086
1087         //* Enable spamasasssin on debian and ubuntu
1088         $configfile = '/etc/default/spamassassin';
1089         if(is_file($configfile)) {
1090             copy($configfile, $configfile.'~');
1091         }
1092         $content = rf($configfile);
1093         $content = str_replace('ENABLED=0', 'ENABLED=1', $content);
1094         wf($configfile, $content);
1095     }
1096
1097     public function configure_getmail() {
1098         global $conf;
1099
1100         $config_dir = $conf['getmail']['config_dir'];
1101
1102         if(!@is_dir($config_dir)) mkdir(escapeshellcmd($config_dir), 0700, true);
1103
1104         $command = 'useradd -d '.$config_dir.' getmail';
1105         if(!is_user('getmail')) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1106
1107         $command = "chown -R getmail $config_dir";
1108         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1109
1110         $command = "chmod -R 700 $config_dir";
1111         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1112     }
1113
1114
1115     public function configure_pureftpd() {
acdd7a 1116         global $conf;
532ae5 1117
L 1118         $config_dir = $conf['pureftpd']['config_dir'];
1119
1120         //* configure pure-ftpd for MySQL authentication against the ispconfig database
1121         $configfile = 'db/mysql.conf';
1122         if(is_file($config_dir.'/'.$configfile)) {
1123             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1124         }
1125         if(is_file($config_dir.'/'.$configfile.'~')) {
1126             chmod($config_dir.'/'.$configfile.'~', 0400);
1127         }
615a0a 1128         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/pureftpd_mysql.conf.master', 'tpl/pureftpd_mysql.conf.master');
532ae5 1129         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 1130         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1131         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1132         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1133         $content = str_replace('{server_id}', $conf['server_id'], $content);
1134         wf($config_dir.'/'.$configfile, $content);
1135         chmod($config_dir.'/'.$configfile, 0600);
1136         chown($config_dir.'/'.$configfile, 'root');
1137         chgrp($config_dir.'/'.$configfile, 'root');
1138         // **enable chrooting
1139         //exec('mkdir -p '.$config_dir.'/conf/ChrootEveryone');
1140         exec('echo "yes" > '.$config_dir.'/conf/ChrootEveryone');
1141         exec('echo "yes" > '.$config_dir.'/conf/BrokenClientsCompatibility');
1142         exec('echo "yes" > '.$config_dir.'/conf/DisplayDotFiles');
1143
1144         if(is_file('/etc/default/pure-ftpd-common')) {
7fe908 1145             replaceLine('/etc/default/pure-ftpd-common', 'STANDALONE_OR_INETD=inetd', 'STANDALONE_OR_INETD=standalone', 1, 0);
MC 1146             replaceLine('/etc/default/pure-ftpd-common', 'VIRTUALCHROOT=false', 'VIRTUALCHROOT=true', 1, 0);
532ae5 1147         }
L 1148
1149         if(is_file('/etc/inetd.conf')) {
7fe908 1150             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 1151             exec($this->getinitcommand('openbsd-inetd', 'restart'));
33bcd0 1152             //if(is_file($conf['init_scripts'].'/'.'openbsd-inetd')) exec($conf['init_scripts'].'/'.'openbsd-inetd restart');
532ae5 1153         }
L 1154
1155         if(!is_file('/etc/pure-ftpd/conf/DontResolve')) exec('echo "yes" > /etc/pure-ftpd/conf/DontResolve');
1156     }
1157
1158     public function configure_mydns() {
1159         global $conf;
1160
1161         // configure pam for SMTP authentication agains the ispconfig database
1162         $configfile = 'mydns.conf';
7fe908 1163         if(is_file($conf['mydns']['config_dir'].'/'.$configfile)) copy($conf['mydns']['config_dir'].'/'.$configfile, $conf['mydns']['config_dir'].'/'.$configfile.'~');
532ae5 1164         if(is_file($conf['mydns']['config_dir'].'/'.$configfile.'~')) chmod($conf['mydns']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1165         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1166         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1167         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1168         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1169         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1170         $content = str_replace('{server_id}', $conf['server_id'], $content);
1171         wf($conf['mydns']['config_dir'].'/'.$configfile, $content);
532ae5 1172         chmod($conf['mydns']['config_dir'].'/'.$configfile, 0600);
L 1173         chown($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1174         chgrp($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1175
1176     }
1177
1178     public function configure_powerdns() {
1179         global $conf;
1180
1181         //* Create the database
1182         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['powerdns']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
1183             $this->error('Unable to create MySQL database: '.$conf['powerdns']['database'].'.');
1184         }
1185
1186         //* Create the ISPConfig database user in the local database
1187         $query = "GRANT ALL ON `".$conf['powerdns']['database']."` . * TO '".$conf['mysql']['ispconfig_user']."'@'localhost';";
1188         if(!$this->db->query($query)) {
1189             $this->error('Unable to create user for powerdns database Error: '.$this->db->errorMessage);
1190         }
1191
1192         //* Reload database privelages
1193         $this->db->query('FLUSH PRIVILEGES;');
1194
1195         //* load the powerdns databse dump
1196         if($conf['mysql']['admin_password'] == '') {
1197             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",
7fe908 1198                 __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
532ae5 1199         } else {
L 1200             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",
7fe908 1201                 __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
532ae5 1202         }
L 1203
1204         //* Create the powerdns config file
1205         $configfile = 'pdns.local';
7fe908 1206         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile)) copy($conf['powerdns']['config_dir'].'/'.$configfile, $conf['powerdns']['config_dir'].'/'.$configfile.'~');
532ae5 1207         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile.'~')) chmod($conf['powerdns']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1208         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1209         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1210         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1211         $content = str_replace('{powerdns_database}', $conf['powerdns']['database'], $content);
1212         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1213         wf($conf['powerdns']['config_dir'].'/'.$configfile, $content);
532ae5 1214         chmod($conf['powerdns']['config_dir'].'/'.$configfile, 0600);
L 1215         chown($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1216         chgrp($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1217
1218
1219     }
1220
1221     public function configure_bind() {
1222         global $conf;
1223
7fe908 1224         //* Check if the zonefile directory has a slash at the end
MC 1225         $content=$conf['bind']['bind_zonefiles_dir'];
1226         if(substr($content, -1, 1) != '/') {
1227             $content .= '/';
532ae5 1228         }
L 1229
1230         //* Create the slave subdirectory
7fe908 1231         $content .= 'slave';
MC 1232         if(!@is_dir($content)) mkdir($content, 0770, true);
532ae5 1233
7fe908 1234         //* Chown the slave subdirectory to $conf['bind']['bind_user']
MC 1235         chown($content, $conf['bind']['bind_user']);
1236         chgrp($content, $conf['bind']['bind_group']);
532ae5 1237
L 1238     }
1239
1240
1241
1242     public function configure_apache() {
1243         global $conf;
1244
4ffb51 1245         if($conf['apache']['installed'] == false) return;
532ae5 1246         //* Create the logging directory for the vhost logfiles
L 1247         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1248
1249         if(is_file('/etc/suphp/suphp.conf')) {
7fe908 1250             replaceLine('/etc/suphp/suphp.conf', 'php=php:/usr/bin', 'x-httpd-suphp="php:/usr/bin/php-cgi"', 0);
532ae5 1251             //replaceLine('/etc/suphp/suphp.conf','docroot=','docroot=/var/clients',0);
7fe908 1252             replaceLine('/etc/suphp/suphp.conf', 'umask=0077', 'umask=0022', 0);
532ae5 1253         }
L 1254
1255         if(is_file('/etc/apache2/sites-enabled/000-default')) {
7fe908 1256             replaceLine('/etc/apache2/sites-available/000-default', 'NameVirtualHost *', 'NameVirtualHost *:80', 1, 0);
MC 1257             replaceLine('/etc/apache2/sites-available/000-default', '<VirtualHost *>', '<VirtualHost *:80>', 1, 0);
532ae5 1258         }
L 1259
1260         if(is_file('/etc/apache2/ports.conf')) {
1261             // add a line "Listen 443" to ports conf if line does not exist
7fe908 1262             replaceLine('/etc/apache2/ports.conf', 'Listen 443', 'Listen 443', 1);
14001d 1263             
TB 1264             // Comment out the namevirtualhost lines, as they were added by ispconfig in ispconfig.conf file again
1265             replaceLine('/etc/apache2/ports.conf', 'NameVirtualHost *:80', '# NameVirtualHost *:80', 1);
1266             replaceLine('/etc/apache2/ports.conf', 'NameVirtualHost *:443', '# NameVirtualHost *:443', 1);
532ae5 1267         }
L 1268
8eca28 1269         if(is_file('/etc/apache2/apache.conf')) {
MC 1270             if(hasLine('/etc/apache2/apache.conf', 'Include sites-enabled/', 1) == false) {
39e5f0 1271                 if(hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.conf', 1) == false && hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/', 1) == false) {
8eca28 1272                     replaceLine('/etc/apache2/apache.conf', 'Include sites-enabled/', 'Include sites-enabled/', 1, 1);
MC 1273                 } elseif(hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.vhost', 1) == false) {
39e5f0 1274                     replaceLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.vhost', 'IncludeOptional sites-enabled/', 1, 1);
TB 1275                 }
1276             }
1277         }
1278         
1279         if(is_file('/etc/apache2/apache2.conf')) {
1280             if(hasLine('/etc/apache2/apache2.conf', 'Include sites-enabled/', 1) == false && hasLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/', 1) == false) {
d10d15 1281                 if(hasLine('/etc/apache2/apache2.conf', 'Include sites-enabled/*.conf', 1) == true) {
TB 1282                     replaceLine('/etc/apache2/apache2.conf', 'Include sites-enabled/*.conf', 'Include sites-enabled/', 1, 1);
39e5f0 1283                 } elseif(hasLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/*.conf', 1) == true) {
TB 1284                     replaceLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/*.conf', 'IncludeOptional sites-enabled/', 1, 1);
8eca28 1285                 }
MC 1286             }
1287         }
532ae5 1288
L 1289         //* Copy the ISPConfig configuration include
1290         $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1291         $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1292
ccbf14 1293         $tpl = new tpl('apache_ispconfig.conf.master');
TB 1294         $tpl->setVar('apache_version',getapacheversion());
1295         
532ae5 1296         $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
ccbf14 1297         $ip_addresses = array();
TB 1298         
532ae5 1299         if(is_array($records) && count($records) > 0) {
L 1300             foreach($records as $rec) {
a2156e 1301                 if($rec['ip_type'] == 'IPv6') {
T 1302                     $ip_address = '['.$rec['ip_address'].']';
1303                 } else {
1304                     $ip_address = $rec['ip_address'];
1305                 }
7fe908 1306                 $ports = explode(',', $rec['virtualhost_port']);
a2156e 1307                 if(is_array($ports)) {
T 1308                     foreach($ports as $port) {
1309                         $port = intval($port);
1310                         if($port > 0 && $port < 65536 && $ip_address != '') {
ccbf14 1311                             $ip_addresses[] = array('ip_address' => $ip_address, 'port' => $port);
a2156e 1312                         }
T 1313                     }
1314                 }
532ae5 1315             }
L 1316         }
855547 1317         
3de838 1318         if(count($ip_addresses) > 0) $tpl->setLoop('ip_adresses',$ip_addresses);
855547 1319         
ccbf14 1320         wf($vhost_conf_dir.'/ispconfig.conf', $tpl->grab());
TB 1321         unset($tpl);
532ae5 1322
L 1323         if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.conf')) {
7fe908 1324             symlink($vhost_conf_dir.'/ispconfig.conf', $vhost_conf_enabled_dir.'/000-ispconfig.conf');
532ae5 1325         }
L 1326
1327         //* make sure that webalizer finds its config file when it is directly in /etc
1328         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1329             mkdir('/etc/webalizer');
7fe908 1330             symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf');
532ae5 1331         }
L 1332
1333         if(is_file('/etc/webalizer/webalizer.conf')) {
1334             // Change webalizer mode to incremental
7fe908 1335             replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0);
MC 1336             replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental     yes', 0, 0);
1337             replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName     webalizer.hist', 0, 0);
532ae5 1338         }
a8ccf6 1339
532ae5 1340         // Check the awsatst script
L 1341         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
7fe908 1342         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 1343         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1);
a8ccf6 1344
532ae5 1345         //* add a sshusers group
L 1346         $command = 'groupadd sshusers';
1347         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1348
1349     }
a8ccf6 1350
4ffb51 1351     public function configure_nginx(){
80e3c9 1352         global $conf;
a8ccf6 1353
4ffb51 1354         if($conf['nginx']['installed'] == false) return;
F 1355         //* Create the logging directory for the vhost logfiles
1356         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1357
1358         //* make sure that webalizer finds its config file when it is directly in /etc
1359         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1360             mkdir('/etc/webalizer');
7fe908 1361             symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf');
4ffb51 1362         }
F 1363
1364         if(is_file('/etc/webalizer/webalizer.conf')) {
1365             // Change webalizer mode to incremental
7fe908 1366             replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0);
MC 1367             replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental     yes', 0, 0);
1368             replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName     webalizer.hist', 0, 0);
4ffb51 1369         }
a8ccf6 1370
4ffb51 1371         // Check the awsatst script
F 1372         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
7fe908 1373         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 1374         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1);
a8ccf6 1375
4ffb51 1376         //* add a sshusers group
F 1377         $command = 'groupadd sshusers';
1378         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a8ccf6 1379
4ffb51 1380         /*
80e3c9 1381         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
T 1382         $ip_address = gethostbyname($row["server_name"]);
1383         $server_name = $row["server_name"];
1384
1385         //setup proxy.conf
1386         $configfile = 'proxy.conf';
1387         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile)) copy($conf["nginx"]["config_dir"].'/'.$configfile,$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1388         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1389         $content = rf("tpl/nginx_".$configfile.".master");
1390         wf($conf["nginx"]["config_dir"].'/'.$configfile,$content);
1391         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/'.$configfile);
1392         exec('chown root:root '.$conf["nginx"]["config_dir"].'/'.$configfile);
1393
1394         //setup conf.d/cache.conf
1395         $configfile = 'cache.conf';
1396         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.'~');
1397         if(is_file($conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~');
1398         $content = rf("tpl/nginx_".$configfile.".master");
1399         wf($conf["nginx"]["config_dir"].'/conf.d/'.$configfile,$content);
1400         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1401         exec('chown root:root '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1402
1403         //setup cache directories
1404         mkdir('/var/cache/nginx/cache');
1405         exec('chown www-data:www-data /var/cache/nginx/cache');
1406         mkdir('/var/cache/nginx/temp');
1407         exec('chown www-data:www-data /var/cache/nginx/temp');
4ffb51 1408         */
80e3c9 1409     }
a8ccf6 1410
d083f2 1411     public function configure_fail2ban() {
7fe908 1412         // To Do
MC 1413     }
a8ccf6 1414
80e3c9 1415     public function configure_squid()
T 1416     {
1417         global $conf;
1418         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
1419         $ip_address = gethostbyname($row["server_name"]);
1420         $server_name = $row["server_name"];
a8ccf6 1421
80e3c9 1422         $configfile = 'squid.conf';
7fe908 1423         if(is_file($conf["squid"]["config_dir"].'/'.$configfile)) copy($conf["squid"]["config_dir"].'/'.$configfile, $conf["squid"]["config_dir"].'/'.$configfile.'~');
80e3c9 1424         if(is_file($conf["squid"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["squid"]["config_dir"].'/'.$configfile.'~');
615a0a 1425         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master");
7fe908 1426         $content = str_replace('{server_name}', $server_name, $content);
MC 1427         $content = str_replace('{ip_address}', $ip_address, $content);
1428         $content = str_replace('{config_dir}', $conf['squid']['config_dir'], $content);
1429         wf($conf["squid"]["config_dir"].'/'.$configfile, $content);
80e3c9 1430         exec('chmod 600 '.$conf["squid"]["config_dir"].'/'.$configfile);
T 1431         exec('chown root:root '.$conf["squid"]["config_dir"].'/'.$configfile);
1432     }
a8ccf6 1433
992797 1434     /*
80e3c9 1435     public function configure_ufw_firewall()
T 1436     {
1437         $configfile = 'ufw.conf';
1438         if(is_file('/etc/ufw/ufw.conf')) copy('/etc/ufw/ufw.conf','/etc/ufw/ufw.conf~');
1439         $content = rf("tpl/".$configfile.".master");
1440         wf('/etc/ufw/ufw.conf',$content);
1441         exec('chmod 600 /etc/ufw/ufw.conf');
a8ccf6 1442         exec('chown root:root /etc/ufw/ufw.conf');
80e3c9 1443     }
992797 1444     */
532ae5 1445
992797 1446     public function configure_firewall() {
532ae5 1447         global $conf;
L 1448
1449         $dist_init_scripts = $conf['init_scripts'];
1450
1451         if(is_dir('/etc/Bastille.backup')) caselog('rm -rf /etc/Bastille.backup', __FILE__, __LINE__);
1452         if(is_dir('/etc/Bastille')) caselog('mv -f /etc/Bastille /etc/Bastille.backup', __FILE__, __LINE__);
1453         @mkdir('/etc/Bastille', 0700);
1454         if(is_dir('/etc/Bastille.backup/firewall.d')) caselog('cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/', __FILE__, __LINE__);
615a0a 1455         if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) {
7fe908 1456             caselog('cp -f ' . $conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
MC 1457         } else {
1458             caselog('cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
1459         }
532ae5 1460         caselog('chmod 644 /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
L 1461         $content = rf('/etc/Bastille/bastille-firewall.cfg');
1462         $content = str_replace('{DNS_SERVERS}', '', $content);
1463
1464         $tcp_public_services = '';
1465         $udp_public_services = '';
1466
1467         $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id']));
1468
1469         if(trim($row['tcp_port']) != '' || trim($row['udp_port']) != '') {
7fe908 1470             $tcp_public_services = trim(str_replace(',', ' ', $row['tcp_port']));
MC 1471             $udp_public_services = trim(str_replace(',', ' ', $row['udp_port']));
532ae5 1472         } else {
L 1473             $tcp_public_services = '21 22 25 53 80 110 143 443 3306 8080 10000';
1474             $udp_public_services = '53';
1475         }
1476
1477         if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
1478             $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
1479             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']));
1480         }
1481
1482         $content = str_replace('{TCP_PUBLIC_SERVICES}', $tcp_public_services, $content);
1483         $content = str_replace('{UDP_PUBLIC_SERVICES}', $udp_public_services, $content);
1484
1485         wf('/etc/Bastille/bastille-firewall.cfg', $content);
1486
1487         if(is_file($dist_init_scripts.'/bastille-firewall')) caselog('mv -f '.$dist_init_scripts.'/bastille-firewall '.$dist_init_scripts.'/bastille-firewall.backup', __FILE__, __LINE__);
1488         caselog('cp -f apps/bastille-firewall '.$dist_init_scripts, __FILE__, __LINE__);
1489         caselog('chmod 700 '.$dist_init_scripts.'/bastille-firewall', __FILE__, __LINE__);
1490
1491         if(is_file('/sbin/bastille-ipchains')) caselog('mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup', __FILE__, __LINE__);
1492         caselog('cp -f apps/bastille-ipchains /sbin', __FILE__, __LINE__);
1493         caselog('chmod 700 /sbin/bastille-ipchains', __FILE__, __LINE__);
1494
1495         if(is_file('/sbin/bastille-netfilter')) caselog('mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup', __FILE__, __LINE__);
1496         caselog('cp -f apps/bastille-netfilter /sbin', __FILE__, __LINE__);
1497         caselog('chmod 700 /sbin/bastille-netfilter', __FILE__, __LINE__);
1498
1499         if(!@is_dir('/var/lock/subsys')) caselog('mkdir /var/lock/subsys', __FILE__, __LINE__);
1500
1501         exec('which ipchains &> /dev/null', $ipchains_location, $ret_val);
1502         if(!is_file('/sbin/ipchains') && !is_link('/sbin/ipchains') && $ret_val == 0) phpcaselog(@symlink(shell_exec('which ipchains'), '/sbin/ipchains'), 'create symlink', __FILE__, __LINE__);
1503         unset($ipchains_location);
1504         exec('which iptables &> /dev/null', $iptables_location, $ret_val);
1505         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__);
1506         unset($iptables_location);
1507
1508     }
1509
1510     public function configure_vlogger() {
1511         global $conf;
1512
1513         //** Configure vlogger to use traffic logging to mysql (master) db
1514         $configfile = 'vlogger-dbi.conf';
7fe908 1515         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile)) copy($conf['vlogger']['config_dir'].'/'.$configfile, $conf['vlogger']['config_dir'].'/'.$configfile.'~');
532ae5 1516         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile.'~')) chmod($conf['vlogger']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1517         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1518         if($conf['mysql']['master_slave_setup'] == 'y') {
7fe908 1519             $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
MC 1520             $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1521             $content = str_replace('{mysql_server_database}', $conf['mysql']['master_database'], $content);
1522             $content = str_replace('{mysql_server_ip}', $conf['mysql']['master_host'], $content);
532ae5 1523         } else {
7fe908 1524             $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1525             $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1526             $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1527             $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
532ae5 1528         }
7fe908 1529         wf($conf['vlogger']['config_dir'].'/'.$configfile, $content);
532ae5 1530         chmod($conf['vlogger']['config_dir'].'/'.$configfile, 0600);
L 1531         chown($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1532         chgrp($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1533
1534     }
1535
1536     public function configure_apps_vhost() {
1537         global $conf;
1538
1539         //* Create the ispconfig apps vhost user and group
165152 1540         if($conf['apache']['installed'] == true){
4ffb51 1541             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
F 1542             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1543             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1544
4ffb51 1545             $command = 'groupadd '.$apps_vhost_user;
F 1546             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1547
4ffb51 1548             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
F 1549             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1550
L 1551
5edf40 1552             //$command = 'adduser '.$conf['apache']['user'].' '.$apps_vhost_group;
TB 1553             $command = 'usermod -a -G '.$apps_vhost_group.' '.$conf['apache']['user'];
4ffb51 1554             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1555
99b55b 1556             if(!@is_dir($install_dir)){
F 1557                 mkdir($install_dir, 0755, true);
1558             } else {
1559                 chmod($install_dir, 0755);
1560             }
4ffb51 1561             chown($install_dir, $apps_vhost_user);
F 1562             chgrp($install_dir, $apps_vhost_group);
532ae5 1563
4ffb51 1564             //* Copy the apps vhost file
F 1565             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1566             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1567             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'':'ServerName '.$conf['web']['apps_vhost_servername'];
d0356f 1568             
TB 1569             //* Get the apps vhost port
1570             if($this->is_update == true) {
1571                 $conf['web']['apps_vhost_port'] = get_apps_vhost_port_number();
1572             }
532ae5 1573
4ffb51 1574             // Dont just copy over the virtualhost template but add some custom settings
ccbf14 1575             $tpl = new tpl('apache_apps.vhost.master');
TB 1576             $tpl->setVar('apps_vhost_ip',$conf['web']['apps_vhost_ip']);
1577             $tpl->setVar('apps_vhost_port',$conf['web']['apps_vhost_port']);
1578             $tpl->setVar('apps_vhost_dir',$conf['web']['website_basedir'].'/apps');
1579             $tpl->setVar('apps_vhost_basedir',$conf['web']['website_basedir']);
1580             $tpl->setVar('apps_vhost_servername',$apps_vhost_servername);
1581             $tpl->setVar('apache_version',getapacheversion());
532ae5 1582
L 1583
4ffb51 1584             // comment out the listen directive if port is 80 or 443
F 1585             if($conf['web']['apps_vhost_ip'] == 80 or $conf['web']['apps_vhost_ip'] == 443) {
ccbf14 1586                 $tpl->setVar('vhost_port_listen','#');
4ffb51 1587             } else {
ccbf14 1588                 $tpl->setVar('vhost_port_listen','');
4ffb51 1589             }
532ae5 1590
ccbf14 1591             wf($vhost_conf_dir.'/apps.vhost', $tpl->grab());
TB 1592             unset($tpl);
532ae5 1593
4ffb51 1594             //copy('tpl/apache_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
F 1595             //* and create the symlink
7e1cfb 1596             if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
F 1597             if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
7fe908 1598                 symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost');
4ffb51 1599             }
a8ccf6 1600
4ffb51 1601             if(!is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter')) {
615a0a 1602                 $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_apps_fcgi_starter.master', 'tpl/apache_apps_fcgi_starter.master');
526b99 1603                 $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content);
T 1604                 $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content);
4ffb51 1605                 mkdir($conf['web']['website_basedir'].'/php-fcgi-scripts/apps', 0755, true);
526b99 1606                 //copy('tpl/apache_apps_fcgi_starter.master',$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
T 1607                 wf($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter', $content);
4ffb51 1608                 exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
F 1609                 exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps');
1610
7fe908 1611             }
532ae5 1612         }
165152 1613         if($conf['nginx']['installed'] == true){
4ffb51 1614             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
F 1615             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1616             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1617
4ffb51 1618             $command = 'groupadd '.$apps_vhost_user;
F 1619             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1620
1621             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
1622             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1623
1624
11f2ad 1625             //$command = 'adduser '.$conf['nginx']['user'].' '.$apps_vhost_group;
TB 1626             $command = 'usermod -a -G '.$apps_vhost_group.' '.$conf['nginx']['user'];
4ffb51 1627             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
F 1628
6e2d48 1629             if(!@is_dir($install_dir)){
F 1630                 mkdir($install_dir, 0755, true);
1631             } else {
1632                 chmod($install_dir, 0755);
1633             }
4ffb51 1634             chown($install_dir, $apps_vhost_user);
F 1635             chgrp($install_dir, $apps_vhost_group);
1636
1637             //* Copy the apps vhost file
1638             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
1639             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
1640             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'_':$conf['web']['apps_vhost_servername'];
1641
1642             // Dont just copy over the virtualhost template but add some custom settings
615a0a 1643             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_apps.vhost.master', 'tpl/nginx_apps.vhost.master');
a8ccf6 1644
4ffb51 1645             if($conf['web']['apps_vhost_ip'] == '_default_'){
F 1646                 $apps_vhost_ip = '';
1647             } else {
1648                 $apps_vhost_ip = $conf['web']['apps_vhost_ip'].':';
1649             }
a8ccf6 1650
ca0b77 1651             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
7fe908 1652             if(substr($socket_dir, -1) != '/') $socket_dir .= '/';
ca0b77 1653             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
F 1654             $fpm_socket = $socket_dir.'apps.sock';
8ab3cd 1655             $cgi_socket = escapeshellcmd($conf['nginx']['cgi_socket']);
4ffb51 1656
F 1657             $content = str_replace('{apps_vhost_ip}', $apps_vhost_ip, $content);
1658             $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content);
1659             $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content);
1660             $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content);
ca0b77 1661             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1662             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
8ab3cd 1663             $content = str_replace('{cgi_socket}', $cgi_socket, $content);
7fe908 1664
183c47 1665             if(file_exists('/var/run/php5-fpm.sock')){
F 1666                 $use_tcp = '#';
1667                 $use_socket = '';
1668             } else {
1669                 $use_tcp = '';
1670                 $use_socket = '#';
1671             }
1672             $content = str_replace('{use_tcp}', $use_tcp, $content);
1673             $content = str_replace('{use_socket}', $use_socket, $content);
4ffb51 1674
F 1675             wf($vhost_conf_dir.'/apps.vhost', $content);
a8ccf6 1676
fbb24a 1677             // PHP-FPM
F 1678             // Dont just copy over the php-fpm pool template but add some custom settings
615a0a 1679             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apps_php_fpm_pool.conf.master', 'tpl/apps_php_fpm_pool.conf.master');
fbb24a 1680             $content = str_replace('{fpm_pool}', 'apps', $content);
ca0b77 1681             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1682             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
fbb24a 1683             $content = str_replace('{fpm_user}', $apps_vhost_user, $content);
F 1684             $content = str_replace('{fpm_group}', $apps_vhost_group, $content);
1685             wf($conf['nginx']['php_fpm_pool_dir'].'/apps.conf', $content);
4ffb51 1686
F 1687             //copy('tpl/nginx_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
1688             //* and create the symlink
7e1cfb 1689             if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
F 1690             if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
7fe908 1691                 symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost');
4ffb51 1692             }
a8ccf6 1693
532ae5 1694         }
L 1695     }
a8ccf6 1696
532ae5 1697     public function make_ispconfig_ssl_cert() {
b04e82 1698         global $conf,$autoinstall;
532ae5 1699
L 1700         $install_dir = $conf['ispconfig_install_dir'];
a8ccf6 1701
532ae5 1702         $ssl_crt_file = $install_dir.'/interface/ssl/ispserver.crt';
L 1703         $ssl_csr_file = $install_dir.'/interface/ssl/ispserver.csr';
1704         $ssl_key_file = $install_dir.'/interface/ssl/ispserver.key';
a8ccf6 1705
532ae5 1706         if(!@is_dir($install_dir.'/interface/ssl')) mkdir($install_dir.'/interface/ssl', 0755, true);
a8ccf6 1707
7fe908 1708         $ssl_pw = substr(md5(mt_rand()), 0, 6);
532ae5 1709         exec("openssl genrsa -des3 -passout pass:$ssl_pw -out $ssl_key_file 4096");
b04e82 1710         if(AUTOINSTALL){
TB 1711             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 1712         } else {
FT 1713             exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -out $ssl_csr_file");
1714         }
532ae5 1715         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 1716         exec("openssl rsa -passin pass:$ssl_pw -in $ssl_key_file -out $ssl_key_file.insecure");
7fe908 1717         rename($ssl_key_file, $ssl_key_file.'.secure');
MC 1718         rename($ssl_key_file.'.insecure', $ssl_key_file);
a8ccf6 1719
532ae5 1720     }
L 1721
1722     public function install_ispconfig() {
1723         global $conf;
1724
1725         $install_dir = $conf['ispconfig_install_dir'];
1726
1727         //* Create the ISPConfig installation directory
1728         if(!@is_dir($install_dir)) {
1729             $command = "mkdir $install_dir";
1730             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1731         }
1732
1733         //* Create a ISPConfig user and group
1734         $command = 'groupadd ispconfig';
1735         if(!is_group('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1736
1737         $command = 'useradd -g ispconfig -d '.$install_dir.' ispconfig';
1738         if(!is_user('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1739
1740         //* copy the ISPConfig interface part
1741         $command = 'cp -rf ../interface '.$install_dir;
1742         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1743
1744         //* copy the ISPConfig server part
1745         $command = 'cp -rf ../server '.$install_dir;
1746         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a13af2 1747         
fb6c56 1748         //* Make a backup of the security settings
TB 1749         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~');
1750         
a13af2 1751         //* copy the ISPConfig security part
TB 1752         $command = 'cp -rf ../security '.$install_dir;
1753         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
fb6c56 1754         
TB 1755         //* Apply changed security_settings.ini values to new security_settings.ini file
1756         if(is_file('/usr/local/ispconfig/security/security_settings.ini~')) {
1757             $security_settings_old = ini_to_array(file_get_contents('/usr/local/ispconfig/security/security_settings.ini~'));
1758             $security_settings_new = ini_to_array(file_get_contents('/usr/local/ispconfig/security/security_settings.ini'));
1759             if(is_array($security_settings_new) && is_array($security_settings_old)) {
1760                 foreach($security_settings_new as $section => $sval) {
1761                     if(is_array($sval)) {
1762                         foreach($sval as $key => $val) {
1763                             if(isset($security_settings_old[$section]) && isset($security_settings_old[$section][$key])) {
1764                                 $security_settings_new[$section][$key] = $security_settings_old[$section][$key];
1765                             }
1766                         }
1767                     }
1768                 }
1769                 file_put_contents('/usr/local/ispconfig/security/security_settings.ini',array_to_ini($security_settings_new));
1770             }
1771         }
532ae5 1772
L 1773         //* Create a symlink, so ISPConfig is accessible via web
1774         // Replaced by a separate vhost definition for port 8080
1775         // $command = "ln -s $install_dir/interface/web/ /var/www/ispconfig";
1776         // caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1777
1778         //* Create the config file for ISPConfig interface
1779         $configfile = 'config.inc.php';
1780         if(is_file($install_dir.'/interface/lib/'.$configfile)) {
1781             copy($install_dir.'/interface/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1782         }
615a0a 1783         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1784         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
7fe908 1785         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
532ae5 1786         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
L 1787         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1788
1789         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1790         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1791         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1792         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1793
1794         $content = str_replace('{server_id}', $conf['server_id'], $content);
1795         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
b63764 1796         $content = str_replace('{language}', $conf['language'], $content);
8cf78b 1797         $content = str_replace('{timezone}', $conf['timezone'], $content);
f598b0 1798         $content = str_replace('{theme}', $conf['theme'], $content);
992797 1799         $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content);
b63764 1800
532ae5 1801         wf($install_dir.'/interface/lib/'.$configfile, $content);
L 1802
1803         //* Create the config file for ISPConfig server
1804         $configfile = 'config.inc.php';
1805         if(is_file($install_dir.'/server/lib/'.$configfile)) {
1806             copy($install_dir.'/server/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1807         }
615a0a 1808         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1809         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 1810         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1811         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1812         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1813
1814         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1815         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1816         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1817         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1818
1819         $content = str_replace('{server_id}', $conf['server_id'], $content);
1820         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
1821         $content = str_replace('{language}', $conf['language'], $content);
8cf78b 1822         $content = str_replace('{timezone}', $conf['timezone'], $content);
f598b0 1823         $content = str_replace('{theme}', $conf['theme'], $content);
992797 1824         $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content);
532ae5 1825
L 1826         wf($install_dir.'/server/lib/'.$configfile, $content);
1827
1828         //* Create the config file for remote-actions (but only, if it does not exist, because
1829         //  the value is a autoinc-value and so changed by the remoteaction_core_module
1830         if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) {
1831             $content = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
1832             wf($install_dir.'/server/lib/remote_action.inc.php', $content);
1833         }
1834
1835         //* Enable the server modules and plugins.
1836         // TODO: Implement a selector which modules and plugins shall be enabled.
1837         $dir = $install_dir.'/server/mods-available/';
1838         if (is_dir($dir)) {
1839             if ($dh = opendir($dir)) {
1840                 while (($file = readdir($dh)) !== false) {
7fe908 1841                     if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') {
MC 1842                         include_once $install_dir.'/server/mods-available/'.$file;
1843                         $module_name = substr($file, 0, -8);
532ae5 1844                         $tmp = new $module_name;
L 1845                         if($tmp->onInstall()) {
1846                             if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) {
1847                                 @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-enabled/'.$file);
1848                                 // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-enabled/'.$file);
1849                             }
1850                             if (strpos($file, '_core_module') !== false) {
1851                                 if(!@is_link($install_dir.'/server/mods-core/'.$file)) {
1852                                     @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-core/'.$file);
1853                                     // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-core/'.$file);
1854                                 }
1855                             }
1856                         }
1857                         unset($tmp);
1858                     }
1859                 }
1860                 closedir($dh);
1861             }
1862         }
1863
1864         $dir = $install_dir.'/server/plugins-available/';
1865         if (is_dir($dir)) {
1866             if ($dh = opendir($dir)) {
1867                 while (($file = readdir($dh)) !== false) {
4ffb51 1868                     if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue;
F 1869                     if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue;
7fe908 1870                     if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') {
MC 1871                         include_once $install_dir.'/server/plugins-available/'.$file;
1872                         $plugin_name = substr($file, 0, -8);
532ae5 1873                         $tmp = new $plugin_name;
7fe908 1874                         if(method_exists($tmp, 'onInstall') && $tmp->onInstall()) {
532ae5 1875                             if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) {
L 1876                                 @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file);
1877                                 //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-enabled/'.$file);
1878                             }
1879                             if (strpos($file, '_core_plugin') !== false) {
1880                                 if(!@is_link($install_dir.'/server/plugins-core/'.$file)) {
1881                                     @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-core/'.$file);
1882                                     //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-core/'.$file);
1883                                 }
1884                             }
1885                         }
1886                         unset($tmp);
1887                     }
1888                 }
1889                 closedir($dh);
1890             }
1891         }
1892
1893         // Update the server config
1894         $mail_server_enabled = ($conf['services']['mail'])?1:0;
1895         $web_server_enabled = ($conf['services']['web'])?1:0;
1896         $dns_server_enabled = ($conf['services']['dns'])?1:0;
1897         $file_server_enabled = ($conf['services']['file'])?1:0;
1898         $db_server_enabled = ($conf['services']['db'])?1:0;
8cf955 1899         $vserver_server_enabled = ($conf['openvz']['installed'])?1:0;
80e3c9 1900         $proxy_server_enabled = ($conf['services']['proxy'])?1:0;
T 1901         $firewall_server_enabled = ($conf['services']['firewall'])?1:0;
532ae5 1902
80e3c9 1903         $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 1904
L 1905         if($conf['mysql']['master_slave_setup'] == 'y') {
1906             $this->dbmaster->query($sql);
1907             $this->db->query($sql);
1908         } else {
1909             $this->db->query($sql);
1910         }
1911
1912
3e0fc8 1913         // chown install dir to root and chmod 755
TB 1914         $command = 'chown root:root '.$install_dir;
1915         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1916         $command = 'chmod 755 '.$install_dir;
532ae5 1917         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 1918
fa029b 1919         //* Chmod the files and directories in the install dir
3e0fc8 1920         $command = 'chmod -R 750 '.$install_dir.'/*';
TB 1921         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1922
1923         //* chown the interface files to the ispconfig user and group
1924         $command = 'chown -R ispconfig:ispconfig '.$install_dir.'/interface';
1925         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1926         
1927         //* chown the server files to the root user and group
1928         $command = 'chown -R root:root '.$install_dir.'/server';
532ae5 1929         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
fa029b 1930         
TB 1931         //* chown the security files to the root user and group
1932         $command = 'chown -R root:root '.$install_dir.'/security';
1933         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1934         
1935         //* chown the security directory and security_settings.ini to root:ispconfig
1936         $command = 'chown root:ispconfig '.$install_dir.'/security/security_settings.ini';
1937         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1938         $command = 'chown root:ispconfig '.$install_dir.'/security';
1939         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
cb1221 1940         $command = 'chown root:ispconfig '.$install_dir.'/security/ids.whitelist';
TB 1941         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1942         $command = 'chown root:ispconfig '.$install_dir.'/security/ids.htmlfield';
1943         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1944         $command = 'chown root:ispconfig '.$install_dir.'/security/apache_directives.blacklist';
1945         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1946
L 1947         //* Make the global language file directory group writable
1948         exec("chmod -R 770 $install_dir/interface/lib/lang");
1949
1950         //* Make the temp directory for language file exports writable
1951         if(is_dir($install_dir.'/interface/web/temp')) exec("chmod -R 770 $install_dir/interface/web/temp");
1952
1953         //* Make all interface language file directories group writable
1954         $handle = @opendir($install_dir.'/interface/web');
7fe908 1955         while ($file = @readdir($handle)) {
532ae5 1956             if ($file != '.' && $file != '..') {
L 1957                 if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) {
1958                     $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang');
7fe908 1959                     chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang', 0770);
MC 1960                     while ($lang_file = @readdir($handle2)) {
532ae5 1961                         if ($lang_file != '.' && $lang_file != '..') {
7fe908 1962                             chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file, 0770);
532ae5 1963                         }
L 1964                     }
1965                 }
1966             }
1967         }
a8ccf6 1968
477d4e 1969         //* Make the APS directories group writable
T 1970         exec("chmod -R 770 $install_dir/interface/web/sites/aps_meta_packages");
1971         exec("chmod -R 770 $install_dir/server/aps_packages");
532ae5 1972
L 1973         //* make sure that the server config file (not the interface one) is only readable by the root user
bfcdef 1974         chmod($install_dir.'/server/lib/config.inc.php', 0600);
T 1975         chown($install_dir.'/server/lib/config.inc.php', 'root');
1976         chgrp($install_dir.'/server/lib/config.inc.php', 'root');
7fe908 1977
bfcdef 1978         //* Make sure thet the interface config file is readable by user ispconfig only
T 1979         chmod($install_dir.'/interface/lib/config.inc.php', 0600);
1980         chown($install_dir.'/interface/lib/config.inc.php', 'ispconfig');
1981         chgrp($install_dir.'/interface/lib/config.inc.php', 'ispconfig');
532ae5 1982
L 1983         chmod($install_dir.'/server/lib/remote_action.inc.php', 0600);
1984         chown($install_dir.'/server/lib/remote_action.inc.php', 'root');
1985         chgrp($install_dir.'/server/lib/remote_action.inc.php', 'root');
1986
1987         if(@is_file($install_dir.'/server/lib/mysql_clientdb.conf')) {
1988             chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
1989             chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1990             chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1991         }
a8ccf6 1992
8cf78b 1993         if(is_dir($install_dir.'/interface/invoices')) {
e94a9f 1994             exec('chmod -R 770 '.escapeshellarg($install_dir.'/interface/invoices'));
T 1995             exec('chown -R ispconfig:ispconfig '.escapeshellarg($install_dir.'/interface/invoices'));
edf806 1996         }
532ae5 1997
L 1998         // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing
1999         // and must be fixed as this will allow the apache user to read the ispconfig files.
2000         // Later this must run as own apache server or via suexec!
63b369 2001         if($conf['apache']['installed'] == true){
F 2002             $command = 'adduser '.$conf['apache']['user'].' ispconfig';
2003             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 2004             if(is_group('ispapps')){
F 2005                 $command = 'adduser '.$conf['apache']['user'].' ispapps';
2006                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2007             }
63b369 2008         }
F 2009         if($conf['nginx']['installed'] == true){
2010             $command = 'adduser '.$conf['nginx']['user'].' ispconfig';
2011             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 2012             if(is_group('ispapps')){
F 2013                 $command = 'adduser '.$conf['nginx']['user'].' ispapps';
2014                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2015             }
63b369 2016         }
532ae5 2017
L 2018         //* Make the shell scripts executable
2019         $command = "chmod +x $install_dir/server/scripts/*.sh";
2020         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2021
7e1cfb 2022         if($conf['apache']['installed'] == true && $this->install_ispconfig_interface == true){
4ffb51 2023             //* Copy the ISPConfig vhost for the controlpanel
F 2024             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
2025             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
532ae5 2026
4ffb51 2027             // Dont just copy over the virtualhost template but add some custom settings
ccbf14 2028             $tpl = new tpl('apache_ispconfig.vhost.master');
TB 2029             $tpl->setVar('vhost_port',$conf['apache']['vhost_port']);
532ae5 2030
4ffb51 2031             // comment out the listen directive if port is 80 or 443
F 2032             if($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) {
ccbf14 2033                 $tpl->setVar('vhost_port_listen','#');
4ffb51 2034             } else {
ccbf14 2035                 $tpl->setVar('vhost_port_listen','');
4ffb51 2036             }
a8ccf6 2037
4ffb51 2038             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
ccbf14 2039                 $tpl->setVar('ssl_comment','');
4ffb51 2040             } else {
ccbf14 2041                 $tpl->setVar('ssl_comment','#');
4ffb51 2042             }
10b4c8 2043             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 2044                 $tpl->setVar('ssl_bundle_comment','');
10b4c8 2045             } else {
ccbf14 2046                 $tpl->setVar('ssl_bundle_comment','#');
10b4c8 2047             }
ccbf14 2048             
TB 2049             $tpl->setVar('apache_version',getapacheversion());
532ae5 2050
ccbf14 2051             wf($vhost_conf_dir.'/ispconfig.vhost', $tpl->grab());
532ae5 2052
4ffb51 2053             //* and create the symlink
7e1cfb 2054             if($this->is_update == false) {
4ffb51 2055                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
F 2056                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
7fe908 2057                     symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost');
4ffb51 2058                 }
F 2059             }
cc6568 2060             //if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) {
7fe908 2061             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master');
MC 2062             $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content);
2063             $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content);
2064             @mkdir('/var/www/php-fcgi-scripts/ispconfig', 0755, true);
2065             wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content);
2066             exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter');
2067             @symlink($install_dir.'/interface/web', '/var/www/ispconfig');
2068             exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig');
cc6568 2069             //}
532ae5 2070         }
a8ccf6 2071
7e1cfb 2072         if($conf['nginx']['installed'] == true && $this->install_ispconfig_interface == true){
4ffb51 2073             //* Copy the ISPConfig vhost for the controlpanel
F 2074             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
2075             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
532ae5 2076
4ffb51 2077             // Dont just copy over the virtualhost template but add some custom settings
615a0a 2078             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_ispconfig.vhost.master', 'tpl/nginx_ispconfig.vhost.master');
4ffb51 2079             $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content);
a8ccf6 2080
4ffb51 2081             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
f9b8d0 2082                 $content = str_replace('{ssl_on}', 'on', $content);
4ffb51 2083                 $content = str_replace('{ssl_comment}', '', $content);
F 2084                 $content = str_replace('{fastcgi_ssl}', 'on', $content);
2085             } else {
f9b8d0 2086                 $content = str_replace('{ssl_on}', 'off', $content);
4ffb51 2087                 $content = str_replace('{ssl_comment}', '#', $content);
F 2088                 $content = str_replace('{fastcgi_ssl}', 'off', $content);
2089             }
a8ccf6 2090
ca0b77 2091             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
7fe908 2092             if(substr($socket_dir, -1) != '/') $socket_dir .= '/';
ca0b77 2093             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
F 2094             $fpm_socket = $socket_dir.'ispconfig.sock';
a8ccf6 2095
ca0b77 2096             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 2097             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
a8ccf6 2098
4ffb51 2099             wf($vhost_conf_dir.'/ispconfig.vhost', $content);
a8ccf6 2100
4ffb51 2101             unset($content);
a8ccf6 2102
4ffb51 2103             // PHP-FPM
F 2104             // Dont just copy over the php-fpm pool template but add some custom settings
615a0a 2105             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/php_fpm_pool.conf.master', 'tpl/php_fpm_pool.conf.master');
4ffb51 2106             $content = str_replace('{fpm_pool}', 'ispconfig', $content);
ca0b77 2107             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 2108             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
4ffb51 2109             $content = str_replace('{fpm_user}', 'ispconfig', $content);
F 2110             $content = str_replace('{fpm_group}', 'ispconfig', $content);
2111             wf($conf['nginx']['php_fpm_pool_dir'].'/ispconfig.conf', $content);
2112
2113             //copy('tpl/nginx_ispconfig.vhost.master', $vhost_conf_dir.'/ispconfig.vhost');
2114             //* and create the symlink
7e1cfb 2115             if($this->is_update == false) {
4ffb51 2116                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
F 2117                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
7fe908 2118                     symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost');
4ffb51 2119                 }
F 2120             }
532ae5 2121         }
L 2122
2123         //* Install the update script
b34f99 2124         if(is_file('/usr/local/bin/ispconfig_update_from_dev.sh')) unlink('/usr/local/bin/ispconfig_update_from_dev.sh');
MC 2125         chown($install_dir.'/server/scripts/update_from_dev.sh', 'root');
2126         chmod($install_dir.'/server/scripts/update_from_dev.sh', 0700);
532ae5 2127         chown($install_dir.'/server/scripts/update_from_tgz.sh', 'root');
L 2128         chmod($install_dir.'/server/scripts/update_from_tgz.sh', 0700);
2129         chown($install_dir.'/server/scripts/ispconfig_update.sh', 'root');
2130         chmod($install_dir.'/server/scripts/ispconfig_update.sh', 0700);
b34f99 2131         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');
7fe908 2132         if(!is_link('/usr/local/bin/ispconfig_update.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update.sh');
532ae5 2133
L 2134         //* Make the logs readable for the ispconfig user
2135         if(@is_file('/var/log/mail.log')) exec('chmod +r /var/log/mail.log');
2136         if(@is_file('/var/log/mail.warn')) exec('chmod +r /var/log/mail.warn');
2137         if(@is_file('/var/log/mail.err')) exec('chmod +r /var/log/mail.err');
2138         if(@is_file('/var/log/messages')) exec('chmod +r /var/log/messages');
2139         if(@is_file('/var/log/clamav/clamav.log')) exec('chmod +r /var/log/clamav/clamav.log');
2140         if(@is_file('/var/log/clamav/freshclam.log')) exec('chmod +r /var/log/clamav/freshclam.log');
2141
2142         //* Create the ispconfig log file and directory
2143         if(!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) {
2144             if(!is_dir($conf['ispconfig_log_dir'])) mkdir($conf['ispconfig_log_dir'], 0755);
2145             touch($conf['ispconfig_log_dir'].'/ispconfig.log');
2146         }
a8ccf6 2147
99c89b 2148         //* Create the ispconfig auth log file and set uid/gid
a8ccf6 2149         if(!is_file($conf['ispconfig_log_dir'].'/auth.log')) {
99c89b 2150             touch($conf['ispconfig_log_dir'].'/auth.log');
a8ccf6 2151         }
0799f8 2152         exec('chown ispconfig:ispconfig '. $conf['ispconfig_log_dir'].'/auth.log');
T 2153         exec('chmod 660 '. $conf['ispconfig_log_dir'].'/auth.log');
a8ccf6 2154
0c5b42 2155         if(is_user('getmail')) {
7fe908 2156             rename($install_dir.'/server/scripts/run-getmail.sh', '/usr/local/bin/run-getmail.sh');
0c5b42 2157             if(is_user('getmail')) chown('/usr/local/bin/run-getmail.sh', 'getmail');
T 2158             chmod('/usr/local/bin/run-getmail.sh', 0744);
2159         }
532ae5 2160
L 2161         //* Add Log-Rotation
2162         if (is_dir('/etc/logrotate.d')) {
2163             @unlink('/etc/logrotate.d/logispc3'); // ignore, if the file is not there
2164             /* We rotate these logs in cron_daily.php
2165             $fh = fopen('/etc/logrotate.d/logispc3', 'w');
2166             fwrite($fh,
2167                     "$conf['ispconfig_log_dir']/ispconfig.log { \n" .
2168                     "    weekly \n" .
2169                     "    missingok \n" .
2170                     "    rotate 4 \n" .
2171                     "    compress \n" .
2172                     "    delaycompress \n" .
2173                     "} \n" .
2174                     "$conf['ispconfig_log_dir']/cron.log { \n" .
2175                     "    weekly \n" .
2176                     "    missingok \n" .
2177                     "    rotate 4 \n" .
2178                     "    compress \n" .
2179                     "    delaycompress \n" .
2180                     "}");
2181             fclose($fh);
2182             */
2183         }
7fe908 2184
d71bae 2185         //* Remove Domain module as its functions are available in the client module now
T 2186         if(@is_dir('/usr/local/ispconfig/interface/web/domain')) exec('rm -rf /usr/local/ispconfig/interface/web/domain');
f30628 2187         
TB 2188         //* Disable rkhunter run and update in debian cronjob as ispconfig is running and updating rkhunter
2189         if(is_file('/etc/default/rkhunter')) {
2190             replaceLine('/etc/default/rkhunter', 'CRON_DAILY_RUN="yes"', 'CRON_DAILY_RUN="no"', 1, 0);
2191             replaceLine('/etc/default/rkhunter', 'CRON_DB_UPDATE="yes"', 'CRON_DB_UPDATE="no"', 1, 0);
2192         }
2193         
021aec 2194         // Add symlink for patch tool
TB 2195         if(!is_link('/usr/local/bin/ispconfig_patch')) exec('ln -s /usr/local/ispconfig/server/scripts/ispconfig_patch /usr/local/bin/ispconfig_patch');
5b3f25 2196         
532ae5 2197     }
L 2198
2199     public function configure_dbserver() {
2200         global $conf;
2201
2202         //* If this server shall act as database server for client DB's, we configure this here
2203         $install_dir = $conf['ispconfig_install_dir'];
2204
2205         // Create a file with the database login details which
2206         // are used to create the client databases.
2207
2208         if(!is_dir($install_dir.'/server/lib')) {
2209             $command = "mkdir $install_dir/server/lib";
2210             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2211         }
2212
615a0a 2213         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mysql_clientdb.conf.master', 'tpl/mysql_clientdb.conf.master');
7fe908 2214         $content = str_replace('{hostname}', $conf['mysql']['host'], $content);
MC 2215         $content = str_replace('{username}', $conf['mysql']['admin_user'], $content);
2216         $content = str_replace('{password}', $conf['mysql']['admin_password'], $content);
2217         wf($install_dir.'/server/lib/mysql_clientdb.conf', $content);
532ae5 2218         chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
L 2219         chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
a8ccf6 2220         chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
532ae5 2221
L 2222     }
2223
2224     public function install_crontab() {
2225         global $conf;
2226
2227         $install_dir = $conf['ispconfig_install_dir'];
2228
2229         //* Root Crontab
2230         exec('crontab -u root -l > crontab.txt');
2231         $existing_root_cron_jobs = file('crontab.txt');
2232
2233         // remove existing ispconfig cronjobs, in case the syntax has changed
2234         foreach($existing_root_cron_jobs as $key => $val) {
7fe908 2235             if(stristr($val, $install_dir)) unset($existing_root_cron_jobs[$key]);
532ae5 2236         }
L 2237
2238         $root_cron_jobs = array(
7fe908 2239             "* * * * * ".$install_dir."/server/server.sh 2>&1 > /dev/null | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done",
MC 2240             "30 00 * * * ".$install_dir."/server/cron_daily.sh 2>&1 > /dev/null | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done"
532ae5 2241         );
a8ccf6 2242
b6a10a 2243         if ($conf['nginx']['installed'] == true) {
F 2244             $root_cron_jobs[] = "0 0 * * * ".$install_dir."/server/scripts/create_daily_nginx_access_logs.sh &> /dev/null";
2245         }
a8ccf6 2246
532ae5 2247         foreach($root_cron_jobs as $cron_job) {
L 2248             if(!in_array($cron_job."\n", $existing_root_cron_jobs)) {
2249                 $existing_root_cron_jobs[] = $cron_job."\n";
2250             }
2251         }
2252         file_put_contents('crontab.txt', $existing_root_cron_jobs);
2253         exec('crontab -u root crontab.txt &> /dev/null');
2254         unlink('crontab.txt');
2255
2256         //* Getmail crontab
2257         if(is_user('getmail')) {
2258             $cf = $conf['getmail'];
2259             exec('crontab -u getmail -l > crontab.txt');
2260             $existing_cron_jobs = file('crontab.txt');
2261
2262             $cron_jobs = array(
7fe908 2263                 '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null'
532ae5 2264             );
L 2265
2266             // remove existing ispconfig cronjobs, in case the syntax has changed
2267             foreach($existing_cron_jobs as $key => $val) {
7fe908 2268                 if(stristr($val, 'getmail')) unset($existing_cron_jobs[$key]);
532ae5 2269             }
L 2270
2271             foreach($cron_jobs as $cron_job) {
2272                 if(!in_array($cron_job."\n", $existing_cron_jobs)) {
2273                     $existing_cron_jobs[] = $cron_job."\n";
2274                 }
2275             }
2276             file_put_contents('crontab.txt', $existing_cron_jobs);
2277             exec('crontab -u getmail crontab.txt &> /dev/null');
2278             unlink('crontab.txt');
2279         }
2280
2281         touch($conf['ispconfig_log_dir'].'/cron.log');
cc6568 2282         chmod($conf['ispconfig_log_dir'].'/cron.log', 0660);
532ae5 2283
L 2284     }
5b3f25 2285     
TB 2286     // This function is called at the end of the update process and contains code to clean up parts of old ISPCONfig releases
2287     public function cleanup_ispconfig() {
2288         global $app,$conf;
2289         
2290         // Remove directories recursively
2291         if(is_dir('/usr/local/ispconfig/interface/web/designer')) exec('rm -rf /usr/local/ispconfig/interface/web/designer');
4c3fcd 2292         if(is_dir('/usr/local/ispconfig/interface/web/themes/default-304')) exec('rm -rf /usr/local/ispconfig/interface/web/themes/default-304');
5b3f25 2293         
TB 2294         // Remove files
2295         if(is_file('/usr/local/ispconfig/interface/lib/classes/db_firebird.inc.php')) unlink('/usr/local/ispconfig/interface/lib/classes/db_firebird.inc.php');
2296         if(is_file('/usr/local/ispconfig/interface/lib/classes/form.inc.php')) unlink('/usr/local/ispconfig/interface/lib/classes/form.inc.php');
2297         
2298         
2299         
2300     }
7fe908 2301
33bcd0 2302     public function getinitcommand($servicename, $action, $init_script_directory = ''){
FT 2303         global $conf;
2304         // systemd
6061d5 2305         if(is_executable('/bin/systemd') || is_executable('/usr/bin/systemctl')){
33bcd0 2306             return 'systemctl '.$action.' '.$servicename.'.service';
FT 2307         }
2308         // upstart
2309         if(is_executable('/sbin/initctl')){
2310             exec('/sbin/initctl version 2>/dev/null | /bin/grep -q upstart', $retval['output'], $retval['retval']);
2311             if(intval($retval['retval']) == 0) return 'service '.$servicename.' '.$action;
2312         }
2313         // sysvinit
2314         if($init_script_directory == '') $init_script_directory = $conf['init_scripts'];
2315         if(substr($init_script_directory, -1) === '/') $init_script_directory = substr($init_script_directory, 0, -1);
2316         return $init_script_directory.'/'.$servicename.' '.$action;
2317     }
532ae5 2318
L 2319     /**
2320      * Helper function - get the path to a template file based on
2321      * the local part of the filename. Checks first for the existence
2322      * of a distribution specific file and if not found looks in the
2323      * base template folder. Optionally the behaviour can be changed
2324      * by setting the 2nd parameter which will fetch the contents
2325      * of the template file and return it instead of the path. The 3rd
2326      * parameter further extends this behaviour by filtering the contents
2327      * by inserting the ispconfig database credentials using the {} placeholders.
2328      *
2329      * @param string $tLocal local part of filename
2330      * @param bool $tRf
2331      * @param bool $tDBCred
2332      * @return string Relative path to the chosen template file
2333      */
2334     protected function get_template_file($tLocal, $tRf=false, $tDBCred=false) {
2335         global $conf, $dist;
2336
2337         $final_path = '';
7fe908 2338         $dist_template = $conf['ispconfig_install_dir'] . '/server/conf-custom/install/' . $tLocal . '.master';
MC 2339         if (file_exists($dist_template)) {
532ae5 2340             $final_path = $dist_template;
L 2341         } else {
7fe908 2342             $dist_template = 'dist/tpl/'.strtolower($dist['name'])."/$tLocal.master";
MC 2343             if (file_exists($dist_template)) {
2344                 $final_path = $dist_template;
2345             } else {
2346                 $final_path = "tpl/$tLocal.master";
2347             }
2348         }
532ae5 2349
L 2350         if (!$tRf) {
2351             return $final_path;
2352         } else {
2353             return (!$tDBCred) ? rf($final_path) : $this->insert_db_credentials(rf($final_path));
2354         }
2355     }
2356
2357     /**
2358      * Helper function - writes the contents to a config file
2359      * and performs a backup if the file exist. Additionally
2360      * if the file exists the new file will be given the
2361      * same rights and ownership as the original. Optionally the
2362      * rights and/or ownership can be overriden by appending umask,
2363      * user and group to the parameters. Providing only uid and gid
2364      * values will result in only a chown.
2365      *
2366      * @param $tConf
2367      * @param $tContents
2368      * @return bool
2369      */
2370     protected function write_config_file($tConf, $tContents) {
2371         // Backup config file before writing new contents and stat file
2372         if ( is_file($tConf) ) {
2373             $stat = exec('stat -c \'%a %U %G\' '.escapeshellarg($tConf), $output, $res);
2374             if ($res == 0) { // stat successfull
8cddcd 2375                 list($access, $user, $group) = explode(" ", $stat);
532ae5 2376             }
L 2377
2378             if ( copy($tConf, $tConf.'~') ) {
2379                 chmod($tConf.'~', 0400);
2380             }
2381         }
2382
2383         wf($tConf, $tContents); // write file
2384
2385         if (func_num_args() >= 4) // override rights and/or ownership
7fe908 2386             {
532ae5 2387             $args = func_get_args();
L 2388             $output = array_slice($args, 2);
2389
2390             switch (sizeof($output)) {
7fe908 2391             case 3:
MC 2392                 $umask = array_shift($output);
2393                 if (is_numeric($umask) && preg_match('/^0?[0-7]{3}$/', $umask)) {
2394                     $access = $umask;
2395                 }
2396             case 2:
2397                 if (is_user($output[0]) && is_group($output[1])) {
2398                     list($user, $group) = $output;
2399                 }
2400                 break;
532ae5 2401             }
L 2402         }
2403
2404         if (!empty($user) && !empty($group)) {
2405             chown($tConf, $user);
2406             chgrp($tConf, $group);
2407         }
2408
2409         if (!empty($access)) {
2410             exec("chmod $access $tConf");
2411         }
2412     }
2413
2414     /**
2415      * Helper function - filter the contents of a config
2416      * file by inserting the common ispconfig database
2417      * credentials.
2418      *
2419      * @param $tContents
2420      * @return string
2421      */
2422     protected function insert_db_credentials($tContents) {
2423         global $conf;
2424
2425         $tContents = str_replace('{mysql_server_ispconfig_user}', $conf["mysql"]["ispconfig_user"], $tContents);
2426         $tContents = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $tContents);
2427         $tContents = str_replace('{mysql_server_database}', $conf["mysql"]["database"], $tContents);
2428         $tContents = str_replace('{mysql_server_ip}', $conf["mysql"]["ip"], $tContents);
7fe908 2429         $tContents = str_replace('{mysql_server_host}', $conf['mysql']['host'], $tContents);
MC 2430         $tContents = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $tContents);
532ae5 2431
L 2432         return $tContents;
2433     }
7fe908 2434
532ae5 2435 }
L 2436
e514ae 2437 ?>