Till Brehm
2015-05-07 5538547761447df757fa42d68c0bf17e219a6a73
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);
1fc360 986         $dovecot_version = $tmp[0];
31e0d1 987         unset($tmp);
a8ccf6 988
31e0d1 989         //* Copy dovecot configuration file
1fc360 990         if(version_compare($dovecot_version,2) >= 0) {
7fe908 991             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master')) {
MC 992                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master', $config_dir.'/'.$configfile);
993             } else {
994                 copy('tpl/debian_dovecot2.conf.master', $config_dir.'/'.$configfile);
995             }
65576f 996             replaceLine($config_dir.'/'.$configfile, 'postmaster_address = postmaster@example.com', 'postmaster_address = postmaster@'.$conf['hostname'], 1, 0);
1fc360 997             if(version_compare($dovecot_version,2.1) < 0) {
TB 998                 removeLine($config_dir.'/'.$configfile, 'ssl_protocols =');
999             }
31e0d1 1000         } else {
7fe908 1001             if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master')) {
MC 1002                 copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master', $config_dir.'/'.$configfile);
1003             } else {
1004                 copy('tpl/debian_dovecot.conf.master', $config_dir.'/'.$configfile);
1005             }
31e0d1 1006         }
532ae5 1007
L 1008         //* dovecot-sql.conf
1009         $configfile = 'dovecot-sql.conf';
1010         if(is_file($config_dir.'/'.$configfile)) {
1011             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1012         }
edf806 1013         if(is_file($config_dir.'/'.$configfile.'~')) chmod($config_dir.'/'.$configfile.'~', 0400);
615a0a 1014         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot-sql.conf.master', 'tpl/debian_dovecot-sql.conf.master');
7fe908 1015         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1016         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1017         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1018         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
032b86 1019         $content = str_replace('{server_id}', $conf['server_id'], $content);
532ae5 1020         wf($config_dir.'/'.$configfile, $content);
L 1021
1022         chmod($config_dir.'/'.$configfile, 0600);
1023         chown($config_dir.'/'.$configfile, 'root');
1024         chgrp($config_dir.'/'.$configfile, 'root');
5e7306 1025         
TB 1026         // Dovecot shall ignore mounts in website directory
7db4cd 1027         if(is_installed('doveadm')) exec("doveadm mount add '/var/www/*' ignore > /dev/null 2> /dev/null");
532ae5 1028
L 1029     }
1030
1031     public function configure_amavis() {
1032         global $conf;
1033
1034         // amavisd user config file
1035         $configfile = 'amavisd_user_config';
7fe908 1036         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~');
553854 1037         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user~')) chmod($conf['amavis']['config_dir'].'/50-user~', 0400);
615a0a 1038         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1039         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1040         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1041         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1042         $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content);
1043         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1044         wf($conf['amavis']['config_dir'].'/conf.d/50-user', $content);
553854 1045         chmod($conf['amavis']['config_dir'].'/conf.d/50-user', 0640);
532ae5 1046
L 1047         // TODO: chmod and chown on the config file
1048
1049
1050         // Adding the amavisd commands to the postfix configuration
864ee2 1051         // Add array for no error in foreach and maybe future options
X 1052         $postconf_commands = array ();
a8ccf6 1053
864ee2 1054         // Check for amavisd -> pure webserver with postfix for mailing without antispam
ac28b5 1055         if ($conf['amavis']['installed']) {
864ee2 1056             $postconf_commands[] = 'content_filter = amavis:[127.0.0.1]:10024';
X 1057             $postconf_commands[] = 'receive_override_options = no_address_mappings';
1058         }
532ae5 1059
L 1060         // Make a backup copy of the main.cf file
7fe908 1061         copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~2');
532ae5 1062
L 1063         // Executing the postconf commands
1064         foreach($postconf_commands as $cmd) {
1065             $command = "postconf -e '$cmd'";
1066             caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1067         }
1068
1069         // Append the configuration for amavisd to the master.cf file
7fe908 1070         if(is_file($conf['postfix']['config_dir'].'/master.cf')) copy($conf['postfix']['config_dir'].'/master.cf', $conf['postfix']['config_dir'].'/master.cf~');
532ae5 1071         $content = rf($conf['postfix']['config_dir'].'/master.cf');
L 1072         // Only add the content if we had not addded it before
7fe908 1073         if(!stristr($content, '127.0.0.1:10025')) {
532ae5 1074             unset($content);
615a0a 1075             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', 'tpl/master_cf_amavis.master');
7fe908 1076             af($conf['postfix']['config_dir'].'/master.cf', $content);
532ae5 1077         }
L 1078         unset($content);
1079
1080         // Add the clamav user to the amavis group
1081         exec('adduser clamav amavis');
1082
1083
1084     }
1085
1086     public function configure_spamassassin() {
1087         global $conf;
1088
1089         //* Enable spamasasssin on debian and ubuntu
1090         $configfile = '/etc/default/spamassassin';
1091         if(is_file($configfile)) {
1092             copy($configfile, $configfile.'~');
1093         }
1094         $content = rf($configfile);
1095         $content = str_replace('ENABLED=0', 'ENABLED=1', $content);
1096         wf($configfile, $content);
1097     }
1098
1099     public function configure_getmail() {
1100         global $conf;
1101
1102         $config_dir = $conf['getmail']['config_dir'];
1103
1104         if(!@is_dir($config_dir)) mkdir(escapeshellcmd($config_dir), 0700, true);
1105
1106         $command = 'useradd -d '.$config_dir.' getmail';
1107         if(!is_user('getmail')) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1108
1109         $command = "chown -R getmail $config_dir";
1110         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1111
1112         $command = "chmod -R 700 $config_dir";
1113         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1114     }
1115
1116
1117     public function configure_pureftpd() {
acdd7a 1118         global $conf;
532ae5 1119
L 1120         $config_dir = $conf['pureftpd']['config_dir'];
1121
1122         //* configure pure-ftpd for MySQL authentication against the ispconfig database
1123         $configfile = 'db/mysql.conf';
1124         if(is_file($config_dir.'/'.$configfile)) {
1125             copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~');
1126         }
1127         if(is_file($config_dir.'/'.$configfile.'~')) {
1128             chmod($config_dir.'/'.$configfile.'~', 0400);
1129         }
615a0a 1130         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/pureftpd_mysql.conf.master', 'tpl/pureftpd_mysql.conf.master');
532ae5 1131         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 1132         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1133         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1134         $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
1135         $content = str_replace('{server_id}', $conf['server_id'], $content);
1136         wf($config_dir.'/'.$configfile, $content);
1137         chmod($config_dir.'/'.$configfile, 0600);
1138         chown($config_dir.'/'.$configfile, 'root');
1139         chgrp($config_dir.'/'.$configfile, 'root');
1140         // **enable chrooting
1141         //exec('mkdir -p '.$config_dir.'/conf/ChrootEveryone');
1142         exec('echo "yes" > '.$config_dir.'/conf/ChrootEveryone');
1143         exec('echo "yes" > '.$config_dir.'/conf/BrokenClientsCompatibility');
1144         exec('echo "yes" > '.$config_dir.'/conf/DisplayDotFiles');
1145
1146         if(is_file('/etc/default/pure-ftpd-common')) {
7fe908 1147             replaceLine('/etc/default/pure-ftpd-common', 'STANDALONE_OR_INETD=inetd', 'STANDALONE_OR_INETD=standalone', 1, 0);
MC 1148             replaceLine('/etc/default/pure-ftpd-common', 'VIRTUALCHROOT=false', 'VIRTUALCHROOT=true', 1, 0);
532ae5 1149         }
L 1150
1151         if(is_file('/etc/inetd.conf')) {
7fe908 1152             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 1153             exec($this->getinitcommand('openbsd-inetd', 'restart'));
33bcd0 1154             //if(is_file($conf['init_scripts'].'/'.'openbsd-inetd')) exec($conf['init_scripts'].'/'.'openbsd-inetd restart');
532ae5 1155         }
L 1156
1157         if(!is_file('/etc/pure-ftpd/conf/DontResolve')) exec('echo "yes" > /etc/pure-ftpd/conf/DontResolve');
1158     }
1159
1160     public function configure_mydns() {
1161         global $conf;
1162
1163         // configure pam for SMTP authentication agains the ispconfig database
1164         $configfile = 'mydns.conf';
7fe908 1165         if(is_file($conf['mydns']['config_dir'].'/'.$configfile)) copy($conf['mydns']['config_dir'].'/'.$configfile, $conf['mydns']['config_dir'].'/'.$configfile.'~');
532ae5 1166         if(is_file($conf['mydns']['config_dir'].'/'.$configfile.'~')) chmod($conf['mydns']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1167         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1168         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1169         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1170         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1171         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1172         $content = str_replace('{server_id}', $conf['server_id'], $content);
1173         wf($conf['mydns']['config_dir'].'/'.$configfile, $content);
532ae5 1174         chmod($conf['mydns']['config_dir'].'/'.$configfile, 0600);
L 1175         chown($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1176         chgrp($conf['mydns']['config_dir'].'/'.$configfile, 'root');
1177
1178     }
1179
1180     public function configure_powerdns() {
1181         global $conf;
1182
1183         //* Create the database
1184         if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['powerdns']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
1185             $this->error('Unable to create MySQL database: '.$conf['powerdns']['database'].'.');
1186         }
1187
1188         //* Create the ISPConfig database user in the local database
1189         $query = "GRANT ALL ON `".$conf['powerdns']['database']."` . * TO '".$conf['mysql']['ispconfig_user']."'@'localhost';";
1190         if(!$this->db->query($query)) {
1191             $this->error('Unable to create user for powerdns database Error: '.$this->db->errorMessage);
1192         }
1193
1194         //* Reload database privelages
1195         $this->db->query('FLUSH PRIVILEGES;');
1196
1197         //* load the powerdns databse dump
1198         if($conf['mysql']['admin_password'] == '') {
1199             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 1200                 __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
532ae5 1201         } else {
L 1202             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 1203                 __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql');
532ae5 1204         }
L 1205
1206         //* Create the powerdns config file
1207         $configfile = 'pdns.local';
7fe908 1208         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile)) copy($conf['powerdns']['config_dir'].'/'.$configfile, $conf['powerdns']['config_dir'].'/'.$configfile.'~');
532ae5 1209         if(is_file($conf['powerdns']['config_dir'].'/'.$configfile.'~')) chmod($conf['powerdns']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1210         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
7fe908 1211         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1212         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1213         $content = str_replace('{powerdns_database}', $conf['powerdns']['database'], $content);
1214         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1215         wf($conf['powerdns']['config_dir'].'/'.$configfile, $content);
532ae5 1216         chmod($conf['powerdns']['config_dir'].'/'.$configfile, 0600);
L 1217         chown($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1218         chgrp($conf['powerdns']['config_dir'].'/'.$configfile, 'root');
1219
1220
1221     }
1222
1223     public function configure_bind() {
1224         global $conf;
1225
7fe908 1226         //* Check if the zonefile directory has a slash at the end
MC 1227         $content=$conf['bind']['bind_zonefiles_dir'];
1228         if(substr($content, -1, 1) != '/') {
1229             $content .= '/';
532ae5 1230         }
L 1231
1232         //* Create the slave subdirectory
7fe908 1233         $content .= 'slave';
fc7f1b 1234         if(!@is_dir($content)) mkdir($content, 2770, true);
532ae5 1235
7fe908 1236         //* Chown the slave subdirectory to $conf['bind']['bind_user']
MC 1237         chown($content, $conf['bind']['bind_user']);
1238         chgrp($content, $conf['bind']['bind_group']);
fc7f1b 1239         chmod($content, 2770);
532ae5 1240
L 1241     }
1242
1243
1244
1245     public function configure_apache() {
1246         global $conf;
1247
4ffb51 1248         if($conf['apache']['installed'] == false) return;
532ae5 1249         //* Create the logging directory for the vhost logfiles
L 1250         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1251
1252         if(is_file('/etc/suphp/suphp.conf')) {
7fe908 1253             replaceLine('/etc/suphp/suphp.conf', 'php=php:/usr/bin', 'x-httpd-suphp="php:/usr/bin/php-cgi"', 0);
532ae5 1254             //replaceLine('/etc/suphp/suphp.conf','docroot=','docroot=/var/clients',0);
7fe908 1255             replaceLine('/etc/suphp/suphp.conf', 'umask=0077', 'umask=0022', 0);
532ae5 1256         }
L 1257
1258         if(is_file('/etc/apache2/sites-enabled/000-default')) {
7fe908 1259             replaceLine('/etc/apache2/sites-available/000-default', 'NameVirtualHost *', 'NameVirtualHost *:80', 1, 0);
MC 1260             replaceLine('/etc/apache2/sites-available/000-default', '<VirtualHost *>', '<VirtualHost *:80>', 1, 0);
532ae5 1261         }
L 1262
1263         if(is_file('/etc/apache2/ports.conf')) {
1264             // add a line "Listen 443" to ports conf if line does not exist
7fe908 1265             replaceLine('/etc/apache2/ports.conf', 'Listen 443', 'Listen 443', 1);
14001d 1266             
TB 1267             // Comment out the namevirtualhost lines, as they were added by ispconfig in ispconfig.conf file again
1268             replaceLine('/etc/apache2/ports.conf', 'NameVirtualHost *:80', '# NameVirtualHost *:80', 1);
1269             replaceLine('/etc/apache2/ports.conf', 'NameVirtualHost *:443', '# NameVirtualHost *:443', 1);
532ae5 1270         }
L 1271
8eca28 1272         if(is_file('/etc/apache2/apache.conf')) {
MC 1273             if(hasLine('/etc/apache2/apache.conf', 'Include sites-enabled/', 1) == false) {
39e5f0 1274                 if(hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.conf', 1) == false && hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/', 1) == false) {
8eca28 1275                     replaceLine('/etc/apache2/apache.conf', 'Include sites-enabled/', 'Include sites-enabled/', 1, 1);
MC 1276                 } elseif(hasLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.vhost', 1) == false) {
39e5f0 1277                     replaceLine('/etc/apache2/apache.conf', 'IncludeOptional sites-enabled/*.vhost', 'IncludeOptional sites-enabled/', 1, 1);
TB 1278                 }
1279             }
1280         }
1281         
1282         if(is_file('/etc/apache2/apache2.conf')) {
1283             if(hasLine('/etc/apache2/apache2.conf', 'Include sites-enabled/', 1) == false && hasLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/', 1) == false) {
d10d15 1284                 if(hasLine('/etc/apache2/apache2.conf', 'Include sites-enabled/*.conf', 1) == true) {
TB 1285                     replaceLine('/etc/apache2/apache2.conf', 'Include sites-enabled/*.conf', 'Include sites-enabled/', 1, 1);
39e5f0 1286                 } elseif(hasLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/*.conf', 1) == true) {
TB 1287                     replaceLine('/etc/apache2/apache2.conf', 'IncludeOptional sites-enabled/*.conf', 'IncludeOptional sites-enabled/', 1, 1);
8eca28 1288                 }
MC 1289             }
1290         }
532ae5 1291
L 1292         //* Copy the ISPConfig configuration include
1293         $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1294         $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1295
ccbf14 1296         $tpl = new tpl('apache_ispconfig.conf.master');
TB 1297         $tpl->setVar('apache_version',getapacheversion());
1298         
532ae5 1299         $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
ccbf14 1300         $ip_addresses = array();
TB 1301         
532ae5 1302         if(is_array($records) && count($records) > 0) {
L 1303             foreach($records as $rec) {
a2156e 1304                 if($rec['ip_type'] == 'IPv6') {
T 1305                     $ip_address = '['.$rec['ip_address'].']';
1306                 } else {
1307                     $ip_address = $rec['ip_address'];
1308                 }
7fe908 1309                 $ports = explode(',', $rec['virtualhost_port']);
a2156e 1310                 if(is_array($ports)) {
T 1311                     foreach($ports as $port) {
1312                         $port = intval($port);
1313                         if($port > 0 && $port < 65536 && $ip_address != '') {
ccbf14 1314                             $ip_addresses[] = array('ip_address' => $ip_address, 'port' => $port);
a2156e 1315                         }
T 1316                     }
1317                 }
532ae5 1318             }
L 1319         }
855547 1320         
3de838 1321         if(count($ip_addresses) > 0) $tpl->setLoop('ip_adresses',$ip_addresses);
855547 1322         
ccbf14 1323         wf($vhost_conf_dir.'/ispconfig.conf', $tpl->grab());
TB 1324         unset($tpl);
532ae5 1325
L 1326         if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.conf')) {
7fe908 1327             symlink($vhost_conf_dir.'/ispconfig.conf', $vhost_conf_enabled_dir.'/000-ispconfig.conf');
532ae5 1328         }
L 1329
1330         //* make sure that webalizer finds its config file when it is directly in /etc
1331         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1332             mkdir('/etc/webalizer');
7fe908 1333             symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf');
532ae5 1334         }
L 1335
1336         if(is_file('/etc/webalizer/webalizer.conf')) {
1337             // Change webalizer mode to incremental
7fe908 1338             replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0);
MC 1339             replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental     yes', 0, 0);
1340             replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName     webalizer.hist', 0, 0);
532ae5 1341         }
a8ccf6 1342
532ae5 1343         // Check the awsatst script
L 1344         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
7fe908 1345         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 1346         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1);
a8ccf6 1347
532ae5 1348         //* add a sshusers group
L 1349         $command = 'groupadd sshusers';
1350         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1351
1352     }
a8ccf6 1353
4ffb51 1354     public function configure_nginx(){
80e3c9 1355         global $conf;
a8ccf6 1356
4ffb51 1357         if($conf['nginx']['installed'] == false) return;
F 1358         //* Create the logging directory for the vhost logfiles
1359         if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true);
1360
1361         //* make sure that webalizer finds its config file when it is directly in /etc
1362         if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) {
1363             mkdir('/etc/webalizer');
7fe908 1364             symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf');
4ffb51 1365         }
F 1366
1367         if(is_file('/etc/webalizer/webalizer.conf')) {
1368             // Change webalizer mode to incremental
7fe908 1369             replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0);
MC 1370             replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental     yes', 0, 0);
1371             replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName     webalizer.hist', 0, 0);
4ffb51 1372         }
a8ccf6 1373
4ffb51 1374         // Check the awsatst script
F 1375         if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools');
7fe908 1376         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 1377         if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1);
a8ccf6 1378
4ffb51 1379         //* add a sshusers group
F 1380         $command = 'groupadd sshusers';
1381         if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a8ccf6 1382
4ffb51 1383         /*
80e3c9 1384         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
T 1385         $ip_address = gethostbyname($row["server_name"]);
1386         $server_name = $row["server_name"];
1387
1388         //setup proxy.conf
1389         $configfile = 'proxy.conf';
1390         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile)) copy($conf["nginx"]["config_dir"].'/'.$configfile,$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1391         if(is_file($conf["nginx"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/'.$configfile.'~');
1392         $content = rf("tpl/nginx_".$configfile.".master");
1393         wf($conf["nginx"]["config_dir"].'/'.$configfile,$content);
1394         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/'.$configfile);
1395         exec('chown root:root '.$conf["nginx"]["config_dir"].'/'.$configfile);
1396
1397         //setup conf.d/cache.conf
1398         $configfile = 'cache.conf';
1399         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.'~');
1400         if(is_file($conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~');
1401         $content = rf("tpl/nginx_".$configfile.".master");
1402         wf($conf["nginx"]["config_dir"].'/conf.d/'.$configfile,$content);
1403         exec('chmod 600 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1404         exec('chown root:root '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
1405
1406         //setup cache directories
1407         mkdir('/var/cache/nginx/cache');
1408         exec('chown www-data:www-data /var/cache/nginx/cache');
1409         mkdir('/var/cache/nginx/temp');
1410         exec('chown www-data:www-data /var/cache/nginx/temp');
4ffb51 1411         */
80e3c9 1412     }
a8ccf6 1413
d083f2 1414     public function configure_fail2ban() {
7fe908 1415         // To Do
MC 1416     }
a8ccf6 1417
80e3c9 1418     public function configure_squid()
T 1419     {
1420         global $conf;
1421         $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
1422         $ip_address = gethostbyname($row["server_name"]);
1423         $server_name = $row["server_name"];
a8ccf6 1424
80e3c9 1425         $configfile = 'squid.conf';
7fe908 1426         if(is_file($conf["squid"]["config_dir"].'/'.$configfile)) copy($conf["squid"]["config_dir"].'/'.$configfile, $conf["squid"]["config_dir"].'/'.$configfile.'~');
80e3c9 1427         if(is_file($conf["squid"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["squid"]["config_dir"].'/'.$configfile.'~');
615a0a 1428         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master");
7fe908 1429         $content = str_replace('{server_name}', $server_name, $content);
MC 1430         $content = str_replace('{ip_address}', $ip_address, $content);
1431         $content = str_replace('{config_dir}', $conf['squid']['config_dir'], $content);
1432         wf($conf["squid"]["config_dir"].'/'.$configfile, $content);
80e3c9 1433         exec('chmod 600 '.$conf["squid"]["config_dir"].'/'.$configfile);
T 1434         exec('chown root:root '.$conf["squid"]["config_dir"].'/'.$configfile);
1435     }
a8ccf6 1436
992797 1437     /*
80e3c9 1438     public function configure_ufw_firewall()
T 1439     {
1440         $configfile = 'ufw.conf';
1441         if(is_file('/etc/ufw/ufw.conf')) copy('/etc/ufw/ufw.conf','/etc/ufw/ufw.conf~');
1442         $content = rf("tpl/".$configfile.".master");
1443         wf('/etc/ufw/ufw.conf',$content);
1444         exec('chmod 600 /etc/ufw/ufw.conf');
a8ccf6 1445         exec('chown root:root /etc/ufw/ufw.conf');
80e3c9 1446     }
992797 1447     */
532ae5 1448
992797 1449     public function configure_firewall() {
532ae5 1450         global $conf;
L 1451
1452         $dist_init_scripts = $conf['init_scripts'];
1453
1454         if(is_dir('/etc/Bastille.backup')) caselog('rm -rf /etc/Bastille.backup', __FILE__, __LINE__);
1455         if(is_dir('/etc/Bastille')) caselog('mv -f /etc/Bastille /etc/Bastille.backup', __FILE__, __LINE__);
1456         @mkdir('/etc/Bastille', 0700);
1457         if(is_dir('/etc/Bastille.backup/firewall.d')) caselog('cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/', __FILE__, __LINE__);
615a0a 1458         if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) {
7fe908 1459             caselog('cp -f ' . $conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
MC 1460         } else {
1461             caselog('cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
1462         }
532ae5 1463         caselog('chmod 644 /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__);
L 1464         $content = rf('/etc/Bastille/bastille-firewall.cfg');
1465         $content = str_replace('{DNS_SERVERS}', '', $content);
1466
1467         $tcp_public_services = '';
1468         $udp_public_services = '';
1469
1470         $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id']));
1471
1472         if(trim($row['tcp_port']) != '' || trim($row['udp_port']) != '') {
7fe908 1473             $tcp_public_services = trim(str_replace(',', ' ', $row['tcp_port']));
MC 1474             $udp_public_services = trim(str_replace(',', ' ', $row['udp_port']));
532ae5 1475         } else {
L 1476             $tcp_public_services = '21 22 25 53 80 110 143 443 3306 8080 10000';
1477             $udp_public_services = '53';
1478         }
1479
1480         if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
1481             $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
1482             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']));
1483         }
1484
1485         $content = str_replace('{TCP_PUBLIC_SERVICES}', $tcp_public_services, $content);
1486         $content = str_replace('{UDP_PUBLIC_SERVICES}', $udp_public_services, $content);
1487
1488         wf('/etc/Bastille/bastille-firewall.cfg', $content);
1489
1490         if(is_file($dist_init_scripts.'/bastille-firewall')) caselog('mv -f '.$dist_init_scripts.'/bastille-firewall '.$dist_init_scripts.'/bastille-firewall.backup', __FILE__, __LINE__);
1491         caselog('cp -f apps/bastille-firewall '.$dist_init_scripts, __FILE__, __LINE__);
1492         caselog('chmod 700 '.$dist_init_scripts.'/bastille-firewall', __FILE__, __LINE__);
1493
1494         if(is_file('/sbin/bastille-ipchains')) caselog('mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup', __FILE__, __LINE__);
1495         caselog('cp -f apps/bastille-ipchains /sbin', __FILE__, __LINE__);
1496         caselog('chmod 700 /sbin/bastille-ipchains', __FILE__, __LINE__);
1497
1498         if(is_file('/sbin/bastille-netfilter')) caselog('mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup', __FILE__, __LINE__);
1499         caselog('cp -f apps/bastille-netfilter /sbin', __FILE__, __LINE__);
1500         caselog('chmod 700 /sbin/bastille-netfilter', __FILE__, __LINE__);
1501
1502         if(!@is_dir('/var/lock/subsys')) caselog('mkdir /var/lock/subsys', __FILE__, __LINE__);
1503
1504         exec('which ipchains &> /dev/null', $ipchains_location, $ret_val);
1505         if(!is_file('/sbin/ipchains') && !is_link('/sbin/ipchains') && $ret_val == 0) phpcaselog(@symlink(shell_exec('which ipchains'), '/sbin/ipchains'), 'create symlink', __FILE__, __LINE__);
1506         unset($ipchains_location);
1507         exec('which iptables &> /dev/null', $iptables_location, $ret_val);
1508         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__);
1509         unset($iptables_location);
1510
1511     }
1512
1513     public function configure_vlogger() {
1514         global $conf;
1515
1516         //** Configure vlogger to use traffic logging to mysql (master) db
1517         $configfile = 'vlogger-dbi.conf';
7fe908 1518         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile)) copy($conf['vlogger']['config_dir'].'/'.$configfile, $conf['vlogger']['config_dir'].'/'.$configfile.'~');
532ae5 1519         if(is_file($conf['vlogger']['config_dir'].'/'.$configfile.'~')) chmod($conf['vlogger']['config_dir'].'/'.$configfile.'~', 0400);
615a0a 1520         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1521         if($conf['mysql']['master_slave_setup'] == 'y') {
7fe908 1522             $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
MC 1523             $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1524             $content = str_replace('{mysql_server_database}', $conf['mysql']['master_database'], $content);
1525             $content = str_replace('{mysql_server_ip}', $conf['mysql']['master_host'], $content);
532ae5 1526         } else {
7fe908 1527             $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
MC 1528             $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1529             $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1530             $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content);
532ae5 1531         }
7fe908 1532         wf($conf['vlogger']['config_dir'].'/'.$configfile, $content);
532ae5 1533         chmod($conf['vlogger']['config_dir'].'/'.$configfile, 0600);
L 1534         chown($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1535         chgrp($conf['vlogger']['config_dir'].'/'.$configfile, 'root');
1536
1537     }
1538
1539     public function configure_apps_vhost() {
1540         global $conf;
1541
1542         //* Create the ispconfig apps vhost user and group
165152 1543         if($conf['apache']['installed'] == true){
4ffb51 1544             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
F 1545             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1546             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1547
4ffb51 1548             $command = 'groupadd '.$apps_vhost_user;
F 1549             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1550
4ffb51 1551             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
F 1552             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1553
L 1554
5edf40 1555             //$command = 'adduser '.$conf['apache']['user'].' '.$apps_vhost_group;
TB 1556             $command = 'usermod -a -G '.$apps_vhost_group.' '.$conf['apache']['user'];
4ffb51 1557             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1558
99b55b 1559             if(!@is_dir($install_dir)){
F 1560                 mkdir($install_dir, 0755, true);
1561             } else {
1562                 chmod($install_dir, 0755);
1563             }
4ffb51 1564             chown($install_dir, $apps_vhost_user);
F 1565             chgrp($install_dir, $apps_vhost_group);
532ae5 1566
4ffb51 1567             //* Copy the apps vhost file
F 1568             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
1569             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
1570             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'':'ServerName '.$conf['web']['apps_vhost_servername'];
d0356f 1571             
TB 1572             //* Get the apps vhost port
1573             if($this->is_update == true) {
1574                 $conf['web']['apps_vhost_port'] = get_apps_vhost_port_number();
1575             }
532ae5 1576
4ffb51 1577             // Dont just copy over the virtualhost template but add some custom settings
ccbf14 1578             $tpl = new tpl('apache_apps.vhost.master');
TB 1579             $tpl->setVar('apps_vhost_ip',$conf['web']['apps_vhost_ip']);
1580             $tpl->setVar('apps_vhost_port',$conf['web']['apps_vhost_port']);
1581             $tpl->setVar('apps_vhost_dir',$conf['web']['website_basedir'].'/apps');
1582             $tpl->setVar('apps_vhost_basedir',$conf['web']['website_basedir']);
1583             $tpl->setVar('apps_vhost_servername',$apps_vhost_servername);
1584             $tpl->setVar('apache_version',getapacheversion());
532ae5 1585
L 1586
4ffb51 1587             // comment out the listen directive if port is 80 or 443
F 1588             if($conf['web']['apps_vhost_ip'] == 80 or $conf['web']['apps_vhost_ip'] == 443) {
ccbf14 1589                 $tpl->setVar('vhost_port_listen','#');
4ffb51 1590             } else {
ccbf14 1591                 $tpl->setVar('vhost_port_listen','');
4ffb51 1592             }
532ae5 1593
ccbf14 1594             wf($vhost_conf_dir.'/apps.vhost', $tpl->grab());
TB 1595             unset($tpl);
532ae5 1596
4ffb51 1597             //copy('tpl/apache_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
F 1598             //* and create the symlink
7e1cfb 1599             if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
F 1600             if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
7fe908 1601                 symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost');
4ffb51 1602             }
a8ccf6 1603
4ffb51 1604             if(!is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter')) {
615a0a 1605                 $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_apps_fcgi_starter.master', 'tpl/apache_apps_fcgi_starter.master');
526b99 1606                 $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content);
T 1607                 $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content);
4ffb51 1608                 mkdir($conf['web']['website_basedir'].'/php-fcgi-scripts/apps', 0755, true);
526b99 1609                 //copy('tpl/apache_apps_fcgi_starter.master',$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
T 1610                 wf($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter', $content);
4ffb51 1611                 exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter');
F 1612                 exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps');
1613
7fe908 1614             }
532ae5 1615         }
165152 1616         if($conf['nginx']['installed'] == true){
4ffb51 1617             $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']);
F 1618             $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']);
1619             $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps');
532ae5 1620
4ffb51 1621             $command = 'groupadd '.$apps_vhost_user;
F 1622             if(!is_group($apps_vhost_group)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1623
1624             $command = 'useradd -g '.$apps_vhost_group.' -d '.$install_dir.' '.$apps_vhost_group;
1625             if(!is_user($apps_vhost_user)) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1626
1627
11f2ad 1628             //$command = 'adduser '.$conf['nginx']['user'].' '.$apps_vhost_group;
TB 1629             $command = 'usermod -a -G '.$apps_vhost_group.' '.$conf['nginx']['user'];
4ffb51 1630             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
F 1631
6e2d48 1632             if(!@is_dir($install_dir)){
F 1633                 mkdir($install_dir, 0755, true);
1634             } else {
1635                 chmod($install_dir, 0755);
1636             }
4ffb51 1637             chown($install_dir, $apps_vhost_user);
F 1638             chgrp($install_dir, $apps_vhost_group);
1639
1640             //* Copy the apps vhost file
1641             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
1642             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
1643             $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '')?'_':$conf['web']['apps_vhost_servername'];
1644
1645             // Dont just copy over the virtualhost template but add some custom settings
615a0a 1646             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_apps.vhost.master', 'tpl/nginx_apps.vhost.master');
a8ccf6 1647
4ffb51 1648             if($conf['web']['apps_vhost_ip'] == '_default_'){
F 1649                 $apps_vhost_ip = '';
1650             } else {
1651                 $apps_vhost_ip = $conf['web']['apps_vhost_ip'].':';
1652             }
a8ccf6 1653
ca0b77 1654             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
7fe908 1655             if(substr($socket_dir, -1) != '/') $socket_dir .= '/';
ca0b77 1656             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
F 1657             $fpm_socket = $socket_dir.'apps.sock';
8ab3cd 1658             $cgi_socket = escapeshellcmd($conf['nginx']['cgi_socket']);
4ffb51 1659
F 1660             $content = str_replace('{apps_vhost_ip}', $apps_vhost_ip, $content);
1661             $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content);
1662             $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content);
1663             $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content);
ca0b77 1664             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1665             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
8ab3cd 1666             $content = str_replace('{cgi_socket}', $cgi_socket, $content);
7fe908 1667
183c47 1668             if(file_exists('/var/run/php5-fpm.sock')){
F 1669                 $use_tcp = '#';
1670                 $use_socket = '';
1671             } else {
1672                 $use_tcp = '';
1673                 $use_socket = '#';
1674             }
1675             $content = str_replace('{use_tcp}', $use_tcp, $content);
1676             $content = str_replace('{use_socket}', $use_socket, $content);
4ffb51 1677
F 1678             wf($vhost_conf_dir.'/apps.vhost', $content);
a8ccf6 1679
fbb24a 1680             // PHP-FPM
F 1681             // Dont just copy over the php-fpm pool template but add some custom settings
615a0a 1682             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apps_php_fpm_pool.conf.master', 'tpl/apps_php_fpm_pool.conf.master');
fbb24a 1683             $content = str_replace('{fpm_pool}', 'apps', $content);
ca0b77 1684             //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content);
F 1685             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
fbb24a 1686             $content = str_replace('{fpm_user}', $apps_vhost_user, $content);
F 1687             $content = str_replace('{fpm_group}', $apps_vhost_group, $content);
1688             wf($conf['nginx']['php_fpm_pool_dir'].'/apps.conf', $content);
4ffb51 1689
F 1690             //copy('tpl/nginx_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost");
1691             //* and create the symlink
7e1cfb 1692             if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost');
F 1693             if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) {
7fe908 1694                 symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost');
4ffb51 1695             }
a8ccf6 1696
532ae5 1697         }
L 1698     }
a8ccf6 1699
532ae5 1700     public function make_ispconfig_ssl_cert() {
b04e82 1701         global $conf,$autoinstall;
532ae5 1702
L 1703         $install_dir = $conf['ispconfig_install_dir'];
a8ccf6 1704
532ae5 1705         $ssl_crt_file = $install_dir.'/interface/ssl/ispserver.crt';
L 1706         $ssl_csr_file = $install_dir.'/interface/ssl/ispserver.csr';
1707         $ssl_key_file = $install_dir.'/interface/ssl/ispserver.key';
a8ccf6 1708
532ae5 1709         if(!@is_dir($install_dir.'/interface/ssl')) mkdir($install_dir.'/interface/ssl', 0755, true);
a8ccf6 1710
7fe908 1711         $ssl_pw = substr(md5(mt_rand()), 0, 6);
532ae5 1712         exec("openssl genrsa -des3 -passout pass:$ssl_pw -out $ssl_key_file 4096");
b04e82 1713         if(AUTOINSTALL){
TB 1714             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 1715         } else {
FT 1716             exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -out $ssl_csr_file");
1717         }
532ae5 1718         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 1719         exec("openssl rsa -passin pass:$ssl_pw -in $ssl_key_file -out $ssl_key_file.insecure");
7fe908 1720         rename($ssl_key_file, $ssl_key_file.'.secure');
MC 1721         rename($ssl_key_file.'.insecure', $ssl_key_file);
980485 1722         
TB 1723         exec('chown -R root:root /usr/local/ispconfig/interface/ssl');
a8ccf6 1724
532ae5 1725     }
L 1726
1727     public function install_ispconfig() {
1728         global $conf;
1729
1730         $install_dir = $conf['ispconfig_install_dir'];
1731
1732         //* Create the ISPConfig installation directory
1733         if(!@is_dir($install_dir)) {
1734             $command = "mkdir $install_dir";
1735             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1736         }
1737
1738         //* Create a ISPConfig user and group
1739         $command = 'groupadd ispconfig';
1740         if(!is_group('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1741
1742         $command = 'useradd -g ispconfig -d '.$install_dir.' ispconfig';
1743         if(!is_user('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1744
1745         //* copy the ISPConfig interface part
1746         $command = 'cp -rf ../interface '.$install_dir;
1747         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1748
1749         //* copy the ISPConfig server part
1750         $command = 'cp -rf ../server '.$install_dir;
1751         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
a13af2 1752         
fb6c56 1753         //* Make a backup of the security settings
TB 1754         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~');
1755         
a13af2 1756         //* copy the ISPConfig security part
TB 1757         $command = 'cp -rf ../security '.$install_dir;
1758         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
fb6c56 1759         
TB 1760         //* Apply changed security_settings.ini values to new security_settings.ini file
1761         if(is_file('/usr/local/ispconfig/security/security_settings.ini~')) {
1762             $security_settings_old = ini_to_array(file_get_contents('/usr/local/ispconfig/security/security_settings.ini~'));
1763             $security_settings_new = ini_to_array(file_get_contents('/usr/local/ispconfig/security/security_settings.ini'));
1764             if(is_array($security_settings_new) && is_array($security_settings_old)) {
1765                 foreach($security_settings_new as $section => $sval) {
1766                     if(is_array($sval)) {
1767                         foreach($sval as $key => $val) {
1768                             if(isset($security_settings_old[$section]) && isset($security_settings_old[$section][$key])) {
1769                                 $security_settings_new[$section][$key] = $security_settings_old[$section][$key];
1770                             }
1771                         }
1772                     }
1773                 }
1774                 file_put_contents('/usr/local/ispconfig/security/security_settings.ini',array_to_ini($security_settings_new));
1775             }
1776         }
532ae5 1777
L 1778         //* Create a symlink, so ISPConfig is accessible via web
1779         // Replaced by a separate vhost definition for port 8080
1780         // $command = "ln -s $install_dir/interface/web/ /var/www/ispconfig";
1781         // caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1782
1783         //* Create the config file for ISPConfig interface
1784         $configfile = 'config.inc.php';
1785         if(is_file($install_dir.'/interface/lib/'.$configfile)) {
1786             copy($install_dir.'/interface/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1787         }
615a0a 1788         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1789         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
7fe908 1790         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
532ae5 1791         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
L 1792         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1793
1794         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1795         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1796         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1797         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1798
1799         $content = str_replace('{server_id}', $conf['server_id'], $content);
1800         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
b63764 1801         $content = str_replace('{language}', $conf['language'], $content);
8cf78b 1802         $content = str_replace('{timezone}', $conf['timezone'], $content);
f598b0 1803         $content = str_replace('{theme}', $conf['theme'], $content);
992797 1804         $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content);
b63764 1805
532ae5 1806         wf($install_dir.'/interface/lib/'.$configfile, $content);
L 1807
1808         //* Create the config file for ISPConfig server
1809         $configfile = 'config.inc.php';
1810         if(is_file($install_dir.'/server/lib/'.$configfile)) {
1811             copy($install_dir.'/server/lib/'.$configfile, $install_dir.'/interface/lib/'.$configfile.'~');
1812         }
615a0a 1813         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master');
532ae5 1814         $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content);
L 1815         $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content);
1816         $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content);
1817         $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content);
1818
1819         $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content);
1820         $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content);
1821         $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content);
1822         $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content);
1823
1824         $content = str_replace('{server_id}', $conf['server_id'], $content);
1825         $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content);
1826         $content = str_replace('{language}', $conf['language'], $content);
8cf78b 1827         $content = str_replace('{timezone}', $conf['timezone'], $content);
f598b0 1828         $content = str_replace('{theme}', $conf['theme'], $content);
992797 1829         $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content);
532ae5 1830
L 1831         wf($install_dir.'/server/lib/'.$configfile, $content);
1832
1833         //* Create the config file for remote-actions (but only, if it does not exist, because
1834         //  the value is a autoinc-value and so changed by the remoteaction_core_module
1835         if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) {
1836             $content = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
1837             wf($install_dir.'/server/lib/remote_action.inc.php', $content);
1838         }
1839
1840         //* Enable the server modules and plugins.
1841         // TODO: Implement a selector which modules and plugins shall be enabled.
1842         $dir = $install_dir.'/server/mods-available/';
1843         if (is_dir($dir)) {
1844             if ($dh = opendir($dir)) {
1845                 while (($file = readdir($dh)) !== false) {
7fe908 1846                     if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') {
MC 1847                         include_once $install_dir.'/server/mods-available/'.$file;
1848                         $module_name = substr($file, 0, -8);
532ae5 1849                         $tmp = new $module_name;
L 1850                         if($tmp->onInstall()) {
1851                             if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) {
1852                                 @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-enabled/'.$file);
1853                                 // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-enabled/'.$file);
1854                             }
1855                             if (strpos($file, '_core_module') !== false) {
1856                                 if(!@is_link($install_dir.'/server/mods-core/'.$file)) {
1857                                     @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-core/'.$file);
1858                                     // @symlink($install_dir.'/server/mods-available/'.$file, '../mods-core/'.$file);
1859                                 }
1860                             }
1861                         }
1862                         unset($tmp);
1863                     }
1864                 }
1865                 closedir($dh);
1866             }
1867         }
1868
1869         $dir = $install_dir.'/server/plugins-available/';
1870         if (is_dir($dir)) {
1871             if ($dh = opendir($dir)) {
1872                 while (($file = readdir($dh)) !== false) {
4ffb51 1873                     if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue;
F 1874                     if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue;
7fe908 1875                     if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') {
MC 1876                         include_once $install_dir.'/server/plugins-available/'.$file;
1877                         $plugin_name = substr($file, 0, -8);
532ae5 1878                         $tmp = new $plugin_name;
7fe908 1879                         if(method_exists($tmp, 'onInstall') && $tmp->onInstall()) {
532ae5 1880                             if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) {
L 1881                                 @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file);
1882                                 //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-enabled/'.$file);
1883                             }
1884                             if (strpos($file, '_core_plugin') !== false) {
1885                                 if(!@is_link($install_dir.'/server/plugins-core/'.$file)) {
1886                                     @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-core/'.$file);
1887                                     //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-core/'.$file);
1888                                 }
1889                             }
1890                         }
1891                         unset($tmp);
1892                     }
1893                 }
1894                 closedir($dh);
1895             }
1896         }
1897
1898         // Update the server config
1899         $mail_server_enabled = ($conf['services']['mail'])?1:0;
1900         $web_server_enabled = ($conf['services']['web'])?1:0;
1901         $dns_server_enabled = ($conf['services']['dns'])?1:0;
1902         $file_server_enabled = ($conf['services']['file'])?1:0;
1903         $db_server_enabled = ($conf['services']['db'])?1:0;
8cf955 1904         $vserver_server_enabled = ($conf['openvz']['installed'])?1:0;
80e3c9 1905         $proxy_server_enabled = ($conf['services']['proxy'])?1:0;
T 1906         $firewall_server_enabled = ($conf['services']['firewall'])?1:0;
532ae5 1907
80e3c9 1908         $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 1909
L 1910         if($conf['mysql']['master_slave_setup'] == 'y') {
1911             $this->dbmaster->query($sql);
1912             $this->db->query($sql);
1913         } else {
1914             $this->db->query($sql);
1915         }
1916
1917
3e0fc8 1918         // chown install dir to root and chmod 755
TB 1919         $command = 'chown root:root '.$install_dir;
1920         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1921         $command = 'chmod 755 '.$install_dir;
532ae5 1922         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
L 1923
fa029b 1924         //* Chmod the files and directories in the install dir
3e0fc8 1925         $command = 'chmod -R 750 '.$install_dir.'/*';
TB 1926         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1927
1928         //* chown the interface files to the ispconfig user and group
1929         $command = 'chown -R ispconfig:ispconfig '.$install_dir.'/interface';
1930         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1931         
1932         //* chown the server files to the root user and group
1933         $command = 'chown -R root:root '.$install_dir.'/server';
532ae5 1934         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
fa029b 1935         
TB 1936         //* chown the security files to the root user and group
1937         $command = 'chown -R root:root '.$install_dir.'/security';
1938         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1939         
1940         //* chown the security directory and security_settings.ini to root:ispconfig
1941         $command = 'chown root:ispconfig '.$install_dir.'/security/security_settings.ini';
1942         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1943         $command = 'chown root:ispconfig '.$install_dir.'/security';
1944         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
cb1221 1945         $command = 'chown root:ispconfig '.$install_dir.'/security/ids.whitelist';
TB 1946         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1947         $command = 'chown root:ispconfig '.$install_dir.'/security/ids.htmlfield';
1948         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
1949         $command = 'chown root:ispconfig '.$install_dir.'/security/apache_directives.blacklist';
1950         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
532ae5 1951
L 1952         //* Make the global language file directory group writable
1953         exec("chmod -R 770 $install_dir/interface/lib/lang");
1954
1955         //* Make the temp directory for language file exports writable
1956         if(is_dir($install_dir.'/interface/web/temp')) exec("chmod -R 770 $install_dir/interface/web/temp");
1957
1958         //* Make all interface language file directories group writable
1959         $handle = @opendir($install_dir.'/interface/web');
7fe908 1960         while ($file = @readdir($handle)) {
532ae5 1961             if ($file != '.' && $file != '..') {
L 1962                 if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) {
1963                     $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang');
7fe908 1964                     chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang', 0770);
MC 1965                     while ($lang_file = @readdir($handle2)) {
532ae5 1966                         if ($lang_file != '.' && $lang_file != '..') {
7fe908 1967                             chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file, 0770);
532ae5 1968                         }
L 1969                     }
1970                 }
1971             }
1972         }
a8ccf6 1973
477d4e 1974         //* Make the APS directories group writable
T 1975         exec("chmod -R 770 $install_dir/interface/web/sites/aps_meta_packages");
1976         exec("chmod -R 770 $install_dir/server/aps_packages");
532ae5 1977
L 1978         //* make sure that the server config file (not the interface one) is only readable by the root user
bfcdef 1979         chmod($install_dir.'/server/lib/config.inc.php', 0600);
T 1980         chown($install_dir.'/server/lib/config.inc.php', 'root');
1981         chgrp($install_dir.'/server/lib/config.inc.php', 'root');
7fe908 1982
bfcdef 1983         //* Make sure thet the interface config file is readable by user ispconfig only
T 1984         chmod($install_dir.'/interface/lib/config.inc.php', 0600);
1985         chown($install_dir.'/interface/lib/config.inc.php', 'ispconfig');
1986         chgrp($install_dir.'/interface/lib/config.inc.php', 'ispconfig');
532ae5 1987
L 1988         chmod($install_dir.'/server/lib/remote_action.inc.php', 0600);
1989         chown($install_dir.'/server/lib/remote_action.inc.php', 'root');
1990         chgrp($install_dir.'/server/lib/remote_action.inc.php', 'root');
1991
1992         if(@is_file($install_dir.'/server/lib/mysql_clientdb.conf')) {
1993             chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
1994             chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1995             chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
1996         }
a8ccf6 1997
8cf78b 1998         if(is_dir($install_dir.'/interface/invoices')) {
e94a9f 1999             exec('chmod -R 770 '.escapeshellarg($install_dir.'/interface/invoices'));
T 2000             exec('chown -R ispconfig:ispconfig '.escapeshellarg($install_dir.'/interface/invoices'));
edf806 2001         }
980485 2002         
TB 2003         exec('chown -R root:root /usr/local/ispconfig/interface/ssl');
532ae5 2004
L 2005         // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing
2006         // and must be fixed as this will allow the apache user to read the ispconfig files.
2007         // Later this must run as own apache server or via suexec!
63b369 2008         if($conf['apache']['installed'] == true){
F 2009             $command = 'adduser '.$conf['apache']['user'].' ispconfig';
2010             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 2011             if(is_group('ispapps')){
F 2012                 $command = 'adduser '.$conf['apache']['user'].' ispapps';
2013                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2014             }
63b369 2015         }
F 2016         if($conf['nginx']['installed'] == true){
2017             $command = 'adduser '.$conf['nginx']['user'].' ispconfig';
2018             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
272aec 2019             if(is_group('ispapps')){
F 2020                 $command = 'adduser '.$conf['nginx']['user'].' ispapps';
2021                 caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2022             }
63b369 2023         }
532ae5 2024
L 2025         //* Make the shell scripts executable
2026         $command = "chmod +x $install_dir/server/scripts/*.sh";
2027         caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2028
7e1cfb 2029         if($conf['apache']['installed'] == true && $this->install_ispconfig_interface == true){
4ffb51 2030             //* Copy the ISPConfig vhost for the controlpanel
F 2031             $vhost_conf_dir = $conf['apache']['vhost_conf_dir'];
2032             $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir'];
532ae5 2033
4ffb51 2034             // Dont just copy over the virtualhost template but add some custom settings
ccbf14 2035             $tpl = new tpl('apache_ispconfig.vhost.master');
TB 2036             $tpl->setVar('vhost_port',$conf['apache']['vhost_port']);
532ae5 2037
4ffb51 2038             // comment out the listen directive if port is 80 or 443
F 2039             if($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) {
ccbf14 2040                 $tpl->setVar('vhost_port_listen','#');
4ffb51 2041             } else {
ccbf14 2042                 $tpl->setVar('vhost_port_listen','');
4ffb51 2043             }
a8ccf6 2044
4ffb51 2045             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
ccbf14 2046                 $tpl->setVar('ssl_comment','');
4ffb51 2047             } else {
ccbf14 2048                 $tpl->setVar('ssl_comment','#');
4ffb51 2049             }
10b4c8 2050             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 2051                 $tpl->setVar('ssl_bundle_comment','');
10b4c8 2052             } else {
ccbf14 2053                 $tpl->setVar('ssl_bundle_comment','#');
10b4c8 2054             }
ccbf14 2055             
TB 2056             $tpl->setVar('apache_version',getapacheversion());
532ae5 2057
ccbf14 2058             wf($vhost_conf_dir.'/ispconfig.vhost', $tpl->grab());
532ae5 2059
4ffb51 2060             //* and create the symlink
7e1cfb 2061             if($this->is_update == false) {
4ffb51 2062                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
F 2063                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
7fe908 2064                     symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost');
4ffb51 2065                 }
F 2066             }
cc6568 2067             //if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) {
7fe908 2068             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master');
MC 2069             $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content);
2070             $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content);
2071             @mkdir('/var/www/php-fcgi-scripts/ispconfig', 0755, true);
2072             wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content);
2073             exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter');
2074             @symlink($install_dir.'/interface/web', '/var/www/ispconfig');
2075             exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig');
cc6568 2076             //}
532ae5 2077         }
a8ccf6 2078
7e1cfb 2079         if($conf['nginx']['installed'] == true && $this->install_ispconfig_interface == true){
4ffb51 2080             //* Copy the ISPConfig vhost for the controlpanel
F 2081             $vhost_conf_dir = $conf['nginx']['vhost_conf_dir'];
2082             $vhost_conf_enabled_dir = $conf['nginx']['vhost_conf_enabled_dir'];
532ae5 2083
4ffb51 2084             // Dont just copy over the virtualhost template but add some custom settings
615a0a 2085             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_ispconfig.vhost.master', 'tpl/nginx_ispconfig.vhost.master');
4ffb51 2086             $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content);
a8ccf6 2087
4ffb51 2088             if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) {
f9b8d0 2089                 $content = str_replace('{ssl_on}', 'on', $content);
4ffb51 2090                 $content = str_replace('{ssl_comment}', '', $content);
F 2091                 $content = str_replace('{fastcgi_ssl}', 'on', $content);
2092             } else {
f9b8d0 2093                 $content = str_replace('{ssl_on}', 'off', $content);
4ffb51 2094                 $content = str_replace('{ssl_comment}', '#', $content);
F 2095                 $content = str_replace('{fastcgi_ssl}', 'off', $content);
2096             }
a8ccf6 2097
ca0b77 2098             $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']);
7fe908 2099             if(substr($socket_dir, -1) != '/') $socket_dir .= '/';
ca0b77 2100             if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir);
F 2101             $fpm_socket = $socket_dir.'ispconfig.sock';
a8ccf6 2102
ca0b77 2103             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 2104             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
a8ccf6 2105
4ffb51 2106             wf($vhost_conf_dir.'/ispconfig.vhost', $content);
a8ccf6 2107
4ffb51 2108             unset($content);
a8ccf6 2109
4ffb51 2110             // PHP-FPM
F 2111             // Dont just copy over the php-fpm pool template but add some custom settings
615a0a 2112             $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/php_fpm_pool.conf.master', 'tpl/php_fpm_pool.conf.master');
4ffb51 2113             $content = str_replace('{fpm_pool}', 'ispconfig', $content);
ca0b77 2114             //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content);
F 2115             $content = str_replace('{fpm_socket}', $fpm_socket, $content);
4ffb51 2116             $content = str_replace('{fpm_user}', 'ispconfig', $content);
F 2117             $content = str_replace('{fpm_group}', 'ispconfig', $content);
2118             wf($conf['nginx']['php_fpm_pool_dir'].'/ispconfig.conf', $content);
2119
2120             //copy('tpl/nginx_ispconfig.vhost.master', $vhost_conf_dir.'/ispconfig.vhost');
2121             //* and create the symlink
7e1cfb 2122             if($this->is_update == false) {
4ffb51 2123                 if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost');
F 2124                 if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) {
7fe908 2125                     symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost');
4ffb51 2126                 }
F 2127             }
532ae5 2128         }
L 2129
2130         //* Install the update script
b34f99 2131         if(is_file('/usr/local/bin/ispconfig_update_from_dev.sh')) unlink('/usr/local/bin/ispconfig_update_from_dev.sh');
MC 2132         chown($install_dir.'/server/scripts/update_from_dev.sh', 'root');
2133         chmod($install_dir.'/server/scripts/update_from_dev.sh', 0700);
532ae5 2134         chown($install_dir.'/server/scripts/update_from_tgz.sh', 'root');
L 2135         chmod($install_dir.'/server/scripts/update_from_tgz.sh', 0700);
2136         chown($install_dir.'/server/scripts/ispconfig_update.sh', 'root');
2137         chmod($install_dir.'/server/scripts/ispconfig_update.sh', 0700);
b34f99 2138         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 2139         if(!is_link('/usr/local/bin/ispconfig_update.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update.sh');
532ae5 2140
L 2141         //* Make the logs readable for the ispconfig user
2142         if(@is_file('/var/log/mail.log')) exec('chmod +r /var/log/mail.log');
2143         if(@is_file('/var/log/mail.warn')) exec('chmod +r /var/log/mail.warn');
2144         if(@is_file('/var/log/mail.err')) exec('chmod +r /var/log/mail.err');
2145         if(@is_file('/var/log/messages')) exec('chmod +r /var/log/messages');
2146         if(@is_file('/var/log/clamav/clamav.log')) exec('chmod +r /var/log/clamav/clamav.log');
2147         if(@is_file('/var/log/clamav/freshclam.log')) exec('chmod +r /var/log/clamav/freshclam.log');
2148
2149         //* Create the ispconfig log file and directory
2150         if(!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) {
2151             if(!is_dir($conf['ispconfig_log_dir'])) mkdir($conf['ispconfig_log_dir'], 0755);
2152             touch($conf['ispconfig_log_dir'].'/ispconfig.log');
2153         }
a8ccf6 2154
99c89b 2155         //* Create the ispconfig auth log file and set uid/gid
a8ccf6 2156         if(!is_file($conf['ispconfig_log_dir'].'/auth.log')) {
99c89b 2157             touch($conf['ispconfig_log_dir'].'/auth.log');
a8ccf6 2158         }
0799f8 2159         exec('chown ispconfig:ispconfig '. $conf['ispconfig_log_dir'].'/auth.log');
T 2160         exec('chmod 660 '. $conf['ispconfig_log_dir'].'/auth.log');
a8ccf6 2161
0c5b42 2162         if(is_user('getmail')) {
7fe908 2163             rename($install_dir.'/server/scripts/run-getmail.sh', '/usr/local/bin/run-getmail.sh');
0c5b42 2164             if(is_user('getmail')) chown('/usr/local/bin/run-getmail.sh', 'getmail');
T 2165             chmod('/usr/local/bin/run-getmail.sh', 0744);
2166         }
532ae5 2167
L 2168         //* Add Log-Rotation
2169         if (is_dir('/etc/logrotate.d')) {
2170             @unlink('/etc/logrotate.d/logispc3'); // ignore, if the file is not there
2171             /* We rotate these logs in cron_daily.php
2172             $fh = fopen('/etc/logrotate.d/logispc3', 'w');
2173             fwrite($fh,
2174                     "$conf['ispconfig_log_dir']/ispconfig.log { \n" .
2175                     "    weekly \n" .
2176                     "    missingok \n" .
2177                     "    rotate 4 \n" .
2178                     "    compress \n" .
2179                     "    delaycompress \n" .
2180                     "} \n" .
2181                     "$conf['ispconfig_log_dir']/cron.log { \n" .
2182                     "    weekly \n" .
2183                     "    missingok \n" .
2184                     "    rotate 4 \n" .
2185                     "    compress \n" .
2186                     "    delaycompress \n" .
2187                     "}");
2188             fclose($fh);
2189             */
2190         }
7fe908 2191
d71bae 2192         //* Remove Domain module as its functions are available in the client module now
T 2193         if(@is_dir('/usr/local/ispconfig/interface/web/domain')) exec('rm -rf /usr/local/ispconfig/interface/web/domain');
f30628 2194         
TB 2195         //* Disable rkhunter run and update in debian cronjob as ispconfig is running and updating rkhunter
2196         if(is_file('/etc/default/rkhunter')) {
2197             replaceLine('/etc/default/rkhunter', 'CRON_DAILY_RUN="yes"', 'CRON_DAILY_RUN="no"', 1, 0);
2198             replaceLine('/etc/default/rkhunter', 'CRON_DB_UPDATE="yes"', 'CRON_DB_UPDATE="no"', 1, 0);
2199         }
2200         
021aec 2201         // Add symlink for patch tool
TB 2202         if(!is_link('/usr/local/bin/ispconfig_patch')) exec('ln -s /usr/local/ispconfig/server/scripts/ispconfig_patch /usr/local/bin/ispconfig_patch');
5b3f25 2203         
553854 2204         // Change mode of a few files from amavisd
TB 2205         if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user')) chmod($conf['amavis']['config_dir'].'/conf.d/50-user', 0640);
2206         if(is_file($conf['amavis']['config_dir'].'/50-user~')) chmod($conf['amavis']['config_dir'].'/50-user~', 0400);
2207         if(is_file($conf['amavis']['config_dir'].'/amavisd.conf')) chmod($conf['amavis']['config_dir'].'/amavisd.conf', 0640);
2208         if(is_file($conf['amavis']['config_dir'].'/amavisd.conf~')) chmod($conf['amavis']['config_dir'].'/amavisd.conf~', 0400);
532ae5 2209     }
L 2210
2211     public function configure_dbserver() {
2212         global $conf;
2213
2214         //* If this server shall act as database server for client DB's, we configure this here
2215         $install_dir = $conf['ispconfig_install_dir'];
2216
2217         // Create a file with the database login details which
2218         // are used to create the client databases.
2219
2220         if(!is_dir($install_dir.'/server/lib')) {
2221             $command = "mkdir $install_dir/server/lib";
2222             caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
2223         }
2224
615a0a 2225         $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mysql_clientdb.conf.master', 'tpl/mysql_clientdb.conf.master');
7fe908 2226         $content = str_replace('{hostname}', $conf['mysql']['host'], $content);
MC 2227         $content = str_replace('{username}', $conf['mysql']['admin_user'], $content);
67fede 2228         $content = str_replace('{password}', addslashes($conf['mysql']['admin_password']), $content);
7fe908 2229         wf($install_dir.'/server/lib/mysql_clientdb.conf', $content);
532ae5 2230         chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600);
L 2231         chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
a8ccf6 2232         chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root');
532ae5 2233
L 2234     }
2235
2236     public function install_crontab() {
2237         global $conf;
2238
2239         $install_dir = $conf['ispconfig_install_dir'];
2240
2241         //* Root Crontab
2242         exec('crontab -u root -l > crontab.txt');
2243         $existing_root_cron_jobs = file('crontab.txt');
2244
2245         // remove existing ispconfig cronjobs, in case the syntax has changed
2246         foreach($existing_root_cron_jobs as $key => $val) {
7fe908 2247             if(stristr($val, $install_dir)) unset($existing_root_cron_jobs[$key]);
532ae5 2248         }
L 2249
2250         $root_cron_jobs = array(
7fe908 2251             "* * * * * ".$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 2252             "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 2253         );
a8ccf6 2254
b6a10a 2255         if ($conf['nginx']['installed'] == true) {
F 2256             $root_cron_jobs[] = "0 0 * * * ".$install_dir."/server/scripts/create_daily_nginx_access_logs.sh &> /dev/null";
2257         }
a8ccf6 2258
532ae5 2259         foreach($root_cron_jobs as $cron_job) {
L 2260             if(!in_array($cron_job."\n", $existing_root_cron_jobs)) {
2261                 $existing_root_cron_jobs[] = $cron_job."\n";
2262             }
2263         }
2264         file_put_contents('crontab.txt', $existing_root_cron_jobs);
2265         exec('crontab -u root crontab.txt &> /dev/null');
2266         unlink('crontab.txt');
2267
2268         //* Getmail crontab
2269         if(is_user('getmail')) {
2270             $cf = $conf['getmail'];
2271             exec('crontab -u getmail -l > crontab.txt');
2272             $existing_cron_jobs = file('crontab.txt');
2273
2274             $cron_jobs = array(
7fe908 2275                 '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null'
532ae5 2276             );
L 2277
2278             // remove existing ispconfig cronjobs, in case the syntax has changed
2279             foreach($existing_cron_jobs as $key => $val) {
7fe908 2280                 if(stristr($val, 'getmail')) unset($existing_cron_jobs[$key]);
532ae5 2281             }
L 2282
2283             foreach($cron_jobs as $cron_job) {
2284                 if(!in_array($cron_job."\n", $existing_cron_jobs)) {
2285                     $existing_cron_jobs[] = $cron_job."\n";
2286                 }
2287             }
2288             file_put_contents('crontab.txt', $existing_cron_jobs);
2289             exec('crontab -u getmail crontab.txt &> /dev/null');
2290             unlink('crontab.txt');
2291         }
2292
2293         touch($conf['ispconfig_log_dir'].'/cron.log');
cc6568 2294         chmod($conf['ispconfig_log_dir'].'/cron.log', 0660);
532ae5 2295
L 2296     }
5b3f25 2297     
TB 2298     // This function is called at the end of the update process and contains code to clean up parts of old ISPCONfig releases
2299     public function cleanup_ispconfig() {
2300         global $app,$conf;
2301         
2302         // Remove directories recursively
2303         if(is_dir('/usr/local/ispconfig/interface/web/designer')) exec('rm -rf /usr/local/ispconfig/interface/web/designer');
4c3fcd 2304         if(is_dir('/usr/local/ispconfig/interface/web/themes/default-304')) exec('rm -rf /usr/local/ispconfig/interface/web/themes/default-304');
5b3f25 2305         
TB 2306         // Remove files
2307         if(is_file('/usr/local/ispconfig/interface/lib/classes/db_firebird.inc.php')) unlink('/usr/local/ispconfig/interface/lib/classes/db_firebird.inc.php');
2308         if(is_file('/usr/local/ispconfig/interface/lib/classes/form.inc.php')) unlink('/usr/local/ispconfig/interface/lib/classes/form.inc.php');
2309         
2310         
2311         
2312     }
7fe908 2313
33bcd0 2314     public function getinitcommand($servicename, $action, $init_script_directory = ''){
FT 2315         global $conf;
2316         // upstart
2317         if(is_executable('/sbin/initctl')){
2318             exec('/sbin/initctl version 2>/dev/null | /bin/grep -q upstart', $retval['output'], $retval['retval']);
2319             if(intval($retval['retval']) == 0) return 'service '.$servicename.' '.$action;
2320         }
bc04c3 2321         // systemd
TB 2322         if(is_executable('/bin/systemd') || is_executable('/usr/bin/systemctl')){
2323             return 'systemctl '.$action.' '.$servicename.'.service';
2324         }
33bcd0 2325         // sysvinit
FT 2326         if($init_script_directory == '') $init_script_directory = $conf['init_scripts'];
2327         if(substr($init_script_directory, -1) === '/') $init_script_directory = substr($init_script_directory, 0, -1);
2328         return $init_script_directory.'/'.$servicename.' '.$action;
2329     }
532ae5 2330
L 2331     /**
2332      * Helper function - get the path to a template file based on
2333      * the local part of the filename. Checks first for the existence
2334      * of a distribution specific file and if not found looks in the
2335      * base template folder. Optionally the behaviour can be changed
2336      * by setting the 2nd parameter which will fetch the contents
2337      * of the template file and return it instead of the path. The 3rd
2338      * parameter further extends this behaviour by filtering the contents
2339      * by inserting the ispconfig database credentials using the {} placeholders.
2340      *
2341      * @param string $tLocal local part of filename
2342      * @param bool $tRf
2343      * @param bool $tDBCred
2344      * @return string Relative path to the chosen template file
2345      */
2346     protected function get_template_file($tLocal, $tRf=false, $tDBCred=false) {
2347         global $conf, $dist;
2348
2349         $final_path = '';
7fe908 2350         $dist_template = $conf['ispconfig_install_dir'] . '/server/conf-custom/install/' . $tLocal . '.master';
MC 2351         if (file_exists($dist_template)) {
532ae5 2352             $final_path = $dist_template;
L 2353         } else {
7fe908 2354             $dist_template = 'dist/tpl/'.strtolower($dist['name'])."/$tLocal.master";
MC 2355             if (file_exists($dist_template)) {
2356                 $final_path = $dist_template;
2357             } else {
2358                 $final_path = "tpl/$tLocal.master";
2359             }
2360         }
532ae5 2361
L 2362         if (!$tRf) {
2363             return $final_path;
2364         } else {
2365             return (!$tDBCred) ? rf($final_path) : $this->insert_db_credentials(rf($final_path));
2366         }
2367     }
2368
2369     /**
2370      * Helper function - writes the contents to a config file
2371      * and performs a backup if the file exist. Additionally
2372      * if the file exists the new file will be given the
2373      * same rights and ownership as the original. Optionally the
2374      * rights and/or ownership can be overriden by appending umask,
2375      * user and group to the parameters. Providing only uid and gid
2376      * values will result in only a chown.
2377      *
2378      * @param $tConf
2379      * @param $tContents
2380      * @return bool
2381      */
2382     protected function write_config_file($tConf, $tContents) {
2383         // Backup config file before writing new contents and stat file
2384         if ( is_file($tConf) ) {
2385             $stat = exec('stat -c \'%a %U %G\' '.escapeshellarg($tConf), $output, $res);
2386             if ($res == 0) { // stat successfull
8cddcd 2387                 list($access, $user, $group) = explode(" ", $stat);
532ae5 2388             }
L 2389
2390             if ( copy($tConf, $tConf.'~') ) {
2391                 chmod($tConf.'~', 0400);
2392             }
2393         }
2394
2395         wf($tConf, $tContents); // write file
2396
2397         if (func_num_args() >= 4) // override rights and/or ownership
7fe908 2398             {
532ae5 2399             $args = func_get_args();
L 2400             $output = array_slice($args, 2);
2401
2402             switch (sizeof($output)) {
7fe908 2403             case 3:
MC 2404                 $umask = array_shift($output);
2405                 if (is_numeric($umask) && preg_match('/^0?[0-7]{3}$/', $umask)) {
2406                     $access = $umask;
2407                 }
2408             case 2:
2409                 if (is_user($output[0]) && is_group($output[1])) {
2410                     list($user, $group) = $output;
2411                 }
2412                 break;
532ae5 2413             }
L 2414         }
2415
2416         if (!empty($user) && !empty($group)) {
2417             chown($tConf, $user);
2418             chgrp($tConf, $group);
2419         }
2420
2421         if (!empty($access)) {
2422             exec("chmod $access $tConf");
2423         }
2424     }
2425
2426     /**
2427      * Helper function - filter the contents of a config
2428      * file by inserting the common ispconfig database
2429      * credentials.
2430      *
2431      * @param $tContents
2432      * @return string
2433      */
2434     protected function insert_db_credentials($tContents) {
2435         global $conf;
2436
2437         $tContents = str_replace('{mysql_server_ispconfig_user}', $conf["mysql"]["ispconfig_user"], $tContents);
2438         $tContents = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $tContents);
2439         $tContents = str_replace('{mysql_server_database}', $conf["mysql"]["database"], $tContents);
2440         $tContents = str_replace('{mysql_server_ip}', $conf["mysql"]["ip"], $tContents);
7fe908 2441         $tContents = str_replace('{mysql_server_host}', $conf['mysql']['host'], $tContents);
MC 2442         $tContents = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $tContents);
532ae5 2443
L 2444         return $tContents;
2445     }
7fe908 2446
532ae5 2447 }
L 2448
e514ae 2449 ?>