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