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