From 06a55ef91e280687e6a85912769dc35aeb84a151 Mon Sep 17 00:00:00 2001 From: Grigory Morozov Date: Mon, 26 Sep 2016 22:52:03 +0700 Subject: [PATCH 001/179] Prevent duplicates in ipsandports table --- install/froxlor.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index f30c943a..a91c7023 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -280,7 +280,8 @@ CREATE TABLE `panel_ipsandports` ( `default_vhostconf_domain` text, `ssl_cert_chainfile` varchar(255) NOT NULL, `docroot` varchar(255) NOT NULL default '', - PRIMARY KEY (`id`) + PRIMARY KEY (`id`), + UNIQUE KEY `ip_port` (`ip`,`port`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; From dc428b7de2b8aa25f46fed8ac08e833564cd4ba5 Mon Sep 17 00:00:00 2001 From: Grigory Morozov Date: Mon, 26 Sep 2016 23:23:11 +0700 Subject: [PATCH 002/179] Adding unique key to ipsandports on upgrade Please guide on checking the correct Froxlor version, not sure how it works --- install/updates/froxlor/0.9/update_0.9.inc.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 7da2b984..750d05b3 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3321,6 +3321,14 @@ if (isFroxlorVersion('0.9.35.1')) { updateToVersion('0.9.36'); } +if (isFroxlorVersion('0.9.37')) { + showUpdateStep("Updating from 0.9.37 to 0.9.38", false); + showUpdateStep("Adding unique key to ipsandports table"); + Database::query("ALTER TABLE `" . TABLE_PANEL_IPSANDPORTS . "` ADD UNIQUE KEY `ip_port` (`ip`,`port`)"); + lastStepStatus(0); + updateToVersion('0.9.38'); +} + if (isDatabaseVersion('201604270')) { showUpdateStep("Adding new dns related tables and settings"); From 3ff85e167c158720297c6f7f1a8611850d3ef958 Mon Sep 17 00:00:00 2001 From: Grigory Morozov Date: Tue, 27 Sep 2016 23:08:30 +0700 Subject: [PATCH 003/179] Update update_0.9.inc.php --- install/updates/froxlor/0.9/update_0.9.inc.php | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 750d05b3..cc2463b7 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3321,14 +3321,6 @@ if (isFroxlorVersion('0.9.35.1')) { updateToVersion('0.9.36'); } -if (isFroxlorVersion('0.9.37')) { - showUpdateStep("Updating from 0.9.37 to 0.9.38", false); - showUpdateStep("Adding unique key to ipsandports table"); - Database::query("ALTER TABLE `" . TABLE_PANEL_IPSANDPORTS . "` ADD UNIQUE KEY `ip_port` (`ip`,`port`)"); - lastStepStatus(0); - updateToVersion('0.9.38'); -} - if (isDatabaseVersion('201604270')) { showUpdateStep("Adding new dns related tables and settings"); @@ -3483,3 +3475,10 @@ if (isDatabaseVersion('201609120')) { updateToDbVersion('201609200'); } + +if (isDatabaseVersion('201609200')) { + showUpdateStep("Adding unique key to ipsandports table"); + Database::query("ALTER TABLE `" . TABLE_PANEL_IPSANDPORTS . "` ADD UNIQUE KEY `ip_port` (`ip`,`port`)"); + lastStepStatus(0); + updateToDbVersion('201609270'); +} From b0326c640c15470c495ee23312961d84ab175179 Mon Sep 17 00:00:00 2001 From: Dominic Schallert Date: Sun, 13 Nov 2016 14:41:39 +0100 Subject: [PATCH 004/179] Feature #1671 Checkbox to enable/disable PHP (vhost settings + fpm pool) for an entire vhost --- admin_domains.php | 23 ++++++++++++++++++- install/froxlor.sql | 1 + .../updates/froxlor/0.9/update_0.9.inc.php | 11 +++++++++ .../admin/domains/formfield.domains_add.php | 8 +++++++ .../admin/domains/formfield.domains_edit.php | 8 +++++++ 5 files changed, 50 insertions(+), 1 deletion(-) diff --git a/admin_domains.php b/admin_domains.php index 0f86f7b6..93fe910c 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -453,6 +453,7 @@ if ($page == 'domains' || $page == 'overview') { if ($userinfo['caneditphpsettings'] == '1' || $userinfo['change_serversettings'] == '1') { + $phpenabled = isset($POST_['phpenabled']) ? intval($_POST['phpenabled']) : 0; $openbasedir = isset($_POST['openbasedir']) ? intval($_POST['openbasedir']) : 0; if ((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) { @@ -493,7 +494,9 @@ if ($page == 'domains' || $page == 'overview') { } } else { + $phpenabled = '1'; $openbasedir = '1'; + if ((int) Settings::Get('phpfpm.enabled') == 1) { $phpsettingid = Settings::Get('phpfpm.defaultini'); } else { @@ -688,6 +691,10 @@ if ($page == 'domains' || $page == 'overview') { if (count($ipandports) == 0) { standard_error('noipportgiven'); } + + if($phpenabled != '1') { + $phpenabled = '0'; + } if ($openbasedir != '1') { $openbasedir = '0'; @@ -768,6 +775,7 @@ if ($page == 'domains' || $page == 'overview') { 'ipandport' => serialize($ipandports), 'ssl_redirect' => $ssl_redirect, 'ssl_ipandport' => serialize($ssl_ipandports), + 'phpenabled' => $phpenabled, 'openbasedir' => $openbasedir, 'phpsettingid' => $phpsettingid, 'mod_fcgid_starter' => $mod_fcgid_starter, @@ -816,6 +824,7 @@ if ($page == 'domains' || $page == 'overview') { 'email_only' => $email_only, 'subcanemaildomain' => $subcanemaildomain, 'caneditdomain' => $caneditdomain, + 'phpenabled' => $phpenabled, 'openbasedir' => $openbasedir, 'speciallogfile' => $speciallogfile, 'specialsettings' => $specialsettings, @@ -852,6 +861,7 @@ if ($page == 'domains' || $page == 'overview') { `email_only` = :email_only, `subcanemaildomain` = :subcanemaildomain, `caneditdomain` = :caneditdomain, + `phpenabled` = :phpenabled, `openbasedir` = :openbasedir, `speciallogfile` = :speciallogfile, `specialsettings` = :specialsettings, @@ -1326,6 +1336,7 @@ if ($page == 'domains' || $page == 'overview') { if ($userinfo['caneditphpsettings'] == '1' || $userinfo['change_serversettings'] == '1') { + $phpenabled = isset($_POST['phpenabled']) ? intval($_POST['phpenabled']) : 0; $openbasedir = isset($_POST['openbasedir']) ? intval($_POST['openbasedir']) : 0; if ((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) { @@ -1360,6 +1371,7 @@ if ($page == 'domains' || $page == 'overview') { $mod_fcgid_maxrequests = $result['mod_fcgid_maxrequests']; } } else { + $phpenabled = $result['phpenabled']; $openbasedir = $result['openbasedir']; $phpsettingid = $result['phpsettingid']; $mod_fcgid_starter = $result['mod_fcgid_starter']; @@ -1471,6 +1483,10 @@ if ($page == 'domains' || $page == 'overview') { if (! preg_match('/^https?\:\/\//', $documentroot)) { $documentroot = makeCorrectDir($documentroot); } + + if ($phpenabled != '1') { + $phpenabled = '0'; + } if ($openbasedir != '1') { $openbasedir = '0'; @@ -1580,6 +1596,7 @@ if ($page == 'domains' || $page == 'overview') { 'dkim' => $dkim, 'selectserveralias' => $serveraliasoption, 'ssl_redirect' => $ssl_redirect, + 'phpenabled' => $phpenabled, 'openbasedir' => $openbasedir, 'phpsettingid' => $phpsettingid, 'mod_fcgid_starter' => $mod_fcgid_starter, @@ -1615,7 +1632,7 @@ if ($page == 'domains' || $page == 'overview') { $wwwserveralias = ($serveraliasoption == '1') ? '1' : '0'; $iswildcarddomain = ($serveraliasoption == '0') ? '1' : '0'; - if ($documentroot != $result['documentroot'] || $ssl_redirect != $result['ssl_redirect'] || $wwwserveralias != $result['wwwserveralias'] || $iswildcarddomain != $result['iswildcarddomain'] || $openbasedir != $result['openbasedir'] || $phpsettingid != $result['phpsettingid'] || $mod_fcgid_starter != $result['mod_fcgid_starter'] || $mod_fcgid_maxrequests != $result['mod_fcgid_maxrequests'] || $specialsettings != $result['specialsettings'] || $aliasdomain != $result['aliasdomain'] || $issubof != $result['ismainbutsubto'] || $email_only != $result['email_only'] || ($speciallogfile != $result['speciallogfile'] && $speciallogverified == '1') || $letsencrypt != $result['letsencrypt'] || $hsts_maxage != $result['hsts'] || $hsts_sub != $result['hsts_sub'] || $hsts_preload != $result['hsts_preload']) { + if ($documentroot != $result['documentroot'] || $ssl_redirect != $result['ssl_redirect'] || $wwwserveralias != $result['wwwserveralias'] || $iswildcarddomain != $result['iswildcarddomain'] || $phpenabled != $result['phpenabled'] || $openbasedir != $result['openbasedir'] || $phpsettingid != $result['phpsettingid'] || $mod_fcgid_starter != $result['mod_fcgid_starter'] || $mod_fcgid_maxrequests != $result['mod_fcgid_maxrequests'] || $specialsettings != $result['specialsettings'] || $aliasdomain != $result['aliasdomain'] || $issubof != $result['ismainbutsubto'] || $email_only != $result['email_only'] || ($speciallogfile != $result['speciallogfile'] && $speciallogverified == '1') || $letsencrypt != $result['letsencrypt'] || $hsts_maxage != $result['hsts'] || $hsts_sub != $result['hsts_sub'] || $hsts_preload != $result['hsts_preload']) { inserttask('1'); } @@ -1756,6 +1773,7 @@ if ($page == 'domains' || $page == 'overview') { $update_data['zonefile'] = $zonefile; $update_data['wwwserveralias'] = $wwwserveralias; $update_data['iswildcarddomain'] = $iswildcarddomain; + $update_data['phpenabled'] = $phpenabled; $update_data['openbasedir'] = $openbasedir; $update_data['speciallogfile'] = $speciallogfile; $update_data['phpsettingid'] = $phpsettingid; @@ -1787,6 +1805,7 @@ if ($page == 'domains' || $page == 'overview') { `zonefile` = :zonefile, `wwwserveralias` = :wwwserveralias, `iswildcarddomain` = :iswildcarddomain, + `phpenabled` = :phpenabled, `openbasedir` = :openbasedir, `speciallogfile` = :speciallogfile, `phpsettingid` = :phpsettingid, @@ -1806,6 +1825,7 @@ if ($page == 'domains' || $page == 'overview') { $_update_data['customerid'] = $customerid; $_update_data['adminid'] = $adminid; + $_update_data['phpenabled'] = $phpenabled; $_update_data['openbasedir'] = $openbasedir; $_update_data['phpsettingid'] = $phpsettingid; $_update_data['mod_fcgid_starter'] = $mod_fcgid_starter; @@ -1824,6 +1844,7 @@ if ($page == 'domains' || $page == 'overview') { UPDATE `" . TABLE_PANEL_DOMAINS . "` SET `customerid` = :customerid, `adminid` = :adminid, + `phpenabled` = :phpenabled, `openbasedir` = :openbasedir, `phpsettingid` = :phpsettingid, `mod_fcgid_starter` = :mod_fcgid_starter, diff --git a/install/froxlor.sql b/install/froxlor.sql index e8ad16bb..c81dc912 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -237,6 +237,7 @@ CREATE TABLE `panel_domains` ( `dkim_pubkey` text, `wwwserveralias` tinyint(1) NOT NULL default '1', `parentdomainid` int(11) NOT NULL default '0', + `phpenabled` tinyint(1) NOT NULL default '0', `openbasedir` tinyint(1) NOT NULL default '0', `openbasedir_path` tinyint(1) NOT NULL default '0', `speciallogfile` tinyint(1) NOT NULL default '0', diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index c9968770..36f5aad1 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3513,3 +3513,14 @@ if (isFroxlorVersion('0.9.38-rc1')) { showUpdateStep("Updating from 0.9.38-rc1 to 0.9.38-rc2", false); updateToVersion('0.9.38-rc2'); } + +if (isFroxlorVersion('0.9.38-rc2')) { + + showUpdateStep("Updating from 0.9.38-rc2 to 0.9.38-rc3", false); + + showUpdateStep("Updating database table definition for panel_domains"); + Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `phpenabled` tinyint(1) NOT NULL default '1' AFTER `openbasedir`;"); + lastStepStatus(0); + + updateToVersion('0.9.38-rc3'); +} diff --git a/lib/formfields/admin/domains/formfield.domains_add.php b/lib/formfields/admin/domains/formfield.domains_add.php index 15ca70e4..bce5b886 100644 --- a/lib/formfields/admin/domains/formfield.domains_add.php +++ b/lib/formfields/admin/domains/formfield.domains_add.php @@ -202,6 +202,14 @@ return array( 'image' => 'icons/domain_add.png', 'visible' => (($userinfo['change_serversettings'] == '1' || $userinfo['caneditphpsettings'] == '1') ? true : false), 'fields' => array( + 'phpenabled' => array( + 'label' => $lng['admin']['phpenabled'], + 'type' => 'checkbox', + 'values' => array( + array ('label' => $lng['panel']['yes'], 'value' => '1') + ), + 'value' => array('1') + ), 'openbasedir' => array( 'label' => 'OpenBasedir', 'type' => 'checkbox', diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index 11b6c6bc..73e00497 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -225,6 +225,14 @@ return array( 'image' => 'icons/domain_edit.png', 'visible' => (($userinfo['change_serversettings'] == '1' || $userinfo['caneditphpsettings'] == '1') ? true : false), 'fields' => array( + 'phpenabled' => array( + 'label' => $lng['admin']['phpenabled'], + 'type' => 'checkbox', + 'values' => array( + array ('label' => $lng['panel']['yes'], 'value' => '1') + ), + 'value' => array('1') + ), 'openbasedir' => array( 'label' => 'OpenBasedir', 'type' => 'checkbox', From 1519db16373f487ccee3305bb6fb5adc5a4f1f0e Mon Sep 17 00:00:00 2001 From: Dominic Date: Sun, 13 Nov 2016 14:48:50 +0100 Subject: [PATCH 005/179] Update update_0.9.inc.php --- install/updates/froxlor/0.9/update_0.9.inc.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 36f5aad1..71e7441e 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3519,7 +3519,7 @@ if (isFroxlorVersion('0.9.38-rc2')) { showUpdateStep("Updating from 0.9.38-rc2 to 0.9.38-rc3", false); showUpdateStep("Updating database table definition for panel_domains"); - Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `phpenabled` tinyint(1) NOT NULL default '1' AFTER `openbasedir`;"); + Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `phpenabled` tinyint(1) NOT NULL default '1' AFTER `parentdomainid`;"); lastStepStatus(0); updateToVersion('0.9.38-rc3'); From e5053bad154b505e5cb6ca7f5dd34aa1163aeb31 Mon Sep 17 00:00:00 2001 From: Dominic Schallert Date: Sun, 13 Nov 2016 15:15:43 +0100 Subject: [PATCH 006/179] Introduced phpenabled_customer and phpenabled_vhost, updated cron scripts, updated dbversion --- install/froxlor.sql | 2 +- .../updates/froxlor/0.9/update_0.9.inc.php | 20 +++++++++---------- lib/classes/webserver/class.WebserverBase.php | 5 +++-- lib/version.inc.php | 2 +- .../jobs/cron_tasks.inc.http.10.apache.php | 2 +- .../cron_tasks.inc.http.15.apache_fcgid.php | 2 +- .../cron_tasks.inc.http.25.lighttpd_fcgid.php | 2 +- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 6 +++--- .../cron_tasks.inc.http.35.nginx_phpfpm.php | 2 +- 9 files changed, 21 insertions(+), 22 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index c81dc912..a8dc13c3 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -578,7 +578,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38-rc2'), - ('panel', 'db_version', '201610070'); + ('panel', 'db_version', '201611130'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 71e7441e..cce1ebfd 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3502,6 +3502,15 @@ if (isDatabaseVersion('201609240')) { updateToDbVersion('201610070'); } +if (isDatabaseVersion('201610070')) { + + showUpdateStep("Updating database table definition for panel_domains"); + Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `phpenabled` tinyint(1) NOT NULL default '1' AFTER `parentdomainid`;"); + lastStepStatus(0); + + updateToDbVersion('201611130'); +} + if (isFroxlorVersion('0.9.37')) { showUpdateStep("Updating from 0.9.37 to 0.9.38-rc1", false); @@ -3513,14 +3522,3 @@ if (isFroxlorVersion('0.9.38-rc1')) { showUpdateStep("Updating from 0.9.38-rc1 to 0.9.38-rc2", false); updateToVersion('0.9.38-rc2'); } - -if (isFroxlorVersion('0.9.38-rc2')) { - - showUpdateStep("Updating from 0.9.38-rc2 to 0.9.38-rc3", false); - - showUpdateStep("Updating database table definition for panel_domains"); - Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `phpenabled` tinyint(1) NOT NULL default '1' AFTER `parentdomainid`;"); - lastStepStatus(0); - - updateToVersion('0.9.38-rc3'); -} diff --git a/lib/classes/webserver/class.WebserverBase.php b/lib/classes/webserver/class.WebserverBase.php index d67b9868..b827f04c 100644 --- a/lib/classes/webserver/class.WebserverBase.php +++ b/lib/classes/webserver/class.WebserverBase.php @@ -31,8 +31,9 @@ class WebserverBase { $query = "SELECT `d`.*, `pd`.`domain` AS `parentdomain`, `c`.`loginname`, `d`.`phpsettingid`, `c`.`adminid`, `c`.`guid`, `c`.`email`, `c`.`documentroot` AS `customerroot`, `c`.`deactivated`, - `c`.`phpenabled` AS `phpenabled`, `d`.`mod_fcgid_starter`, - `d`.`mod_fcgid_maxrequests` + `c`.`phpenabled` AS `phpenabled_customer`, + `d`.`phpenabled` AS `phpenabled_vhost`, + `d`.`mod_fcgid_starter`,`d`.`mod_fcgid_maxrequests` FROM `".TABLE_PANEL_DOMAINS."` `d` LEFT JOIN `".TABLE_PANEL_CUSTOMERS."` `c` USING(`customerid`) diff --git a/lib/version.inc.php b/lib/version.inc.php index ef48a2b2..72c746d7 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38-rc2'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201610070'; +$dbversion = '201611130'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 156435a3..f597dcad 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -488,7 +488,7 @@ class apache extends HttpConfigBase { $php_options_text = ''; - if ($domain['phpenabled'] == '1') { + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { // This vHost has PHP enabled and we are using the regular mod_php if ($domain['openbasedir'] == '1') { diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index 6e569d8f..6c9bd2a2 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -23,7 +23,7 @@ class apache_fcgid extends apache { $php_options_text = ''; - if($domain['phpenabled'] == '1') + if($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig((int)$domain['phpsettingid']); diff --git a/scripts/jobs/cron_tasks.inc.http.25.lighttpd_fcgid.php b/scripts/jobs/cron_tasks.inc.http.25.lighttpd_fcgid.php index 9f2e4ad2..a53c4b24 100644 --- a/scripts/jobs/cron_tasks.inc.http.25.lighttpd_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.25.lighttpd_fcgid.php @@ -21,7 +21,7 @@ class lighttpd_fcgid extends lighttpd { $php_options_text = ''; - if($domain['phpenabled'] == '1') + if($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig((int)$domain['phpsettingid']); diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index b282b1e1..6d2fb617 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -838,7 +838,7 @@ class nginx extends HttpConfigBase protected function composePhpOptions($domain, $ssl_vhost = false) { $phpopts = ''; - if ($domain['phpenabled'] == '1') { + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { $phpopts = "\tlocation ~ \.php {\n"; $phpopts .= "\t\t" . 'try_files ' . $domain['nonexistinguri'] . ' @php;' . "\n"; $phpopts .= "\t" . '}' . "\n\n"; @@ -874,7 +874,7 @@ class nginx extends HttpConfigBase $webroot_text .= "\n\t" . 'location / {' . "\n"; - if ($domain['phpenabled'] == '1') { + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { $webroot_text .= "\t" . 'index index.php index.html index.htm;' . "\n"; $webroot_text .= "\t\t" . 'try_files $uri $uri/ @rewrites;' . "\n"; } else { @@ -887,7 +887,7 @@ class nginx extends HttpConfigBase } $webroot_text .= "\t" . '}' . "\n\n"; - if ($domain['phpenabled'] == '1') { + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { $webroot_text .= "\tlocation @rewrites {\n"; $webroot_text .= "\t\trewrite ^ /index.php last;\n"; $webroot_text .= "\t}\n\n"; diff --git a/scripts/jobs/cron_tasks.inc.http.35.nginx_phpfpm.php b/scripts/jobs/cron_tasks.inc.http.35.nginx_phpfpm.php index f47ccd82..4a94c51d 100644 --- a/scripts/jobs/cron_tasks.inc.http.35.nginx_phpfpm.php +++ b/scripts/jobs/cron_tasks.inc.http.35.nginx_phpfpm.php @@ -20,7 +20,7 @@ class nginx_phpfpm extends nginx protected function composePhpOptions($domain, $ssl_vhost = false) { $php_options_text = ''; - if ($domain['phpenabled'] == '1') { + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig((int)$domain['phpsettingid']); From d93cfff1729d7e0cd1756f0a2997d68dd3941d07 Mon Sep 17 00:00:00 2001 From: Dominic Schallert Date: Sun, 13 Nov 2016 15:18:07 +0100 Subject: [PATCH 007/179] updates always at the end of the file --- install/updates/froxlor/0.9/update_0.9.inc.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index cce1ebfd..7f2387ae 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3502,15 +3502,6 @@ if (isDatabaseVersion('201609240')) { updateToDbVersion('201610070'); } -if (isDatabaseVersion('201610070')) { - - showUpdateStep("Updating database table definition for panel_domains"); - Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `phpenabled` tinyint(1) NOT NULL default '1' AFTER `parentdomainid`;"); - lastStepStatus(0); - - updateToDbVersion('201611130'); -} - if (isFroxlorVersion('0.9.37')) { showUpdateStep("Updating from 0.9.37 to 0.9.38-rc1", false); @@ -3522,3 +3513,12 @@ if (isFroxlorVersion('0.9.38-rc1')) { showUpdateStep("Updating from 0.9.38-rc1 to 0.9.38-rc2", false); updateToVersion('0.9.38-rc2'); } + +if (isDatabaseVersion('201610070')) { + + showUpdateStep("Updating database table definition for panel_domains"); + Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `phpenabled` tinyint(1) NOT NULL default '1' AFTER `parentdomainid`;"); + lastStepStatus(0); + + updateToDbVersion('201611130'); +} From 30087548b0b7cbb0ca8e35cb304b9841a8dba50d Mon Sep 17 00:00:00 2001 From: Dominic Schallert Date: Sun, 13 Nov 2016 15:33:56 +0100 Subject: [PATCH 008/179] Fixed the checkbox value --- lib/formfields/admin/domains/formfield.domains_edit.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index 73e00497..d458b5d3 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -231,7 +231,7 @@ return array( 'values' => array( array ('label' => $lng['panel']['yes'], 'value' => '1') ), - 'value' => array('1') + 'value' => array($result['phpenabled']) ), 'openbasedir' => array( 'label' => 'OpenBasedir', From 2c00f982d8beb14a6e74a460f8fffabd409d5f4c Mon Sep 17 00:00:00 2001 From: Janos Muzsi Date: Thu, 24 Nov 2016 22:55:57 +0100 Subject: [PATCH 009/179] Change redirect host from main domain name to requested domain name --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 2 +- scripts/jobs/cron_tasks.inc.http.20.lighttpd.php | 14 ++++++++------ scripts/jobs/cron_tasks.inc.http.30.nginx.php | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index b6a9697a..16cf71e8 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -808,7 +808,7 @@ class apache extends HttpConfigBase $_sslport = ":" . $ssldestport['port']; } - $domain['documentroot'] = 'https://' . $domain['domain'] . $_sslport . '/'; + $domain['documentroot'] = 'https://%{HTTP_HOST}' . $_sslport . '/'; } if ($ssl_vhost === true && $domain['ssl'] == '1' && Settings::Get('system.use_ssl') == '1') { diff --git a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php index a1869a42..9ca21da1 100644 --- a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php +++ b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php @@ -424,7 +424,7 @@ class lighttpd extends HttpConfigBase $_sslport = ":" . $ssldestport['port']; } - $domain['documentroot'] = 'https://' . $domain['domain'] . $_sslport . '/'; + $domain['documentroot'] = 'https://%1' . $_sslport . '/'; } // avoid using any whitespaces @@ -435,11 +435,13 @@ class lighttpd extends HttpConfigBase // Get domain's redirect code $code = getDomainRedirectCode($domain['id'], '301'); - - $vhost_content .= ' url.redirect-code = ' . $code. "\n"; - $vhost_content .= ' url.redirect = (' . "\n"; - $vhost_content .= ' "^/(.*)$" => "' . $uri . '$1"' . "\n"; - $vhost_content .= ' )' . "\n"; + + $vhost_content .= ' $HTTP["host"] =~ "^(.*)$" {'. "\n"; + $vhost_content .= ' url.redirect-code = ' . $code. "\n"; + $vhost_content .= ' url.redirect = (' . "\n"; + $vhost_content .= ' "^/(.*)$" => "' . $uri . '$1"' . "\n"; + $vhost_content .= ' )' . "\n"; + $vhost_content .= ' }' . "\n"; } else { mkDirWithCorrectOwnership($domain['customerroot'], $domain['documentroot'], $domain['guid'], $domain['guid'], true, true); diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index a99f41bf..4d93ab23 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -447,7 +447,7 @@ class nginx extends HttpConfigBase $_sslport = ":" . $ssldestport['port']; } - $domain['documentroot'] = 'https://' . $domain['domain'] . $_sslport . '/'; + $domain['documentroot'] = 'https://$host' . $_sslport . '/'; } // avoid using any whitespaces From 18b45c749daea040b78ef0726ea4ea27584b1dab Mon Sep 17 00:00:00 2001 From: Michael Wyraz Date: Fri, 25 Nov 2016 09:54:47 +0100 Subject: [PATCH 010/179] Better handling for letsencrypt errors after failed registration or changed license --- .../updates/froxlor/0.9/update_0.9.inc.php | 26 ++++ lib/classes/ssl/class.lescript.php | 118 +++++++++++++++--- lib/version.inc.php | 2 +- scripts/jobs/cron_letsencrypt.php | 2 + 4 files changed, 133 insertions(+), 15 deletions(-) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 8fb02c7a..3fd04142 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3546,3 +3546,29 @@ if (isFroxlorVersion('0.9.38.2')) { showUpdateStep("Updating from 0.9.38.2 to 0.9.38.3", false); updateToVersion('0.9.38.3'); } + +if (isDatabaseVersion('201611180')) { + + showUpdateStep("Adding field to reflect let's-encrypt registration status"); + Database::query("ALTER TABLE `".TABLE_PANEL_CUSTOMERS."` add `leregistered` TINYINT(1) NOT NULL DEFAULT 0;"); + lastStepStatus(0); + + updateToDbVersion('201611240'); +} + +if (isDatabaseVersion('201611240')) { + + showUpdateStep("Adding new setting to reflect let's-encrypt registration status"); + $stmt = Database::prepare(" + INSERT INTO `" . TABLE_PANEL_SETTINGS . "` SET + `settinggroup` = 'system', + `varname` = :varname, + `value` = :value"); + Database::pexecute($stmt, array( + 'varname' => 'leregistered', + 'value' => '0' + )); + lastStepStatus(0); + + updateToDbVersion('201611241'); +} diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index dc8ec83b..1d3aa5bb 100644 --- a/lib/classes/ssl/class.lescript.php +++ b/lib/classes/ssl/class.lescript.php @@ -38,6 +38,12 @@ class lescript private $accountKey; + private $customerid; + + private $isFroxlorVhost; + + private $isLeProduction; + private $version; public function __construct($logger, $version = '1') @@ -57,44 +63,71 @@ class lescript { // Let's see if we have the private accountkey $this->accountKey = $certrow['leprivatekey']; - if (! $this->accountKey || $this->accountKey == 'unset' || Settings::Get('system.letsencryptca') != 'production') { + $this->customerId = $certrow['customerid']; + $this->isFroxlorVhost = $isFroxlorVhost; + $this->isLeProduction = (Settings::Get('system.letsencryptca') == 'production'); + + $leregistered=$certrow['leregistered']; + + if (! $this->accountKey || $this->accountKey == 'unset' || !$this->isLeProduction) { // generate and save new private key for account // --------------------------------------------- - $this->log('Starting new account registration'); + $this->log('Creating new account key'); $keys = $this->generateKey(); // Only store the accountkey in production, in staging always generate a new key - if (Settings::Get('system.letsencryptca') == 'production') { + if ($this->isLeProduction) { if ($isFroxlorVhost) { Settings::Set('system.lepublickey', $keys['public']); Settings::Set('system.leprivatekey', $keys['private']); + Settings::Set('system.leregistered', 0); // key is not registered } else { - $upd_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `lepublickey` = :public, `leprivatekey` = :private " . "WHERE `customerid` = :customerid;"); + $upd_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `lepublickey` = :public, `leprivatekey` = :private, `leregistered` = :registered " . "WHERE `customerid` = :customerid;"); Database::pexecute($upd_stmt, array( 'public' => $keys['public'], 'private' => $keys['private'], - 'customerid' => $certrow['customerid'] + 'registered' => 0, + 'customerid' => $this->customerId )); } } + $leregistered=0; $this->accountKey = $keys['private']; + } else { + $this->log('Using existing account key'); + } + if ($leregistered==0) { // Account not registered + + $this->log('Starting new account registration'); $response = $this->postNewReg(); - if ($this->client->getLastCode() != 201) { + if ($this->client->getLastCode() == 409) { + $this->log('The key was already registered. Using existing account.'); + } else if ($this->client->getLastCode() == 201) { + $this->log('New account registered.'); + } else { throw new \RuntimeException("Account not initialized, probably due to rate limiting. Whole response: " . json_encode($response)); } + $accountUrl=$this->client->getLastLocation(); + + $this->log('Accepting lets encrypt Terms of Service'); + $this->license = $this->client->getAgreementURL(); - // Terms of Servce are optional according to ACME specs; if no ToS are presented, no need to update registration + // Terms of Service are optional according to ACME specs; if no ToS are presented, no need to update registration if (!empty($this->license)) { - $this->postRegAgreement(parse_url($this->client->getLastLocation(), PHP_URL_PATH)); + $response = $this->postRegAgreement(parse_url($accountUrl, PHP_URL_PATH)); + if ($this->client->getLastCode() != 202) { + throw new \RuntimeException("Terms of Service not accepted. Whole response: " . json_encode($response)); + } } - $this->log('New account certificate registered'); - } else { - $this->log('Account already registered. Continuing.'); + $leregistered=1; + $this->setLeRegisteredState($leregistered); // Account registered + $this->log('Lets encrypt Terms of Service accepted'); } + } /** @@ -136,11 +169,17 @@ class lescript ) )); + if ($this->client->getLastCode() == 403) { + $this->log("Got status 403 - setting LE status to unregistered."); + $this->setLeRegisteredState(0); + throw new RuntimeException("Got 'unauthorized' response - we need to re-register at next run. Whole response: " . json_encode($response)); + } + // if response is not an array but a string, it's most likely a server-error, e.g. // ErrorAn error occurred while processing your request. //

Reference #179.d8be1402.1458059103.3613c4db if (! is_array($response)) { - throw new RuntimeException("Invalid response from LE for domain $domain. Whole response: " . $response); + throw new RuntimeException("Invalid response from LE for domain $domain. Whole response: " . json_encode($response)); } if (! array_key_exists('challenges', $response)) { @@ -309,6 +348,21 @@ class lescript ); } + private function setLeRegisteredState($state) + { + if ($this->isLeProduction) { + if ($this->isFroxlorVhost) { + Settings::Set('system.leregistered', $state); + } else { + $upd_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `leregistered` = :registered " . "WHERE `customerid` = :customerid;"); + Database::pexecute($upd_stmt, array( + 'registered' => $state, + 'customerid' => $this->customerId + )); + } + } + } + private function parsePemFromBody($body) { $pem = chunk_split(base64_encode($body), 64, "\n"); @@ -537,10 +591,46 @@ class Client return $matches[1]; } + public function getAgreementURLFromLastResponse() + { + if (preg_match_all('~Link: <(.+)>;rel="terms-of-service"~', $this->lastHeader, $matches)) { + return $matches[1][0]; + } + return ""; + } + public function getAgreementURLFromDirectory() + { + // FIXME: Current license should be found in /directory but LE does not implement this yet + // $this->curl('GET', '/directory'); + return ""; + } + public function getAgreementURLFromTermsUrl() + { + $this->curl('GET', '/terms'); + if (preg_match_all('~Location: (.+)~', $this->lastHeader, $matches)) { + return trim($matches[1][0]); + } + return ""; + } + public function getAgreementURL() { - preg_match_all('~Link: <(.+)>;rel="terms-of-service"~', $this->lastHeader, $matches); - return $matches[1][0]; + // 1. check the header of the last response + $license=$this->getAgreementURLFromLastResponse(); + if (!empty($license)) return $license; + + // 2. query directory for license + $license=$this->getAgreementURLFromDirectory(); + if (!empty($license)) return $license; + + // 3. query /terms endpoint (not ACME standard but implemented by let's enrypt) + $license=$this->getAgreementURLFromTermsUrl(); + if (!empty($license)) return $license; + + // Fallback: use latest known license. This is only valid for let's encrypt and should be removed as soon as there is an official + // ACME-endpoint to get the current ToS + return "xxxhttps://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf]"; + // return ""; } } diff --git a/lib/version.inc.php b/lib/version.inc.php index 915532b7..056ce6e4 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.3'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201611180'; +$dbversion = '201611241'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/scripts/jobs/cron_letsencrypt.php b/scripts/jobs/cron_letsencrypt.php index 2101fcca..126d7dcd 100644 --- a/scripts/jobs/cron_letsencrypt.php +++ b/scripts/jobs/cron_letsencrypt.php @@ -43,6 +43,7 @@ $certificates_stmt = Database::query(" dom.`ssl_redirect`, cust.`leprivatekey`, cust.`lepublickey`, + cust.`leregistered`, cust.`customerid`, cust.`loginname` FROM @@ -103,6 +104,7 @@ if (Settings::Get('system.le_froxlor_enabled') == '1') { 'documentroot' => FROXLOR_INSTALL_DIR, 'leprivatekey' => Settings::Get('system.leprivatekey'), 'lepublickey' => Settings::Get('system.lepublickey'), + 'leregistered' => Settings::Get('system.leregistered'), 'ssl_redirect' => Settings::Get('system.le_froxlor_redirect'), 'expirationdate' => null, 'ssl_cert_file' => null, From 559bd6d892dff34777d60164ac7e392403c2174e Mon Sep 17 00:00:00 2001 From: Michael Wyraz Date: Fri, 25 Nov 2016 10:52:50 +0100 Subject: [PATCH 011/179] Better db update --- .../updates/froxlor/0.9/update_0.9.inc.php | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 3fd04142..d6288caf 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3549,25 +3549,12 @@ if (isFroxlorVersion('0.9.38.2')) { if (isDatabaseVersion('201611180')) { - showUpdateStep("Adding field to reflect let's-encrypt registration status"); + showUpdateStep("Adding field for let's-encrypt registration status"); Database::query("ALTER TABLE `".TABLE_PANEL_CUSTOMERS."` add `leregistered` TINYINT(1) NOT NULL DEFAULT 0;"); lastStepStatus(0); - updateToDbVersion('201611240'); -} - -if (isDatabaseVersion('201611240')) { - - showUpdateStep("Adding new setting to reflect let's-encrypt registration status"); - $stmt = Database::prepare(" - INSERT INTO `" . TABLE_PANEL_SETTINGS . "` SET - `settinggroup` = 'system', - `varname` = :varname, - `value` = :value"); - Database::pexecute($stmt, array( - 'varname' => 'leregistered', - 'value' => '0' - )); + showUpdateStep("Adding system setting for let's-encrypt registration status"); + Settings::AddNew('system.leregistered', '0'); lastStepStatus(0); updateToDbVersion('201611241'); From 7b6bbcec48a40602fbaf9e248420a9deab4a7d93 Mon Sep 17 00:00:00 2001 From: micw Date: Sun, 27 Nov 2016 12:45:06 +0100 Subject: [PATCH 012/179] Fixed default LE license URL (removed testing stuff) --- lib/classes/ssl/class.lescript.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index 1d3aa5bb..f0d7c11f 100644 --- a/lib/classes/ssl/class.lescript.php +++ b/lib/classes/ssl/class.lescript.php @@ -629,7 +629,7 @@ class Client // Fallback: use latest known license. This is only valid for let's encrypt and should be removed as soon as there is an official // ACME-endpoint to get the current ToS - return "xxxhttps://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf]"; + return "https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"; // return ""; } From 1b18ec45be83088085f0834aa29f8d7f1c4a712b Mon Sep 17 00:00:00 2001 From: Janos Muzsi Date: Sun, 27 Nov 2016 23:18:23 +0100 Subject: [PATCH 013/179] correcting lighttpd settings --- scripts/jobs/cron_tasks.inc.http.20.lighttpd.php | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php index 9ca21da1..5b7fc780 100644 --- a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php +++ b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php @@ -435,13 +435,11 @@ class lighttpd extends HttpConfigBase // Get domain's redirect code $code = getDomainRedirectCode($domain['id'], '301'); - - $vhost_content .= ' $HTTP["host"] =~ "^(.*)$" {'. "\n"; - $vhost_content .= ' url.redirect-code = ' . $code. "\n"; - $vhost_content .= ' url.redirect = (' . "\n"; - $vhost_content .= ' "^/(.*)$" => "' . $uri . '$1"' . "\n"; - $vhost_content .= ' )' . "\n"; - $vhost_content .= ' }' . "\n"; + + $vhost_content .= ' url.redirect-code = ' . $code. "\n"; + $vhost_content .= ' url.redirect = (' . "\n"; + $vhost_content .= ' "^/(.*)$" => "' . $uri . '$1"' . "\n"; + $vhost_content .= ' )' . "\n"; } else { mkDirWithCorrectOwnership($domain['customerroot'], $domain['documentroot'], $domain['guid'], $domain['guid'], true, true); From 225539d2e7cf61f6e7c0440c424c9d6bb201ae30 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 29 Nov 2016 09:34:33 +0100 Subject: [PATCH 014/179] show ssl-related settings only if customer has ssl-ip assigned (not yet checked per domain); fix hsts-includeSubdomain setting for fresh installations Signed-off-by: Michael Kaufmann (d00p) --- customer_domains.php | 16 +++++++++++++--- install/froxlor.sql | 2 +- .../customer/domains/formfield.domains_add.php | 8 ++------ .../customer/domains/formfield.domains_edit.php | 8 ++------ 4 files changed, 18 insertions(+), 16 deletions(-) diff --git a/customer_domains.php b/customer_domains.php index 06471cb8..cc2a637e 100644 --- a/customer_domains.php +++ b/customer_domains.php @@ -517,7 +517,12 @@ if ($page == 'overview') { // check if we at least have one ssl-ip/port, #1179 $ssl_ipsandports = ''; - $ssl_ip_stmt = Database::prepare("SELECT COUNT(*) as countSSL FROM `panel_ipsandports` WHERE `ssl`='1'"); + $ssl_ip_stmt = Database::prepare(" + SELECT COUNT(*) as countSSL + FROM `".TABLE_PANEL_IPSANDPORTS."` pip + LEFT JOIN `".TABLE_DOMAINTOIP."` dti ON dti.id_ipandports = pip.id + WHERE pip.`ssl`='1' + "); Database::pexecute($ssl_ip_stmt); $resultX = $ssl_ip_stmt->fetch(PDO::FETCH_ASSOC); if (isset($resultX['countSSL']) && (int)$resultX['countSSL'] > 0) { @@ -797,8 +802,13 @@ if ($page == 'overview') { // check if we at least have one ssl-ip/port, #1179 $ssl_ipsandports = ''; - $ssl_ip_stmt = Database::prepare("SELECT COUNT(*) as countSSL FROM `panel_ipsandports` WHERE `ssl`='1'"); - Database::pexecute($ssl_ip_stmt); + $ssl_ip_stmt = Database::prepare(" + SELECT COUNT(*) as countSSL + FROM `".TABLE_PANEL_IPSANDPORTS."` pip + LEFT JOIN `".TABLE_DOMAINTOIP."` dti ON dti.id_ipandports = pip.id + WHERE `dti`.`id_domain` = :id_domain AND pip.`ssl`='1' + "); + Database::pexecute($ssl_ip_stmt, array("id_domain" => $result['id'])); $resultX = $ssl_ip_stmt->fetch(PDO::FETCH_ASSOC); if (isset($resultX['countSSL']) && (int)$resultX['countSSL'] > 0) { $ssl_ipsandports = 'notempty'; diff --git a/install/froxlor.sql b/install/froxlor.sql index b1962ab5..947e6b3a 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -544,7 +544,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('system', 'mail_smtp_user', ''), ('system', 'mail_smtp_passwd', ''), ('system', 'hsts_maxage', '0'), - ('system', 'hsts_sub', '0'), + ('system', 'hsts_incsub', '0'), ('system', 'hsts_preload', '0'), ('panel', 'decimal_places', '4'), ('panel', 'adminmail', 'admin@SERVERNAME'), diff --git a/lib/formfields/customer/domains/formfield.domains_add.php b/lib/formfields/customer/domains/formfield.domains_add.php index 1371e579..238adfff 100644 --- a/lib/formfields/customer/domains/formfield.domains_add.php +++ b/lib/formfields/customer/domains/formfield.domains_add.php @@ -76,10 +76,9 @@ return array( 'section_bssl' => array( 'title' => $lng['admin']['webserversettings_ssl'], 'image' => 'icons/domain_add.png', - 'visible' => Settings::Get('system.use_ssl') == '1' ? true : false, + 'visible' => Settings::Get('system.use_ssl') == '1' ? ($ssl_ipsandports != '' ? true : false) : false, 'fields' => array( 'ssl_redirect' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false), 'label' => $lng['domains']['ssl_redirect']['title'], 'desc' => $lng['domains']['ssl_redirect']['description'], 'type' => 'checkbox', @@ -89,7 +88,7 @@ return array( 'value' => array() ), 'letsencrypt' => array( - 'visible' => (Settings::Get('system.leenabled') == '1' ? ($ssl_ipsandports != '' ? true : false) : false), + 'visible' => (Settings::Get('system.leenabled') == '1' ? true : false), 'label' => $lng['customer']['letsencrypt']['title'], 'desc' => $lng['customer']['letsencrypt']['description'], 'type' => 'checkbox', @@ -99,7 +98,6 @@ return array( 'value' => array() ), 'hsts_maxage' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false), 'label' => $lng['admin']['domain_hsts_maxage']['title'], 'desc' => $lng['admin']['domain_hsts_maxage']['description'], 'type' => 'int', @@ -108,7 +106,6 @@ return array( 'value' => 0 ), 'hsts_sub' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false), 'label' => $lng['admin']['domain_hsts_incsub']['title'], 'desc' => $lng['admin']['domain_hsts_incsub']['description'], 'type' => 'checkbox', @@ -118,7 +115,6 @@ return array( 'value' => array() ), 'hsts_preload' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false), 'label' => $lng['admin']['domain_hsts_preload']['title'], 'desc' => $lng['admin']['domain_hsts_preload']['description'], 'type' => 'checkbox', diff --git a/lib/formfields/customer/domains/formfield.domains_edit.php b/lib/formfields/customer/domains/formfield.domains_edit.php index 94bab096..6ac6d186 100644 --- a/lib/formfields/customer/domains/formfield.domains_edit.php +++ b/lib/formfields/customer/domains/formfield.domains_edit.php @@ -87,10 +87,9 @@ return array( 'section_bssl' => array( 'title' => $lng['admin']['webserversettings_ssl'], 'image' => 'icons/domain_edit.png', - 'visible' => Settings::Get('system.use_ssl') == '1' ? true : false, + 'visible' => Settings::Get('system.use_ssl') == '1' ? ($ssl_ipsandports != '' ? (domainHasSslIpPort($result['id']) ? true : false) : false) : false, 'fields' => array( 'ssl_redirect' => array( - 'visible' => (Settings::Get('system.use_ssl') == '1' ? ($ssl_ipsandports != '' ? (domainHasSslIpPort($result['id']) ? true : false) : false) : false), 'label' => $lng['domains']['ssl_redirect']['title'], 'desc' => $lng['domains']['ssl_redirect']['description'] . ($result['temporary_ssl_redirect'] > 1 ? $lng['domains']['ssl_redirect_temporarilydisabled'] : ''), 'type' => 'checkbox', @@ -100,7 +99,7 @@ return array( 'value' => array($result['ssl_redirect']) ), 'letsencrypt' => array( - 'visible' => (Settings::Get('system.use_ssl') == '1' ? (Settings::Get('system.leenabled') == '1' ? ($ssl_ipsandports != '' ? (domainHasSslIpPort($result['id']) ? true : false) : false) : false) : false), + 'visible' => Settings::Get('system.leenabled') == '1' ? true : false, 'label' => $lng['customer']['letsencrypt']['title'], 'desc' => $lng['customer']['letsencrypt']['description'], 'type' => 'checkbox', @@ -110,7 +109,6 @@ return array( 'value' => array($result['letsencrypt']) ), 'hsts_maxage' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false), 'label' => $lng['admin']['domain_hsts_maxage']['title'], 'desc' => $lng['admin']['domain_hsts_maxage']['description'], 'type' => 'int', @@ -119,7 +117,6 @@ return array( 'value' => $result['hsts'] ), 'hsts_sub' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false), 'label' => $lng['admin']['domain_hsts_incsub']['title'], 'desc' => $lng['admin']['domain_hsts_incsub']['description'], 'type' => 'checkbox', @@ -129,7 +126,6 @@ return array( 'value' => array($result['hsts_sub']) ), 'hsts_preload' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false), 'label' => $lng['admin']['domain_hsts_preload']['title'], 'desc' => $lng['admin']['domain_hsts_preload']['description'], 'type' => 'checkbox', From 001786dd9719cd117225c4aebc1bb95c1e9bafb7 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 9 Dec 2016 13:33:57 +0100 Subject: [PATCH 015/179] fix incorrect User-Agent header in let's encrypt class, fixes #1683 Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/ssl/class.lescript.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index dc8ec83b..82f3056f 100644 --- a/lib/classes/ssl/class.lescript.php +++ b/lib/classes/ssl/class.lescript.php @@ -188,7 +188,7 @@ class lescript $this->log("Token for $domain saved at $tokenPath and should be available at $uri"); // simple self check - $selfcheckContextOptions = array('http' => array('header' => "User Agent: Froxlor/".$this->version)); + $selfcheckContextOptions = array('http' => array('header' => "User-Agent: Froxlor/".$this->version)); $selfcheckContext = stream_context_create($selfcheckContextOptions); if ($payload !== trim(@file_get_contents($uri, false, $selfcheckContext))) { $errmsg = json_encode(error_get_last()); From 18514f018069c1a5f9b3b812ff775a82fcf702e6 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 10 Dec 2016 21:43:28 +0100 Subject: [PATCH 016/179] fix undefined array when processing specialsettings, fixes #1684 Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 9 +++++++++ .../jobs/cron_tasks.inc.http.20.lighttpd.php | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index b6a9697a..1f45d934 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -344,6 +344,15 @@ class apache extends HttpConfigBase ); } } // end of ssl-redirect check + else + { + // fallback of froxlor domain-data for processSpecialConfigTemplate() + $domain = array( + 'domain' => Settings::Get('system.hostname'), + 'loginname' => 'froxlor.panel', + 'documentroot' => $mypath + ); + } /** * dirprotection, see #72 diff --git a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php index a1869a42..aa06b527 100644 --- a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php +++ b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php @@ -162,7 +162,25 @@ class lighttpd extends HttpConfigBase $this->lighttpd_data[$vhost_filename] .= "\t" . ')' . "\n"; $this->lighttpd_data[$vhost_filename] .= "\t" . ')' . "\n"; $this->lighttpd_data[$vhost_filename] .= ' )' . "\n"; + } else { + $domain = array( + 'id' => 'none', + 'domain' => Settings::Get('system.hostname'), + 'adminid' => 1, /* first admin-user (superadmin) */ + 'guid' => Settings::Get('system.httpuser'), + 'openbasedir' => 0, + 'email' => Settings::Get('panel.adminmail'), + 'loginname' => 'froxlor.panel', + 'documentroot' => $mypath + ); } + } else { + // fallback of froxlor domain-data for processSpecialConfigTemplate() + $domain = array( + 'domain' => Settings::Get('system.hostname'), + 'loginname' => 'froxlor.panel', + 'documentroot' => $mypath + ); } if ($row_ipsandports['specialsettings'] != '') { From 3a8996aee2125e85872aff2e5b29381dd94258db Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 11 Dec 2016 08:29:54 +0100 Subject: [PATCH 017/179] add missing fields that are only added via update Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index 8856efbf..ea9da93f 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -195,8 +195,9 @@ CREATE TABLE `panel_customers` ( `theme` varchar(255) NOT NULL default 'Sparkle', `custom_notes` text, `custom_notes_show` tinyint(1) NOT NULL default '0', - `lepublickey` mediumtext DEFAULT NULL, - `leprivatekey` mediumtext DEFAULT NULL, + `lepublickey` mediumtext default NULL, + `leprivatekey` mediumtext default NULL, + `leregistered` tinyint(1) NOT NULL default '0' PRIMARY KEY (`customerid`), UNIQUE KEY `loginname` (`loginname`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; @@ -547,6 +548,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('system', 'hsts_maxage', '0'), ('system', 'hsts_incsub', '0'), ('system', 'hsts_preload', '0'), + ('system', 'leregistered', '0'), ('panel', 'decimal_places', '4'), ('panel', 'adminmail', 'admin@SERVERNAME'), ('panel', 'phpmyadmin_url', ''), From 9907775c0d6e62babbe762a641185bfe600191bb Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 11 Dec 2016 09:43:05 +0100 Subject: [PATCH 018/179] fix installation sql Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index 94a3c5ce..5c75be4f 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -197,7 +197,7 @@ CREATE TABLE `panel_customers` ( `custom_notes_show` tinyint(1) NOT NULL default '0', `lepublickey` mediumtext default NULL, `leprivatekey` mediumtext default NULL, - `leregistered` tinyint(1) NOT NULL default '0' + `leregistered` tinyint(1) NOT NULL default '0', PRIMARY KEY (`customerid`), UNIQUE KEY `loginname` (`loginname`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; From 5ed0c3f2f3b2e231d7cbdfa3a64d4947f601cafb Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 11 Dec 2016 09:50:22 +0100 Subject: [PATCH 019/179] code-formatting and put phpenabled flag on a better position Signed-off-by: Michael Kaufmann (d00p) --- .../admin/domains/formfield.domains_add.php | 113 +++++++++---- .../admin/domains/formfield.domains_edit.php | 150 +++++++++++++----- 2 files changed, 187 insertions(+), 76 deletions(-) diff --git a/lib/formfields/admin/domains/formfield.domains_add.php b/lib/formfields/admin/domains/formfield.domains_add.php index 97f79ee7..8482123e 100644 --- a/lib/formfields/admin/domains/formfield.domains_add.php +++ b/lib/formfields/admin/domains/formfield.domains_add.php @@ -14,7 +14,6 @@ * @package Formfields * */ - return array( 'domain_add' => array( 'title' => $lng['admin']['domain_add'], @@ -27,20 +26,20 @@ return array( 'domain' => array( 'label' => 'Domain', 'type' => 'text', - 'mandatory' => true, + 'mandatory' => true ), 'customerid' => array( 'label' => $lng['admin']['customer'], 'type' => 'select', 'select_var' => $customers, - 'mandatory' => true, + 'mandatory' => true ), 'adminid' => array( 'visible' => ($userinfo['customers_see_all'] == '1' ? true : false), 'label' => $lng['admin']['admin'], 'type' => 'select', 'select_var' => $admins, - 'mandatory' => true, + 'mandatory' => true ), 'alias' => array( 'label' => $lng['domains']['aliasdomain'], @@ -58,9 +57,14 @@ return array( 'desc' => $lng['admin']['domain_editable']['desc'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array('1') + 'value' => array( + '1' + ) ), 'add_date' => array( 'label' => $lng['domains']['add_date'], @@ -112,7 +116,10 @@ return array( 'desc' => $lng['admin']['speciallogfile']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), 'value' => array() ), @@ -146,7 +153,10 @@ return array( 'desc' => $lng['domains']['ssl_redirect']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), 'value' => array() ), @@ -156,7 +166,10 @@ return array( 'desc' => $lng['admin']['letsencrypt']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), 'value' => array() ), @@ -181,7 +194,10 @@ return array( 'desc' => $lng['admin']['domain_hsts_incsub']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), 'value' => array() ), @@ -191,46 +207,59 @@ return array( 'desc' => $lng['admin']['domain_hsts_preload']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), 'value' => array() - ), - ), + ) + ) ), 'section_c' => array( 'title' => $lng['admin']['phpserversettings'], 'image' => 'icons/domain_add.png', 'visible' => (($userinfo['change_serversettings'] == '1' || $userinfo['caneditphpsettings'] == '1') ? true : false), 'fields' => array( - 'phpenabled' => array( - 'label' => $lng['admin']['phpenabled'], - 'type' => 'checkbox', - 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), - 'value' => array('1') - ), 'openbasedir' => array( 'label' => 'OpenBasedir', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array('1') + 'value' => array( + '1' + ) + ), + 'phpenabled' => array( + 'label' => $lng['admin']['phpenabled'], + 'type' => 'checkbox', + 'values' => array( + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + '1' + ) ), 'phpsettingid' => array( - 'visible' => (((int)Settings::Get('system.mod_fcgid') == 1 || (int)Settings::Get('phpfpm.enabled') == 1) ? true : false), + 'visible' => (((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) ? true : false), 'label' => $lng['admin']['phpsettings']['title'], 'type' => 'select', 'select_var' => $phpconfigs ), 'mod_fcgid_starter' => array( - 'visible' => ((int)Settings::Get('system.mod_fcgid') == 1 ? true : false), + 'visible' => ((int) Settings::Get('system.mod_fcgid') == 1 ? true : false), 'label' => $lng['admin']['mod_fcgid_starter']['title'], 'type' => 'text' ), 'mod_fcgid_maxrequests' => array( - 'visible' => ((int)Settings::Get('system.mod_fcgid') == 1 ? true : false), + 'visible' => ((int) Settings::Get('system.mod_fcgid') == 1 ? true : false), 'label' => $lng['admin']['mod_fcgid_maxrequests']['title'], 'type' => 'text' ) @@ -245,9 +274,14 @@ return array( 'label' => 'Nameserver', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array('1') + 'value' => array( + '1' + ) ), 'zonefile' => array( 'label' => 'Zonefile', @@ -264,15 +298,23 @@ return array( 'label' => $lng['admin']['emaildomain'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array('1') + 'value' => array( + '1' + ) ), 'email_only' => array( 'label' => $lng['admin']['email_only'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), 'value' => array() ), @@ -286,9 +328,14 @@ return array( 'label' => 'DomainKeys', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array('1') + 'value' => array( + '1' + ) ) ) ) diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index f3a8ab01..22a293cc 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -14,7 +14,6 @@ * @package Formfields * */ - return array( 'domain_edit' => array( 'title' => $lng['admin']['domain_edit'], @@ -28,14 +27,14 @@ return array( 'label' => 'Domain', 'type' => 'label', 'value' => $result['domain'], - 'mandatory' => true, + 'mandatory' => true ), 'customerid' => array( 'label' => $lng['admin']['customer'], 'type' => (Settings::Get('panel.allow_domain_change_customer') == '1' ? 'select' : 'label'), 'select_var' => (isset($customers) ? $customers : null), 'value' => (isset($result['customername']) ? $result['customername'] : null), - 'mandatory' => true, + 'mandatory' => true ), 'adminid' => array( 'visible' => ($userinfo['customers_see_all'] == '1' ? true : false), @@ -43,7 +42,7 @@ return array( 'type' => (Settings::Get('panel.allow_domain_change_admin') == '1' ? 'select' : 'label'), 'select_var' => (isset($admins) ? $admins : null), 'value' => (isset($result['adminname']) ? $result['adminname'] : null), - 'mandatory' => true, + 'mandatory' => true ), 'alias' => array( 'visible' => ($alias_check == '0' ? true : false), @@ -60,16 +59,21 @@ return array( 'associated_info' => array( 'label' => $lng['domains']['associated_with_domain'], 'type' => 'label', - 'value' => $subdomains.' '.$lng['customer']['subdomains'].', '.$alias_check.' '.$lng['domains']['aliasdomains'].', '.$emails.' '.$lng['customer']['emails'].', '.$email_accounts.' '.$lng['customer']['accounts'].', '.$email_forwarders.' '.$lng['customer']['forwarders'] + 'value' => $subdomains . ' ' . $lng['customer']['subdomains'] . ', ' . $alias_check . ' ' . $lng['domains']['aliasdomains'] . ', ' . $emails . ' ' . $lng['customer']['emails'] . ', ' . $email_accounts . ' ' . $lng['customer']['accounts'] . ', ' . $email_forwarders . ' ' . $lng['customer']['forwarders'] ), 'caneditdomain' => array( 'label' => $lng['admin']['domain_editable']['title'], 'desc' => $lng['admin']['domain_editable']['desc'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['caneditdomain']) + 'value' => array( + $result['caneditdomain'] + ) ), 'add_date' => array( 'label' => $lng['domains']['add_date'], @@ -124,9 +128,14 @@ return array( 'desc' => $lng['admin']['speciallogfile']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['speciallogfile']) + 'value' => array( + $result['speciallogfile'] + ) ), 'specialsettings' => array( 'visible' => ($userinfo['change_serversettings'] == '1' ? true : false), @@ -144,9 +153,14 @@ return array( 'desc' => $lng['serversettings']['specialsettingsforsubdomains']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array('1') + 'value' => array( + '1' + ) ) ) ), @@ -169,9 +183,14 @@ return array( 'desc' => $lng['domains']['ssl_redirect']['description'] . ($result['temporary_ssl_redirect'] > 1 ? $lng['domains']['ssl_redirect_temporarilydisabled'] : ''), 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['ssl_redirect']) + 'value' => array( + $result['ssl_redirect'] + ) ), 'letsencrypt' => array( 'visible' => (Settings::Get('system.leenabled') == '1' ? ($ssl_ipsandports != '' ? true : false) : false), @@ -179,9 +198,14 @@ return array( 'desc' => $lng['admin']['letsencrypt']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['letsencrypt']) + 'value' => array( + $result['letsencrypt'] + ) ), 'no_ssl_available_info' => array( 'visible' => ($ssl_ipsandports == '' ? true : false), @@ -204,9 +228,14 @@ return array( 'desc' => $lng['admin']['domain_hsts_incsub']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['hsts_sub']) + 'value' => array( + $result['hsts_sub'] + ) ), 'hsts_preload' => array( 'visible' => ($ssl_ipsandports != '' ? true : false), @@ -214,10 +243,15 @@ return array( 'desc' => $lng['admin']['domain_hsts_preload']['description'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['hsts_preload']) - ), + 'value' => array( + $result['hsts_preload'] + ) + ) ) ), 'section_c' => array( @@ -225,39 +259,49 @@ return array( 'image' => 'icons/domain_edit.png', 'visible' => (($userinfo['change_serversettings'] == '1' || $userinfo['caneditphpsettings'] == '1') ? true : false), 'fields' => array( - 'phpenabled' => array( - 'label' => $lng['admin']['phpenabled'], - 'type' => 'checkbox', - 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), - 'value' => array($result['phpenabled']) - ), 'openbasedir' => array( 'label' => 'OpenBasedir', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['openbasedir']) + 'value' => array( + $result['openbasedir'] + ) + ), + 'phpenabled' => array( + 'label' => $lng['admin']['phpenabled'], + 'type' => 'checkbox', + 'values' => array( + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + $result['phpenabled'] + ) ), 'phpsettingid' => array( - 'visible' => (((int)Settings::Get('system.mod_fcgid') == 1 || (int)Settings::Get('phpfpm.enabled') == 1) ? true : false), + 'visible' => (((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) ? true : false), 'label' => $lng['admin']['phpsettings']['title'], 'type' => 'select', 'select_var' => $phpconfigs ), 'mod_fcgid_starter' => array( - 'visible' => ((int)Settings::Get('system.mod_fcgid') == 1 ? true : false), + 'visible' => ((int) Settings::Get('system.mod_fcgid') == 1 ? true : false), 'label' => $lng['admin']['mod_fcgid_starter']['title'], 'type' => 'text', - 'value' => ((int)$result['mod_fcgid_starter'] != - 1 ? $result['mod_fcgid_starter'] : '') + 'value' => ((int) $result['mod_fcgid_starter'] != - 1 ? $result['mod_fcgid_starter'] : '') ), 'mod_fcgid_maxrequests' => array( - 'visible' => ((int)Settings::Get('system.mod_fcgid') == 1 ? true : false), + 'visible' => ((int) Settings::Get('system.mod_fcgid') == 1 ? true : false), 'label' => $lng['admin']['mod_fcgid_maxrequests']['title'], 'type' => 'text', - 'value' => ((int)$result['mod_fcgid_maxrequests'] != - 1 ? $result['mod_fcgid_maxrequests'] : '') + 'value' => ((int) $result['mod_fcgid_maxrequests'] != - 1 ? $result['mod_fcgid_maxrequests'] : '') ) ) ), @@ -270,9 +314,14 @@ return array( 'label' => 'Nameserver', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['isbinddomain']) + 'value' => array( + $result['isbinddomain'] + ) ), 'zonefile' => array( 'label' => 'Zonefile', @@ -290,17 +339,27 @@ return array( 'label' => $lng['admin']['emaildomain'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['isemaildomain']) + 'value' => array( + $result['isemaildomain'] + ) ), 'email_only' => array( 'label' => $lng['admin']['email_only'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['email_only']) + 'value' => array( + $result['email_only'] + ) ), 'subcanemaildomain' => array( 'label' => $lng['admin']['subdomainforemail'], @@ -312,9 +371,14 @@ return array( 'label' => 'DomainKeys', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), - 'value' => array($result['dkim']) + 'value' => array( + $result['dkim'] + ) ) ) ) From f9101f880b439f47a204ed48c5aead2b430e1a12 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 14 Dec 2016 09:54:49 +0100 Subject: [PATCH 020/179] use namserver IP's for axfr/pdns-config, also add placeholder AXFRSERVERS for axfr-servers setting; fixes #1691 Signed-off-by: Michael Kaufmann (d00p) --- admin_configfiles.php | 15 +++++++++++++++ lib/configfiles/gentoo.xml | 6 ++++-- lib/configfiles/jessie.xml | 6 ++++-- lib/configfiles/precise.xml | 6 ++++-- lib/configfiles/trusty.xml | 9 ++++++--- lib/configfiles/wheezy.xml | 6 ++++-- 6 files changed, 37 insertions(+), 11 deletions(-) diff --git a/admin_configfiles.php b/admin_configfiles.php index efbeba7a..c5e38a88 100644 --- a/admin_configfiles.php +++ b/admin_configfiles.php @@ -30,6 +30,19 @@ if ($userinfo['change_serversettings'] == '1') { $customer_tmpdir = Settings::Get('phpfpm.tmpdir'); } + // try to convert namserver hosts to ip's + $ns_ips = ""; + if (Settings::Get('system.nameservers') != '') { + $nameservers = explode(',', Settings::Get('system.nameservers')); + foreach ($nameservers as $nameserver) { + $nameserver = trim($nameserver); + $nameserver_ips = gethostbynamel($nameserver); + if (is_array($nameserver_ips) && count($nameserver_ips) > 0) { + $ns_ips .= implode(",", $nameserver_ips); + } + } + } + $replace_arr = Array( '' => $sql['user'], '' => 'MYSQL_PASSWORD', @@ -39,6 +52,8 @@ if ($userinfo['change_serversettings'] == '1') { '' => Settings::Get('system.hostname'), '' => Settings::Get('system.ipaddress'), '' => Settings::Get('system.nameservers'), + '' => $ns_ips, + '' => Settings::Get('system.axfrservers'), '' => Settings::Get('system.vmail_homedir'), '' => Settings::Get('system.vmail_uid'), '' => Settings::Get('system.vmail_gid'), diff --git a/lib/configfiles/gentoo.xml b/lib/configfiles/gentoo.xml index 69b4dd8d..cbcda2db 100644 --- a/lib/configfiles/gentoo.xml +++ b/lib/configfiles/gentoo.xml @@ -396,7 +396,8 @@ mail IN A ################################# # allow-axfr-ips Allow zonetransfers only to these subnets # -allow-axfr-ips=127.0.0.0/8,::1, +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: ################################# # allow-dnsupdate-from A global setting to allow DNS updates from these IP ranges. @@ -938,7 +939,8 @@ gmysql-password= ################################# # allow-axfr-ips Allow zonetransfers only to these subnets # -allow-axfr-ips=127.0.0.0/8,::1, +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: ################################# # allow-dnsupdate-from A global setting to allow DNS updates from these IP ranges. diff --git a/lib/configfiles/jessie.xml b/lib/configfiles/jessie.xml index 99322e4b..d6613020 100644 --- a/lib/configfiles/jessie.xml +++ b/lib/configfiles/jessie.xml @@ -380,7 +380,8 @@ exit "$RETVAL" ################################# # allow-axfr-ips Allow zonetransfers only to these subnets # -allow-axfr-ips=127.0.0.0/8,::1, +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: ################################# # allow-dnsupdate-from A global setting to allow DNS updates from these IP ranges. @@ -921,7 +922,8 @@ gmysql-password= ################################# # allow-axfr-ips Allow zonetransfers only to these subnets # -# allow-axfr-ips=127.0.0.0/8,::1, +# allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: ################################# # allow-dnsupdate-from A global setting to allow DNS updates from these IP ranges. diff --git a/lib/configfiles/precise.xml b/lib/configfiles/precise.xml index 512415a4..c985a38e 100644 --- a/lib/configfiles/precise.xml +++ b/lib/configfiles/precise.xml @@ -346,7 +346,8 @@ exit "$RETVAL" +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: allow-recursion=127.0.0.1 config-dir=/etc/powerdns daemon=yes @@ -407,7 +408,8 @@ include-dir=/etc/powerdns/froxlor/ +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: #local-ipv6=YOUR_IPv6_(if_any) bind-config=named.conf bind-check-interval=180 diff --git a/lib/configfiles/trusty.xml b/lib/configfiles/trusty.xml index ba8bdc3f..7a7aeb8d 100644 --- a/lib/configfiles/trusty.xml +++ b/lib/configfiles/trusty.xml @@ -379,7 +379,8 @@ exit "$RETVAL" +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: allow-recursion=127.0.0.1 config-dir=/etc/powerdns daemon=yes @@ -417,7 +418,8 @@ gmysql-password= +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: allow-recursion=127.0.0.1 config-dir=/etc/powerdns daemon=yes @@ -441,7 +443,8 @@ include-dir=/etc/powerdns/froxlor/ +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: #local-ipv6=YOUR_IPv6_(if_any) bind-config=named.conf bind-check-interval=180 diff --git a/lib/configfiles/wheezy.xml b/lib/configfiles/wheezy.xml index 9d1d5c21..6e286017 100644 --- a/lib/configfiles/wheezy.xml +++ b/lib/configfiles/wheezy.xml @@ -424,7 +424,8 @@ exit "$RETVAL" # allow-axfr-ips If enabled, restrict zonetransfers to originate from these # IP addresses # -allow-axfr-ips=127.0.0.0/8,::1, +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: ################################# # allow-recursion List of netmasks that are allowed to recurse @@ -763,7 +764,8 @@ gmysql-password= # allow-axfr-ips If enabled, restrict zonetransfers to originate from these # IP addresses # -allow-axfr-ips= +allow-axfr-ips=127.0.0.0/8,::1, +# add these entries to the list if any speficied: ################################# # allow-recursion List of netmasks that are allowed to recurse From 4502f7ddf5cef412bc7cf9debeb8e61b807d3547 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 16 Dec 2016 10:17:48 +0100 Subject: [PATCH 021/179] fix Settings::Flush(), thx to Ithariel Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/settings/class.Settings.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/classes/settings/class.Settings.php b/lib/classes/settings/class.Settings.php index e90d5245..e6b8a37b 100644 --- a/lib/classes/settings/class.Settings.php +++ b/lib/classes/settings/class.Settings.php @@ -86,6 +86,7 @@ class Settings { while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) { self::$_data[$row['settinggroup']][$row['varname']] = $row['value']; } + return true; } /** @@ -161,10 +162,16 @@ class Settings { if ($instant_save) { $this->_storeSetting($sstr[0], $sstr[1], $value); } else { - if (!is_array(self::$_data[$sstr[0]])) { + // set temporary data for usage + if (!isset(self::$_data[$sstr[0]]) || !is_array(self::$_data[$sstr[0]])) { self::$_data[$sstr[0]] = array(); } self::$_data[$sstr[0]][$sstr[1]] = $value; + // set update-data when invoking Flush() + if (!isset(self::$_updatedata[$sstr[0]]) || !is_array(self::$_updatedata[$sstr[0]])) { + self::$_updatedata[$sstr[0]] = array(); + } + self::$_updatedata[$sstr[0]][$sstr[1]] = $value; } return true; } @@ -223,8 +230,9 @@ class Settings { // now empty the array self::$_updatedata = array(); // re-read in all settings - $this->_readSettings(); + return $this->_readSettings(); } + return false; } /** From 5c008adf16676349766734300513f06b8337325d Mon Sep 17 00:00:00 2001 From: Stefan Weil Date: Thu, 8 Dec 2016 22:00:00 +0100 Subject: [PATCH 022/179] Fix HTML code (wrong tag) `` must be terminated by ``. Signed-off-by: Stefan Weil --- install/templates/dataitemchk.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install/templates/dataitemchk.tpl b/install/templates/dataitemchk.tpl index 9211c223..30279bfa 100644 --- a/install/templates/dataitemchk.tpl +++ b/install/templates/dataitemchk.tpl @@ -1,4 +1,4 @@

- {$fieldlabel} + {$fieldlabel}

From 7a617d0aa49ac5975023cf8275b6dd21a474feb3 Mon Sep 17 00:00:00 2001 From: Stefan Weil Date: Sat, 17 Dec 2016 14:31:07 +0100 Subject: [PATCH 023/179] Fix description in README.md The entry is called "System", not "Server". Signed-off-by: Stefan Weil --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 67c8c554..423e16d4 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ Developed by experienced server administrators, this panel simplifies the effort 3. Point your browser to http://[ip-of-webserver]/froxlor 4. Follow the installer 5. Login as administrator -6. Adjust "Server > Settings" according to your needs -7. Choose your distribution under "Server > Configuration" +6. Adjust "System > Settings" according to your needs +7. Choose your distribution under "System > Configuration" 8. Follow the steps for your services 9. Have fun! From 75622d4737320a29b5c612c2bf77bd96fc113b70 Mon Sep 17 00:00:00 2001 From: pissbeutel Date: Sat, 17 Dec 2016 15:14:02 +0100 Subject: [PATCH 024/179] Changed SOA refresh intervall to be compliant within recommended values See: https://www.denic.de/fileadmin/public/documentation/DENIC-23p.pdf The recommended values according to DENIC are: refresh: 3600 - 86400 retry: 900 - 28800 expire: 604800 - 3600000 negTTL: 180 - 86400 --- lib/functions/dns/function.createDomainZone.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/functions/dns/function.createDomainZone.php b/lib/functions/dns/function.createDomainZone.php index ad21ee45..7c4ca858 100644 --- a/lib/functions/dns/function.createDomainZone.php +++ b/lib/functions/dns/function.createDomainZone.php @@ -279,7 +279,7 @@ function createDomainZone($domain_id, $froxlorhostname = false, $isMainButSubTo $soa_content = $primary_ns . " " . escapeSoaAdminMail(Settings::Get('panel.adminmail')) . " "; $soa_content .= $domain['bindserial'] . " "; // TODO for now, dummy time-periods - $soa_content .= "1800 900 604800 1200"; + $soa_content .= "3600 900 604800 1200"; $soa_record = new DnsEntry('@', 'SOA', $soa_content); array_unshift($zonerecords, $soa_record); From 7a603596c5a43b4df30fafb29beaff661649361a Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 28 Dec 2016 20:13:15 +0100 Subject: [PATCH 025/179] validate ip address on installation --- install/lib/class.FroxlorInstall.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/install/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index 792e8202..37acfc7c 100644 --- a/install/lib/class.FroxlorInstall.php +++ b/install/lib/class.FroxlorInstall.php @@ -177,10 +177,14 @@ class FroxlorInstall } // check system-hostname to be a FQDN - if ($this->_validate_ip($this->_data['servername'], true) !== false) { + if ($this->_validate_ip($this->_data['servername']) !== false) { $this->_data['servername'] = ''; } + if (empty($this->_data['serverip'] || $this->_validate_ip($this->_data['serverip']) == false)) { + return false; + } + if (isset($_POST['installstep']) && $_POST['installstep'] == '1' && $this->_data['admin_pass1'] == $this->_data['admin_pass2'] && $this->_data['admin_pass1'] != '' && $this->_data['admin_pass2'] != '' && $this->_data['mysql_unpriv_pass'] != '' && $this->_data['mysql_root_pass'] != '' && $this->_data['servername'] != '' && $this->_data['serverip'] != '' && $this->_data['httpuser'] != '' && $this->_data['httpgroup'] != '' && $this->_data['mysql_unpriv_user'] != $this->_data['mysql_root_user']) { return true; } @@ -781,7 +785,7 @@ class FroxlorInstall } $formdata .= $this->_getSectionItemString('servername', true, $style); // serverip - if (! empty($_POST['installstep']) && $this->_data['serverip'] == '') { + if (! empty($_POST['installstep']) && ($this->_data['serverip'] == '' || $this->_validate_ip($this->_data['serverip']) == false)) { $style = 'color:red;'; } else { $style = ''; From 437446c49d5e6381aa1f74fc72e1b288cca1947d Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 29 Dec 2016 10:54:25 +0100 Subject: [PATCH 026/179] update phpMailer to 5.2.21 Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/phpmailer/PHPMailerAutoload.php | 72 +- lib/classes/phpmailer/class.PHPMailer.php | 7915 ++++++++++--------- lib/classes/phpmailer/class.SMTP.php | 2423 +++--- 3 files changed, 5284 insertions(+), 5126 deletions(-) diff --git a/lib/classes/phpmailer/PHPMailerAutoload.php b/lib/classes/phpmailer/PHPMailerAutoload.php index eaa2e303..6c3b632d 100644 --- a/lib/classes/phpmailer/PHPMailerAutoload.php +++ b/lib/classes/phpmailer/PHPMailerAutoload.php @@ -1,49 +1,49 @@ - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - * @copyright 2012 - 2014 Marcus Bointon - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @note This program is distributed in the hope that it will be useful - WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ +* PHP Version 5 +* @package PHPMailer +* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project +* @author Marcus Bointon (Synchro/coolbru) +* @author Jim Jagielski (jimjag) +* @author Andy Prevost (codeworxtech) +* @author Brent R. Matzelle (original founder) +* @copyright 2012 - 2014 Marcus Bointon +* @copyright 2010 - 2012 Jim Jagielski +* @copyright 2004 - 2009 Andy Prevost +* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License +* @note This program is distributed in the hope that it will be useful - WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. +*/ /** * PHPMailer SPL autoloader. - * @param string $classname The name of the class to load - */ +* @param string $classname The name of the class to load +*/ function PHPMailerAutoload($classname) { - //Can't use __DIR__ as it's only in PHP 5.3+ - $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php'; - if (is_readable($filename)) { - require $filename; - } + //Can't use __DIR__ as it's only in PHP 5.3+ + $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php'; + if (is_readable($filename)) { + require $filename; + } } if (version_compare(PHP_VERSION, '5.1.2', '>=')) { - //SPL autoloading was introduced in PHP 5.1.2 - if (version_compare(PHP_VERSION, '5.3.0', '>=')) { - spl_autoload_register('PHPMailerAutoload', true, true); - } else { - spl_autoload_register('PHPMailerAutoload'); - } + //SPL autoloading was introduced in PHP 5.1.2 + if (version_compare(PHP_VERSION, '5.3.0', '>=')) { + spl_autoload_register('PHPMailerAutoload', true, true); + } else { + spl_autoload_register('PHPMailerAutoload'); + } } else { - /** - * Fall back to traditional autoload for old PHP versions - * @param string $classname The name of the class to load - */ - function __autoload($classname) - { - PHPMailerAutoload($classname); - } + /** + * Fall back to traditional autoload for old PHP versions + * @param string $classname The name of the class to load + */ + function __autoload($classname) + { + PHPMailerAutoload($classname); + } } diff --git a/lib/classes/phpmailer/class.PHPMailer.php b/lib/classes/phpmailer/class.PHPMailer.php index f9013ebb..cdb9413c 100644 --- a/lib/classes/phpmailer/class.PHPMailer.php +++ b/lib/classes/phpmailer/class.PHPMailer.php @@ -1,3909 +1,4010 @@ - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - * @copyright 2012 - 2014 Marcus Bointon - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @note This program is distributed in the hope that it will be useful - WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ +* PHP Version 5 +* @package PHPMailer +* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project +* @author Marcus Bointon (Synchro/coolbru) +* @author Jim Jagielski (jimjag) +* @author Andy Prevost (codeworxtech) +* @author Brent R. Matzelle (original founder) +* @copyright 2012 - 2014 Marcus Bointon +* @copyright 2010 - 2012 Jim Jagielski +* @copyright 2004 - 2009 Andy Prevost +* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License +* @note This program is distributed in the hope that it will be useful - WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. +*/ /** * PHPMailer - PHP email creation and transport class. - * @package PHPMailer - * @author Marcus Bointon (Synchro/coolbru) - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - */ +* @package PHPMailer +* @author Marcus Bointon (Synchro/coolbru) +* @author Jim Jagielski (jimjag) +* @author Andy Prevost (codeworxtech) +* @author Brent R. Matzelle (original founder) +*/ class PHPMailer { - /** - * The PHPMailer Version number. - * @var string - */ - public $Version = '5.2.16'; - - /** - * Email priority. - * Options: null (default), 1 = High, 3 = Normal, 5 = low. - * When null, the header is not set at all. - * @var integer - */ - public $Priority = null; - - /** - * The character set of the message. - * @var string - */ - public $CharSet = 'iso-8859-1'; - - /** - * The MIME Content-type of the message. - * @var string - */ - public $ContentType = 'text/plain'; - - /** - * The message encoding. - * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". - * @var string - */ - public $Encoding = '8bit'; - - /** - * Holds the most recent mailer error message. - * @var string - */ - public $ErrorInfo = ''; - - /** - * The From email address for the message. - * @var string - */ - public $From = 'root@localhost'; - - /** - * The From name of the message. - * @var string - */ - public $FromName = 'Root User'; - - /** - * The Sender email (Return-Path) of the message. - * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. - * @var string - */ - public $Sender = ''; - - /** - * The Return-Path of the message. - * If empty, it will be set to either From or Sender. - * @var string - * @deprecated Email senders should never set a return-path header; - * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything. - * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference - */ - public $ReturnPath = ''; - - /** - * The Subject of the message. - * @var string - */ - public $Subject = ''; - - /** - * An HTML or plain text message body. - * If HTML then call isHTML(true). - * @var string - */ - public $Body = ''; - - /** - * The plain-text message body. - * This body can be read by mail clients that do not have HTML email - * capability such as mutt & Eudora. - * Clients that can read HTML will view the normal Body. - * @var string - */ - public $AltBody = ''; - - /** - * An iCal message part body. - * Only supported in simple alt or alt_inline message types - * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator - * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ - * @link http://kigkonsult.se/iCalcreator/ - * @var string - */ - public $Ical = ''; - - /** - * The complete compiled MIME message body. - * @access protected - * @var string - */ - protected $MIMEBody = ''; - - /** - * The complete compiled MIME message headers. - * @var string - * @access protected - */ - protected $MIMEHeader = ''; - - /** - * Extra headers that createHeader() doesn't fold in. - * @var string - * @access protected - */ - protected $mailHeader = ''; - - /** - * Word-wrap the message body to this number of chars. - * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. - * @var integer - */ - public $WordWrap = 0; - - /** - * Which method to use to send mail. - * Options: "mail", "sendmail", or "smtp". - * @var string - */ - public $Mailer = 'mail'; - - /** - * The path to the sendmail program. - * @var string - */ - public $Sendmail = '/usr/sbin/sendmail'; - - /** - * Whether mail() uses a fully sendmail-compatible MTA. - * One which supports sendmail's "-oi -f" options. - * @var boolean - */ - public $UseSendmailOptions = true; - - /** - * Path to PHPMailer plugins. - * Useful if the SMTP class is not in the PHP include path. - * @var string - * @deprecated Should not be needed now there is an autoloader. - */ - public $PluginDir = ''; - - /** - * The email address that a reading confirmation should be sent to, also known as read receipt. - * @var string - */ - public $ConfirmReadingTo = ''; - - /** - * The hostname to use in the Message-ID header and as default HELO string. - * If empty, PHPMailer attempts to find one with, in order, - * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value - * 'localhost.localdomain'. - * @var string - */ - public $Hostname = ''; - - /** - * An ID to be used in the Message-ID header. - * If empty, a unique id will be generated. - * @var string - */ - public $MessageID = ''; - - /** - * The message Date to be used in the Date header. - * If empty, the current date will be added. - * @var string - */ - public $MessageDate = ''; - - /** - * SMTP hosts. - * Either a single hostname or multiple semicolon-delimited hostnames. - * You can also specify a different port - * for each host by using this format: [hostname:port] - * (e.g. "smtp1.example.com:25;smtp2.example.com"). - * You can also specify encryption type, for example: - * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). - * Hosts will be tried in order. - * @var string - */ - public $Host = 'localhost'; - - /** - * The default SMTP server port. - * @var integer - * @TODO Why is this needed when the SMTP class takes care of it? - */ - public $Port = 25; - - /** - * The SMTP HELO of the message. - * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find - * one with the same method described above for $Hostname. - * @var string - * @see PHPMailer::$Hostname - */ - public $Helo = ''; - - /** - * What kind of encryption to use on the SMTP connection. - * Options: '', 'ssl' or 'tls' - * @var string - */ - public $SMTPSecure = ''; - - /** - * Whether to enable TLS encryption automatically if a server supports it, - * even if `SMTPSecure` is not set to 'tls'. - * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. - * @var boolean - */ - public $SMTPAutoTLS = true; - - /** - * Whether to use SMTP authentication. - * Uses the Username and Password properties. - * @var boolean - * @see PHPMailer::$Username - * @see PHPMailer::$Password - */ - public $SMTPAuth = false; - - /** - * Options array passed to stream_context_create when connecting via SMTP. - * @var array - */ - public $SMTPOptions = array(); - - /** - * SMTP username. - * @var string - */ - public $Username = ''; - - /** - * SMTP password. - * @var string - */ - public $Password = ''; - - /** - * SMTP auth type. - * Options are CRAM-MD5, LOGIN, PLAIN, NTLM, XOAUTH2, attempted in that order if not specified - * @var string - */ - public $AuthType = ''; - - /** - * SMTP realm. - * Used for NTLM auth - * @var string - */ - public $Realm = ''; - - /** - * SMTP workstation. - * Used for NTLM auth - * @var string - */ - public $Workstation = ''; - - /** - * The SMTP server timeout in seconds. - * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 - * @var integer - */ - public $Timeout = 300; - - /** - * SMTP class debug output mode. - * Debug output level. - * Options: - * * `0` No output - * * `1` Commands - * * `2` Data and commands - * * `3` As 2 plus connection status - * * `4` Low-level data output - * @var integer - * @see SMTP::$do_debug - */ - public $SMTPDebug = 0; - - /** - * How to handle debug output. - * Options: - * * `echo` Output plain-text as-is, appropriate for CLI - * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output - * * `error_log` Output to error log as configured in php.ini - * - * Alternatively, you can provide a callable expecting two params: a message string and the debug level: - * - * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; - * - * @var string|callable - * @see SMTP::$Debugoutput - */ - public $Debugoutput = 'echo'; - - /** - * Whether to keep SMTP connection open after each message. - * If this is set to true then to close the connection - * requires an explicit call to smtpClose(). - * @var boolean - */ - public $SMTPKeepAlive = false; - - /** - * Whether to split multiple to addresses into multiple messages - * or send them all in one message. - * Only supported in `mail` and `sendmail` transports, not in SMTP. - * @var boolean - */ - public $SingleTo = false; - - /** - * Storage for addresses when SingleTo is enabled. - * @var array - * @TODO This should really not be public - */ - public $SingleToArray = array(); - - /** - * Whether to generate VERP addresses on send. - * Only applicable when sending via SMTP. - * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path - * @link http://www.postfix.org/VERP_README.html Postfix VERP info - * @var boolean - */ - public $do_verp = false; - - /** - * Whether to allow sending messages with an empty body. - * @var boolean - */ - public $AllowEmpty = false; - - /** - * The default line ending. - * @note The default remains "\n". We force CRLF where we know - * it must be used via self::CRLF. - * @var string - */ - public $LE = "\n"; - - /** - * DKIM selector. - * @var string - */ - public $DKIM_selector = ''; - - /** - * DKIM Identity. - * Usually the email address used as the source of the email. - * @var string - */ - public $DKIM_identity = ''; - - /** - * DKIM passphrase. - * Used if your key is encrypted. - * @var string - */ - public $DKIM_passphrase = ''; - - /** - * DKIM signing domain name. - * @example 'example.com' - * @var string - */ - public $DKIM_domain = ''; - - /** - * DKIM private key file path. - * @var string - */ - public $DKIM_private = ''; - - /** - * Callback Action function name. - * - * The function that handles the result of the send email action. - * It is called out by send() for each email sent. - * - * Value can be any php callable: http://www.php.net/is_callable - * - * Parameters: - * boolean $result result of the send action - * string $to email address of the recipient - * string $cc cc email addresses - * string $bcc bcc email addresses - * string $subject the subject - * string $body the email body - * string $from email address of sender - * @var string - */ - public $action_function = ''; - - /** - * What to put in the X-Mailer header. - * Options: An empty string for PHPMailer default, whitespace for none, or a string to use - * @var string - */ - public $XMailer = ''; - - /** - * Which validator to use by default when validating email addresses. - * May be a callable to inject your own validator, but there are several built-in validators. - * @see PHPMailer::validateAddress() - * @var string|callable - * @static - */ - public static $validator = 'auto'; - - /** - * An instance of the SMTP sender class. - * @var SMTP - * @access protected - */ - protected $smtp = null; - - /** - * The array of 'to' names and addresses. - * @var array - * @access protected - */ - protected $to = array(); - - /** - * The array of 'cc' names and addresses. - * @var array - * @access protected - */ - protected $cc = array(); - - /** - * The array of 'bcc' names and addresses. - * @var array - * @access protected - */ - protected $bcc = array(); - - /** - * The array of reply-to names and addresses. - * @var array - * @access protected - */ - protected $ReplyTo = array(); - - /** - * An array of all kinds of addresses. - * Includes all of $to, $cc, $bcc - * @var array - * @access protected - * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc - */ - protected $all_recipients = array(); - - /** - * An array of names and addresses queued for validation. - * In send(), valid and non duplicate entries are moved to $all_recipients - * and one of $to, $cc, or $bcc. - * This array is used only for addresses with IDN. - * @var array - * @access protected - * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc - * @see PHPMailer::$all_recipients - */ - protected $RecipientsQueue = array(); - - /** - * An array of reply-to names and addresses queued for validation. - * In send(), valid and non duplicate entries are moved to $ReplyTo. - * This array is used only for addresses with IDN. - * @var array - * @access protected - * @see PHPMailer::$ReplyTo - */ - protected $ReplyToQueue = array(); - - /** - * The array of attachments. - * @var array - * @access protected - */ - protected $attachment = array(); - - /** - * The array of custom headers. - * @var array - * @access protected - */ - protected $CustomHeader = array(); - - /** - * The most recent Message-ID (including angular brackets). - * @var string - * @access protected - */ - protected $lastMessageID = ''; - - /** - * The message's MIME type. - * @var string - * @access protected - */ - protected $message_type = ''; - - /** - * The array of MIME boundary strings. - * @var array - * @access protected - */ - protected $boundary = array(); - - /** - * The array of available languages. - * @var array - * @access protected - */ - protected $language = array(); - - /** - * The number of errors encountered. - * @var integer - * @access protected - */ - protected $error_count = 0; - - /** - * The S/MIME certificate file path. - * @var string - * @access protected - */ - protected $sign_cert_file = ''; - - /** - * The S/MIME key file path. - * @var string - * @access protected - */ - protected $sign_key_file = ''; - - /** - * The optional S/MIME extra certificates ("CA Chain") file path. - * @var string - * @access protected - */ - protected $sign_extracerts_file = ''; - - /** - * The S/MIME password for the key. - * Used only if the key is encrypted. - * @var string - * @access protected - */ - protected $sign_key_pass = ''; - - /** - * Whether to throw exceptions for errors. - * @var boolean - * @access protected - */ - protected $exceptions = false; - - /** - * Unique ID used for message ID and boundaries. - * @var string - * @access protected - */ - protected $uniqueid = ''; - - /** - * Error severity: message only, continue processing. - */ - const STOP_MESSAGE = 0; - - /** - * Error severity: message, likely ok to continue processing. - */ - const STOP_CONTINUE = 1; - - /** - * Error severity: message, plus full stop, critical error reached. - */ - const STOP_CRITICAL = 2; - - /** - * SMTP RFC standard line ending. - */ - const CRLF = "\r\n"; - - /** - * The maximum line length allowed by RFC 2822 section 2.1.1 - * @var integer - */ - const MAX_LINE_LENGTH = 998; - - /** - * Constructor. - * @param boolean $exceptions Should we throw external exceptions? - */ - public function __construct($exceptions = null) - { - if ($exceptions !== null) { - $this->exceptions = (boolean)$exceptions; - } - } - - /** - * Destructor. - */ - public function __destruct() - { - //Close any open SMTP connection nicely - $this->smtpClose(); - } - - /** - * Call mail() in a safe_mode-aware fashion. - * Also, unless sendmail_path points to sendmail (or something that - * claims to be sendmail), don't pass params (not a perfect fix, - * but it will do) - * @param string $to To - * @param string $subject Subject - * @param string $body Message Body - * @param string $header Additional Header(s) - * @param string $params Params - * @access private - * @return boolean - */ - private function mailPassthru($to, $subject, $body, $header, $params) - { - //Check overloading of mail function to avoid double-encoding - if (ini_get('mbstring.func_overload') & 1) { - $subject = $this->secureHeader($subject); - } else { - $subject = $this->encodeHeader($this->secureHeader($subject)); - } - //Can't use additional_parameters in safe_mode - //@link http://php.net/manual/en/function.mail.php - if (ini_get('safe_mode') or !$this->UseSendmailOptions) { - $result = @mail($to, $subject, $body, $header); - } else { - $result = @mail($to, $subject, $body, $header, $params); - } - return $result; - } - - /** - * Output debugging info via user-defined method. - * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug). - * @see PHPMailer::$Debugoutput - * @see PHPMailer::$SMTPDebug - * @param string $str - */ - protected function edebug($str) - { - if ($this->SMTPDebug <= 0) { - return; - } - //Avoid clash with built-in function names - if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { - call_user_func($this->Debugoutput, $str, $this->SMTPDebug); - return; - } - switch ($this->Debugoutput) { - case 'error_log': - //Don't output, just log - error_log($str); - break; - case 'html': - //Cleans up output a bit for a better looking, HTML-safe output - echo htmlentities( - preg_replace('/[\r\n]+/', '', $str), - ENT_QUOTES, - 'UTF-8' - ) - . "
\n"; - break; - case 'echo': - default: - //Normalize line breaks - $str = preg_replace('/\r\n?/ms', "\n", $str); - echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( - "\n", - "\n \t ", - trim($str) - ) . "\n"; - } - } - - /** - * Sets message type to HTML or plain. - * @param boolean $isHtml True for HTML mode. - * @return void - */ - public function isHTML($isHtml = true) - { - if ($isHtml) { - $this->ContentType = 'text/html'; - } else { - $this->ContentType = 'text/plain'; - } - } - - /** - * Send messages using SMTP. - * @return void - */ - public function isSMTP() - { - $this->Mailer = 'smtp'; - } - - /** - * Send messages using PHP's mail() function. - * @return void - */ - public function isMail() - { - $this->Mailer = 'mail'; - } - - /** - * Send messages using $Sendmail. - * @return void - */ - public function isSendmail() - { - $ini_sendmail_path = ini_get('sendmail_path'); - - if (!stristr($ini_sendmail_path, 'sendmail')) { - $this->Sendmail = '/usr/sbin/sendmail'; - } else { - $this->Sendmail = $ini_sendmail_path; - } - $this->Mailer = 'sendmail'; - } - - /** - * Send messages using qmail. - * @return void - */ - public function isQmail() - { - $ini_sendmail_path = ini_get('sendmail_path'); - - if (!stristr($ini_sendmail_path, 'qmail')) { - $this->Sendmail = '/var/qmail/bin/qmail-inject'; - } else { - $this->Sendmail = $ini_sendmail_path; - } - $this->Mailer = 'qmail'; - } - - /** - * Add a "To" address. - * @param string $address The email address to send to - * @param string $name - * @return boolean true on success, false if address already used or invalid in some way - */ - public function addAddress($address, $name = '') - { - return $this->addOrEnqueueAnAddress('to', $address, $name); - } - - /** - * Add a "CC" address. - * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. - * @param string $address The email address to send to - * @param string $name - * @return boolean true on success, false if address already used or invalid in some way - */ - public function addCC($address, $name = '') - { - return $this->addOrEnqueueAnAddress('cc', $address, $name); - } - - /** - * Add a "BCC" address. - * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. - * @param string $address The email address to send to - * @param string $name - * @return boolean true on success, false if address already used or invalid in some way - */ - public function addBCC($address, $name = '') - { - return $this->addOrEnqueueAnAddress('bcc', $address, $name); - } - - /** - * Add a "Reply-To" address. - * @param string $address The email address to reply to - * @param string $name - * @return boolean true on success, false if address already used or invalid in some way - */ - public function addReplyTo($address, $name = '') - { - return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); - } - - /** - * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer - * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still - * be modified after calling this function), addition of such addresses is delayed until send(). - * Addresses that have been added already return false, but do not throw exceptions. - * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' - * @param string $address The email address to send, resp. to reply to - * @param string $name - * @throws phpmailerException - * @return boolean true on success, false if address already used or invalid in some way - * @access protected - */ - protected function addOrEnqueueAnAddress($kind, $address, $name) - { - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - if (($pos = strrpos($address, '@')) === false) { - // At-sign is misssing. - $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address"; - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new phpmailerException($error_message); - } - return false; - } - $params = array($kind, $address, $name); - // Enqueue addresses with IDN until we know the PHPMailer::$CharSet. - if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) { - if ($kind != 'Reply-To') { - if (!array_key_exists($address, $this->RecipientsQueue)) { - $this->RecipientsQueue[$address] = $params; - return true; - } - } else { - if (!array_key_exists($address, $this->ReplyToQueue)) { - $this->ReplyToQueue[$address] = $params; - return true; - } - } - return false; - } - // Immediately add standard addresses without IDN. - return call_user_func_array(array($this, 'addAnAddress'), $params); - } - - /** - * Add an address to one of the recipient arrays or to the ReplyTo array. - * Addresses that have been added already return false, but do not throw exceptions. - * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' - * @param string $address The email address to send, resp. to reply to - * @param string $name - * @throws phpmailerException - * @return boolean true on success, false if address already used or invalid in some way - * @access protected - */ - protected function addAnAddress($kind, $address, $name = '') - { - if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) { - $error_message = $this->lang('Invalid recipient kind: ') . $kind; - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new phpmailerException($error_message); - } - return false; - } - if (!$this->validateAddress($address)) { - $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address"; - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new phpmailerException($error_message); - } - return false; - } - if ($kind != 'Reply-To') { - if (!array_key_exists(strtolower($address), $this->all_recipients)) { - array_push($this->$kind, array($address, $name)); - $this->all_recipients[strtolower($address)] = true; - return true; - } - } else { - if (!array_key_exists(strtolower($address), $this->ReplyTo)) { - $this->ReplyTo[strtolower($address)] = array($address, $name); - return true; - } - } - return false; - } - - /** - * Parse and validate a string containing one or more RFC822-style comma-separated email addresses - * of the form "display name
" into an array of name/address pairs. - * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. - * Note that quotes in the name part are removed. - * @param string $addrstr The address list string - * @param bool $useimap Whether to use the IMAP extension to parse the list - * @return array - * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation - */ - public function parseAddresses($addrstr, $useimap = true) - { - $addresses = array(); - if ($useimap and function_exists('imap_rfc822_parse_adrlist')) { - //Use this built-in parser if it's available - $list = imap_rfc822_parse_adrlist($addrstr, ''); - foreach ($list as $address) { - if ($address->host != '.SYNTAX-ERROR.') { - if ($this->validateAddress($address->mailbox . '@' . $address->host)) { - $addresses[] = array( - 'name' => (property_exists($address, 'personal') ? $address->personal : ''), - 'address' => $address->mailbox . '@' . $address->host - ); - } - } - } - } else { - //Use this simpler parser - $list = explode(',', $addrstr); - foreach ($list as $address) { - $address = trim($address); - //Is there a separate name part? - if (strpos($address, '<') === false) { - //No separate name, just use the whole thing - if ($this->validateAddress($address)) { - $addresses[] = array( - 'name' => '', - 'address' => $address - ); - } - } else { - list($name, $email) = explode('<', $address); - $email = trim(str_replace('>', '', $email)); - if ($this->validateAddress($email)) { - $addresses[] = array( - 'name' => trim(str_replace(array('"', "'"), '', $name)), - 'address' => $email - ); - } - } - } - } - return $addresses; - } - - /** - * Set the From and FromName properties. - * @param string $address - * @param string $name - * @param boolean $auto Whether to also set the Sender address, defaults to true - * @throws phpmailerException - * @return boolean - */ - public function setFrom($address, $name = '', $auto = true) - { - $address = trim($address); - $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim - // Don't validate now addresses with IDN. Will be done in send(). - if (($pos = strrpos($address, '@')) === false or - (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and - !$this->validateAddress($address)) { - $error_message = $this->lang('invalid_address') . " (setFrom) $address"; - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new phpmailerException($error_message); - } - return false; - } - $this->From = $address; - $this->FromName = $name; - if ($auto) { - if (empty($this->Sender)) { - $this->Sender = $address; - } - } - return true; - } - - /** - * Return the Message-ID header of the last email. - * Technically this is the value from the last time the headers were created, - * but it's also the message ID of the last sent message except in - * pathological cases. - * @return string - */ - public function getLastMessageID() - { - return $this->lastMessageID; - } - - /** - * Check that a string looks like an email address. - * @param string $address The email address to check - * @param string|callable $patternselect A selector for the validation pattern to use : - * * `auto` Pick best pattern automatically; - * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14; - * * `pcre` Use old PCRE implementation; - * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; - * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. - * * `noregex` Don't use a regex: super fast, really dumb. - * Alternatively you may pass in a callable to inject your own validator, for example: - * PHPMailer::validateAddress('user@example.com', function($address) { - * return (strpos($address, '@') !== false); - * }); - * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. - * @return boolean - * @static - * @access public - */ - public static function validateAddress($address, $patternselect = null) - { - if (is_null($patternselect)) { - $patternselect = self::$validator; - } - if (is_callable($patternselect)) { - return call_user_func($patternselect, $address); - } - //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 - if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) { - return false; - } - if (!$patternselect or $patternselect == 'auto') { - //Check this constant first so it works when extension_loaded() is disabled by safe mode - //Constant was added in PHP 5.2.4 - if (defined('PCRE_VERSION')) { - //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2 - if (version_compare(PCRE_VERSION, '8.0.3') >= 0) { - $patternselect = 'pcre8'; - } else { - $patternselect = 'pcre'; - } - } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) { - //Fall back to older PCRE - $patternselect = 'pcre'; - } else { - //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension - if (version_compare(PHP_VERSION, '5.2.0') >= 0) { - $patternselect = 'php'; - } else { - $patternselect = 'noregex'; - } - } - } - switch ($patternselect) { - case 'pcre8': - /** - * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains. - * @link http://squiloople.com/2009/12/20/email-address-validation/ - * @copyright 2009-2010 Michael Rushton - * Feel free to use and redistribute this code. But please keep this copyright notice. - */ - return (boolean)preg_match( - '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . - '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . - '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . - '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . - '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . - '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . - '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . - '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . - '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', - $address - ); - case 'pcre': - //An older regex that doesn't need a recent PCRE - return (boolean)preg_match( - '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' . - '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' . - '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' . - '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' . - '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' . - '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' . - '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' . - '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' . - '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' . - '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', - $address - ); - case 'html5': - /** - * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. - * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email) - */ - return (boolean)preg_match( - '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . - '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', - $address - ); - case 'noregex': - //No PCRE! Do something _very_ approximate! - //Check the address is 3 chars or longer and contains an @ that's not the first or last char - return (strlen($address) >= 3 - and strpos($address, '@') >= 1 - and strpos($address, '@') != strlen($address) - 1); - case 'php': - default: - return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL); - } - } - - /** - * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the - * "intl" and "mbstring" PHP extensions. - * @return bool "true" if required functions for IDN support are present - */ - public function idnSupported() - { - // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2. - return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding'); - } - - /** - * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. - * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. - * This function silently returns unmodified address if: - * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) - * - Conversion to punycode is impossible (e.g. required PHP functions are not available) - * or fails for any reason (e.g. domain has characters not allowed in an IDN) - * @see PHPMailer::$CharSet - * @param string $address The email address to convert - * @return string The encoded address in ASCII form - */ - public function punyencodeAddress($address) - { - // Verify we have required functions, CharSet, and at-sign. - if ($this->idnSupported() and - !empty($this->CharSet) and - ($pos = strrpos($address, '@')) !== false) { - $domain = substr($address, ++$pos); - // Verify CharSet string is a valid one, and domain properly encoded in this CharSet. - if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) { - $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet); - if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ? - idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) : - idn_to_ascii($domain)) !== false) { - return substr($address, 0, $pos) . $punycode; - } - } - } - return $address; - } - - /** - * Create a message and send it. - * Uses the sending method specified by $Mailer. - * @throws phpmailerException - * @return boolean false on error - See the ErrorInfo property for details of the error. - */ - public function send() - { - try { - if (!$this->preSend()) { - return false; - } - return $this->postSend(); - } catch (phpmailerException $exc) { - $this->mailHeader = ''; - $this->setError($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - return false; - } - } - - /** - * Prepare a message for sending. - * @throws phpmailerException - * @return boolean - */ - public function preSend() - { - try { - $this->error_count = 0; // Reset errors - $this->mailHeader = ''; - - // Dequeue recipient and Reply-To addresses with IDN - foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { - $params[1] = $this->punyencodeAddress($params[1]); - call_user_func_array(array($this, 'addAnAddress'), $params); - } - if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { - throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL); - } - - // Validate From, Sender, and ConfirmReadingTo addresses - foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) { - $this->$address_kind = trim($this->$address_kind); - if (empty($this->$address_kind)) { - continue; - } - $this->$address_kind = $this->punyencodeAddress($this->$address_kind); - if (!$this->validateAddress($this->$address_kind)) { - $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind; - $this->setError($error_message); - $this->edebug($error_message); - if ($this->exceptions) { - throw new phpmailerException($error_message); - } - return false; - } - } - - // Set whether the message is multipart/alternative - if ($this->alternativeExists()) { - $this->ContentType = 'multipart/alternative'; - } - - $this->setMessageType(); - // Refuse to send an empty message unless we are specifically allowing it - if (!$this->AllowEmpty and empty($this->Body)) { - throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL); - } - - // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) - $this->MIMEHeader = ''; - $this->MIMEBody = $this->createBody(); - // createBody may have added some headers, so retain them - $tempheaders = $this->MIMEHeader; - $this->MIMEHeader = $this->createHeader(); - $this->MIMEHeader .= $tempheaders; - - // To capture the complete message when using mail(), create - // an extra header list which createHeader() doesn't fold in - if ($this->Mailer == 'mail') { - if (count($this->to) > 0) { - $this->mailHeader .= $this->addrAppend('To', $this->to); - } else { - $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); - } - $this->mailHeader .= $this->headerLine( - 'Subject', - $this->encodeHeader($this->secureHeader(trim($this->Subject))) - ); - } - - // Sign with DKIM if enabled - if (!empty($this->DKIM_domain) - && !empty($this->DKIM_private) - && !empty($this->DKIM_selector) - && file_exists($this->DKIM_private)) { - $header_dkim = $this->DKIM_Add( - $this->MIMEHeader . $this->mailHeader, - $this->encodeHeader($this->secureHeader($this->Subject)), - $this->MIMEBody - ); - $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF . - str_replace("\r\n", "\n", $header_dkim) . self::CRLF; - } - return true; - } catch (phpmailerException $exc) { - $this->setError($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - return false; - } - } - - /** - * Actually send a message. - * Send the email via the selected mechanism - * @throws phpmailerException - * @return boolean - */ - public function postSend() - { - try { - // Choose the mailer and send through it - switch ($this->Mailer) { - case 'sendmail': - case 'qmail': - return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); - case 'smtp': - return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); - case 'mail': - return $this->mailSend($this->MIMEHeader, $this->MIMEBody); - default: - $sendMethod = $this->Mailer.'Send'; - if (method_exists($this, $sendMethod)) { - return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); - } - - return $this->mailSend($this->MIMEHeader, $this->MIMEBody); - } - } catch (phpmailerException $exc) { - $this->setError($exc->getMessage()); - $this->edebug($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - } - return false; - } - - /** - * Send mail using the $Sendmail program. - * @param string $header The message headers - * @param string $body The message body - * @see PHPMailer::$Sendmail - * @throws phpmailerException - * @access protected - * @return boolean - */ - protected function sendmailSend($header, $body) - { - if ($this->Sender != '') { - if ($this->Mailer == 'qmail') { - $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); - } else { - $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); - } - } else { - if ($this->Mailer == 'qmail') { - $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail)); - } else { - $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail)); - } - } - if ($this->SingleTo) { - foreach ($this->SingleToArray as $toAddr) { - if (!@$mail = popen($sendmail, 'w')) { - throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fputs($mail, 'To: ' . $toAddr . "\n"); - fputs($mail, $header); - fputs($mail, $body); - $result = pclose($mail); - $this->doCallback( - ($result == 0), - array($toAddr), - $this->cc, - $this->bcc, - $this->Subject, - $body, - $this->From - ); - if ($result != 0) { - throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - } else { - if (!@$mail = popen($sendmail, 'w')) { - throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - fputs($mail, $header); - fputs($mail, $body); - $result = pclose($mail); - $this->doCallback( - ($result == 0), - $this->to, - $this->cc, - $this->bcc, - $this->Subject, - $body, - $this->From - ); - if ($result != 0) { - throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); - } - } - return true; - } - - /** - * Send mail using the PHP mail() function. - * @param string $header The message headers - * @param string $body The message body - * @link http://www.php.net/manual/en/book.mail.php - * @throws phpmailerException - * @access protected - * @return boolean - */ - protected function mailSend($header, $body) - { - $toArr = array(); - foreach ($this->to as $toaddr) { - $toArr[] = $this->addrFormat($toaddr); - } - $to = implode(', ', $toArr); - - $params = null; - //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver - if (!empty($this->Sender)) { - $params = sprintf('-f%s', $this->Sender); - } - if ($this->Sender != '' and !ini_get('safe_mode')) { - $old_from = ini_get('sendmail_from'); - ini_set('sendmail_from', $this->Sender); - } - $result = false; - if ($this->SingleTo and count($toArr) > 1) { - foreach ($toArr as $toAddr) { - $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); - $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From); - } - } else { - $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); - $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From); - } - if (isset($old_from)) { - ini_set('sendmail_from', $old_from); - } - if (!$result) { - throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL); - } - return true; - } - - /** - * Get an instance to use for SMTP operations. - * Override this function to load your own SMTP implementation - * @return SMTP - */ - public function getSMTPInstance() - { - if (!is_object($this->smtp)) { - $this->smtp = new SMTP; - } - return $this->smtp; - } - - /** - * Send mail via SMTP. - * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. - * Uses the PHPMailerSMTP class by default. - * @see PHPMailer::getSMTPInstance() to use a different class. - * @param string $header The message headers - * @param string $body The message body - * @throws phpmailerException - * @uses SMTP - * @access protected - * @return boolean - */ - protected function smtpSend($header, $body) - { - $bad_rcpt = array(); - if (!$this->smtpConnect($this->SMTPOptions)) { - throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); - } - if ('' == $this->Sender) { - $smtp_from = $this->From; - } else { - $smtp_from = $this->Sender; - } - if (!$this->smtp->mail($smtp_from)) { - $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); - throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); - } - - // Attempt to send to all recipients - foreach (array($this->to, $this->cc, $this->bcc) as $togroup) { - foreach ($togroup as $to) { - if (!$this->smtp->recipient($to[0])) { - $error = $this->smtp->getError(); - $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']); - $isSent = false; - } else { - $isSent = true; - } - $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From); - } - } - - // Only send the DATA command if we have viable recipients - if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) { - throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL); - } - if ($this->SMTPKeepAlive) { - $this->smtp->reset(); - } else { - $this->smtp->quit(); - $this->smtp->close(); - } - //Create error message for any bad addresses - if (count($bad_rcpt) > 0) { - $errstr = ''; - foreach ($bad_rcpt as $bad) { - $errstr .= $bad['to'] . ': ' . $bad['error']; - } - throw new phpmailerException( - $this->lang('recipients_failed') . $errstr, - self::STOP_CONTINUE - ); - } - return true; - } - - /** - * Initiate a connection to an SMTP server. - * Returns false if the operation failed. - * @param array $options An array of options compatible with stream_context_create() - * @uses SMTP - * @access public - * @throws phpmailerException - * @return boolean - */ - public function smtpConnect($options = null) - { - if (is_null($this->smtp)) { - $this->smtp = $this->getSMTPInstance(); - } - - //If no options are provided, use whatever is set in the instance - if (is_null($options)) { - $options = $this->SMTPOptions; - } - - // Already connected? - if ($this->smtp->connected()) { - return true; - } - - $this->smtp->setTimeout($this->Timeout); - $this->smtp->setDebugLevel($this->SMTPDebug); - $this->smtp->setDebugOutput($this->Debugoutput); - $this->smtp->setVerp($this->do_verp); - $hosts = explode(';', $this->Host); - $lastexception = null; - - foreach ($hosts as $hostentry) { - $hostinfo = array(); - if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) { - // Not a valid host entry - continue; - } - // $hostinfo[2]: optional ssl or tls prefix - // $hostinfo[3]: the hostname - // $hostinfo[4]: optional port number - // The host string prefix can temporarily override the current setting for SMTPSecure - // If it's not specified, the default value is used - $prefix = ''; - $secure = $this->SMTPSecure; - $tls = ($this->SMTPSecure == 'tls'); - if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) { - $prefix = 'ssl://'; - $tls = false; // Can't have SSL and TLS at the same time - $secure = 'ssl'; - } elseif ($hostinfo[2] == 'tls') { - $tls = true; - // tls doesn't use a prefix - $secure = 'tls'; - } - //Do we need the OpenSSL extension? - $sslext = defined('OPENSSL_ALGO_SHA1'); - if ('tls' === $secure or 'ssl' === $secure) { - //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled - if (!$sslext) { - throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL); - } - } - $host = $hostinfo[3]; - $port = $this->Port; - $tport = (integer)$hostinfo[4]; - if ($tport > 0 and $tport < 65536) { - $port = $tport; - } - if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { - try { - if ($this->Helo) { - $hello = $this->Helo; - } else { - $hello = $this->serverHostname(); - } - $this->smtp->hello($hello); - //Automatically enable TLS encryption if: - // * it's not disabled - // * we have openssl extension - // * we are not already using SSL - // * the server offers STARTTLS - if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) { - $tls = true; - } - if ($tls) { - if (!$this->smtp->startTLS()) { - throw new phpmailerException($this->lang('connect_host')); - } - // We must resend EHLO after TLS negotiation - $this->smtp->hello($hello); - } - if ($this->SMTPAuth) { - if (!$this->smtp->authenticate( - $this->Username, - $this->Password, - $this->AuthType, - $this->Realm, - $this->Workstation - ) - ) { - throw new phpmailerException($this->lang('authenticate')); - } - } - return true; - } catch (phpmailerException $exc) { - $lastexception = $exc; - $this->edebug($exc->getMessage()); - // We must have connected, but then failed TLS or Auth, so close connection nicely - $this->smtp->quit(); - } - } - } - // If we get here, all connection attempts have failed, so close connection hard - $this->smtp->close(); - // As we've caught all exceptions, just report whatever the last one was - if ($this->exceptions and !is_null($lastexception)) { - throw $lastexception; - } - return false; - } - - /** - * Close the active SMTP session if one exists. - * @return void - */ - public function smtpClose() - { - if (is_a($this->smtp, 'SMTP')) { - if ($this->smtp->connected()) { - $this->smtp->quit(); - $this->smtp->close(); - } - } - } - - /** - * Set the language for error messages. - * Returns false if it cannot load the language file. - * The default language is English. - * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") - * @param string $lang_path Path to the language file directory, with trailing separator (slash) - * @return boolean - * @access public - */ - public function setLanguage($langcode = 'en', $lang_path = '') - { - // Define full set of translatable strings in English - $PHPMAILER_LANG = array( - 'authenticate' => 'SMTP Error: Could not authenticate.', - 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', - 'data_not_accepted' => 'SMTP Error: data not accepted.', - 'empty_message' => 'Message body empty', - 'encoding' => 'Unknown encoding: ', - 'execute' => 'Could not execute: ', - 'file_access' => 'Could not access file: ', - 'file_open' => 'File Error: Could not open file: ', - 'from_failed' => 'The following From address failed: ', - 'instantiate' => 'Could not instantiate mail function.', - 'invalid_address' => 'Invalid address: ', - 'mailer_not_supported' => ' mailer is not supported.', - 'provide_address' => 'You must provide at least one recipient email address.', - 'recipients_failed' => 'SMTP Error: The following recipients failed: ', - 'signing' => 'Signing Error: ', - 'smtp_connect_failed' => 'SMTP connect() failed.', - 'smtp_error' => 'SMTP server error: ', - 'variable_set' => 'Cannot set or reset variable: ', - 'extension_missing' => 'Extension missing: ' - ); - if (empty($lang_path)) { - // Calculate an absolute path so it can work if CWD is not here - $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR; - } - $foundlang = true; - $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php'; - // There is no English translation file - if ($langcode != 'en') { - // Make sure language file path is readable - if (!is_readable($lang_file)) { - $foundlang = false; - } else { - // Overwrite language-specific strings. - // This way we'll never have missing translation keys. - $foundlang = include $lang_file; - } - } - $this->language = $PHPMAILER_LANG; - return (boolean)$foundlang; // Returns false if language not found - } - - /** - * Get the array of strings for the current language. - * @return array - */ - public function getTranslations() - { - return $this->language; - } - - /** - * Create recipient headers. - * @access public - * @param string $type - * @param array $addr An array of recipient, - * where each recipient is a 2-element indexed array with element 0 containing an address - * and element 1 containing a name, like: - * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User')) - * @return string - */ - public function addrAppend($type, $addr) - { - $addresses = array(); - foreach ($addr as $address) { - $addresses[] = $this->addrFormat($address); - } - return $type . ': ' . implode(', ', $addresses) . $this->LE; - } - - /** - * Format an address for use in a message header. - * @access public - * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name - * like array('joe@example.com', 'Joe User') - * @return string - */ - public function addrFormat($addr) - { - if (empty($addr[1])) { // No name provided - return $this->secureHeader($addr[0]); - } else { - return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader( - $addr[0] - ) . '>'; - } - } - - /** - * Word-wrap message. - * For use with mailers that do not automatically perform wrapping - * and for quoted-printable encoded messages. - * Original written by philippe. - * @param string $message The message to wrap - * @param integer $length The line length to wrap to - * @param boolean $qp_mode Whether to run in Quoted-Printable mode - * @access public - * @return string - */ - public function wrapText($message, $length, $qp_mode = false) - { - if ($qp_mode) { - $soft_break = sprintf(' =%s', $this->LE); - } else { - $soft_break = $this->LE; - } - // If utf-8 encoding is used, we will need to make sure we don't - // split multibyte characters when we wrap - $is_utf8 = (strtolower($this->CharSet) == 'utf-8'); - $lelen = strlen($this->LE); - $crlflen = strlen(self::CRLF); - - $message = $this->fixEOL($message); - //Remove a trailing line break - if (substr($message, -$lelen) == $this->LE) { - $message = substr($message, 0, -$lelen); - } - - //Split message into lines - $lines = explode($this->LE, $message); - //Message will be rebuilt in here - $message = ''; - foreach ($lines as $line) { - $words = explode(' ', $line); - $buf = ''; - $firstword = true; - foreach ($words as $word) { - if ($qp_mode and (strlen($word) > $length)) { - $space_left = $length - strlen($buf) - $crlflen; - if (!$firstword) { - if ($space_left > 20) { - $len = $space_left; - if ($is_utf8) { - $len = $this->utf8CharBoundary($word, $len); - } elseif (substr($word, $len - 1, 1) == '=') { - $len--; - } elseif (substr($word, $len - 2, 1) == '=') { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = substr($word, $len); - $buf .= ' ' . $part; - $message .= $buf . sprintf('=%s', self::CRLF); - } else { - $message .= $buf . $soft_break; - } - $buf = ''; - } - while (strlen($word) > 0) { - if ($length <= 0) { - break; - } - $len = $length; - if ($is_utf8) { - $len = $this->utf8CharBoundary($word, $len); - } elseif (substr($word, $len - 1, 1) == '=') { - $len--; - } elseif (substr($word, $len - 2, 1) == '=') { - $len -= 2; - } - $part = substr($word, 0, $len); - $word = substr($word, $len); - - if (strlen($word) > 0) { - $message .= $part . sprintf('=%s', self::CRLF); - } else { - $buf = $part; - } - } - } else { - $buf_o = $buf; - if (!$firstword) { - $buf .= ' '; - } - $buf .= $word; - - if (strlen($buf) > $length and $buf_o != '') { - $message .= $buf_o . $soft_break; - $buf = $word; - } - } - $firstword = false; - } - $message .= $buf . self::CRLF; - } - - return $message; - } - - /** - * Find the last character boundary prior to $maxLength in a utf-8 - * quoted-printable encoded string. - * Original written by Colin Brown. - * @access public - * @param string $encodedText utf-8 QP text - * @param integer $maxLength Find the last character boundary prior to this length - * @return integer - */ - public function utf8CharBoundary($encodedText, $maxLength) - { - $foundSplitPos = false; - $lookBack = 3; - while (!$foundSplitPos) { - $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); - $encodedCharPos = strpos($lastChunk, '='); - if (false !== $encodedCharPos) { - // Found start of encoded character byte within $lookBack block. - // Check the encoded byte value (the 2 chars after the '=') - $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); - $dec = hexdec($hex); - if ($dec < 128) { - // Single byte character. - // If the encoded char was found at pos 0, it will fit - // otherwise reduce maxLength to start of the encoded char - if ($encodedCharPos > 0) { - $maxLength = $maxLength - ($lookBack - $encodedCharPos); - } - $foundSplitPos = true; - } elseif ($dec >= 192) { - // First byte of a multi byte character - // Reduce maxLength to split at start of character - $maxLength = $maxLength - ($lookBack - $encodedCharPos); - $foundSplitPos = true; - } elseif ($dec < 192) { - // Middle byte of a multi byte character, look further back - $lookBack += 3; - } - } else { - // No encoded character found - $foundSplitPos = true; - } - } - return $maxLength; - } - - /** - * Apply word wrapping to the message body. - * Wraps the message body to the number of chars set in the WordWrap property. - * You should only do this to plain-text bodies as wrapping HTML tags may break them. - * This is called automatically by createBody(), so you don't need to call it yourself. - * @access public - * @return void - */ - public function setWordWrap() - { - if ($this->WordWrap < 1) { - return; - } - - switch ($this->message_type) { - case 'alt': - case 'alt_inline': - case 'alt_attach': - case 'alt_inline_attach': - $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); - break; - default: - $this->Body = $this->wrapText($this->Body, $this->WordWrap); - break; - } - } - - /** - * Assemble message headers. - * @access public - * @return string The assembled headers - */ - public function createHeader() - { - $result = ''; - - if ($this->MessageDate == '') { - $this->MessageDate = self::rfcDate(); - } - $result .= $this->headerLine('Date', $this->MessageDate); - - // To be created automatically by mail() - if ($this->SingleTo) { - if ($this->Mailer != 'mail') { - foreach ($this->to as $toaddr) { - $this->SingleToArray[] = $this->addrFormat($toaddr); - } - } - } else { - if (count($this->to) > 0) { - if ($this->Mailer != 'mail') { - $result .= $this->addrAppend('To', $this->to); - } - } elseif (count($this->cc) == 0) { - $result .= $this->headerLine('To', 'undisclosed-recipients:;'); - } - } - - $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName))); - - // sendmail and mail() extract Cc from the header before sending - if (count($this->cc) > 0) { - $result .= $this->addrAppend('Cc', $this->cc); - } - - // sendmail and mail() extract Bcc from the header before sending - if (( - $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail' - ) - and count($this->bcc) > 0 - ) { - $result .= $this->addrAppend('Bcc', $this->bcc); - } - - if (count($this->ReplyTo) > 0) { - $result .= $this->addrAppend('Reply-To', $this->ReplyTo); - } - - // mail() sets the subject itself - if ($this->Mailer != 'mail') { - $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); - } - - if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) { - $this->lastMessageID = $this->MessageID; - } else { - $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); - } - $result .= $this->headerLine('Message-ID', $this->lastMessageID); - if (!is_null($this->Priority)) { - $result .= $this->headerLine('X-Priority', $this->Priority); - } - if ($this->XMailer == '') { - $result .= $this->headerLine( - 'X-Mailer', - 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer)' - ); - } else { - $myXmailer = trim($this->XMailer); - if ($myXmailer) { - $result .= $this->headerLine('X-Mailer', $myXmailer); - } - } - - if ($this->ConfirmReadingTo != '') { - $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); - } - - // Add custom headers - foreach ($this->CustomHeader as $header) { - $result .= $this->headerLine( - trim($header[0]), - $this->encodeHeader(trim($header[1])) - ); - } - if (!$this->sign_key_file) { - $result .= $this->headerLine('MIME-Version', '1.0'); - $result .= $this->getMailMIME(); - } - - return $result; - } - - /** - * Get the message MIME type headers. - * @access public - * @return string - */ - public function getMailMIME() - { - $result = ''; - $ismultipart = true; - switch ($this->message_type) { - case 'inline': - $result .= $this->headerLine('Content-Type', 'multipart/related;'); - $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); - break; - case 'attach': - case 'inline_attach': - case 'alt_attach': - case 'alt_inline_attach': - $result .= $this->headerLine('Content-Type', 'multipart/mixed;'); - $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); - break; - case 'alt': - case 'alt_inline': - $result .= $this->headerLine('Content-Type', 'multipart/alternative;'); - $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); - break; - default: - // Catches case 'plain': and case '': - $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); - $ismultipart = false; - break; - } - // RFC1341 part 5 says 7bit is assumed if not specified - if ($this->Encoding != '7bit') { - // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE - if ($ismultipart) { - if ($this->Encoding == '8bit') { - $result .= $this->headerLine('Content-Transfer-Encoding', '8bit'); - } - // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible - } else { - $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); - } - } - - if ($this->Mailer != 'mail') { - $result .= $this->LE; - } - - return $result; - } - - /** - * Returns the whole MIME message. - * Includes complete headers and body. - * Only valid post preSend(). - * @see PHPMailer::preSend() - * @access public - * @return string - */ - public function getSentMIMEMessage() - { - return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody; - } - - /** - * Assemble the message body. - * Returns an empty string on failure. - * @access public - * @throws phpmailerException - * @return string The assembled message body - */ - public function createBody() - { - $body = ''; - //Create unique IDs and preset boundaries - $this->uniqueid = md5(uniqid(time())); - $this->boundary[1] = 'b1_' . $this->uniqueid; - $this->boundary[2] = 'b2_' . $this->uniqueid; - $this->boundary[3] = 'b3_' . $this->uniqueid; - - if ($this->sign_key_file) { - $body .= $this->getMailMIME() . $this->LE; - } - - $this->setWordWrap(); - - $bodyEncoding = $this->Encoding; - $bodyCharSet = $this->CharSet; - //Can we do a 7-bit downgrade? - if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) { - $bodyEncoding = '7bit'; - //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit - $bodyCharSet = 'us-ascii'; - } - //If lines are too long, and we're not already using an encoding that will shorten them, - //change to quoted-printable transfer encoding for the body part only - if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) { - $bodyEncoding = 'quoted-printable'; - } - - $altBodyEncoding = $this->Encoding; - $altBodyCharSet = $this->CharSet; - //Can we do a 7-bit downgrade? - if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) { - $altBodyEncoding = '7bit'; - //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit - $altBodyCharSet = 'us-ascii'; - } - //If lines are too long, and we're not already using an encoding that will shorten them, - //change to quoted-printable transfer encoding for the alt body part only - if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) { - $altBodyEncoding = 'quoted-printable'; - } - //Use this as a preamble in all multipart message types - $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE; - switch ($this->message_type) { - case 'inline': - $body .= $mimepre; - $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->attachAll('inline', $this->boundary[1]); - break; - case 'attach': - $body .= $mimepre; - $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->attachAll('attachment', $this->boundary[1]); - break; - case 'inline_attach': - $body .= $mimepre; - $body .= $this->textLine('--' . $this->boundary[1]); - $body .= $this->headerLine('Content-Type', 'multipart/related;'); - $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); - $body .= $this->LE; - $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->attachAll('inline', $this->boundary[2]); - $body .= $this->LE; - $body .= $this->attachAll('attachment', $this->boundary[1]); - break; - case 'alt': - $body .= $mimepre; - $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding); - $body .= $this->encodeString($this->AltBody, $altBodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= $this->LE . $this->LE; - if (!empty($this->Ical)) { - $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', ''); - $body .= $this->encodeString($this->Ical, $this->Encoding); - $body .= $this->LE . $this->LE; - } - $body .= $this->endBoundary($this->boundary[1]); - break; - case 'alt_inline': - $body .= $mimepre; - $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding); - $body .= $this->encodeString($this->AltBody, $altBodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->textLine('--' . $this->boundary[1]); - $body .= $this->headerLine('Content-Type', 'multipart/related;'); - $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); - $body .= $this->LE; - $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->attachAll('inline', $this->boundary[2]); - $body .= $this->LE; - $body .= $this->endBoundary($this->boundary[1]); - break; - case 'alt_attach': - $body .= $mimepre; - $body .= $this->textLine('--' . $this->boundary[1]); - $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); - $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); - $body .= $this->LE; - $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding); - $body .= $this->encodeString($this->AltBody, $altBodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->endBoundary($this->boundary[2]); - $body .= $this->LE; - $body .= $this->attachAll('attachment', $this->boundary[1]); - break; - case 'alt_inline_attach': - $body .= $mimepre; - $body .= $this->textLine('--' . $this->boundary[1]); - $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); - $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); - $body .= $this->LE; - $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding); - $body .= $this->encodeString($this->AltBody, $altBodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->textLine('--' . $this->boundary[2]); - $body .= $this->headerLine('Content-Type', 'multipart/related;'); - $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"'); - $body .= $this->LE; - $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding); - $body .= $this->encodeString($this->Body, $bodyEncoding); - $body .= $this->LE . $this->LE; - $body .= $this->attachAll('inline', $this->boundary[3]); - $body .= $this->LE; - $body .= $this->endBoundary($this->boundary[2]); - $body .= $this->LE; - $body .= $this->attachAll('attachment', $this->boundary[1]); - break; - default: - // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types - //Reset the `Encoding` property in case we changed it for line length reasons - $this->Encoding = $bodyEncoding; - $body .= $this->encodeString($this->Body, $this->Encoding); - break; - } - - if ($this->isError()) { - $body = ''; - } elseif ($this->sign_key_file) { - try { - if (!defined('PKCS7_TEXT')) { - throw new phpmailerException($this->lang('extension_missing') . 'openssl'); - } - // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1 - $file = tempnam(sys_get_temp_dir(), 'mail'); - if (false === file_put_contents($file, $body)) { - throw new phpmailerException($this->lang('signing') . ' Could not write temp file'); - } - $signed = tempnam(sys_get_temp_dir(), 'signed'); - //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 - if (empty($this->sign_extracerts_file)) { - $sign = @openssl_pkcs7_sign( - $file, - $signed, - 'file://' . realpath($this->sign_cert_file), - array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), - null - ); - } else { - $sign = @openssl_pkcs7_sign( - $file, - $signed, - 'file://' . realpath($this->sign_cert_file), - array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), - null, - PKCS7_DETACHED, - $this->sign_extracerts_file - ); - } - if ($sign) { - @unlink($file); - $body = file_get_contents($signed); - @unlink($signed); - //The message returned by openssl contains both headers and body, so need to split them up - $parts = explode("\n\n", $body, 2); - $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE; - $body = $parts[1]; - } else { - @unlink($file); - @unlink($signed); - throw new phpmailerException($this->lang('signing') . openssl_error_string()); - } - } catch (phpmailerException $exc) { - $body = ''; - if ($this->exceptions) { - throw $exc; - } - } - } - return $body; - } - - /** - * Return the start of a message boundary. - * @access protected - * @param string $boundary - * @param string $charSet - * @param string $contentType - * @param string $encoding - * @return string - */ - protected function getBoundary($boundary, $charSet, $contentType, $encoding) - { - $result = ''; - if ($charSet == '') { - $charSet = $this->CharSet; - } - if ($contentType == '') { - $contentType = $this->ContentType; - } - if ($encoding == '') { - $encoding = $this->Encoding; - } - $result .= $this->textLine('--' . $boundary); - $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); - $result .= $this->LE; - // RFC1341 part 5 says 7bit is assumed if not specified - if ($encoding != '7bit') { - $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); - } - $result .= $this->LE; - - return $result; - } - - /** - * Return the end of a message boundary. - * @access protected - * @param string $boundary - * @return string - */ - protected function endBoundary($boundary) - { - return $this->LE . '--' . $boundary . '--' . $this->LE; - } - - /** - * Set the message type. - * PHPMailer only supports some preset message types, not arbitrary MIME structures. - * @access protected - * @return void - */ - protected function setMessageType() - { - $type = array(); - if ($this->alternativeExists()) { - $type[] = 'alt'; - } - if ($this->inlineImageExists()) { - $type[] = 'inline'; - } - if ($this->attachmentExists()) { - $type[] = 'attach'; - } - $this->message_type = implode('_', $type); - if ($this->message_type == '') { - //The 'plain' message_type refers to the message having a single body element, not that it is plain-text - $this->message_type = 'plain'; - } - } - - /** - * Format a header line. - * @access public - * @param string $name - * @param string $value - * @return string - */ - public function headerLine($name, $value) - { - return $name . ': ' . $value . $this->LE; - } - - /** - * Return a formatted mail line. - * @access public - * @param string $value - * @return string - */ - public function textLine($value) - { - return $value . $this->LE; - } - - /** - * Add an attachment from a path on the filesystem. - * Returns false if the file could not be found or read. - * @param string $path Path to the attachment. - * @param string $name Overrides the attachment name. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @param string $disposition Disposition to use - * @throws phpmailerException - * @return boolean - */ - public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') - { - try { - if (!@is_file($path)) { - throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE); - } - - // If a MIME type is not specified, try to work it out from the file name - if ($type == '') { - $type = self::filenameToType($path); - } - - $filename = basename($path); - if ($name == '') { - $name = $filename; - } - - $this->attachment[] = array( - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, // isStringAttachment - 6 => $disposition, - 7 => 0 - ); - - } catch (phpmailerException $exc) { - $this->setError($exc->getMessage()); - $this->edebug($exc->getMessage()); - if ($this->exceptions) { - throw $exc; - } - return false; - } - return true; - } - - /** - * Return the array of attachments. - * @return array - */ - public function getAttachments() - { - return $this->attachment; - } - - /** - * Attach all file, string, and binary attachments to the message. - * Returns an empty string on failure. - * @access protected - * @param string $disposition_type - * @param string $boundary - * @return string - */ - protected function attachAll($disposition_type, $boundary) - { - // Return text of body - $mime = array(); - $cidUniq = array(); - $incl = array(); - - // Add all attachments - foreach ($this->attachment as $attachment) { - // Check if it is a valid disposition_filter - if ($attachment[6] == $disposition_type) { - // Check for string attachment - $string = ''; - $path = ''; - $bString = $attachment[5]; - if ($bString) { - $string = $attachment[0]; - } else { - $path = $attachment[0]; - } - - $inclhash = md5(serialize($attachment)); - if (in_array($inclhash, $incl)) { - continue; - } - $incl[] = $inclhash; - $name = $attachment[2]; - $encoding = $attachment[3]; - $type = $attachment[4]; - $disposition = $attachment[6]; - $cid = $attachment[7]; - if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) { - continue; - } - $cidUniq[$cid] = true; - - $mime[] = sprintf('--%s%s', $boundary, $this->LE); - //Only include a filename property if we have one - if (!empty($name)) { - $mime[] = sprintf( - 'Content-Type: %s; name="%s"%s', - $type, - $this->encodeHeader($this->secureHeader($name)), - $this->LE - ); - } else { - $mime[] = sprintf( - 'Content-Type: %s%s', - $type, - $this->LE - ); - } - // RFC1341 part 5 says 7bit is assumed if not specified - if ($encoding != '7bit') { - $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE); - } - - if ($disposition == 'inline') { - $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE); - } - - // If a filename contains any of these chars, it should be quoted, - // but not otherwise: RFC2183 & RFC2045 5.1 - // Fixes a warning in IETF's msglint MIME checker - // Allow for bypassing the Content-Disposition header totally - if (!(empty($disposition))) { - $encoded_name = $this->encodeHeader($this->secureHeader($name)); - if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) { - $mime[] = sprintf( - 'Content-Disposition: %s; filename="%s"%s', - $disposition, - $encoded_name, - $this->LE . $this->LE - ); - } else { - if (!empty($encoded_name)) { - $mime[] = sprintf( - 'Content-Disposition: %s; filename=%s%s', - $disposition, - $encoded_name, - $this->LE . $this->LE - ); - } else { - $mime[] = sprintf( - 'Content-Disposition: %s%s', - $disposition, - $this->LE . $this->LE - ); - } - } - } else { - $mime[] = $this->LE; - } - - // Encode as string attachment - if ($bString) { - $mime[] = $this->encodeString($string, $encoding); - if ($this->isError()) { - return ''; - } - $mime[] = $this->LE . $this->LE; - } else { - $mime[] = $this->encodeFile($path, $encoding); - if ($this->isError()) { - return ''; - } - $mime[] = $this->LE . $this->LE; - } - } - } - - $mime[] = sprintf('--%s--%s', $boundary, $this->LE); - - return implode('', $mime); - } - - /** - * Encode a file attachment in requested format. - * Returns an empty string on failure. - * @param string $path The full path to the file - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * @throws phpmailerException - * @access protected - * @return string - */ - protected function encodeFile($path, $encoding = 'base64') - { - try { - if (!is_readable($path)) { - throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE); - } - $magic_quotes = get_magic_quotes_runtime(); - if ($magic_quotes) { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - set_magic_quotes_runtime(false); - } else { - //Doesn't exist in PHP 5.4, but we don't need to check because - //get_magic_quotes_runtime always returns false in 5.4+ - //so it will never get here - ini_set('magic_quotes_runtime', false); - } - } - $file_buffer = file_get_contents($path); - $file_buffer = $this->encodeString($file_buffer, $encoding); - if ($magic_quotes) { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - set_magic_quotes_runtime($magic_quotes); - } else { - ini_set('magic_quotes_runtime', $magic_quotes); - } - } - return $file_buffer; - } catch (Exception $exc) { - $this->setError($exc->getMessage()); - return ''; - } - } - - /** - * Encode a string in requested format. - * Returns an empty string on failure. - * @param string $str The text to encode - * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' - * @access public - * @return string - */ - public function encodeString($str, $encoding = 'base64') - { - $encoded = ''; - switch (strtolower($encoding)) { - case 'base64': - $encoded = chunk_split(base64_encode($str), 76, $this->LE); - break; - case '7bit': - case '8bit': - $encoded = $this->fixEOL($str); - // Make sure it ends with a line break - if (substr($encoded, -(strlen($this->LE))) != $this->LE) { - $encoded .= $this->LE; - } - break; - case 'binary': - $encoded = $str; - break; - case 'quoted-printable': - $encoded = $this->encodeQP($str); - break; - default: - $this->setError($this->lang('encoding') . $encoding); - break; - } - return $encoded; - } - - /** - * Encode a header string optimally. - * Picks shortest of Q, B, quoted-printable or none. - * @access public - * @param string $str - * @param string $position - * @return string - */ - public function encodeHeader($str, $position = 'text') - { - $matchcount = 0; - switch (strtolower($position)) { - case 'phrase': - if (!preg_match('/[\200-\377]/', $str)) { - // Can't use addslashes as we don't know the value of magic_quotes_sybase - $encoded = addcslashes($str, "\0..\37\177\\\""); - if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { - return ($encoded); - } else { - return ("\"$encoded\""); - } - } - $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); - break; - /** @noinspection PhpMissingBreakStatementInspection */ - case 'comment': - $matchcount = preg_match_all('/[()"]/', $str, $matches); - // Intentional fall-through - case 'text': - default: - $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); - break; - } - - //There are no chars that need encoding - if ($matchcount == 0) { - return ($str); - } - - $maxlen = 75 - 7 - strlen($this->CharSet); - // Try to select the encoding which should produce the shortest output - if ($matchcount > strlen($str) / 3) { - // More than a third of the content will need encoding, so B encoding will be most efficient - $encoding = 'B'; - if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) { - // Use a custom function which correctly encodes and wraps long - // multibyte strings without breaking lines within a character - $encoded = $this->base64EncodeWrapMB($str, "\n"); - } else { - $encoded = base64_encode($str); - $maxlen -= $maxlen % 4; - $encoded = trim(chunk_split($encoded, $maxlen, "\n")); - } - } else { - $encoding = 'Q'; - $encoded = $this->encodeQ($str, $position); - $encoded = $this->wrapText($encoded, $maxlen, true); - $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded)); - } - - $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded); - $encoded = trim(str_replace("\n", $this->LE, $encoded)); - - return $encoded; - } - - /** - * Check if a string contains multi-byte characters. - * @access public - * @param string $str multi-byte text to wrap encode - * @return boolean - */ - public function hasMultiBytes($str) - { - if (function_exists('mb_strlen')) { - return (strlen($str) > mb_strlen($str, $this->CharSet)); - } else { // Assume no multibytes (we can't handle without mbstring functions anyway) - return false; - } - } - - /** - * Does a string contain any 8-bit chars (in any charset)? - * @param string $text - * @return boolean - */ - public function has8bitChars($text) - { - return (boolean)preg_match('/[\x80-\xFF]/', $text); - } - - /** - * Encode and wrap long multibyte strings for mail headers - * without breaking lines within a character. - * Adapted from a function by paravoid - * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 - * @access public - * @param string $str multi-byte text to wrap encode - * @param string $linebreak string to use as linefeed/end-of-line - * @return string - */ - public function base64EncodeWrapMB($str, $linebreak = null) - { - $start = '=?' . $this->CharSet . '?B?'; - $end = '?='; - $encoded = ''; - if ($linebreak === null) { - $linebreak = $this->LE; - } - - $mb_length = mb_strlen($str, $this->CharSet); - // Each line must have length <= 75, including $start and $end - $length = 75 - strlen($start) - strlen($end); - // Average multi-byte ratio - $ratio = $mb_length / strlen($str); - // Base64 has a 4:3 ratio - $avgLength = floor($length * $ratio * .75); - - for ($i = 0; $i < $mb_length; $i += $offset) { - $lookBack = 0; - do { - $offset = $avgLength - $lookBack; - $chunk = mb_substr($str, $i, $offset, $this->CharSet); - $chunk = base64_encode($chunk); - $lookBack++; - } while (strlen($chunk) > $length); - $encoded .= $chunk . $linebreak; - } - - // Chomp the last linefeed - $encoded = substr($encoded, 0, -strlen($linebreak)); - return $encoded; - } - - /** - * Encode a string in quoted-printable format. - * According to RFC2045 section 6.7. - * @access public - * @param string $string The text to encode - * @param integer $line_max Number of chars allowed on a line before wrapping - * @return string - * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment - */ - public function encodeQP($string, $line_max = 76) - { - // Use native function if it's available (>= PHP5.3) - if (function_exists('quoted_printable_encode')) { - return quoted_printable_encode($string); - } - // Fall back to a pure PHP implementation - $string = str_replace( - array('%20', '%0D%0A.', '%0D%0A', '%'), - array(' ', "\r\n=2E", "\r\n", '='), - rawurlencode($string) - ); - return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string); - } - - /** - * Backward compatibility wrapper for an old QP encoding function that was removed. - * @see PHPMailer::encodeQP() - * @access public - * @param string $string - * @param integer $line_max - * @param boolean $space_conv - * @return string - * @deprecated Use encodeQP instead. - */ - public function encodeQPphp( - $string, - $line_max = 76, - /** @noinspection PhpUnusedParameterInspection */ $space_conv = false - ) { - return $this->encodeQP($string, $line_max); - } - - /** - * Encode a string using Q encoding. - * @link http://tools.ietf.org/html/rfc2047 - * @param string $str the text to encode - * @param string $position Where the text is going to be used, see the RFC for what that means - * @access public - * @return string - */ - public function encodeQ($str, $position = 'text') - { - // There should not be any EOL in the string - $pattern = ''; - $encoded = str_replace(array("\r", "\n"), '', $str); - switch (strtolower($position)) { - case 'phrase': - // RFC 2047 section 5.3 - $pattern = '^A-Za-z0-9!*+\/ -'; - break; - /** @noinspection PhpMissingBreakStatementInspection */ - case 'comment': - // RFC 2047 section 5.2 - $pattern = '\(\)"'; - // intentional fall-through - // for this reason we build the $pattern without including delimiters and [] - case 'text': - default: - // RFC 2047 section 5.1 - // Replace every high ascii, control, =, ? and _ characters - $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; - break; - } - $matches = array(); - if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { - // If the string contains an '=', make sure it's the first thing we replace - // so as to avoid double-encoding - $eqkey = array_search('=', $matches[0]); - if (false !== $eqkey) { - unset($matches[0][$eqkey]); - array_unshift($matches[0], '='); - } - foreach (array_unique($matches[0]) as $char) { - $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); - } - } - // Replace every spaces to _ (more readable than =20) - return str_replace(' ', '_', $encoded); - } - - /** - * Add a string or binary attachment (non-filesystem). - * This method can be used to attach ascii or binary data, - * such as a BLOB record from a database. - * @param string $string String attachment data. - * @param string $filename Name of the attachment. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File extension (MIME) type. - * @param string $disposition Disposition to use - * @return void - */ - public function addStringAttachment( - $string, - $filename, - $encoding = 'base64', - $type = '', - $disposition = 'attachment' - ) { - // If a MIME type is not specified, try to work it out from the file name - if ($type == '') { - $type = self::filenameToType($filename); - } - // Append to $attachment array - $this->attachment[] = array( - 0 => $string, - 1 => $filename, - 2 => basename($filename), - 3 => $encoding, - 4 => $type, - 5 => true, // isStringAttachment - 6 => $disposition, - 7 => 0 - ); - } - - /** - * Add an embedded (inline) attachment from a file. - * This can include images, sounds, and just about any other document type. - * These differ from 'regular' attachments in that they are intended to be - * displayed inline with the message, not just attached for download. - * This is used in HTML messages that embed the images - * the HTML refers to using the $cid value. - * @param string $path Path to the attachment. - * @param string $cid Content ID of the attachment; Use this to reference - * the content when using an embedded image in HTML. - * @param string $name Overrides the attachment name. - * @param string $encoding File encoding (see $Encoding). - * @param string $type File MIME type. - * @param string $disposition Disposition to use - * @return boolean True on successfully adding an attachment - */ - public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') - { - if (!@is_file($path)) { - $this->setError($this->lang('file_access') . $path); - return false; - } - - // If a MIME type is not specified, try to work it out from the file name - if ($type == '') { - $type = self::filenameToType($path); - } - - $filename = basename($path); - if ($name == '') { - $name = $filename; - } - - // Append to $attachment array - $this->attachment[] = array( - 0 => $path, - 1 => $filename, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => false, // isStringAttachment - 6 => $disposition, - 7 => $cid - ); - return true; - } - - /** - * Add an embedded stringified attachment. - * This can include images, sounds, and just about any other document type. - * Be sure to set the $type to an image type for images: - * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. - * @param string $string The attachment binary data. - * @param string $cid Content ID of the attachment; Use this to reference - * the content when using an embedded image in HTML. - * @param string $name - * @param string $encoding File encoding (see $Encoding). - * @param string $type MIME type. - * @param string $disposition Disposition to use - * @return boolean True on successfully adding an attachment - */ - public function addStringEmbeddedImage( - $string, - $cid, - $name = '', - $encoding = 'base64', - $type = '', - $disposition = 'inline' - ) { - // If a MIME type is not specified, try to work it out from the name - if ($type == '' and !empty($name)) { - $type = self::filenameToType($name); - } - - // Append to $attachment array - $this->attachment[] = array( - 0 => $string, - 1 => $name, - 2 => $name, - 3 => $encoding, - 4 => $type, - 5 => true, // isStringAttachment - 6 => $disposition, - 7 => $cid - ); - return true; - } - - /** - * Check if an inline attachment is present. - * @access public - * @return boolean - */ - public function inlineImageExists() - { - foreach ($this->attachment as $attachment) { - if ($attachment[6] == 'inline') { - return true; - } - } - return false; - } - - /** - * Check if an attachment (non-inline) is present. - * @return boolean - */ - public function attachmentExists() - { - foreach ($this->attachment as $attachment) { - if ($attachment[6] == 'attachment') { - return true; - } - } - return false; - } - - /** - * Check if this message has an alternative body set. - * @return boolean - */ - public function alternativeExists() - { - return !empty($this->AltBody); - } - - /** - * Clear queued addresses of given kind. - * @access protected - * @param string $kind 'to', 'cc', or 'bcc' - * @return void - */ - public function clearQueuedAddresses($kind) - { - $RecipientsQueue = $this->RecipientsQueue; - foreach ($RecipientsQueue as $address => $params) { - if ($params[0] == $kind) { - unset($this->RecipientsQueue[$address]); - } - } - } - - /** - * Clear all To recipients. - * @return void - */ - public function clearAddresses() - { - foreach ($this->to as $to) { - unset($this->all_recipients[strtolower($to[0])]); - } - $this->to = array(); - $this->clearQueuedAddresses('to'); - } - - /** - * Clear all CC recipients. - * @return void - */ - public function clearCCs() - { - foreach ($this->cc as $cc) { - unset($this->all_recipients[strtolower($cc[0])]); - } - $this->cc = array(); - $this->clearQueuedAddresses('cc'); - } - - /** - * Clear all BCC recipients. - * @return void - */ - public function clearBCCs() - { - foreach ($this->bcc as $bcc) { - unset($this->all_recipients[strtolower($bcc[0])]); - } - $this->bcc = array(); - $this->clearQueuedAddresses('bcc'); - } - - /** - * Clear all ReplyTo recipients. - * @return void - */ - public function clearReplyTos() - { - $this->ReplyTo = array(); - $this->ReplyToQueue = array(); - } - - /** - * Clear all recipient types. - * @return void - */ - public function clearAllRecipients() - { - $this->to = array(); - $this->cc = array(); - $this->bcc = array(); - $this->all_recipients = array(); - $this->RecipientsQueue = array(); - } - - /** - * Clear all filesystem, string, and binary attachments. - * @return void - */ - public function clearAttachments() - { - $this->attachment = array(); - } - - /** - * Clear all custom headers. - * @return void - */ - public function clearCustomHeaders() - { - $this->CustomHeader = array(); - } - - /** - * Add an error message to the error container. - * @access protected - * @param string $msg - * @return void - */ - protected function setError($msg) - { - $this->error_count++; - if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { - $lasterror = $this->smtp->getError(); - if (!empty($lasterror['error'])) { - $msg .= $this->lang('smtp_error') . $lasterror['error']; - if (!empty($lasterror['detail'])) { - $msg .= ' Detail: '. $lasterror['detail']; - } - if (!empty($lasterror['smtp_code'])) { - $msg .= ' SMTP code: ' . $lasterror['smtp_code']; - } - if (!empty($lasterror['smtp_code_ex'])) { - $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex']; - } - } - } - $this->ErrorInfo = $msg; - } - - /** - * Return an RFC 822 formatted date. - * @access public - * @return string - * @static - */ - public static function rfcDate() - { - // Set the time zone to whatever the default is to avoid 500 errors - // Will default to UTC if it's not set properly in php.ini - date_default_timezone_set(@date_default_timezone_get()); - return date('D, j M Y H:i:s O'); - } - - /** - * Get the server hostname. - * Returns 'localhost.localdomain' if unknown. - * @access protected - * @return string - */ - protected function serverHostname() - { - $result = 'localhost.localdomain'; - if (!empty($this->Hostname)) { - $result = $this->Hostname; - } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) { - $result = $_SERVER['SERVER_NAME']; - } elseif (function_exists('gethostname') && gethostname() !== false) { - $result = gethostname(); - } elseif (php_uname('n') !== false) { - $result = php_uname('n'); - } - return $result; - } - - /** - * Get an error message in the current language. - * @access protected - * @param string $key - * @return string - */ - protected function lang($key) - { - if (count($this->language) < 1) { - $this->setLanguage('en'); // set the default language - } - - if (array_key_exists($key, $this->language)) { - if ($key == 'smtp_connect_failed') { - //Include a link to troubleshooting docs on SMTP connection failure - //this is by far the biggest cause of support questions - //but it's usually not PHPMailer's fault. - return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; - } - return $this->language[$key]; - } else { - //Return the key as a fallback - return $key; - } - } - - /** - * Check if an error occurred. - * @access public - * @return boolean True if an error did occur. - */ - public function isError() - { - return ($this->error_count > 0); - } - - /** - * Ensure consistent line endings in a string. - * Changes every end of line from CRLF, CR or LF to $this->LE. - * @access public - * @param string $str String to fixEOL - * @return string - */ - public function fixEOL($str) - { - // Normalise to \n - $nstr = str_replace(array("\r\n", "\r"), "\n", $str); - // Now convert LE as needed - if ($this->LE !== "\n") { - $nstr = str_replace("\n", $this->LE, $nstr); - } - return $nstr; - } - - /** - * Add a custom header. - * $name value can be overloaded to contain - * both header name and value (name:value) - * @access public - * @param string $name Custom header name - * @param string $value Header value - * @return void - */ - public function addCustomHeader($name, $value = null) - { - if ($value === null) { - // Value passed in as name:value - $this->CustomHeader[] = explode(':', $name, 2); - } else { - $this->CustomHeader[] = array($name, $value); - } - } - - /** - * Returns all custom headers. - * @return array - */ - public function getCustomHeaders() - { - return $this->CustomHeader; - } - - /** - * Create a message from an HTML string. - * Automatically makes modifications for inline images and backgrounds - * and creates a plain-text version by converting the HTML. - * Overwrites any existing values in $this->Body and $this->AltBody - * @access public - * @param string $message HTML message string - * @param string $basedir baseline directory for path - * @param boolean|callable $advanced Whether to use the internal HTML to text converter - * or your own custom converter @see PHPMailer::html2text() - * @return string $message - */ - public function msgHTML($message, $basedir = '', $advanced = false) - { - preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images); - if (array_key_exists(2, $images)) { - foreach ($images[2] as $imgindex => $url) { - // Convert data URIs into embedded images - if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) { - $data = substr($url, strpos($url, ',')); - if ($match[2]) { - $data = base64_decode($data); - } else { - $data = rawurldecode($data); - } - $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 - if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) { - $message = str_replace( - $images[0][$imgindex], - $images[1][$imgindex] . '="cid:' . $cid . '"', - $message - ); - } - } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) { - // Do not change urls for absolute images (thanks to corvuscorax) - // Do not change urls that are already inline images - $filename = basename($url); - $directory = dirname($url); - if ($directory == '.') { - $directory = ''; - } - $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 - if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { - $basedir .= '/'; - } - if (strlen($directory) > 1 && substr($directory, -1) != '/') { - $directory .= '/'; - } - if ($this->addEmbeddedImage( - $basedir . $directory . $filename, - $cid, - $filename, - 'base64', - self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION)) - ) - ) { - $message = preg_replace( - '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', - $images[1][$imgindex] . '="cid:' . $cid . '"', - $message - ); - } - } - } - } - $this->isHTML(true); - // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better - $this->Body = $this->normalizeBreaks($message); - $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced)); - if (!$this->alternativeExists()) { - $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . - self::CRLF . self::CRLF; - } - return $this->Body; - } - - /** - * Convert an HTML string into plain text. - * This is used by msgHTML(). - * Note - older versions of this function used a bundled advanced converter - * which was been removed for license reasons in #232 - * Example usage: - * - * // Use default conversion - * $plain = $mail->html2text($html); - * // Use your own custom converter - * $plain = $mail->html2text($html, function($html) { - * $converter = new MyHtml2text($html); - * return $converter->get_text(); - * }); - * - * @param string $html The HTML text to convert - * @param boolean|callable $advanced Any boolean value to use the internal converter, - * or provide your own callable for custom conversion. - * @return string - */ - public function html2text($html, $advanced = false) - { - if (is_callable($advanced)) { - return call_user_func($advanced, $html); - } - return html_entity_decode( - trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), - ENT_QUOTES, - $this->CharSet - ); - } - - /** - * Get the MIME type for a file extension. - * @param string $ext File extension - * @access public - * @return string MIME type of file. - * @static - */ - public static function _mime_types($ext = '') - { - $mimes = array( - 'xl' => 'application/excel', - 'js' => 'application/javascript', - 'hqx' => 'application/mac-binhex40', - 'cpt' => 'application/mac-compactpro', - 'bin' => 'application/macbinary', - 'doc' => 'application/msword', - 'word' => 'application/msword', - 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', - 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', - 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', - 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', - 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', - 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', - 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', - 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', - 'class' => 'application/octet-stream', - 'dll' => 'application/octet-stream', - 'dms' => 'application/octet-stream', - 'exe' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'psd' => 'application/octet-stream', - 'sea' => 'application/octet-stream', - 'so' => 'application/octet-stream', - 'oda' => 'application/oda', - 'pdf' => 'application/pdf', - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => 'application/vnd.ms-excel', - 'ppt' => 'application/vnd.ms-powerpoint', - 'wbxml' => 'application/vnd.wap.wbxml', - 'wmlc' => 'application/vnd.wap.wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'php3' => 'application/x-httpd-php', - 'php4' => 'application/x-httpd-php', - 'php' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - 'swf' => 'application/x-shockwave-flash', - 'sit' => 'application/x-stuffit', - 'tar' => 'application/x-tar', - 'tgz' => 'application/x-tar', - 'xht' => 'application/xhtml+xml', - 'xhtml' => 'application/xhtml+xml', - 'zip' => 'application/zip', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mp2' => 'audio/mpeg', - 'mp3' => 'audio/mpeg', - 'mpga' => 'audio/mpeg', - 'aif' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'ram' => 'audio/x-pn-realaudio', - 'rm' => 'audio/x-pn-realaudio', - 'rpm' => 'audio/x-pn-realaudio-plugin', - 'ra' => 'audio/x-realaudio', - 'wav' => 'audio/x-wav', - 'bmp' => 'image/bmp', - 'gif' => 'image/gif', - 'jpeg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'png' => 'image/png', - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'eml' => 'message/rfc822', - 'css' => 'text/css', - 'html' => 'text/html', - 'htm' => 'text/html', - 'shtml' => 'text/html', - 'log' => 'text/plain', - 'text' => 'text/plain', - 'txt' => 'text/plain', - 'rtx' => 'text/richtext', - 'rtf' => 'text/rtf', - 'vcf' => 'text/vcard', - 'vcard' => 'text/vcard', - 'xml' => 'text/xml', - 'xsl' => 'text/xml', - 'mpeg' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mov' => 'video/quicktime', - 'qt' => 'video/quicktime', - 'rv' => 'video/vnd.rn-realvideo', - 'avi' => 'video/x-msvideo', - 'movie' => 'video/x-sgi-movie' - ); - if (array_key_exists(strtolower($ext), $mimes)) { - return $mimes[strtolower($ext)]; - } - return 'application/octet-stream'; - } - - /** - * Map a file name to a MIME type. - * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. - * @param string $filename A file name or full path, does not need to exist as a file - * @return string - * @static - */ - public static function filenameToType($filename) - { - // In case the path is a URL, strip any query string before getting extension - $qpos = strpos($filename, '?'); - if (false !== $qpos) { - $filename = substr($filename, 0, $qpos); - } - $pathinfo = self::mb_pathinfo($filename); - return self::_mime_types($pathinfo['extension']); - } - - /** - * Multi-byte-safe pathinfo replacement. - * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. - * Works similarly to the one in PHP >= 5.2.0 - * @link http://www.php.net/manual/en/function.pathinfo.php#107461 - * @param string $path A filename or path, does not need to exist as a file - * @param integer|string $options Either a PATHINFO_* constant, - * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 - * @return string|array - * @static - */ - public static function mb_pathinfo($path, $options = null) - { - $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''); - $pathinfo = array(); - if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) { - if (array_key_exists(1, $pathinfo)) { - $ret['dirname'] = $pathinfo[1]; - } - if (array_key_exists(2, $pathinfo)) { - $ret['basename'] = $pathinfo[2]; - } - if (array_key_exists(5, $pathinfo)) { - $ret['extension'] = $pathinfo[5]; - } - if (array_key_exists(3, $pathinfo)) { - $ret['filename'] = $pathinfo[3]; - } - } - switch ($options) { - case PATHINFO_DIRNAME: - case 'dirname': - return $ret['dirname']; - case PATHINFO_BASENAME: - case 'basename': - return $ret['basename']; - case PATHINFO_EXTENSION: - case 'extension': - return $ret['extension']; - case PATHINFO_FILENAME: - case 'filename': - return $ret['filename']; - default: - return $ret; - } - } - - /** - * Set or reset instance properties. - * You should avoid this function - it's more verbose, less efficient, more error-prone and - * harder to debug than setting properties directly. - * Usage Example: - * `$mail->set('SMTPSecure', 'tls');` - * is the same as: - * `$mail->SMTPSecure = 'tls';` - * @access public - * @param string $name The property name to set - * @param mixed $value The value to set the property to - * @return boolean - * @TODO Should this not be using the __set() magic function? - */ - public function set($name, $value = '') - { - if (property_exists($this, $name)) { - $this->$name = $value; - return true; - } else { - $this->setError($this->lang('variable_set') . $name); - return false; - } - } - - /** - * Strip newlines to prevent header injection. - * @access public - * @param string $str - * @return string - */ - public function secureHeader($str) - { - return trim(str_replace(array("\r", "\n"), '', $str)); - } - - /** - * Normalize line breaks in a string. - * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. - * Defaults to CRLF (for message bodies) and preserves consecutive breaks. - * @param string $text - * @param string $breaktype What kind of line break to use, defaults to CRLF - * @return string - * @access public - * @static - */ - public static function normalizeBreaks($text, $breaktype = "\r\n") - { - return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); - } - - /** - * Set the public and private key files and password for S/MIME signing. - * @access public - * @param string $cert_filename - * @param string $key_filename - * @param string $key_pass Password for private key - * @param string $extracerts_filename Optional path to chain certificate - */ - public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') - { - $this->sign_cert_file = $cert_filename; - $this->sign_key_file = $key_filename; - $this->sign_key_pass = $key_pass; - $this->sign_extracerts_file = $extracerts_filename; - } - - /** - * Quoted-Printable-encode a DKIM header. - * @access public - * @param string $txt - * @return string - */ - public function DKIM_QP($txt) - { - $line = ''; - for ($i = 0; $i < strlen($txt); $i++) { - $ord = ord($txt[$i]); - if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { - $line .= $txt[$i]; - } else { - $line .= '=' . sprintf('%02X', $ord); - } - } - return $line; - } - - /** - * Generate a DKIM signature. - * @access public - * @param string $signHeader - * @throws phpmailerException - * @return string - */ - public function DKIM_Sign($signHeader) - { - if (!defined('PKCS7_TEXT')) { - if ($this->exceptions) { - throw new phpmailerException($this->lang('extension_missing') . 'openssl'); - } - return ''; - } - $privKeyStr = file_get_contents($this->DKIM_private); - if ($this->DKIM_passphrase != '') { - $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); - } else { - $privKey = openssl_pkey_get_private($privKeyStr); - } - if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { //sha1WithRSAEncryption - openssl_pkey_free($privKey); - return base64_encode($signature); - } - openssl_pkey_free($privKey); - return ''; - } - - /** - * Generate a DKIM canonicalization header. - * @access public - * @param string $signHeader Header - * @return string - */ - public function DKIM_HeaderC($signHeader) - { - $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader); - $lines = explode("\r\n", $signHeader); - foreach ($lines as $key => $line) { - list($heading, $value) = explode(':', $line, 2); - $heading = strtolower($heading); - $value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces - $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value - } - $signHeader = implode("\r\n", $lines); - return $signHeader; - } - - /** - * Generate a DKIM canonicalization body. - * @access public - * @param string $body Message Body - * @return string - */ - public function DKIM_BodyC($body) - { - if ($body == '') { - return "\r\n"; - } - // stabilize line endings - $body = str_replace("\r\n", "\n", $body); - $body = str_replace("\n", "\r\n", $body); - // END stabilize line endings - while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { - $body = substr($body, 0, strlen($body) - 2); - } - return $body; - } - - /** - * Create the DKIM header and body in a new message header. - * @access public - * @param string $headers_line Header lines - * @param string $subject Subject - * @param string $body Body - * @return string - */ - public function DKIM_Add($headers_line, $subject, $body) - { - $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms - $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body - $DKIMquery = 'dns/txt'; // Query method - $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) - $subject_header = "Subject: $subject"; - $headers = explode($this->LE, $headers_line); - $from_header = ''; - $to_header = ''; - $date_header = ''; - $current = ''; - foreach ($headers as $header) { - if (strpos($header, 'From:') === 0) { - $from_header = $header; - $current = 'from_header'; - } elseif (strpos($header, 'To:') === 0) { - $to_header = $header; - $current = 'to_header'; - } elseif (strpos($header, 'Date:') === 0) { - $date_header = $header; - $current = 'date_header'; - } else { - if (!empty($$current) && strpos($header, ' =?') === 0) { - $$current .= $header; - } else { - $current = ''; - } - } - } - $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); - $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); - $date = str_replace('|', '=7C', $this->DKIM_QP($date_header)); - $subject = str_replace( - '|', - '=7C', - $this->DKIM_QP($subject_header) - ); // Copied header fields (dkim-quoted-printable) - $body = $this->DKIM_BodyC($body); - $DKIMlen = strlen($body); // Length of body - $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body - if ('' == $this->DKIM_identity) { - $ident = ''; - } else { - $ident = ' i=' . $this->DKIM_identity . ';'; - } - $dkimhdrs = 'DKIM-Signature: v=1; a=' . - $DKIMsignatureType . '; q=' . - $DKIMquery . '; l=' . - $DKIMlen . '; s=' . - $this->DKIM_selector . - ";\r\n" . - "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" . - "\th=From:To:Date:Subject;\r\n" . - "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" . - "\tz=$from\r\n" . - "\t|$to\r\n" . - "\t|$date\r\n" . - "\t|$subject;\r\n" . - "\tbh=" . $DKIMb64 . ";\r\n" . - "\tb="; - $toSign = $this->DKIM_HeaderC( - $from_header . "\r\n" . - $to_header . "\r\n" . - $date_header . "\r\n" . - $subject_header . "\r\n" . - $dkimhdrs - ); - $signed = $this->DKIM_Sign($toSign); - return $dkimhdrs . $signed . "\r\n"; - } - - /** - * Detect if a string contains a line longer than the maximum line length allowed. - * @param string $str - * @return boolean - * @static - */ - public static function hasLineLongerThanMax($str) - { - //+2 to include CRLF line break for a 1000 total - return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str); - } - - /** - * Allows for public read access to 'to' property. - * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * @access public - * @return array - */ - public function getToAddresses() - { - return $this->to; - } - - /** - * Allows for public read access to 'cc' property. - * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * @access public - * @return array - */ - public function getCcAddresses() - { - return $this->cc; - } - - /** - * Allows for public read access to 'bcc' property. - * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * @access public - * @return array - */ - public function getBccAddresses() - { - return $this->bcc; - } - - /** - * Allows for public read access to 'ReplyTo' property. - * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * @access public - * @return array - */ - public function getReplyToAddresses() - { - return $this->ReplyTo; - } - - /** - * Allows for public read access to 'all_recipients' property. - * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. - * @access public - * @return array - */ - public function getAllRecipientAddresses() - { - return $this->all_recipients; - } - - /** - * Perform a callback. - * @param boolean $isSent - * @param array $to - * @param array $cc - * @param array $bcc - * @param string $subject - * @param string $body - * @param string $from - */ - protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from) - { - if (!empty($this->action_function) && is_callable($this->action_function)) { - $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); - call_user_func_array($this->action_function, $params); - } - } + /** + * The PHPMailer Version number. + * @var string + */ + public $Version = '5.2.21'; + + /** + * Email priority. + * Options: null (default), 1 = High, 3 = Normal, 5 = low. + * When null, the header is not set at all. + * @var integer + */ + public $Priority = null; + + /** + * The character set of the message. + * @var string + */ + public $CharSet = 'iso-8859-1'; + + /** + * The MIME Content-type of the message. + * @var string + */ + public $ContentType = 'text/plain'; + + /** + * The message encoding. + * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". + * @var string + */ + public $Encoding = '8bit'; + + /** + * Holds the most recent mailer error message. + * @var string + */ + public $ErrorInfo = ''; + + /** + * The From email address for the message. + * @var string + */ + public $From = 'root@localhost'; + + /** + * The From name of the message. + * @var string + */ + public $FromName = 'Root User'; + + /** + * The Sender email (Return-Path) of the message. + * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. + * @var string + */ + public $Sender = ''; + + /** + * The Return-Path of the message. + * If empty, it will be set to either From or Sender. + * @var string + * @deprecated Email senders should never set a return-path header; + * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything. + * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference + */ + public $ReturnPath = ''; + + /** + * The Subject of the message. + * @var string + */ + public $Subject = ''; + + /** + * An HTML or plain text message body. + * If HTML then call isHTML(true). + * @var string + */ + public $Body = ''; + + /** + * The plain-text message body. + * This body can be read by mail clients that do not have HTML email + * capability such as mutt & Eudora. + * Clients that can read HTML will view the normal Body. + * @var string + */ + public $AltBody = ''; + + /** + * An iCal message part body. + * Only supported in simple alt or alt_inline message types + * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator + * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/ + * @link http://kigkonsult.se/iCalcreator/ + * @var string + */ + public $Ical = ''; + + /** + * The complete compiled MIME message body. + * @access protected + * @var string + */ + protected $MIMEBody = ''; + + /** + * The complete compiled MIME message headers. + * @var string + * @access protected + */ + protected $MIMEHeader = ''; + + /** + * Extra headers that createHeader() doesn't fold in. + * @var string + * @access protected + */ + protected $mailHeader = ''; + + /** + * Word-wrap the message body to this number of chars. + * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. + * @var integer + */ + public $WordWrap = 0; + + /** + * Which method to use to send mail. + * Options: "mail", "sendmail", or "smtp". + * @var string + */ + public $Mailer = 'mail'; + + /** + * The path to the sendmail program. + * @var string + */ + public $Sendmail = '/usr/sbin/sendmail'; + + /** + * Whether mail() uses a fully sendmail-compatible MTA. + * One which supports sendmail's "-oi -f" options. + * @var boolean + */ + public $UseSendmailOptions = true; + + /** + * Path to PHPMailer plugins. + * Useful if the SMTP class is not in the PHP include path. + * @var string + * @deprecated Should not be needed now there is an autoloader. + */ + public $PluginDir = ''; + + /** + * The email address that a reading confirmation should be sent to, also known as read receipt. + * @var string + */ + public $ConfirmReadingTo = ''; + + /** + * The hostname to use in the Message-ID header and as default HELO string. + * If empty, PHPMailer attempts to find one with, in order, + * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value + * 'localhost.localdomain'. + * @var string + */ + public $Hostname = ''; + + /** + * An ID to be used in the Message-ID header. + * If empty, a unique id will be generated. + * You can set your own, but it must be in the format "", + * as defined in RFC5322 section 3.6.4 or it will be ignored. + * @see https://tools.ietf.org/html/rfc5322#section-3.6.4 + * @var string + */ + public $MessageID = ''; + + /** + * The message Date to be used in the Date header. + * If empty, the current date will be added. + * @var string + */ + public $MessageDate = ''; + + /** + * SMTP hosts. + * Either a single hostname or multiple semicolon-delimited hostnames. + * You can also specify a different port + * for each host by using this format: [hostname:port] + * (e.g. "smtp1.example.com:25;smtp2.example.com"). + * You can also specify encryption type, for example: + * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465"). + * Hosts will be tried in order. + * @var string + */ + public $Host = 'localhost'; + + /** + * The default SMTP server port. + * @var integer + * @TODO Why is this needed when the SMTP class takes care of it? + */ + public $Port = 25; + + /** + * The SMTP HELO of the message. + * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find + * one with the same method described above for $Hostname. + * @var string + * @see PHPMailer::$Hostname + */ + public $Helo = ''; + + /** + * What kind of encryption to use on the SMTP connection. + * Options: '', 'ssl' or 'tls' + * @var string + */ + public $SMTPSecure = ''; + + /** + * Whether to enable TLS encryption automatically if a server supports it, + * even if `SMTPSecure` is not set to 'tls'. + * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid. + * @var boolean + */ + public $SMTPAutoTLS = true; + + /** + * Whether to use SMTP authentication. + * Uses the Username and Password properties. + * @var boolean + * @see PHPMailer::$Username + * @see PHPMailer::$Password + */ + public $SMTPAuth = false; + + /** + * Options array passed to stream_context_create when connecting via SMTP. + * @var array + */ + public $SMTPOptions = array(); + + /** + * SMTP username. + * @var string + */ + public $Username = ''; + + /** + * SMTP password. + * @var string + */ + public $Password = ''; + + /** + * SMTP auth type. + * Options are CRAM-MD5, LOGIN, PLAIN, NTLM, XOAUTH2, attempted in that order if not specified + * @var string + */ + public $AuthType = ''; + + /** + * SMTP realm. + * Used for NTLM auth + * @var string + */ + public $Realm = ''; + + /** + * SMTP workstation. + * Used for NTLM auth + * @var string + */ + public $Workstation = ''; + + /** + * The SMTP server timeout in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 + * @var integer + */ + public $Timeout = 300; + + /** + * SMTP class debug output mode. + * Debug output level. + * Options: + * * `0` No output + * * `1` Commands + * * `2` Data and commands + * * `3` As 2 plus connection status + * * `4` Low-level data output + * @var integer + * @see SMTP::$do_debug + */ + public $SMTPDebug = 0; + + /** + * How to handle debug output. + * Options: + * * `echo` Output plain-text as-is, appropriate for CLI + * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output + * * `error_log` Output to error log as configured in php.ini + * + * Alternatively, you can provide a callable expecting two params: a message string and the debug level: + * + * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; + * + * @var string|callable + * @see SMTP::$Debugoutput + */ + public $Debugoutput = 'echo'; + + /** + * Whether to keep SMTP connection open after each message. + * If this is set to true then to close the connection + * requires an explicit call to smtpClose(). + * @var boolean + */ + public $SMTPKeepAlive = false; + + /** + * Whether to split multiple to addresses into multiple messages + * or send them all in one message. + * Only supported in `mail` and `sendmail` transports, not in SMTP. + * @var boolean + */ + public $SingleTo = false; + + /** + * Storage for addresses when SingleTo is enabled. + * @var array + * @TODO This should really not be public + */ + public $SingleToArray = array(); + + /** + * Whether to generate VERP addresses on send. + * Only applicable when sending via SMTP. + * @link https://en.wikipedia.org/wiki/Variable_envelope_return_path + * @link http://www.postfix.org/VERP_README.html Postfix VERP info + * @var boolean + */ + public $do_verp = false; + + /** + * Whether to allow sending messages with an empty body. + * @var boolean + */ + public $AllowEmpty = false; + + /** + * The default line ending. + * @note The default remains "\n". We force CRLF where we know + * it must be used via self::CRLF. + * @var string + */ + public $LE = "\n"; + + /** + * DKIM selector. + * @var string + */ + public $DKIM_selector = ''; + + /** + * DKIM Identity. + * Usually the email address used as the source of the email. + * @var string + */ + public $DKIM_identity = ''; + + /** + * DKIM passphrase. + * Used if your key is encrypted. + * @var string + */ + public $DKIM_passphrase = ''; + + /** + * DKIM signing domain name. + * @example 'example.com' + * @var string + */ + public $DKIM_domain = ''; + + /** + * DKIM private key file path. + * @var string + */ + public $DKIM_private = ''; + + /** + * DKIM private key string. + * If set, takes precedence over `$DKIM_private`. + * @var string + */ + public $DKIM_private_string = ''; + + /** + * Callback Action function name. + * + * The function that handles the result of the send email action. + * It is called out by send() for each email sent. + * + * Value can be any php callable: http://www.php.net/is_callable + * + * Parameters: + * boolean $result result of the send action + * string $to email address of the recipient + * string $cc cc email addresses + * string $bcc bcc email addresses + * string $subject the subject + * string $body the email body + * string $from email address of sender + * @var string + */ + public $action_function = ''; + + /** + * What to put in the X-Mailer header. + * Options: An empty string for PHPMailer default, whitespace for none, or a string to use + * @var string + */ + public $XMailer = ''; + + /** + * Which validator to use by default when validating email addresses. + * May be a callable to inject your own validator, but there are several built-in validators. + * @see PHPMailer::validateAddress() + * @var string|callable + * @static + */ + public static $validator = 'auto'; + + /** + * An instance of the SMTP sender class. + * @var SMTP + * @access protected + */ + protected $smtp = null; + + /** + * The array of 'to' names and addresses. + * @var array + * @access protected + */ + protected $to = array(); + + /** + * The array of 'cc' names and addresses. + * @var array + * @access protected + */ + protected $cc = array(); + + /** + * The array of 'bcc' names and addresses. + * @var array + * @access protected + */ + protected $bcc = array(); + + /** + * The array of reply-to names and addresses. + * @var array + * @access protected + */ + protected $ReplyTo = array(); + + /** + * An array of all kinds of addresses. + * Includes all of $to, $cc, $bcc + * @var array + * @access protected + * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc + */ + protected $all_recipients = array(); + + /** + * An array of names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $all_recipients + * and one of $to, $cc, or $bcc. + * This array is used only for addresses with IDN. + * @var array + * @access protected + * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc + * @see PHPMailer::$all_recipients + */ + protected $RecipientsQueue = array(); + + /** + * An array of reply-to names and addresses queued for validation. + * In send(), valid and non duplicate entries are moved to $ReplyTo. + * This array is used only for addresses with IDN. + * @var array + * @access protected + * @see PHPMailer::$ReplyTo + */ + protected $ReplyToQueue = array(); + + /** + * The array of attachments. + * @var array + * @access protected + */ + protected $attachment = array(); + + /** + * The array of custom headers. + * @var array + * @access protected + */ + protected $CustomHeader = array(); + + /** + * The most recent Message-ID (including angular brackets). + * @var string + * @access protected + */ + protected $lastMessageID = ''; + + /** + * The message's MIME type. + * @var string + * @access protected + */ + protected $message_type = ''; + + /** + * The array of MIME boundary strings. + * @var array + * @access protected + */ + protected $boundary = array(); + + /** + * The array of available languages. + * @var array + * @access protected + */ + protected $language = array(); + + /** + * The number of errors encountered. + * @var integer + * @access protected + */ + protected $error_count = 0; + + /** + * The S/MIME certificate file path. + * @var string + * @access protected + */ + protected $sign_cert_file = ''; + + /** + * The S/MIME key file path. + * @var string + * @access protected + */ + protected $sign_key_file = ''; + + /** + * The optional S/MIME extra certificates ("CA Chain") file path. + * @var string + * @access protected + */ + protected $sign_extracerts_file = ''; + + /** + * The S/MIME password for the key. + * Used only if the key is encrypted. + * @var string + * @access protected + */ + protected $sign_key_pass = ''; + + /** + * Whether to throw exceptions for errors. + * @var boolean + * @access protected + */ + protected $exceptions = false; + + /** + * Unique ID used for message ID and boundaries. + * @var string + * @access protected + */ + protected $uniqueid = ''; + + /** + * Error severity: message only, continue processing. + */ + const STOP_MESSAGE = 0; + + /** + * Error severity: message, likely ok to continue processing. + */ + const STOP_CONTINUE = 1; + + /** + * Error severity: message, plus full stop, critical error reached. + */ + const STOP_CRITICAL = 2; + + /** + * SMTP RFC standard line ending. + */ + const CRLF = "\r\n"; + + /** + * The maximum line length allowed by RFC 2822 section 2.1.1 + * @var integer + */ + const MAX_LINE_LENGTH = 998; + + /** + * Constructor. + * @param boolean $exceptions Should we throw external exceptions? + */ + public function __construct($exceptions = null) + { + if ($exceptions !== null) { + $this->exceptions = (boolean)$exceptions; + } + } + + /** + * Destructor. + */ + public function __destruct() + { + //Close any open SMTP connection nicely + $this->smtpClose(); + } + + /** + * Call mail() in a safe_mode-aware fashion. + * Also, unless sendmail_path points to sendmail (or something that + * claims to be sendmail), don't pass params (not a perfect fix, + * but it will do) + * @param string $to To + * @param string $subject Subject + * @param string $body Message Body + * @param string $header Additional Header(s) + * @param string $params Params + * @access private + * @return boolean + */ + private function mailPassthru($to, $subject, $body, $header, $params) + { + //Check overloading of mail function to avoid double-encoding + if (ini_get('mbstring.func_overload') & 1) { + $subject = $this->secureHeader($subject); + } else { + $subject = $this->encodeHeader($this->secureHeader($subject)); + } + + //Can't use additional_parameters in safe_mode, calling mail() with null params breaks + //@link http://php.net/manual/en/function.mail.php + if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) { + $result = @mail($to, $subject, $body, $header); + } else { + $result = @mail($to, $subject, $body, $header, $params); + } + return $result; + } + /** + * Output debugging info via user-defined method. + * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug). + * @see PHPMailer::$Debugoutput + * @see PHPMailer::$SMTPDebug + * @param string $str + */ + protected function edebug($str) + { + if ($this->SMTPDebug <= 0) { + return; + } + //Avoid clash with built-in function names + if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { + call_user_func($this->Debugoutput, $str, $this->SMTPDebug); + return; + } + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ) + . "
\n"; + break; + case 'echo': + default: + //Normalize line breaks + $str = preg_replace('/\r\n?/ms', "\n", $str); + echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( + "\n", + "\n \t ", + trim($str) + ) . "\n"; + } + } + + /** + * Sets message type to HTML or plain. + * @param boolean $isHtml True for HTML mode. + * @return void + */ + public function isHTML($isHtml = true) + { + if ($isHtml) { + $this->ContentType = 'text/html'; + } else { + $this->ContentType = 'text/plain'; + } + } + + /** + * Send messages using SMTP. + * @return void + */ + public function isSMTP() + { + $this->Mailer = 'smtp'; + } + + /** + * Send messages using PHP's mail() function. + * @return void + */ + public function isMail() + { + $this->Mailer = 'mail'; + } + + /** + * Send messages using $Sendmail. + * @return void + */ + public function isSendmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (!stristr($ini_sendmail_path, 'sendmail')) { + $this->Sendmail = '/usr/sbin/sendmail'; + } else { + $this->Sendmail = $ini_sendmail_path; + } + $this->Mailer = 'sendmail'; + } + + /** + * Send messages using qmail. + * @return void + */ + public function isQmail() + { + $ini_sendmail_path = ini_get('sendmail_path'); + + if (!stristr($ini_sendmail_path, 'qmail')) { + $this->Sendmail = '/var/qmail/bin/qmail-inject'; + } else { + $this->Sendmail = $ini_sendmail_path; + } + $this->Mailer = 'qmail'; + } + + /** + * Add a "To" address. + * @param string $address The email address to send to + * @param string $name + * @return boolean true on success, false if address already used or invalid in some way + */ + public function addAddress($address, $name = '') + { + return $this->addOrEnqueueAnAddress('to', $address, $name); + } + + /** + * Add a "CC" address. + * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address The email address to send to + * @param string $name + * @return boolean true on success, false if address already used or invalid in some way + */ + public function addCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('cc', $address, $name); + } + + /** + * Add a "BCC" address. + * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. + * @param string $address The email address to send to + * @param string $name + * @return boolean true on success, false if address already used or invalid in some way + */ + public function addBCC($address, $name = '') + { + return $this->addOrEnqueueAnAddress('bcc', $address, $name); + } + + /** + * Add a "Reply-To" address. + * @param string $address The email address to reply to + * @param string $name + * @return boolean true on success, false if address already used or invalid in some way + */ + public function addReplyTo($address, $name = '') + { + return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer + * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still + * be modified after calling this function), addition of such addresses is delayed until send(). + * Addresses that have been added already return false, but do not throw exceptions. + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * @throws phpmailerException + * @return boolean true on success, false if address already used or invalid in some way + * @access protected + */ + protected function addOrEnqueueAnAddress($kind, $address, $name) + { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + if (($pos = strrpos($address, '@')) === false) { + // At-sign is misssing. + $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address"; + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new phpmailerException($error_message); + } + return false; + } + $params = array($kind, $address, $name); + // Enqueue addresses with IDN until we know the PHPMailer::$CharSet. + if ($this->has8bitChars(substr($address, ++$pos)) and $this->idnSupported()) { + if ($kind != 'Reply-To') { + if (!array_key_exists($address, $this->RecipientsQueue)) { + $this->RecipientsQueue[$address] = $params; + return true; + } + } else { + if (!array_key_exists($address, $this->ReplyToQueue)) { + $this->ReplyToQueue[$address] = $params; + return true; + } + } + return false; + } + // Immediately add standard addresses without IDN. + return call_user_func_array(array($this, 'addAnAddress'), $params); + } + + /** + * Add an address to one of the recipient arrays or to the ReplyTo array. + * Addresses that have been added already return false, but do not throw exceptions. + * @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo' + * @param string $address The email address to send, resp. to reply to + * @param string $name + * @throws phpmailerException + * @return boolean true on success, false if address already used or invalid in some way + * @access protected + */ + protected function addAnAddress($kind, $address, $name = '') + { + if (!in_array($kind, array('to', 'cc', 'bcc', 'Reply-To'))) { + $error_message = $this->lang('Invalid recipient kind: ') . $kind; + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new phpmailerException($error_message); + } + return false; + } + if (!$this->validateAddress($address)) { + $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address"; + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new phpmailerException($error_message); + } + return false; + } + if ($kind != 'Reply-To') { + if (!array_key_exists(strtolower($address), $this->all_recipients)) { + array_push($this->$kind, array($address, $name)); + $this->all_recipients[strtolower($address)] = true; + return true; + } + } else { + if (!array_key_exists(strtolower($address), $this->ReplyTo)) { + $this->ReplyTo[strtolower($address)] = array($address, $name); + return true; + } + } + return false; + } + + /** + * Parse and validate a string containing one or more RFC822-style comma-separated email addresses + * of the form "display name
" into an array of name/address pairs. + * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available. + * Note that quotes in the name part are removed. + * @param string $addrstr The address list string + * @param bool $useimap Whether to use the IMAP extension to parse the list + * @return array + * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation + */ + public function parseAddresses($addrstr, $useimap = true) + { + $addresses = array(); + if ($useimap and function_exists('imap_rfc822_parse_adrlist')) { + //Use this built-in parser if it's available + $list = imap_rfc822_parse_adrlist($addrstr, ''); + foreach ($list as $address) { + if ($address->host != '.SYNTAX-ERROR.') { + if ($this->validateAddress($address->mailbox . '@' . $address->host)) { + $addresses[] = array( + 'name' => (property_exists($address, 'personal') ? $address->personal : ''), + 'address' => $address->mailbox . '@' . $address->host + ); + } + } + } + } else { + //Use this simpler parser + $list = explode(',', $addrstr); + foreach ($list as $address) { + $address = trim($address); + //Is there a separate name part? + if (strpos($address, '<') === false) { + //No separate name, just use the whole thing + if ($this->validateAddress($address)) { + $addresses[] = array( + 'name' => '', + 'address' => $address + ); + } + } else { + list($name, $email) = explode('<', $address); + $email = trim(str_replace('>', '', $email)); + if ($this->validateAddress($email)) { + $addresses[] = array( + 'name' => trim(str_replace(array('"', "'"), '', $name)), + 'address' => $email + ); + } + } + } + } + return $addresses; + } + + /** + * Set the From and FromName properties. + * @param string $address + * @param string $name + * @param boolean $auto Whether to also set the Sender address, defaults to true + * @throws phpmailerException + * @return boolean + */ + public function setFrom($address, $name = '', $auto = true) + { + $address = trim($address); + $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim + // Don't validate now addresses with IDN. Will be done in send(). + if (($pos = strrpos($address, '@')) === false or + (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and + !$this->validateAddress($address)) { + $error_message = $this->lang('invalid_address') . " (setFrom) $address"; + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new phpmailerException($error_message); + } + return false; + } + $this->From = $address; + $this->FromName = $name; + if ($auto) { + if (empty($this->Sender)) { + $this->Sender = $address; + } + } + return true; + } + + /** + * Return the Message-ID header of the last email. + * Technically this is the value from the last time the headers were created, + * but it's also the message ID of the last sent message except in + * pathological cases. + * @return string + */ + public function getLastMessageID() + { + return $this->lastMessageID; + } + + /** + * Check that a string looks like an email address. + * @param string $address The email address to check + * @param string|callable $patternselect A selector for the validation pattern to use : + * * `auto` Pick best pattern automatically; + * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14; + * * `pcre` Use old PCRE implementation; + * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; + * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements. + * * `noregex` Don't use a regex: super fast, really dumb. + * Alternatively you may pass in a callable to inject your own validator, for example: + * PHPMailer::validateAddress('user@example.com', function($address) { + * return (strpos($address, '@') !== false); + * }); + * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator. + * @return boolean + * @static + * @access public + */ + public static function validateAddress($address, $patternselect = null) + { + if (is_null($patternselect)) { + $patternselect = self::$validator; + } + if (is_callable($patternselect)) { + return call_user_func($patternselect, $address); + } + //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321 + if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) { + return false; + } + if (!$patternselect or $patternselect == 'auto') { + //Check this constant first so it works when extension_loaded() is disabled by safe mode + //Constant was added in PHP 5.2.4 + if (defined('PCRE_VERSION')) { + //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2 + if (version_compare(PCRE_VERSION, '8.0.3') >= 0) { + $patternselect = 'pcre8'; + } else { + $patternselect = 'pcre'; + } + } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) { + //Fall back to older PCRE + $patternselect = 'pcre'; + } else { + //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension + if (version_compare(PHP_VERSION, '5.2.0') >= 0) { + $patternselect = 'php'; + } else { + $patternselect = 'noregex'; + } + } + } + switch ($patternselect) { + case 'pcre8': + /** + * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains. + * @link http://squiloople.com/2009/12/20/email-address-validation/ + * @copyright 2009-2010 Michael Rushton + * Feel free to use and redistribute this code. But please keep this copyright notice. + */ + return (boolean)preg_match( + '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . + '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . + '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . + '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . + '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . + '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . + '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . + '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', + $address + ); + case 'pcre': + //An older regex that doesn't need a recent PCRE + return (boolean)preg_match( + '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' . + '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' . + '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' . + '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' . + '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' . + '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' . + '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' . + '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' . + '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' . + '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', + $address + ); + case 'html5': + /** + * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements. + * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email) + */ + return (boolean)preg_match( + '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' . + '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD', + $address + ); + case 'noregex': + //No PCRE! Do something _very_ approximate! + //Check the address is 3 chars or longer and contains an @ that's not the first or last char + return (strlen($address) >= 3 + and strpos($address, '@') >= 1 + and strpos($address, '@') != strlen($address) - 1); + case 'php': + default: + return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL); + } + } + + /** + * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the + * "intl" and "mbstring" PHP extensions. + * @return bool "true" if required functions for IDN support are present + */ + public function idnSupported() + { + // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2. + return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding'); + } + + /** + * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. + * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. + * This function silently returns unmodified address if: + * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form) + * - Conversion to punycode is impossible (e.g. required PHP functions are not available) + * or fails for any reason (e.g. domain has characters not allowed in an IDN) + * @see PHPMailer::$CharSet + * @param string $address The email address to convert + * @return string The encoded address in ASCII form + */ + public function punyencodeAddress($address) + { + // Verify we have required functions, CharSet, and at-sign. + if ($this->idnSupported() and + !empty($this->CharSet) and + ($pos = strrpos($address, '@')) !== false) { + $domain = substr($address, ++$pos); + // Verify CharSet string is a valid one, and domain properly encoded in this CharSet. + if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) { + $domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet); + if (($punycode = defined('INTL_IDNA_VARIANT_UTS46') ? + idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46) : + idn_to_ascii($domain)) !== false) { + return substr($address, 0, $pos) . $punycode; + } + } + } + return $address; + } + + /** + * Create a message and send it. + * Uses the sending method specified by $Mailer. + * @throws phpmailerException + * @return boolean false on error - See the ErrorInfo property for details of the error. + */ + public function send() + { + try { + if (!$this->preSend()) { + return false; + } + return $this->postSend(); + } catch (phpmailerException $exc) { + $this->mailHeader = ''; + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + return false; + } + } + + /** + * Prepare a message for sending. + * @throws phpmailerException + * @return boolean + */ + public function preSend() + { + try { + $this->error_count = 0; // Reset errors + $this->mailHeader = ''; + + // Dequeue recipient and Reply-To addresses with IDN + foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { + $params[1] = $this->punyencodeAddress($params[1]); + call_user_func_array(array($this, 'addAnAddress'), $params); + } + if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { + throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL); + } + + // Validate From, Sender, and ConfirmReadingTo addresses + foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) { + $this->$address_kind = trim($this->$address_kind); + if (empty($this->$address_kind)) { + continue; + } + $this->$address_kind = $this->punyencodeAddress($this->$address_kind); + if (!$this->validateAddress($this->$address_kind)) { + $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind; + $this->setError($error_message); + $this->edebug($error_message); + if ($this->exceptions) { + throw new phpmailerException($error_message); + } + return false; + } + } + + // Set whether the message is multipart/alternative + if ($this->alternativeExists()) { + $this->ContentType = 'multipart/alternative'; + } + + $this->setMessageType(); + // Refuse to send an empty message unless we are specifically allowing it + if (!$this->AllowEmpty and empty($this->Body)) { + throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL); + } + + // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) + $this->MIMEHeader = ''; + $this->MIMEBody = $this->createBody(); + // createBody may have added some headers, so retain them + $tempheaders = $this->MIMEHeader; + $this->MIMEHeader = $this->createHeader(); + $this->MIMEHeader .= $tempheaders; + + // To capture the complete message when using mail(), create + // an extra header list which createHeader() doesn't fold in + if ($this->Mailer == 'mail') { + if (count($this->to) > 0) { + $this->mailHeader .= $this->addrAppend('To', $this->to); + } else { + $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + $this->mailHeader .= $this->headerLine( + 'Subject', + $this->encodeHeader($this->secureHeader(trim($this->Subject))) + ); + } + + // Sign with DKIM if enabled + if (!empty($this->DKIM_domain) + && !empty($this->DKIM_selector) + && (!empty($this->DKIM_private_string) + || (!empty($this->DKIM_private) && file_exists($this->DKIM_private)) + ) + ) { + $header_dkim = $this->DKIM_Add( + $this->MIMEHeader . $this->mailHeader, + $this->encodeHeader($this->secureHeader($this->Subject)), + $this->MIMEBody + ); + $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF . + str_replace("\r\n", "\n", $header_dkim) . self::CRLF; + } + return true; + } catch (phpmailerException $exc) { + $this->setError($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + return false; + } + } + + /** + * Actually send a message. + * Send the email via the selected mechanism + * @throws phpmailerException + * @return boolean + */ + public function postSend() + { + try { + // Choose the mailer and send through it + switch ($this->Mailer) { + case 'sendmail': + case 'qmail': + return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody); + case 'smtp': + return $this->smtpSend($this->MIMEHeader, $this->MIMEBody); + case 'mail': + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + default: + $sendMethod = $this->Mailer.'Send'; + if (method_exists($this, $sendMethod)) { + return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); + } + + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); + } + } catch (phpmailerException $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + } + return false; + } + + /** + * Send mail using the $Sendmail program. + * @param string $header The message headers + * @param string $body The message body + * @see PHPMailer::$Sendmail + * @throws phpmailerException + * @access protected + * @return boolean + */ + protected function sendmailSend($header, $body) + { + // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + if (!empty($this->Sender) and self::isShellSafe($this->Sender)) { + if ($this->Mailer == 'qmail') { + $sendmailFmt = '%s -f%s'; + } else { + $sendmailFmt = '%s -oi -f%s -t'; + } + } else { + if ($this->Mailer == 'qmail') { + $sendmailFmt = '%s'; + } else { + $sendmailFmt = '%s -oi -t'; + } + } + + // TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing. + $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); + + if ($this->SingleTo) { + foreach ($this->SingleToArray as $toAddr) { + if (!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, 'To: ' . $toAddr . "\n"); + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + $this->doCallback( + ($result == 0), + array($toAddr), + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From + ); + if ($result != 0) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + } else { + if (!@$mail = popen($sendmail, 'w')) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + fputs($mail, $header); + fputs($mail, $body); + $result = pclose($mail); + $this->doCallback( + ($result == 0), + $this->to, + $this->cc, + $this->bcc, + $this->Subject, + $body, + $this->From + ); + if ($result != 0) { + throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL); + } + } + return true; + } + + /** + * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. + * + * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows. + * @param string $string The string to be validated + * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report + * @access protected + * @return boolean + */ + protected static function isShellSafe($string) + { + // Future-proof + if (escapeshellcmd($string) !== $string + or !in_array(escapeshellarg($string), array("'$string'", "\"$string\"")) + ) { + return false; + } + + $length = strlen($string); + + for ($i = 0; $i < $length; $i++) { + $c = $string[$i]; + + // All other characters have a special meaning in at least one common shell, including = and +. + // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. + // Note that this does permit non-Latin alphanumeric characters based on the current locale. + if (!ctype_alnum($c) && strpos('@_-.', $c) === false) { + return false; + } + } + + return true; + } + + /** + * Send mail using the PHP mail() function. + * @param string $header The message headers + * @param string $body The message body + * @link http://www.php.net/manual/en/book.mail.php + * @throws phpmailerException + * @access protected + * @return boolean + */ + protected function mailSend($header, $body) + { + $toArr = array(); + foreach ($this->to as $toaddr) { + $toArr[] = $this->addrFormat($toaddr); + } + $to = implode(', ', $toArr); + + $params = null; + //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver + if (!empty($this->Sender) and $this->validateAddress($this->Sender)) { + // CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped. + if (self::isShellSafe($this->Sender)) { + $params = sprintf('-f%s', $this->Sender); + } + } + if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) { + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + } + $result = false; + if ($this->SingleTo and count($toArr) > 1) { + foreach ($toArr as $toAddr) { + $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params); + $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From); + } + } else { + $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params); + $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From); + } + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + if (!$result) { + throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL); + } + return true; + } + + /** + * Get an instance to use for SMTP operations. + * Override this function to load your own SMTP implementation + * @return SMTP + */ + public function getSMTPInstance() + { + if (!is_object($this->smtp)) { + $this->smtp = new SMTP; + } + return $this->smtp; + } + + /** + * Send mail via SMTP. + * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. + * Uses the PHPMailerSMTP class by default. + * @see PHPMailer::getSMTPInstance() to use a different class. + * @param string $header The message headers + * @param string $body The message body + * @throws phpmailerException + * @uses SMTP + * @access protected + * @return boolean + */ + protected function smtpSend($header, $body) + { + $bad_rcpt = array(); + if (!$this->smtpConnect($this->SMTPOptions)) { + throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL); + } + if (!empty($this->Sender) and $this->validateAddress($this->Sender)) { + $smtp_from = $this->Sender; + } else { + $smtp_from = $this->From; + } + if (!$this->smtp->mail($smtp_from)) { + $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); + throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); + } + + // Attempt to send to all recipients + foreach (array($this->to, $this->cc, $this->bcc) as $togroup) { + foreach ($togroup as $to) { + if (!$this->smtp->recipient($to[0])) { + $error = $this->smtp->getError(); + $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']); + $isSent = false; + } else { + $isSent = true; + } + $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From); + } + } + + // Only send the DATA command if we have viable recipients + if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) { + throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL); + } + if ($this->SMTPKeepAlive) { + $this->smtp->reset(); + } else { + $this->smtp->quit(); + $this->smtp->close(); + } + //Create error message for any bad addresses + if (count($bad_rcpt) > 0) { + $errstr = ''; + foreach ($bad_rcpt as $bad) { + $errstr .= $bad['to'] . ': ' . $bad['error']; + } + throw new phpmailerException( + $this->lang('recipients_failed') . $errstr, + self::STOP_CONTINUE + ); + } + return true; + } + + /** + * Initiate a connection to an SMTP server. + * Returns false if the operation failed. + * @param array $options An array of options compatible with stream_context_create() + * @uses SMTP + * @access public + * @throws phpmailerException + * @return boolean + */ + public function smtpConnect($options = null) + { + if (is_null($this->smtp)) { + $this->smtp = $this->getSMTPInstance(); + } + + //If no options are provided, use whatever is set in the instance + if (is_null($options)) { + $options = $this->SMTPOptions; + } + + // Already connected? + if ($this->smtp->connected()) { + return true; + } + + $this->smtp->setTimeout($this->Timeout); + $this->smtp->setDebugLevel($this->SMTPDebug); + $this->smtp->setDebugOutput($this->Debugoutput); + $this->smtp->setVerp($this->do_verp); + $hosts = explode(';', $this->Host); + $lastexception = null; + + foreach ($hosts as $hostentry) { + $hostinfo = array(); + if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) { + // Not a valid host entry + continue; + } + // $hostinfo[2]: optional ssl or tls prefix + // $hostinfo[3]: the hostname + // $hostinfo[4]: optional port number + // The host string prefix can temporarily override the current setting for SMTPSecure + // If it's not specified, the default value is used + $prefix = ''; + $secure = $this->SMTPSecure; + $tls = ($this->SMTPSecure == 'tls'); + if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) { + $prefix = 'ssl://'; + $tls = false; // Can't have SSL and TLS at the same time + $secure = 'ssl'; + } elseif ($hostinfo[2] == 'tls') { + $tls = true; + // tls doesn't use a prefix + $secure = 'tls'; + } + //Do we need the OpenSSL extension? + $sslext = defined('OPENSSL_ALGO_SHA1'); + if ('tls' === $secure or 'ssl' === $secure) { + //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled + if (!$sslext) { + throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL); + } + } + $host = $hostinfo[3]; + $port = $this->Port; + $tport = (integer)$hostinfo[4]; + if ($tport > 0 and $tport < 65536) { + $port = $tport; + } + if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { + try { + if ($this->Helo) { + $hello = $this->Helo; + } else { + $hello = $this->serverHostname(); + } + $this->smtp->hello($hello); + //Automatically enable TLS encryption if: + // * it's not disabled + // * we have openssl extension + // * we are not already using SSL + // * the server offers STARTTLS + if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) { + $tls = true; + } + if ($tls) { + if (!$this->smtp->startTLS()) { + throw new phpmailerException($this->lang('connect_host')); + } + // We must resend EHLO after TLS negotiation + $this->smtp->hello($hello); + } + if ($this->SMTPAuth) { + if (!$this->smtp->authenticate( + $this->Username, + $this->Password, + $this->AuthType, + $this->Realm, + $this->Workstation + ) + ) { + throw new phpmailerException($this->lang('authenticate')); + } + } + return true; + } catch (phpmailerException $exc) { + $lastexception = $exc; + $this->edebug($exc->getMessage()); + // We must have connected, but then failed TLS or Auth, so close connection nicely + $this->smtp->quit(); + } + } + } + // If we get here, all connection attempts have failed, so close connection hard + $this->smtp->close(); + // As we've caught all exceptions, just report whatever the last one was + if ($this->exceptions and !is_null($lastexception)) { + throw $lastexception; + } + return false; + } + + /** + * Close the active SMTP session if one exists. + * @return void + */ + public function smtpClose() + { + if (is_a($this->smtp, 'SMTP')) { + if ($this->smtp->connected()) { + $this->smtp->quit(); + $this->smtp->close(); + } + } + } + + /** + * Set the language for error messages. + * Returns false if it cannot load the language file. + * The default language is English. + * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr") + * @param string $lang_path Path to the language file directory, with trailing separator (slash) + * @return boolean + * @access public + */ + public function setLanguage($langcode = 'en', $lang_path = '') + { + // Backwards compatibility for renamed language codes + $renamed_langcodes = array( + 'br' => 'pt_br', + 'cz' => 'cs', + 'dk' => 'da', + 'no' => 'nb', + 'se' => 'sv', + ); + + if (isset($renamed_langcodes[$langcode])) { + $langcode = $renamed_langcodes[$langcode]; + } + + // Define full set of translatable strings in English + $PHPMAILER_LANG = array( + 'authenticate' => 'SMTP Error: Could not authenticate.', + 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', + 'data_not_accepted' => 'SMTP Error: data not accepted.', + 'empty_message' => 'Message body empty', + 'encoding' => 'Unknown encoding: ', + 'execute' => 'Could not execute: ', + 'file_access' => 'Could not access file: ', + 'file_open' => 'File Error: Could not open file: ', + 'from_failed' => 'The following From address failed: ', + 'instantiate' => 'Could not instantiate mail function.', + 'invalid_address' => 'Invalid address: ', + 'mailer_not_supported' => ' mailer is not supported.', + 'provide_address' => 'You must provide at least one recipient email address.', + 'recipients_failed' => 'SMTP Error: The following recipients failed: ', + 'signing' => 'Signing Error: ', + 'smtp_connect_failed' => 'SMTP connect() failed.', + 'smtp_error' => 'SMTP server error: ', + 'variable_set' => 'Cannot set or reset variable: ', + 'extension_missing' => 'Extension missing: ' + ); + if (empty($lang_path)) { + // Calculate an absolute path so it can work if CWD is not here + $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR; + } + //Validate $langcode + if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) { + $langcode = 'en'; + } + $foundlang = true; + $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php'; + // There is no English translation file + if ($langcode != 'en') { + // Make sure language file path is readable + if (!is_readable($lang_file)) { + $foundlang = false; + } else { + // Overwrite language-specific strings. + // This way we'll never have missing translation keys. + $foundlang = include $lang_file; + } + } + $this->language = $PHPMAILER_LANG; + return (boolean)$foundlang; // Returns false if language not found + } + + /** + * Get the array of strings for the current language. + * @return array + */ + public function getTranslations() + { + return $this->language; + } + + /** + * Create recipient headers. + * @access public + * @param string $type + * @param array $addr An array of recipient, + * where each recipient is a 2-element indexed array with element 0 containing an address + * and element 1 containing a name, like: + * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User')) + * @return string + */ + public function addrAppend($type, $addr) + { + $addresses = array(); + foreach ($addr as $address) { + $addresses[] = $this->addrFormat($address); + } + return $type . ': ' . implode(', ', $addresses) . $this->LE; + } + + /** + * Format an address for use in a message header. + * @access public + * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name + * like array('joe@example.com', 'Joe User') + * @return string + */ + public function addrFormat($addr) + { + if (empty($addr[1])) { // No name provided + return $this->secureHeader($addr[0]); + } else { + return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader( + $addr[0] + ) . '>'; + } + } + + /** + * Word-wrap message. + * For use with mailers that do not automatically perform wrapping + * and for quoted-printable encoded messages. + * Original written by philippe. + * @param string $message The message to wrap + * @param integer $length The line length to wrap to + * @param boolean $qp_mode Whether to run in Quoted-Printable mode + * @access public + * @return string + */ + public function wrapText($message, $length, $qp_mode = false) + { + if ($qp_mode) { + $soft_break = sprintf(' =%s', $this->LE); + } else { + $soft_break = $this->LE; + } + // If utf-8 encoding is used, we will need to make sure we don't + // split multibyte characters when we wrap + $is_utf8 = (strtolower($this->CharSet) == 'utf-8'); + $lelen = strlen($this->LE); + $crlflen = strlen(self::CRLF); + + $message = $this->fixEOL($message); + //Remove a trailing line break + if (substr($message, -$lelen) == $this->LE) { + $message = substr($message, 0, -$lelen); + } + + //Split message into lines + $lines = explode($this->LE, $message); + //Message will be rebuilt in here + $message = ''; + foreach ($lines as $line) { + $words = explode(' ', $line); + $buf = ''; + $firstword = true; + foreach ($words as $word) { + if ($qp_mode and (strlen($word) > $length)) { + $space_left = $length - strlen($buf) - $crlflen; + if (!$firstword) { + if ($space_left > 20) { + $len = $space_left; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == '=') { + $len--; + } elseif (substr($word, $len - 2, 1) == '=') { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= ' ' . $part; + $message .= $buf . sprintf('=%s', self::CRLF); + } else { + $message .= $buf . $soft_break; + } + $buf = ''; + } + while (strlen($word) > 0) { + if ($length <= 0) { + break; + } + $len = $length; + if ($is_utf8) { + $len = $this->utf8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == '=') { + $len--; + } elseif (substr($word, $len - 2, 1) == '=') { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + + if (strlen($word) > 0) { + $message .= $part . sprintf('=%s', self::CRLF); + } else { + $buf = $part; + } + } + } else { + $buf_o = $buf; + if (!$firstword) { + $buf .= ' '; + } + $buf .= $word; + + if (strlen($buf) > $length and $buf_o != '') { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + $firstword = false; + } + $message .= $buf . self::CRLF; + } + + return $message; + } + + /** + * Find the last character boundary prior to $maxLength in a utf-8 + * quoted-printable encoded string. + * Original written by Colin Brown. + * @access public + * @param string $encodedText utf-8 QP text + * @param integer $maxLength Find the last character boundary prior to this length + * @return integer + */ + public function utf8CharBoundary($encodedText, $maxLength) + { + $foundSplitPos = false; + $lookBack = 3; + while (!$foundSplitPos) { + $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); + $encodedCharPos = strpos($lastChunk, '='); + if (false !== $encodedCharPos) { + // Found start of encoded character byte within $lookBack block. + // Check the encoded byte value (the 2 chars after the '=') + $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); + $dec = hexdec($hex); + if ($dec < 128) { + // Single byte character. + // If the encoded char was found at pos 0, it will fit + // otherwise reduce maxLength to start of the encoded char + if ($encodedCharPos > 0) { + $maxLength = $maxLength - ($lookBack - $encodedCharPos); + } + $foundSplitPos = true; + } elseif ($dec >= 192) { + // First byte of a multi byte character + // Reduce maxLength to split at start of character + $maxLength = $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec < 192) { + // Middle byte of a multi byte character, look further back + $lookBack += 3; + } + } else { + // No encoded character found + $foundSplitPos = true; + } + } + return $maxLength; + } + + /** + * Apply word wrapping to the message body. + * Wraps the message body to the number of chars set in the WordWrap property. + * You should only do this to plain-text bodies as wrapping HTML tags may break them. + * This is called automatically by createBody(), so you don't need to call it yourself. + * @access public + * @return void + */ + public function setWordWrap() + { + if ($this->WordWrap < 1) { + return; + } + + switch ($this->message_type) { + case 'alt': + case 'alt_inline': + case 'alt_attach': + case 'alt_inline_attach': + $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->wrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assemble message headers. + * @access public + * @return string The assembled headers + */ + public function createHeader() + { + $result = ''; + + if ($this->MessageDate == '') { + $this->MessageDate = self::rfcDate(); + } + $result .= $this->headerLine('Date', $this->MessageDate); + + // To be created automatically by mail() + if ($this->SingleTo) { + if ($this->Mailer != 'mail') { + foreach ($this->to as $toaddr) { + $this->SingleToArray[] = $this->addrFormat($toaddr); + } + } + } else { + if (count($this->to) > 0) { + if ($this->Mailer != 'mail') { + $result .= $this->addrAppend('To', $this->to); + } + } elseif (count($this->cc) == 0) { + $result .= $this->headerLine('To', 'undisclosed-recipients:;'); + } + } + + $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName))); + + // sendmail and mail() extract Cc from the header before sending + if (count($this->cc) > 0) { + $result .= $this->addrAppend('Cc', $this->cc); + } + + // sendmail and mail() extract Bcc from the header before sending + if (( + $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail' + ) + and count($this->bcc) > 0 + ) { + $result .= $this->addrAppend('Bcc', $this->bcc); + } + + if (count($this->ReplyTo) > 0) { + $result .= $this->addrAppend('Reply-To', $this->ReplyTo); + } + + // mail() sets the subject itself + if ($this->Mailer != 'mail') { + $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); + } + + // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 + // https://tools.ietf.org/html/rfc5322#section-3.6.4 + if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) { + $this->lastMessageID = $this->MessageID; + } else { + $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname()); + } + $result .= $this->headerLine('Message-ID', $this->lastMessageID); + if (!is_null($this->Priority)) { + $result .= $this->headerLine('X-Priority', $this->Priority); + } + if ($this->XMailer == '') { + $result .= $this->headerLine( + 'X-Mailer', + 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer)' + ); + } else { + $myXmailer = trim($this->XMailer); + if ($myXmailer) { + $result .= $this->headerLine('X-Mailer', $myXmailer); + } + } + + if ($this->ConfirmReadingTo != '') { + $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); + } + + // Add custom headers + foreach ($this->CustomHeader as $header) { + $result .= $this->headerLine( + trim($header[0]), + $this->encodeHeader(trim($header[1])) + ); + } + if (!$this->sign_key_file) { + $result .= $this->headerLine('MIME-Version', '1.0'); + $result .= $this->getMailMIME(); + } + + return $result; + } + + /** + * Get the message MIME type headers. + * @access public + * @return string + */ + public function getMailMIME() + { + $result = ''; + $ismultipart = true; + switch ($this->message_type) { + case 'inline': + $result .= $this->headerLine('Content-Type', 'multipart/related;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + case 'attach': + case 'inline_attach': + case 'alt_attach': + case 'alt_inline_attach': + $result .= $this->headerLine('Content-Type', 'multipart/mixed;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + case 'alt': + case 'alt_inline': + $result .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + default: + // Catches case 'plain': and case '': + $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet); + $ismultipart = false; + break; + } + // RFC1341 part 5 says 7bit is assumed if not specified + if ($this->Encoding != '7bit') { + // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE + if ($ismultipart) { + if ($this->Encoding == '8bit') { + $result .= $this->headerLine('Content-Transfer-Encoding', '8bit'); + } + // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible + } else { + $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); + } + } + + if ($this->Mailer != 'mail') { + $result .= $this->LE; + } + + return $result; + } + + /** + * Returns the whole MIME message. + * Includes complete headers and body. + * Only valid post preSend(). + * @see PHPMailer::preSend() + * @access public + * @return string + */ + public function getSentMIMEMessage() + { + return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody; + } + + /** + * Create unique ID + * @return string + */ + protected function generateId() { + return md5(uniqid(time())); + } + + /** + * Assemble the message body. + * Returns an empty string on failure. + * @access public + * @throws phpmailerException + * @return string The assembled message body + */ + public function createBody() + { + $body = ''; + //Create unique IDs and preset boundaries + $this->uniqueid = $this->generateId(); + $this->boundary[1] = 'b1_' . $this->uniqueid; + $this->boundary[2] = 'b2_' . $this->uniqueid; + $this->boundary[3] = 'b3_' . $this->uniqueid; + + if ($this->sign_key_file) { + $body .= $this->getMailMIME() . $this->LE; + } + + $this->setWordWrap(); + + $bodyEncoding = $this->Encoding; + $bodyCharSet = $this->CharSet; + //Can we do a 7-bit downgrade? + if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) { + $bodyEncoding = '7bit'; + //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit + $bodyCharSet = 'us-ascii'; + } + //If lines are too long, and we're not already using an encoding that will shorten them, + //change to quoted-printable transfer encoding for the body part only + if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) { + $bodyEncoding = 'quoted-printable'; + } + + $altBodyEncoding = $this->Encoding; + $altBodyCharSet = $this->CharSet; + //Can we do a 7-bit downgrade? + if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) { + $altBodyEncoding = '7bit'; + //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit + $altBodyCharSet = 'us-ascii'; + } + //If lines are too long, and we're not already using an encoding that will shorten them, + //change to quoted-printable transfer encoding for the alt body part only + if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) { + $altBodyEncoding = 'quoted-printable'; + } + //Use this as a preamble in all multipart message types + $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE; + switch ($this->message_type) { + case 'inline': + $body .= $mimepre; + $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[1]); + break; + case 'attach': + $body .= $mimepre; + $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'inline_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt': + $body .= $mimepre; + $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= $this->LE . $this->LE; + if (!empty($this->Ical)) { + $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', ''); + $body .= $this->encodeString($this->Ical, $this->Encoding); + $body .= $this->LE . $this->LE; + } + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_inline': + $body .= $mimepre; + $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[2]); + $body .= $this->LE; + $body .= $this->endBoundary($this->boundary[1]); + break; + case 'alt_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->endBoundary($this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + case 'alt_inline_attach': + $body .= $mimepre; + $body .= $this->textLine('--' . $this->boundary[1]); + $body .= $this->headerLine('Content-Type', 'multipart/alternative;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding); + $body .= $this->encodeString($this->AltBody, $altBodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->textLine('--' . $this->boundary[2]); + $body .= $this->headerLine('Content-Type', 'multipart/related;'); + $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"'); + $body .= $this->LE; + $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding); + $body .= $this->encodeString($this->Body, $bodyEncoding); + $body .= $this->LE . $this->LE; + $body .= $this->attachAll('inline', $this->boundary[3]); + $body .= $this->LE; + $body .= $this->endBoundary($this->boundary[2]); + $body .= $this->LE; + $body .= $this->attachAll('attachment', $this->boundary[1]); + break; + default: + // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types + //Reset the `Encoding` property in case we changed it for line length reasons + $this->Encoding = $bodyEncoding; + $body .= $this->encodeString($this->Body, $this->Encoding); + break; + } + + if ($this->isError()) { + $body = ''; + } elseif ($this->sign_key_file) { + try { + if (!defined('PKCS7_TEXT')) { + throw new phpmailerException($this->lang('extension_missing') . 'openssl'); + } + // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1 + $file = tempnam(sys_get_temp_dir(), 'mail'); + if (false === file_put_contents($file, $body)) { + throw new phpmailerException($this->lang('signing') . ' Could not write temp file'); + } + $signed = tempnam(sys_get_temp_dir(), 'signed'); + //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197 + if (empty($this->sign_extracerts_file)) { + $sign = @openssl_pkcs7_sign( + $file, + $signed, + 'file://' . realpath($this->sign_cert_file), + array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), + null + ); + } else { + $sign = @openssl_pkcs7_sign( + $file, + $signed, + 'file://' . realpath($this->sign_cert_file), + array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), + null, + PKCS7_DETACHED, + $this->sign_extracerts_file + ); + } + if ($sign) { + @unlink($file); + $body = file_get_contents($signed); + @unlink($signed); + //The message returned by openssl contains both headers and body, so need to split them up + $parts = explode("\n\n", $body, 2); + $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE; + $body = $parts[1]; + } else { + @unlink($file); + @unlink($signed); + throw new phpmailerException($this->lang('signing') . openssl_error_string()); + } + } catch (phpmailerException $exc) { + $body = ''; + if ($this->exceptions) { + throw $exc; + } + } + } + return $body; + } + + /** + * Return the start of a message boundary. + * @access protected + * @param string $boundary + * @param string $charSet + * @param string $contentType + * @param string $encoding + * @return string + */ + protected function getBoundary($boundary, $charSet, $contentType, $encoding) + { + $result = ''; + if ($charSet == '') { + $charSet = $this->CharSet; + } + if ($contentType == '') { + $contentType = $this->ContentType; + } + if ($encoding == '') { + $encoding = $this->Encoding; + } + $result .= $this->textLine('--' . $boundary); + $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet); + $result .= $this->LE; + // RFC1341 part 5 says 7bit is assumed if not specified + if ($encoding != '7bit') { + $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); + } + $result .= $this->LE; + + return $result; + } + + /** + * Return the end of a message boundary. + * @access protected + * @param string $boundary + * @return string + */ + protected function endBoundary($boundary) + { + return $this->LE . '--' . $boundary . '--' . $this->LE; + } + + /** + * Set the message type. + * PHPMailer only supports some preset message types, not arbitrary MIME structures. + * @access protected + * @return void + */ + protected function setMessageType() + { + $type = array(); + if ($this->alternativeExists()) { + $type[] = 'alt'; + } + if ($this->inlineImageExists()) { + $type[] = 'inline'; + } + if ($this->attachmentExists()) { + $type[] = 'attach'; + } + $this->message_type = implode('_', $type); + if ($this->message_type == '') { + //The 'plain' message_type refers to the message having a single body element, not that it is plain-text + $this->message_type = 'plain'; + } + } + + /** + * Format a header line. + * @access public + * @param string $name + * @param string $value + * @return string + */ + public function headerLine($name, $value) + { + return $name . ': ' . $value . $this->LE; + } + + /** + * Return a formatted mail line. + * @access public + * @param string $value + * @return string + */ + public function textLine($value) + { + return $value . $this->LE; + } + + /** + * Add an attachment from a path on the filesystem. + * Returns false if the file could not be found or read. + * @param string $path Path to the attachment. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @param string $disposition Disposition to use + * @throws phpmailerException + * @return boolean + */ + public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') + { + try { + if (!@is_file($path)) { + throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE); + } + + // If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($path); + } + + $filename = basename($path); + if ($name == '') { + $name = $filename; + } + + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => $disposition, + 7 => 0 + ); + + } catch (phpmailerException $exc) { + $this->setError($exc->getMessage()); + $this->edebug($exc->getMessage()); + if ($this->exceptions) { + throw $exc; + } + return false; + } + return true; + } + + /** + * Return the array of attachments. + * @return array + */ + public function getAttachments() + { + return $this->attachment; + } + + /** + * Attach all file, string, and binary attachments to the message. + * Returns an empty string on failure. + * @access protected + * @param string $disposition_type + * @param string $boundary + * @return string + */ + protected function attachAll($disposition_type, $boundary) + { + // Return text of body + $mime = array(); + $cidUniq = array(); + $incl = array(); + + // Add all attachments + foreach ($this->attachment as $attachment) { + // Check if it is a valid disposition_filter + if ($attachment[6] == $disposition_type) { + // Check for string attachment + $string = ''; + $path = ''; + $bString = $attachment[5]; + if ($bString) { + $string = $attachment[0]; + } else { + $path = $attachment[0]; + } + + $inclhash = md5(serialize($attachment)); + if (in_array($inclhash, $incl)) { + continue; + } + $incl[] = $inclhash; + $name = $attachment[2]; + $encoding = $attachment[3]; + $type = $attachment[4]; + $disposition = $attachment[6]; + $cid = $attachment[7]; + if ($disposition == 'inline' && array_key_exists($cid, $cidUniq)) { + continue; + } + $cidUniq[$cid] = true; + + $mime[] = sprintf('--%s%s', $boundary, $this->LE); + //Only include a filename property if we have one + if (!empty($name)) { + $mime[] = sprintf( + 'Content-Type: %s; name="%s"%s', + $type, + $this->encodeHeader($this->secureHeader($name)), + $this->LE + ); + } else { + $mime[] = sprintf( + 'Content-Type: %s%s', + $type, + $this->LE + ); + } + // RFC1341 part 5 says 7bit is assumed if not specified + if ($encoding != '7bit') { + $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE); + } + + if ($disposition == 'inline') { + $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE); + } + + // If a filename contains any of these chars, it should be quoted, + // but not otherwise: RFC2183 & RFC2045 5.1 + // Fixes a warning in IETF's msglint MIME checker + // Allow for bypassing the Content-Disposition header totally + if (!(empty($disposition))) { + $encoded_name = $this->encodeHeader($this->secureHeader($name)); + if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) { + $mime[] = sprintf( + 'Content-Disposition: %s; filename="%s"%s', + $disposition, + $encoded_name, + $this->LE . $this->LE + ); + } else { + if (!empty($encoded_name)) { + $mime[] = sprintf( + 'Content-Disposition: %s; filename=%s%s', + $disposition, + $encoded_name, + $this->LE . $this->LE + ); + } else { + $mime[] = sprintf( + 'Content-Disposition: %s%s', + $disposition, + $this->LE . $this->LE + ); + } + } + } else { + $mime[] = $this->LE; + } + + // Encode as string attachment + if ($bString) { + $mime[] = $this->encodeString($string, $encoding); + if ($this->isError()) { + return ''; + } + $mime[] = $this->LE . $this->LE; + } else { + $mime[] = $this->encodeFile($path, $encoding); + if ($this->isError()) { + return ''; + } + $mime[] = $this->LE . $this->LE; + } + } + } + + $mime[] = sprintf('--%s--%s', $boundary, $this->LE); + + return implode('', $mime); + } + + /** + * Encode a file attachment in requested format. + * Returns an empty string on failure. + * @param string $path The full path to the file + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @throws phpmailerException + * @access protected + * @return string + */ + protected function encodeFile($path, $encoding = 'base64') + { + try { + if (!is_readable($path)) { + throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE); + } + $magic_quotes = get_magic_quotes_runtime(); + if ($magic_quotes) { + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + set_magic_quotes_runtime(false); + } else { + //Doesn't exist in PHP 5.4, but we don't need to check because + //get_magic_quotes_runtime always returns false in 5.4+ + //so it will never get here + ini_set('magic_quotes_runtime', false); + } + } + $file_buffer = file_get_contents($path); + $file_buffer = $this->encodeString($file_buffer, $encoding); + if ($magic_quotes) { + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + set_magic_quotes_runtime($magic_quotes); + } else { + ini_set('magic_quotes_runtime', $magic_quotes); + } + } + return $file_buffer; + } catch (Exception $exc) { + $this->setError($exc->getMessage()); + return ''; + } + } + + /** + * Encode a string in requested format. + * Returns an empty string on failure. + * @param string $str The text to encode + * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' + * @access public + * @return string + */ + public function encodeString($str, $encoding = 'base64') + { + $encoded = ''; + switch (strtolower($encoding)) { + case 'base64': + $encoded = chunk_split(base64_encode($str), 76, $this->LE); + break; + case '7bit': + case '8bit': + $encoded = $this->fixEOL($str); + // Make sure it ends with a line break + if (substr($encoded, -(strlen($this->LE))) != $this->LE) { + $encoded .= $this->LE; + } + break; + case 'binary': + $encoded = $str; + break; + case 'quoted-printable': + $encoded = $this->encodeQP($str); + break; + default: + $this->setError($this->lang('encoding') . $encoding); + break; + } + return $encoded; + } + + /** + * Encode a header string optimally. + * Picks shortest of Q, B, quoted-printable or none. + * @access public + * @param string $str + * @param string $position + * @return string + */ + public function encodeHeader($str, $position = 'text') + { + $matchcount = 0; + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + // Can't use addslashes as we don't know the value of magic_quotes_sybase + $encoded = addcslashes($str, "\0..\37\177\\\""); + if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { + return ($encoded); + } else { + return ("\"$encoded\""); + } + } + $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + /** @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + $matchcount = preg_match_all('/[()"]/', $str, $matches); + // Intentional fall-through + case 'text': + default: + $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + //There are no chars that need encoding + if ($matchcount == 0) { + return ($str); + } + + $maxlen = 75 - 7 - strlen($this->CharSet); + // Try to select the encoding which should produce the shortest output + if ($matchcount > strlen($str) / 3) { + // More than a third of the content will need encoding, so B encoding will be most efficient + $encoding = 'B'; + if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) { + // Use a custom function which correctly encodes and wraps long + // multibyte strings without breaking lines within a character + $encoded = $this->base64EncodeWrapMB($str, "\n"); + } else { + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } + } else { + $encoding = 'Q'; + $encoded = $this->encodeQ($str, $position); + $encoded = $this->wrapText($encoded, $maxlen, true); + $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded)); + } + + $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded); + $encoded = trim(str_replace("\n", $this->LE, $encoded)); + + return $encoded; + } + + /** + * Check if a string contains multi-byte characters. + * @access public + * @param string $str multi-byte text to wrap encode + * @return boolean + */ + public function hasMultiBytes($str) + { + if (function_exists('mb_strlen')) { + return (strlen($str) > mb_strlen($str, $this->CharSet)); + } else { // Assume no multibytes (we can't handle without mbstring functions anyway) + return false; + } + } + + /** + * Does a string contain any 8-bit chars (in any charset)? + * @param string $text + * @return boolean + */ + public function has8bitChars($text) + { + return (boolean)preg_match('/[\x80-\xFF]/', $text); + } + + /** + * Encode and wrap long multibyte strings for mail headers + * without breaking lines within a character. + * Adapted from a function by paravoid + * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283 + * @access public + * @param string $str multi-byte text to wrap encode + * @param string $linebreak string to use as linefeed/end-of-line + * @return string + */ + public function base64EncodeWrapMB($str, $linebreak = null) + { + $start = '=?' . $this->CharSet . '?B?'; + $end = '?='; + $encoded = ''; + if ($linebreak === null) { + $linebreak = $this->LE; + } + + $mb_length = mb_strlen($str, $this->CharSet); + // Each line must have length <= 75, including $start and $end + $length = 75 - strlen($start) - strlen($end); + // Average multi-byte ratio + $ratio = $mb_length / strlen($str); + // Base64 has a 4:3 ratio + $avgLength = floor($length * $ratio * .75); + + for ($i = 0; $i < $mb_length; $i += $offset) { + $lookBack = 0; + do { + $offset = $avgLength - $lookBack; + $chunk = mb_substr($str, $i, $offset, $this->CharSet); + $chunk = base64_encode($chunk); + $lookBack++; + } while (strlen($chunk) > $length); + $encoded .= $chunk . $linebreak; + } + + // Chomp the last linefeed + $encoded = substr($encoded, 0, -strlen($linebreak)); + return $encoded; + } + + /** + * Encode a string in quoted-printable format. + * According to RFC2045 section 6.7. + * @access public + * @param string $string The text to encode + * @param integer $line_max Number of chars allowed on a line before wrapping + * @return string + * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment + */ + public function encodeQP($string, $line_max = 76) + { + // Use native function if it's available (>= PHP5.3) + if (function_exists('quoted_printable_encode')) { + return quoted_printable_encode($string); + } + // Fall back to a pure PHP implementation + $string = str_replace( + array('%20', '%0D%0A.', '%0D%0A', '%'), + array(' ', "\r\n=2E", "\r\n", '='), + rawurlencode($string) + ); + return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string); + } + + /** + * Backward compatibility wrapper for an old QP encoding function that was removed. + * @see PHPMailer::encodeQP() + * @access public + * @param string $string + * @param integer $line_max + * @param boolean $space_conv + * @return string + * @deprecated Use encodeQP instead. + */ + public function encodeQPphp( + $string, + $line_max = 76, + /** @noinspection PhpUnusedParameterInspection */ $space_conv = false + ) { + return $this->encodeQP($string, $line_max); + } + + /** + * Encode a string using Q encoding. + * @link http://tools.ietf.org/html/rfc2047 + * @param string $str the text to encode + * @param string $position Where the text is going to be used, see the RFC for what that means + * @access public + * @return string + */ + public function encodeQ($str, $position = 'text') + { + // There should not be any EOL in the string + $pattern = ''; + $encoded = str_replace(array("\r", "\n"), '', $str); + switch (strtolower($position)) { + case 'phrase': + // RFC 2047 section 5.3 + $pattern = '^A-Za-z0-9!*+\/ -'; + break; + /** @noinspection PhpMissingBreakStatementInspection */ + case 'comment': + // RFC 2047 section 5.2 + $pattern = '\(\)"'; + // intentional fall-through + // for this reason we build the $pattern without including delimiters and [] + case 'text': + default: + // RFC 2047 section 5.1 + // Replace every high ascii, control, =, ? and _ characters + $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern; + break; + } + $matches = array(); + if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { + // If the string contains an '=', make sure it's the first thing we replace + // so as to avoid double-encoding + $eqkey = array_search('=', $matches[0]); + if (false !== $eqkey) { + unset($matches[0][$eqkey]); + array_unshift($matches[0], '='); + } + foreach (array_unique($matches[0]) as $char) { + $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); + } + } + // Replace every spaces to _ (more readable than =20) + return str_replace(' ', '_', $encoded); + } + + /** + * Add a string or binary attachment (non-filesystem). + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * @param string $string String attachment data. + * @param string $filename Name of the attachment. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @param string $disposition Disposition to use + * @return void + */ + public function addStringAttachment( + $string, + $filename, + $encoding = 'base64', + $type = '', + $disposition = 'attachment' + ) { + // If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($filename); + } + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $filename, + 2 => basename($filename), + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => $disposition, + 7 => 0 + ); + } + + /** + * Add an embedded (inline) attachment from a file. + * This can include images, sounds, and just about any other document type. + * These differ from 'regular' attachments in that they are intended to be + * displayed inline with the message, not just attached for download. + * This is used in HTML messages that embed the images + * the HTML refers to using the $cid value. + * @param string $path Path to the attachment. + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File MIME type. + * @param string $disposition Disposition to use + * @return boolean True on successfully adding an attachment + */ + public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') + { + if (!@is_file($path)) { + $this->setError($this->lang('file_access') . $path); + return false; + } + + // If a MIME type is not specified, try to work it out from the file name + if ($type == '') { + $type = self::filenameToType($path); + } + + $filename = basename($path); + if ($name == '') { + $name = $filename; + } + + // Append to $attachment array + $this->attachment[] = array( + 0 => $path, + 1 => $filename, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => false, // isStringAttachment + 6 => $disposition, + 7 => $cid + ); + return true; + } + + /** + * Add an embedded stringified attachment. + * This can include images, sounds, and just about any other document type. + * Be sure to set the $type to an image type for images: + * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. + * @param string $string The attachment binary data. + * @param string $cid Content ID of the attachment; Use this to reference + * the content when using an embedded image in HTML. + * @param string $name + * @param string $encoding File encoding (see $Encoding). + * @param string $type MIME type. + * @param string $disposition Disposition to use + * @return boolean True on successfully adding an attachment + */ + public function addStringEmbeddedImage( + $string, + $cid, + $name = '', + $encoding = 'base64', + $type = '', + $disposition = 'inline' + ) { + // If a MIME type is not specified, try to work it out from the name + if ($type == '' and !empty($name)) { + $type = self::filenameToType($name); + } + + // Append to $attachment array + $this->attachment[] = array( + 0 => $string, + 1 => $name, + 2 => $name, + 3 => $encoding, + 4 => $type, + 5 => true, // isStringAttachment + 6 => $disposition, + 7 => $cid + ); + return true; + } + + /** + * Check if an inline attachment is present. + * @access public + * @return boolean + */ + public function inlineImageExists() + { + foreach ($this->attachment as $attachment) { + if ($attachment[6] == 'inline') { + return true; + } + } + return false; + } + + /** + * Check if an attachment (non-inline) is present. + * @return boolean + */ + public function attachmentExists() + { + foreach ($this->attachment as $attachment) { + if ($attachment[6] == 'attachment') { + return true; + } + } + return false; + } + + /** + * Check if this message has an alternative body set. + * @return boolean + */ + public function alternativeExists() + { + return !empty($this->AltBody); + } + + /** + * Clear queued addresses of given kind. + * @access protected + * @param string $kind 'to', 'cc', or 'bcc' + * @return void + */ + public function clearQueuedAddresses($kind) + { + $RecipientsQueue = $this->RecipientsQueue; + foreach ($RecipientsQueue as $address => $params) { + if ($params[0] == $kind) { + unset($this->RecipientsQueue[$address]); + } + } + } + + /** + * Clear all To recipients. + * @return void + */ + public function clearAddresses() + { + foreach ($this->to as $to) { + unset($this->all_recipients[strtolower($to[0])]); + } + $this->to = array(); + $this->clearQueuedAddresses('to'); + } + + /** + * Clear all CC recipients. + * @return void + */ + public function clearCCs() + { + foreach ($this->cc as $cc) { + unset($this->all_recipients[strtolower($cc[0])]); + } + $this->cc = array(); + $this->clearQueuedAddresses('cc'); + } + + /** + * Clear all BCC recipients. + * @return void + */ + public function clearBCCs() + { + foreach ($this->bcc as $bcc) { + unset($this->all_recipients[strtolower($bcc[0])]); + } + $this->bcc = array(); + $this->clearQueuedAddresses('bcc'); + } + + /** + * Clear all ReplyTo recipients. + * @return void + */ + public function clearReplyTos() + { + $this->ReplyTo = array(); + $this->ReplyToQueue = array(); + } + + /** + * Clear all recipient types. + * @return void + */ + public function clearAllRecipients() + { + $this->to = array(); + $this->cc = array(); + $this->bcc = array(); + $this->all_recipients = array(); + $this->RecipientsQueue = array(); + } + + /** + * Clear all filesystem, string, and binary attachments. + * @return void + */ + public function clearAttachments() + { + $this->attachment = array(); + } + + /** + * Clear all custom headers. + * @return void + */ + public function clearCustomHeaders() + { + $this->CustomHeader = array(); + } + + /** + * Add an error message to the error container. + * @access protected + * @param string $msg + * @return void + */ + protected function setError($msg) + { + $this->error_count++; + if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { + $lasterror = $this->smtp->getError(); + if (!empty($lasterror['error'])) { + $msg .= $this->lang('smtp_error') . $lasterror['error']; + if (!empty($lasterror['detail'])) { + $msg .= ' Detail: '. $lasterror['detail']; + } + if (!empty($lasterror['smtp_code'])) { + $msg .= ' SMTP code: ' . $lasterror['smtp_code']; + } + if (!empty($lasterror['smtp_code_ex'])) { + $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex']; + } + } + } + $this->ErrorInfo = $msg; + } + + /** + * Return an RFC 822 formatted date. + * @access public + * @return string + * @static + */ + public static function rfcDate() + { + // Set the time zone to whatever the default is to avoid 500 errors + // Will default to UTC if it's not set properly in php.ini + date_default_timezone_set(@date_default_timezone_get()); + return date('D, j M Y H:i:s O'); + } + + /** + * Get the server hostname. + * Returns 'localhost.localdomain' if unknown. + * @access protected + * @return string + */ + protected function serverHostname() + { + $result = 'localhost.localdomain'; + if (!empty($this->Hostname)) { + $result = $this->Hostname; + } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) { + $result = $_SERVER['SERVER_NAME']; + } elseif (function_exists('gethostname') && gethostname() !== false) { + $result = gethostname(); + } elseif (php_uname('n') !== false) { + $result = php_uname('n'); + } + return $result; + } + + /** + * Get an error message in the current language. + * @access protected + * @param string $key + * @return string + */ + protected function lang($key) + { + if (count($this->language) < 1) { + $this->setLanguage('en'); // set the default language + } + + if (array_key_exists($key, $this->language)) { + if ($key == 'smtp_connect_failed') { + //Include a link to troubleshooting docs on SMTP connection failure + //this is by far the biggest cause of support questions + //but it's usually not PHPMailer's fault. + return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting'; + } + return $this->language[$key]; + } else { + //Return the key as a fallback + return $key; + } + } + + /** + * Check if an error occurred. + * @access public + * @return boolean True if an error did occur. + */ + public function isError() + { + return ($this->error_count > 0); + } + + /** + * Ensure consistent line endings in a string. + * Changes every end of line from CRLF, CR or LF to $this->LE. + * @access public + * @param string $str String to fixEOL + * @return string + */ + public function fixEOL($str) + { + // Normalise to \n + $nstr = str_replace(array("\r\n", "\r"), "\n", $str); + // Now convert LE as needed + if ($this->LE !== "\n") { + $nstr = str_replace("\n", $this->LE, $nstr); + } + return $nstr; + } + + /** + * Add a custom header. + * $name value can be overloaded to contain + * both header name and value (name:value) + * @access public + * @param string $name Custom header name + * @param string $value Header value + * @return void + */ + public function addCustomHeader($name, $value = null) + { + if ($value === null) { + // Value passed in as name:value + $this->CustomHeader[] = explode(':', $name, 2); + } else { + $this->CustomHeader[] = array($name, $value); + } + } + + /** + * Returns all custom headers. + * @return array + */ + public function getCustomHeaders() + { + return $this->CustomHeader; + } + + /** + * Create a message body from an HTML string. + * Automatically inlines images and creates a plain-text version by converting the HTML, + * overwriting any existing values in Body and AltBody. + * $basedir is used when handling relative image paths, e.g. + * will look for an image file in $basedir/images/a.png and convert it to inline. + * If you don't want to apply these transformations to your HTML, just set Body and AltBody yourself. + * @access public + * @param string $message HTML message string + * @param string $basedir base directory for relative paths to images + * @param boolean|callable $advanced Whether to use the internal HTML to text converter + * or your own custom converter @see PHPMailer::html2text() + * @return string $message The transformed message Body + */ + public function msgHTML($message, $basedir = '', $advanced = false) + { + preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images); + if (array_key_exists(2, $images)) { + foreach ($images[2] as $imgindex => $url) { + // Convert data URIs into embedded images + if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) { + $data = substr($url, strpos($url, ',')); + if ($match[2]) { + $data = base64_decode($data); + } else { + $data = rawurldecode($data); + } + $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 + if ($this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, 'base64', $match[1])) { + $message = str_replace( + $images[0][$imgindex], + $images[1][$imgindex] . '="cid:' . $cid . '"', + $message + ); + } + } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) { + // Do not change urls for absolute images (thanks to corvuscorax) + // Do not change urls that are already inline images + $filename = basename($url); + $directory = dirname($url); + if ($directory == '.') { + $directory = ''; + } + $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 + if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { + $basedir .= '/'; + } + if (strlen($directory) > 1 && substr($directory, -1) != '/') { + $directory .= '/'; + } + if ($this->addEmbeddedImage( + $basedir . $directory . $filename, + $cid, + $filename, + 'base64', + self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION)) + ) + ) { + $message = preg_replace( + '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', + $images[1][$imgindex] . '="cid:' . $cid . '"', + $message + ); + } + } + } + } + $this->isHTML(true); + // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better + $this->Body = $this->normalizeBreaks($message); + $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced)); + if (!$this->alternativeExists()) { + $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . + self::CRLF . self::CRLF; + } + return $this->Body; + } + + /** + * Convert an HTML string into plain text. + * This is used by msgHTML(). + * Note - older versions of this function used a bundled advanced converter + * which was been removed for license reasons in #232. + * Example usage: + * + * // Use default conversion + * $plain = $mail->html2text($html); + * // Use your own custom converter + * $plain = $mail->html2text($html, function($html) { + * $converter = new MyHtml2text($html); + * return $converter->get_text(); + * }); + * + * @param string $html The HTML text to convert + * @param boolean|callable $advanced Any boolean value to use the internal converter, + * or provide your own callable for custom conversion. + * @return string + */ + public function html2text($html, $advanced = false) + { + if (is_callable($advanced)) { + return call_user_func($advanced, $html); + } + return html_entity_decode( + trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), + ENT_QUOTES, + $this->CharSet + ); + } + + /** + * Get the MIME type for a file extension. + * @param string $ext File extension + * @access public + * @return string MIME type of file. + * @static + */ + public static function _mime_types($ext = '') + { + $mimes = array( + 'xl' => 'application/excel', + 'js' => 'application/javascript', + 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'bin' => 'application/macbinary', + 'doc' => 'application/msword', + 'word' => 'application/msword', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', + 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', + 'class' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'dms' => 'application/octet-stream', + 'exe' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'psd' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'so' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => 'application/pdf', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => 'application/x-tar', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'zip' => 'application/zip', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mpga' => 'audio/mpeg', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'ra' => 'audio/x-realaudio', + 'wav' => 'audio/x-wav', + 'bmp' => 'image/bmp', + 'gif' => 'image/gif', + 'jpeg' => 'image/jpeg', + 'jpe' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'png' => 'image/png', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'eml' => 'message/rfc822', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'log' => 'text/plain', + 'text' => 'text/plain', + 'txt' => 'text/plain', + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'vcf' => 'text/vcard', + 'vcard' => 'text/vcard', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'mpeg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mov' => 'video/quicktime', + 'qt' => 'video/quicktime', + 'rv' => 'video/vnd.rn-realvideo', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie' + ); + if (array_key_exists(strtolower($ext), $mimes)) { + return $mimes[strtolower($ext)]; + } + return 'application/octet-stream'; + } + + /** + * Map a file name to a MIME type. + * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. + * @param string $filename A file name or full path, does not need to exist as a file + * @return string + * @static + */ + public static function filenameToType($filename) + { + // In case the path is a URL, strip any query string before getting extension + $qpos = strpos($filename, '?'); + if (false !== $qpos) { + $filename = substr($filename, 0, $qpos); + } + $pathinfo = self::mb_pathinfo($filename); + return self::_mime_types($pathinfo['extension']); + } + + /** + * Multi-byte-safe pathinfo replacement. + * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. + * Works similarly to the one in PHP >= 5.2.0 + * @link http://www.php.net/manual/en/function.pathinfo.php#107461 + * @param string $path A filename or path, does not need to exist as a file + * @param integer|string $options Either a PATHINFO_* constant, + * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 + * @return string|array + * @static + */ + public static function mb_pathinfo($path, $options = null) + { + $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''); + $pathinfo = array(); + if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) { + if (array_key_exists(1, $pathinfo)) { + $ret['dirname'] = $pathinfo[1]; + } + if (array_key_exists(2, $pathinfo)) { + $ret['basename'] = $pathinfo[2]; + } + if (array_key_exists(5, $pathinfo)) { + $ret['extension'] = $pathinfo[5]; + } + if (array_key_exists(3, $pathinfo)) { + $ret['filename'] = $pathinfo[3]; + } + } + switch ($options) { + case PATHINFO_DIRNAME: + case 'dirname': + return $ret['dirname']; + case PATHINFO_BASENAME: + case 'basename': + return $ret['basename']; + case PATHINFO_EXTENSION: + case 'extension': + return $ret['extension']; + case PATHINFO_FILENAME: + case 'filename': + return $ret['filename']; + default: + return $ret; + } + } + + /** + * Set or reset instance properties. + * You should avoid this function - it's more verbose, less efficient, more error-prone and + * harder to debug than setting properties directly. + * Usage Example: + * `$mail->set('SMTPSecure', 'tls');` + * is the same as: + * `$mail->SMTPSecure = 'tls';` + * @access public + * @param string $name The property name to set + * @param mixed $value The value to set the property to + * @return boolean + * @TODO Should this not be using the __set() magic function? + */ + public function set($name, $value = '') + { + if (property_exists($this, $name)) { + $this->$name = $value; + return true; + } else { + $this->setError($this->lang('variable_set') . $name); + return false; + } + } + + /** + * Strip newlines to prevent header injection. + * @access public + * @param string $str + * @return string + */ + public function secureHeader($str) + { + return trim(str_replace(array("\r", "\n"), '', $str)); + } + + /** + * Normalize line breaks in a string. + * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. + * Defaults to CRLF (for message bodies) and preserves consecutive breaks. + * @param string $text + * @param string $breaktype What kind of line break to use, defaults to CRLF + * @return string + * @access public + * @static + */ + public static function normalizeBreaks($text, $breaktype = "\r\n") + { + return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); + } + + /** + * Set the public and private key files and password for S/MIME signing. + * @access public + * @param string $cert_filename + * @param string $key_filename + * @param string $key_pass Password for private key + * @param string $extracerts_filename Optional path to chain certificate + */ + public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '') + { + $this->sign_cert_file = $cert_filename; + $this->sign_key_file = $key_filename; + $this->sign_key_pass = $key_pass; + $this->sign_extracerts_file = $extracerts_filename; + } + + /** + * Quoted-Printable-encode a DKIM header. + * @access public + * @param string $txt + * @return string + */ + public function DKIM_QP($txt) + { + $line = ''; + for ($i = 0; $i < strlen($txt); $i++) { + $ord = ord($txt[$i]); + if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) { + $line .= $txt[$i]; + } else { + $line .= '=' . sprintf('%02X', $ord); + } + } + return $line; + } + + /** + * Generate a DKIM signature. + * @access public + * @param string $signHeader + * @throws phpmailerException + * @return string The DKIM signature value + */ + public function DKIM_Sign($signHeader) + { + if (!defined('PKCS7_TEXT')) { + if ($this->exceptions) { + throw new phpmailerException($this->lang('extension_missing') . 'openssl'); + } + return ''; + } + $privKeyStr = !empty($this->DKIM_private_string) ? $this->DKIM_private_string : file_get_contents($this->DKIM_private); + if ('' != $this->DKIM_passphrase) { + $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); + } else { + $privKey = openssl_pkey_get_private($privKeyStr); + } + //Workaround for missing digest algorithms in old PHP & OpenSSL versions + //@link http://stackoverflow.com/a/11117338/333340 + if (version_compare(PHP_VERSION, '5.3.0') >= 0 and + in_array('sha256WithRSAEncryption', openssl_get_md_methods(true))) { + if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) { + openssl_pkey_free($privKey); + return base64_encode($signature); + } + } else { + $pinfo = openssl_pkey_get_details($privKey); + $hash = hash('sha256', $signHeader); + //'Magic' constant for SHA256 from RFC3447 + //@link https://tools.ietf.org/html/rfc3447#page-43 + $t = '3031300d060960864801650304020105000420' . $hash; + $pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3); + $eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t); + + if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) { + openssl_pkey_free($privKey); + return base64_encode($signature); + } + } + openssl_pkey_free($privKey); + return ''; + } + + /** + * Generate a DKIM canonicalization header. + * @access public + * @param string $signHeader Header + * @return string + */ + public function DKIM_HeaderC($signHeader) + { + $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader); + $lines = explode("\r\n", $signHeader); + foreach ($lines as $key => $line) { + list($heading, $value) = explode(':', $line, 2); + $heading = strtolower($heading); + $value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces + $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value + } + $signHeader = implode("\r\n", $lines); + return $signHeader; + } + + /** + * Generate a DKIM canonicalization body. + * @access public + * @param string $body Message Body + * @return string + */ + public function DKIM_BodyC($body) + { + if ($body == '') { + return "\r\n"; + } + // stabilize line endings + $body = str_replace("\r\n", "\n", $body); + $body = str_replace("\n", "\r\n", $body); + // END stabilize line endings + while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { + $body = substr($body, 0, strlen($body) - 2); + } + return $body; + } + + /** + * Create the DKIM header and body in a new message header. + * @access public + * @param string $headers_line Header lines + * @param string $subject Subject + * @param string $body Body + * @return string + */ + public function DKIM_Add($headers_line, $subject, $body) + { + $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms + $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body + $DKIMquery = 'dns/txt'; // Query method + $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) + $subject_header = "Subject: $subject"; + $headers = explode($this->LE, $headers_line); + $from_header = ''; + $to_header = ''; + $date_header = ''; + $current = ''; + foreach ($headers as $header) { + if (strpos($header, 'From:') === 0) { + $from_header = $header; + $current = 'from_header'; + } elseif (strpos($header, 'To:') === 0) { + $to_header = $header; + $current = 'to_header'; + } elseif (strpos($header, 'Date:') === 0) { + $date_header = $header; + $current = 'date_header'; + } else { + if (!empty($$current) && strpos($header, ' =?') === 0) { + $$current .= $header; + } else { + $current = ''; + } + } + } + $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); + $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); + $date = str_replace('|', '=7C', $this->DKIM_QP($date_header)); + $subject = str_replace( + '|', + '=7C', + $this->DKIM_QP($subject_header) + ); // Copied header fields (dkim-quoted-printable) + $body = $this->DKIM_BodyC($body); + $DKIMlen = strlen($body); // Length of body + $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body + if ('' == $this->DKIM_identity) { + $ident = ''; + } else { + $ident = ' i=' . $this->DKIM_identity . ';'; + } + $dkimhdrs = 'DKIM-Signature: v=1; a=' . + $DKIMsignatureType . '; q=' . + $DKIMquery . '; l=' . + $DKIMlen . '; s=' . + $this->DKIM_selector . + ";\r\n" . + "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" . + "\th=From:To:Date:Subject;\r\n" . + "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" . + "\tz=$from\r\n" . + "\t|$to\r\n" . + "\t|$date\r\n" . + "\t|$subject;\r\n" . + "\tbh=" . $DKIMb64 . ";\r\n" . + "\tb="; + $toSign = $this->DKIM_HeaderC( + $from_header . "\r\n" . + $to_header . "\r\n" . + $date_header . "\r\n" . + $subject_header . "\r\n" . + $dkimhdrs + ); + $signed = $this->DKIM_Sign($toSign); + return $dkimhdrs . $signed . "\r\n"; + } + + /** + * Detect if a string contains a line longer than the maximum line length allowed. + * @param string $str + * @return boolean + * @static + */ + public static function hasLineLongerThanMax($str) + { + //+2 to include CRLF line break for a 1000 total + return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str); + } + + /** + * Allows for public read access to 'to' property. + * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * @access public + * @return array + */ + public function getToAddresses() + { + return $this->to; + } + + /** + * Allows for public read access to 'cc' property. + * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * @access public + * @return array + */ + public function getCcAddresses() + { + return $this->cc; + } + + /** + * Allows for public read access to 'bcc' property. + * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * @access public + * @return array + */ + public function getBccAddresses() + { + return $this->bcc; + } + + /** + * Allows for public read access to 'ReplyTo' property. + * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * @access public + * @return array + */ + public function getReplyToAddresses() + { + return $this->ReplyTo; + } + + /** + * Allows for public read access to 'all_recipients' property. + * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. + * @access public + * @return array + */ + public function getAllRecipientAddresses() + { + return $this->all_recipients; + } + + /** + * Perform a callback. + * @param boolean $isSent + * @param array $to + * @param array $cc + * @param array $bcc + * @param string $subject + * @param string $body + * @param string $from + */ + protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from) + { + if (!empty($this->action_function) && is_callable($this->action_function)) { + $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); + call_user_func_array($this->action_function, $params); + } + } } /** @@ -3912,13 +4013,13 @@ class PHPMailer */ class phpmailerException extends Exception { - /** - * Prettify error message output - * @return string - */ - public function errorMessage() - { - $errorMsg = '' . $this->getMessage() . "
\n"; - return $errorMsg; - } + /** + * Prettify error message output + * @return string + */ + public function errorMessage() + { + $errorMsg = '' . $this->getMessage() . "
\n"; + return $errorMsg; + } } diff --git a/lib/classes/phpmailer/class.SMTP.php b/lib/classes/phpmailer/class.SMTP.php index 0c016f12..886782dc 100644 --- a/lib/classes/phpmailer/class.SMTP.php +++ b/lib/classes/phpmailer/class.SMTP.php @@ -1,1192 +1,1249 @@ - * @author Jim Jagielski (jimjag) - * @author Andy Prevost (codeworxtech) - * @author Brent R. Matzelle (original founder) - * @copyright 2014 Marcus Bointon - * @copyright 2010 - 2012 Jim Jagielski - * @copyright 2004 - 2009 Andy Prevost - * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License - * @note This program is distributed in the hope that it will be useful - WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ +* PHP Version 5 +* @package PHPMailer +* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project +* @author Marcus Bointon (Synchro/coolbru) +* @author Jim Jagielski (jimjag) +* @author Andy Prevost (codeworxtech) +* @author Brent R. Matzelle (original founder) +* @copyright 2014 Marcus Bointon +* @copyright 2010 - 2012 Jim Jagielski +* @copyright 2004 - 2009 Andy Prevost +* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License +* @note This program is distributed in the hope that it will be useful - WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. +*/ /** * PHPMailer RFC821 SMTP email transport class. - * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. - * @package PHPMailer - * @author Chris Ryan - * @author Marcus Bointon - */ +* Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. +* @package PHPMailer +* @author Chris Ryan +* @author Marcus Bointon +*/ class SMTP { - /** - * The PHPMailer SMTP version number. - * @var string - */ - const VERSION = '5.2.16'; - - /** - * SMTP line break constant. - * @var string - */ - const CRLF = "\r\n"; - - /** - * The SMTP port to use if one is not specified. - * @var integer - */ - const DEFAULT_SMTP_PORT = 25; - - /** - * The maximum line length allowed by RFC 2822 section 2.1.1 - * @var integer - */ - const MAX_LINE_LENGTH = 998; - - /** - * Debug level for no output - */ - const DEBUG_OFF = 0; - - /** - * Debug level to show client -> server messages - */ - const DEBUG_CLIENT = 1; - - /** - * Debug level to show client -> server and server -> client messages - */ - const DEBUG_SERVER = 2; - - /** - * Debug level to show connection status, client -> server and server -> client messages - */ - const DEBUG_CONNECTION = 3; - - /** - * Debug level to show all messages - */ - const DEBUG_LOWLEVEL = 4; - - /** - * The PHPMailer SMTP Version number. - * @var string - * @deprecated Use the `VERSION` constant instead - * @see SMTP::VERSION - */ - public $Version = '5.2.16'; - - /** - * SMTP server port number. - * @var integer - * @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead - * @see SMTP::DEFAULT_SMTP_PORT - */ - public $SMTP_PORT = 25; - - /** - * SMTP reply line ending. - * @var string - * @deprecated Use the `CRLF` constant instead - * @see SMTP::CRLF - */ - public $CRLF = "\r\n"; - - /** - * Debug output level. - * Options: - * * self::DEBUG_OFF (`0`) No debug output, default - * * self::DEBUG_CLIENT (`1`) Client commands - * * self::DEBUG_SERVER (`2`) Client commands and server responses - * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status - * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages - * @var integer - */ - public $do_debug = self::DEBUG_OFF; - - /** - * How to handle debug output. - * Options: - * * `echo` Output plain-text as-is, appropriate for CLI - * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output - * * `error_log` Output to error log as configured in php.ini - * - * Alternatively, you can provide a callable expecting two params: a message string and the debug level: - * - * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; - * - * @var string|callable - */ - public $Debugoutput = 'echo'; - - /** - * Whether to use VERP. - * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path - * @link http://www.postfix.org/VERP_README.html Info on VERP - * @var boolean - */ - public $do_verp = false; - - /** - * The timeout value for connection, in seconds. - * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 - * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure. - * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2 - * @var integer - */ - public $Timeout = 300; - - /** - * How long to wait for commands to complete, in seconds. - * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 - * @var integer - */ - public $Timelimit = 300; - - /** - * The socket for the server connection. - * @var resource - */ - protected $smtp_conn; - - /** - * Error information, if any, for the last SMTP command. - * @var array - */ - protected $error = array( - 'error' => '', - 'detail' => '', - 'smtp_code' => '', - 'smtp_code_ex' => '' - ); - - /** - * The reply the server sent to us for HELO. - * If null, no HELO string has yet been received. - * @var string|null - */ - protected $helo_rply = null; - - /** - * The set of SMTP extensions sent in reply to EHLO command. - * Indexes of the array are extension names. - * Value at index 'HELO' or 'EHLO' (according to command that was sent) - * represents the server name. In case of HELO it is the only element of the array. - * Other values can be boolean TRUE or an array containing extension options. - * If null, no HELO/EHLO string has yet been received. - * @var array|null - */ - protected $server_caps = null; - - /** - * The most recent reply received from the server. - * @var string - */ - protected $last_reply = ''; - - /** - * Output debugging info via a user-selected method. - * @see SMTP::$Debugoutput - * @see SMTP::$do_debug - * @param string $str Debug string to output - * @param integer $level The debug level of this message; see DEBUG_* constants - * @return void - */ - protected function edebug($str, $level = 0) - { - if ($level > $this->do_debug) { - return; - } - //Avoid clash with built-in function names - if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { - call_user_func($this->Debugoutput, $str, $this->do_debug); - return; - } - switch ($this->Debugoutput) { - case 'error_log': - //Don't output, just log - error_log($str); - break; - case 'html': - //Cleans up output a bit for a better looking, HTML-safe output - echo htmlentities( - preg_replace('/[\r\n]+/', '', $str), - ENT_QUOTES, - 'UTF-8' - ) - . "
\n"; - break; - case 'echo': - default: - //Normalize line breaks - $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str); - echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( - "\n", - "\n \t ", - trim($str) - )."\n"; - } - } - - /** - * Connect to an SMTP server. - * @param string $host SMTP server IP or host name - * @param integer $port The port number to connect to - * @param integer $timeout How long to wait for the connection to open - * @param array $options An array of options for stream_context_create() - * @access public - * @return boolean - */ - public function connect($host, $port = null, $timeout = 30, $options = array()) - { - static $streamok; - //This is enabled by default since 5.0.0 but some providers disable it - //Check this once and cache the result - if (is_null($streamok)) { - $streamok = function_exists('stream_socket_client'); - } - // Clear errors to avoid confusion - $this->setError(''); - // Make sure we are __not__ connected - if ($this->connected()) { - // Already connected, generate error - $this->setError('Already connected to a server'); - return false; - } - if (empty($port)) { - $port = self::DEFAULT_SMTP_PORT; - } - // Connect to the SMTP server - $this->edebug( - "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true), - self::DEBUG_CONNECTION - ); - $errno = 0; - $errstr = ''; - if ($streamok) { - $socket_context = stream_context_create($options); - //Suppress errors; connection failures are handled at a higher level - $this->smtp_conn = @stream_socket_client( - $host . ":" . $port, - $errno, - $errstr, - $timeout, - STREAM_CLIENT_CONNECT, - $socket_context - ); - } else { - //Fall back to fsockopen which should work in more places, but is missing some features - $this->edebug( - "Connection: stream_socket_client not available, falling back to fsockopen", - self::DEBUG_CONNECTION - ); - $this->smtp_conn = fsockopen( - $host, - $port, - $errno, - $errstr, - $timeout - ); - } - // Verify we connected properly - if (!is_resource($this->smtp_conn)) { - $this->setError( - 'Failed to connect to server', - $errno, - $errstr - ); - $this->edebug( - 'SMTP ERROR: ' . $this->error['error'] - . ": $errstr ($errno)", - self::DEBUG_CLIENT - ); - return false; - } - $this->edebug('Connection: opened', self::DEBUG_CONNECTION); - // SMTP server can take longer to respond, give longer timeout for first read - // Windows does not have support for this timeout function - if (substr(PHP_OS, 0, 3) != 'WIN') { - $max = ini_get('max_execution_time'); - // Don't bother if unlimited - if ($max != 0 && $timeout > $max) { - @set_time_limit($timeout); - } - stream_set_timeout($this->smtp_conn, $timeout, 0); - } - // Get any announcement - $announce = $this->get_lines(); - $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER); - return true; - } - - /** - * Initiate a TLS (encrypted) session. - * @access public - * @return boolean - */ - public function startTLS() - { - if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { - return false; - } - - //Allow the best TLS version(s) we can - $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; - - //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT - //so add them back in manually if we can - if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { - $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; - $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; - } - - // Begin encrypted connection - if (!stream_socket_enable_crypto( - $this->smtp_conn, - true, - $crypto_method - )) { - return false; - } - return true; - } - - /** - * Perform SMTP authentication. - * Must be run after hello(). - * @see hello() - * @param string $username The user name - * @param string $password The password - * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2) - * @param string $realm The auth realm for NTLM - * @param string $workstation The auth workstation for NTLM - * @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth) - * @return bool True if successfully authenticated.* @access public - */ - public function authenticate( - $username, - $password, - $authtype = null, - $realm = '', - $workstation = '', - $OAuth = null - ) { - if (!$this->server_caps) { - $this->setError('Authentication is not allowed before HELO/EHLO'); - return false; - } - - if (array_key_exists('EHLO', $this->server_caps)) { - // SMTP extensions are available. Let's try to find a proper authentication method - - if (!array_key_exists('AUTH', $this->server_caps)) { - $this->setError('Authentication is not allowed at this stage'); - // 'at this stage' means that auth may be allowed after the stage changes - // e.g. after STARTTLS - return false; - } - - self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL); - self::edebug( - 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), - self::DEBUG_LOWLEVEL - ); - - if (empty($authtype)) { - foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN', 'NTLM', 'XOAUTH2') as $method) { - if (in_array($method, $this->server_caps['AUTH'])) { - $authtype = $method; - break; - } - } - if (empty($authtype)) { - $this->setError('No supported authentication methods found'); - return false; - } - self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL); - } - - if (!in_array($authtype, $this->server_caps['AUTH'])) { - $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); - return false; - } - } elseif (empty($authtype)) { - $authtype = 'LOGIN'; - } - switch ($authtype) { - case 'PLAIN': - // Start authentication - if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { - return false; - } - // Send encoded username and password - if (!$this->sendCommand( - 'User & Password', - base64_encode("\0" . $username . "\0" . $password), - 235 - ) - ) { - return false; - } - break; - case 'LOGIN': - // Start authentication - if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { - return false; - } - if (!$this->sendCommand("Username", base64_encode($username), 334)) { - return false; - } - if (!$this->sendCommand("Password", base64_encode($password), 235)) { - return false; - } - break; - case 'XOAUTH2': - //If the OAuth Instance is not set. Can be a case when PHPMailer is used - //instead of PHPMailerOAuth - if (is_null($OAuth)) { - return false; - } - $oauth = $OAuth->getOauth64(); - - // Start authentication - if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { - return false; - } - break; - case 'NTLM': - /* - * ntlm_sasl_client.php - * Bundled with Permission - * - * How to telnet in windows: - * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx - * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication - */ - require_once 'extras/ntlm_sasl_client.php'; - $temp = new stdClass; - $ntlm_client = new ntlm_sasl_client_class; - //Check that functions are available - if (!$ntlm_client->Initialize($temp)) { - $this->setError($temp->error); - $this->edebug( - 'You need to enable some modules in your php.ini file: ' - . $this->error['error'], - self::DEBUG_CLIENT - ); - return false; - } - //msg1 - $msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1 - - if (!$this->sendCommand( - 'AUTH NTLM', - 'AUTH NTLM ' . base64_encode($msg1), - 334 - ) - ) { - return false; - } - //Though 0 based, there is a white space after the 3 digit number - //msg2 - $challenge = substr($this->last_reply, 3); - $challenge = base64_decode($challenge); - $ntlm_res = $ntlm_client->NTLMResponse( - substr($challenge, 24, 8), - $password - ); - //msg3 - $msg3 = $ntlm_client->TypeMsg3( - $ntlm_res, - $username, - $realm, - $workstation - ); - // send encoded username - return $this->sendCommand('Username', base64_encode($msg3), 235); - case 'CRAM-MD5': - // Start authentication - if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { - return false; - } - // Get the challenge - $challenge = base64_decode(substr($this->last_reply, 4)); - - // Build the response - $response = $username . ' ' . $this->hmac($challenge, $password); - - // send encoded credentials - return $this->sendCommand('Username', base64_encode($response), 235); - default: - $this->setError("Authentication method \"$authtype\" is not supported"); - return false; - } - return true; - } - - /** - * Calculate an MD5 HMAC hash. - * Works like hash_hmac('md5', $data, $key) - * in case that function is not available - * @param string $data The data to hash - * @param string $key The key to hash with - * @access protected - * @return string - */ - protected function hmac($data, $key) - { - if (function_exists('hash_hmac')) { - return hash_hmac('md5', $data, $key); - } - - // The following borrowed from - // http://php.net/manual/en/function.mhash.php#27225 - - // RFC 2104 HMAC implementation for php. - // Creates an md5 HMAC. - // Eliminates the need to install mhash to compute a HMAC - // by Lance Rushing - - $bytelen = 64; // byte length for md5 - if (strlen($key) > $bytelen) { - $key = pack('H*', md5($key)); - } - $key = str_pad($key, $bytelen, chr(0x00)); - $ipad = str_pad('', $bytelen, chr(0x36)); - $opad = str_pad('', $bytelen, chr(0x5c)); - $k_ipad = $key ^ $ipad; - $k_opad = $key ^ $opad; - - return md5($k_opad . pack('H*', md5($k_ipad . $data))); - } - - /** - * Check connection state. - * @access public - * @return boolean True if connected. - */ - public function connected() - { - if (is_resource($this->smtp_conn)) { - $sock_status = stream_get_meta_data($this->smtp_conn); - if ($sock_status['eof']) { - // The socket is valid but we are not connected - $this->edebug( - 'SMTP NOTICE: EOF caught while checking if connected', - self::DEBUG_CLIENT - ); - $this->close(); - return false; - } - return true; // everything looks good - } - return false; - } - - /** - * Close the socket and clean up the state of the class. - * Don't use this function without first trying to use QUIT. - * @see quit() - * @access public - * @return void - */ - public function close() - { - $this->setError(''); - $this->server_caps = null; - $this->helo_rply = null; - if (is_resource($this->smtp_conn)) { - // close the connection and cleanup - fclose($this->smtp_conn); - $this->smtp_conn = null; //Makes for cleaner serialization - $this->edebug('Connection: closed', self::DEBUG_CONNECTION); - } - } - - /** - * Send an SMTP DATA command. - * Issues a data command and sends the msg_data to the server, - * finializing the mail transaction. $msg_data is the message - * that is to be send with the headers. Each header needs to be - * on a single line followed by a with the message headers - * and the message body being separated by and additional . - * Implements rfc 821: DATA - * @param string $msg_data Message data to send - * @access public - * @return boolean - */ - public function data($msg_data) - { - //This will use the standard timelimit - if (!$this->sendCommand('DATA', 'DATA', 354)) { - return false; - } - - /* The server is ready to accept data! - * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF) - * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into - * smaller lines to fit within the limit. - * We will also look for lines that start with a '.' and prepend an additional '.'. - * NOTE: this does not count towards line-length limit. - */ - - // Normalize line breaks before exploding - $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data)); - - /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field - * of the first line (':' separated) does not contain a space then it _should_ be a header and we will - * process all lines before a blank line as headers. - */ - - $field = substr($lines[0], 0, strpos($lines[0], ':')); - $in_headers = false; - if (!empty($field) && strpos($field, ' ') === false) { - $in_headers = true; - } - - foreach ($lines as $line) { - $lines_out = array(); - if ($in_headers and $line == '') { - $in_headers = false; - } - //Break this line up into several smaller lines if it's too long - //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len), - while (isset($line[self::MAX_LINE_LENGTH])) { - //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on - //so as to avoid breaking in the middle of a word - $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' '); - //Deliberately matches both false and 0 - if (!$pos) { - //No nice break found, add a hard break - $pos = self::MAX_LINE_LENGTH - 1; - $lines_out[] = substr($line, 0, $pos); - $line = substr($line, $pos); - } else { - //Break at the found point - $lines_out[] = substr($line, 0, $pos); - //Move along by the amount we dealt with - $line = substr($line, $pos + 1); - } - //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1 - if ($in_headers) { - $line = "\t" . $line; - } - } - $lines_out[] = $line; - - //Send the lines to the server - foreach ($lines_out as $line_out) { - //RFC2821 section 4.5.2 - if (!empty($line_out) and $line_out[0] == '.') { - $line_out = '.' . $line_out; - } - $this->client_send($line_out . self::CRLF); - } - } - - //Message data has been sent, complete the command - //Increase timelimit for end of DATA command - $savetimelimit = $this->Timelimit; - $this->Timelimit = $this->Timelimit * 2; - $result = $this->sendCommand('DATA END', '.', 250); - //Restore timelimit - $this->Timelimit = $savetimelimit; - return $result; - } - - /** - * Send an SMTP HELO or EHLO command. - * Used to identify the sending server to the receiving server. - * This makes sure that client and server are in a known state. - * Implements RFC 821: HELO - * and RFC 2821 EHLO. - * @param string $host The host name or IP to connect to - * @access public - * @return boolean - */ - public function hello($host = '') - { - //Try extended hello first (RFC 2821) - return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host)); - } - - /** - * Send an SMTP HELO or EHLO command. - * Low-level implementation used by hello() - * @see hello() - * @param string $hello The HELO string - * @param string $host The hostname to say we are - * @access protected - * @return boolean - */ - protected function sendHello($hello, $host) - { - $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); - $this->helo_rply = $this->last_reply; - if ($noerror) { - $this->parseHelloFields($hello); - } else { - $this->server_caps = null; - } - return $noerror; - } - - /** - * Parse a reply to HELO/EHLO command to discover server extensions. - * In case of HELO, the only parameter that can be discovered is a server name. - * @access protected - * @param string $type - 'HELO' or 'EHLO' - */ - protected function parseHelloFields($type) - { - $this->server_caps = array(); - $lines = explode("\n", $this->helo_rply); - - foreach ($lines as $n => $s) { - //First 4 chars contain response code followed by - or space - $s = trim(substr($s, 4)); - if (empty($s)) { - continue; - } - $fields = explode(' ', $s); - if (!empty($fields)) { - if (!$n) { - $name = $type; - $fields = $fields[0]; - } else { - $name = array_shift($fields); - switch ($name) { - case 'SIZE': - $fields = ($fields ? $fields[0] : 0); - break; - case 'AUTH': - if (!is_array($fields)) { - $fields = array(); - } - break; - default: - $fields = true; - } - } - $this->server_caps[$name] = $fields; - } - } - } - - /** - * Send an SMTP MAIL command. - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more recipient - * commands may be called followed by a data command. - * Implements rfc 821: MAIL FROM: - * @param string $from Source address of this message - * @access public - * @return boolean - */ - public function mail($from) - { - $useVerp = ($this->do_verp ? ' XVERP' : ''); - return $this->sendCommand( - 'MAIL FROM', - 'MAIL FROM:<' . $from . '>' . $useVerp, - 250 - ); - } - - /** - * Send an SMTP QUIT command. - * Closes the socket if there is no error or the $close_on_error argument is true. - * Implements from rfc 821: QUIT - * @param boolean $close_on_error Should the connection close if an error occurs? - * @access public - * @return boolean - */ - public function quit($close_on_error = true) - { - $noerror = $this->sendCommand('QUIT', 'QUIT', 221); - $err = $this->error; //Save any error - if ($noerror or $close_on_error) { - $this->close(); - $this->error = $err; //Restore any error from the quit command - } - return $noerror; - } - - /** - * Send an SMTP RCPT command. - * Sets the TO argument to $toaddr. - * Returns true if the recipient was accepted false if it was rejected. - * Implements from rfc 821: RCPT TO: - * @param string $address The address the message is being sent to - * @access public - * @return boolean - */ - public function recipient($address) - { - return $this->sendCommand( - 'RCPT TO', - 'RCPT TO:<' . $address . '>', - array(250, 251) - ); - } - - /** - * Send an SMTP RSET command. - * Abort any transaction that is currently in progress. - * Implements rfc 821: RSET - * @access public - * @return boolean True on success. - */ - public function reset() - { - return $this->sendCommand('RSET', 'RSET', 250); - } - - /** - * Send a command to an SMTP server and check its return code. - * @param string $command The command name - not sent to the server - * @param string $commandstring The actual command to send - * @param integer|array $expect One or more expected integer success codes - * @access protected - * @return boolean True on success. - */ - protected function sendCommand($command, $commandstring, $expect) - { - if (!$this->connected()) { - $this->setError("Called $command without being connected"); - return false; - } - //Reject line breaks in all commands - if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) { - $this->setError("Command '$command' contained line breaks"); - return false; - } - $this->client_send($commandstring . self::CRLF); - - $this->last_reply = $this->get_lines(); - // Fetch SMTP code and possible error code explanation - $matches = array(); - if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) { - $code = $matches[1]; - $code_ex = (count($matches) > 2 ? $matches[2] : null); - // Cut off error code from each response line - $detail = preg_replace( - "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m", - '', - $this->last_reply - ); - } else { - // Fall back to simple parsing if regex fails - $code = substr($this->last_reply, 0, 3); - $code_ex = null; - $detail = substr($this->last_reply, 4); - } - - $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); - - if (!in_array($code, (array)$expect)) { - $this->setError( - "$command command failed", - $detail, - $code, - $code_ex - ); - $this->edebug( - 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, - self::DEBUG_CLIENT - ); - return false; - } - - $this->setError(''); - return true; - } - - /** - * Send an SMTP SAML command. - * Starts a mail transaction from the email address specified in $from. - * Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more recipient - * commands may be called followed by a data command. This command - * will send the message to the users terminal if they are logged - * in and send them an email. - * Implements rfc 821: SAML FROM: - * @param string $from The address the message is from - * @access public - * @return boolean - */ - public function sendAndMail($from) - { - return $this->sendCommand('SAML', "SAML FROM:$from", 250); - } - - /** - * Send an SMTP VRFY command. - * @param string $name The name to verify - * @access public - * @return boolean - */ - public function verify($name) - { - return $this->sendCommand('VRFY', "VRFY $name", array(250, 251)); - } - - /** - * Send an SMTP NOOP command. - * Used to keep keep-alives alive, doesn't actually do anything - * @access public - * @return boolean - */ - public function noop() - { - return $this->sendCommand('NOOP', 'NOOP', 250); - } - - /** - * Send an SMTP TURN command. - * This is an optional command for SMTP that this class does not support. - * This method is here to make the RFC821 Definition complete for this class - * and _may_ be implemented in future - * Implements from rfc 821: TURN - * @access public - * @return boolean - */ - public function turn() - { - $this->setError('The SMTP TURN command is not implemented'); - $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); - return false; - } - - /** - * Send raw data to the server. - * @param string $data The data to send - * @access public - * @return integer|boolean The number of bytes sent to the server or false on error - */ - public function client_send($data) - { - $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT); - return fwrite($this->smtp_conn, $data); - } - - /** - * Get the latest error. - * @access public - * @return array - */ - public function getError() - { - return $this->error; - } - - /** - * Get SMTP extensions available on the server - * @access public - * @return array|null - */ - public function getServerExtList() - { - return $this->server_caps; - } - - /** - * A multipurpose method - * The method works in three ways, dependent on argument value and current state - * 1. HELO/EHLO was not sent - returns null and set up $this->error - * 2. HELO was sent - * $name = 'HELO': returns server name - * $name = 'EHLO': returns boolean false - * $name = any string: returns null and set up $this->error - * 3. EHLO was sent - * $name = 'HELO'|'EHLO': returns server name - * $name = any string: if extension $name exists, returns boolean True - * or its options. Otherwise returns boolean False - * In other words, one can use this method to detect 3 conditions: - * - null returned: handshake was not or we don't know about ext (refer to $this->error) - * - false returned: the requested feature exactly not exists - * - positive value returned: the requested feature exists - * @param string $name Name of SMTP extension or 'HELO'|'EHLO' - * @return mixed - */ - public function getServerExt($name) - { - if (!$this->server_caps) { - $this->setError('No HELO/EHLO was sent'); - return null; - } - - // the tight logic knot ;) - if (!array_key_exists($name, $this->server_caps)) { - if ($name == 'HELO') { - return $this->server_caps['EHLO']; - } - if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) { - return false; - } - $this->setError('HELO handshake was used. Client knows nothing about server extensions'); - return null; - } - - return $this->server_caps[$name]; - } - - /** - * Get the last reply from the server. - * @access public - * @return string - */ - public function getLastReply() - { - return $this->last_reply; - } - - /** - * Read the SMTP server's response. - * Either before eof or socket timeout occurs on the operation. - * With SMTP we can tell if we have more lines to read if the - * 4th character is '-' symbol. If it is a space then we don't - * need to read anything else. - * @access protected - * @return string - */ - protected function get_lines() - { - // If the connection is bad, give up straight away - if (!is_resource($this->smtp_conn)) { - return ''; - } - $data = ''; - $endtime = 0; - stream_set_timeout($this->smtp_conn, $this->Timeout); - if ($this->Timelimit > 0) { - $endtime = time() + $this->Timelimit; - } - while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { - $str = @fgets($this->smtp_conn, 515); - $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL); - $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL); - $data .= $str; - // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen - if ((isset($str[3]) and $str[3] == ' ')) { - break; - } - // Timed-out? Log and break - $info = stream_get_meta_data($this->smtp_conn); - if ($info['timed_out']) { - $this->edebug( - 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)', - self::DEBUG_LOWLEVEL - ); - break; - } - // Now check if reads took too long - if ($endtime and time() > $endtime) { - $this->edebug( - 'SMTP -> get_lines(): timelimit reached ('. - $this->Timelimit . ' sec)', - self::DEBUG_LOWLEVEL - ); - break; - } - } - return $data; - } - - /** - * Enable or disable VERP address generation. - * @param boolean $enabled - */ - public function setVerp($enabled = false) - { - $this->do_verp = $enabled; - } - - /** - * Get VERP address generation mode. - * @return boolean - */ - public function getVerp() - { - return $this->do_verp; - } - - /** - * Set error messages and codes. - * @param string $message The error message - * @param string $detail Further detail on the error - * @param string $smtp_code An associated SMTP error code - * @param string $smtp_code_ex Extended SMTP code - */ - protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') - { - $this->error = array( - 'error' => $message, - 'detail' => $detail, - 'smtp_code' => $smtp_code, - 'smtp_code_ex' => $smtp_code_ex - ); - } - - /** - * Set debug output method. - * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it. - */ - public function setDebugOutput($method = 'echo') - { - $this->Debugoutput = $method; - } - - /** - * Get debug output method. - * @return string - */ - public function getDebugOutput() - { - return $this->Debugoutput; - } - - /** - * Set debug output level. - * @param integer $level - */ - public function setDebugLevel($level = 0) - { - $this->do_debug = $level; - } - - /** - * Get debug output level. - * @return integer - */ - public function getDebugLevel() - { - return $this->do_debug; - } - - /** - * Set SMTP timeout. - * @param integer $timeout - */ - public function setTimeout($timeout = 0) - { - $this->Timeout = $timeout; - } - - /** - * Get SMTP timeout. - * @return integer - */ - public function getTimeout() - { - return $this->Timeout; - } + /** + * The PHPMailer SMTP version number. + * @var string + */ + const VERSION = '5.2.21'; + + /** + * SMTP line break constant. + * @var string + */ + const CRLF = "\r\n"; + + /** + * The SMTP port to use if one is not specified. + * @var integer + */ + const DEFAULT_SMTP_PORT = 25; + + /** + * The maximum line length allowed by RFC 2822 section 2.1.1 + * @var integer + */ + const MAX_LINE_LENGTH = 998; + + /** + * Debug level for no output + */ + const DEBUG_OFF = 0; + + /** + * Debug level to show client -> server messages + */ + const DEBUG_CLIENT = 1; + + /** + * Debug level to show client -> server and server -> client messages + */ + const DEBUG_SERVER = 2; + + /** + * Debug level to show connection status, client -> server and server -> client messages + */ + const DEBUG_CONNECTION = 3; + + /** + * Debug level to show all messages + */ + const DEBUG_LOWLEVEL = 4; + + /** + * The PHPMailer SMTP Version number. + * @var string + * @deprecated Use the `VERSION` constant instead + * @see SMTP::VERSION + */ + public $Version = '5.2.21'; + + /** + * SMTP server port number. + * @var integer + * @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead + * @see SMTP::DEFAULT_SMTP_PORT + */ + public $SMTP_PORT = 25; + + /** + * SMTP reply line ending. + * @var string + * @deprecated Use the `CRLF` constant instead + * @see SMTP::CRLF + */ + public $CRLF = "\r\n"; + + /** + * Debug output level. + * Options: + * * self::DEBUG_OFF (`0`) No debug output, default + * * self::DEBUG_CLIENT (`1`) Client commands + * * self::DEBUG_SERVER (`2`) Client commands and server responses + * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status + * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages + * @var integer + */ + public $do_debug = self::DEBUG_OFF; + + /** + * How to handle debug output. + * Options: + * * `echo` Output plain-text as-is, appropriate for CLI + * * `html` Output escaped, line breaks converted to `
`, appropriate for browser output + * * `error_log` Output to error log as configured in php.ini + * + * Alternatively, you can provide a callable expecting two params: a message string and the debug level: + * + * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";}; + * + * @var string|callable + */ + public $Debugoutput = 'echo'; + + /** + * Whether to use VERP. + * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path + * @link http://www.postfix.org/VERP_README.html Info on VERP + * @var boolean + */ + public $do_verp = false; + + /** + * The timeout value for connection, in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 + * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure. + * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2 + * @var integer + */ + public $Timeout = 300; + + /** + * How long to wait for commands to complete, in seconds. + * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 + * @var integer + */ + public $Timelimit = 300; + + /** + * @var array patterns to extract smtp transaction id from smtp reply + * Only first capture group will be use, use non-capturing group to deal with it + * Extend this class to override this property to fulfil your needs. + */ + protected $smtp_transaction_id_patterns = array( + 'exim' => '/[0-9]{3} OK id=(.*)/', + 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/', + 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/' + ); + + /** + * The socket for the server connection. + * @var resource + */ + protected $smtp_conn; + + /** + * Error information, if any, for the last SMTP command. + * @var array + */ + protected $error = array( + 'error' => '', + 'detail' => '', + 'smtp_code' => '', + 'smtp_code_ex' => '' + ); + + /** + * The reply the server sent to us for HELO. + * If null, no HELO string has yet been received. + * @var string|null + */ + protected $helo_rply = null; + + /** + * The set of SMTP extensions sent in reply to EHLO command. + * Indexes of the array are extension names. + * Value at index 'HELO' or 'EHLO' (according to command that was sent) + * represents the server name. In case of HELO it is the only element of the array. + * Other values can be boolean TRUE or an array containing extension options. + * If null, no HELO/EHLO string has yet been received. + * @var array|null + */ + protected $server_caps = null; + + /** + * The most recent reply received from the server. + * @var string + */ + protected $last_reply = ''; + + /** + * Output debugging info via a user-selected method. + * @see SMTP::$Debugoutput + * @see SMTP::$do_debug + * @param string $str Debug string to output + * @param integer $level The debug level of this message; see DEBUG_* constants + * @return void + */ + protected function edebug($str, $level = 0) + { + if ($level > $this->do_debug) { + return; + } + //Avoid clash with built-in function names + if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { + call_user_func($this->Debugoutput, $str, $level); + return; + } + switch ($this->Debugoutput) { + case 'error_log': + //Don't output, just log + error_log($str); + break; + case 'html': + //Cleans up output a bit for a better looking, HTML-safe output + echo htmlentities( + preg_replace('/[\r\n]+/', '', $str), + ENT_QUOTES, + 'UTF-8' + ) + . "
\n"; + break; + case 'echo': + default: + //Normalize line breaks + $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str); + echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( + "\n", + "\n \t ", + trim($str) + )."\n"; + } + } + + /** + * Connect to an SMTP server. + * @param string $host SMTP server IP or host name + * @param integer $port The port number to connect to + * @param integer $timeout How long to wait for the connection to open + * @param array $options An array of options for stream_context_create() + * @access public + * @return boolean + */ + public function connect($host, $port = null, $timeout = 30, $options = array()) + { + static $streamok; + //This is enabled by default since 5.0.0 but some providers disable it + //Check this once and cache the result + if (is_null($streamok)) { + $streamok = function_exists('stream_socket_client'); + } + // Clear errors to avoid confusion + $this->setError(''); + // Make sure we are __not__ connected + if ($this->connected()) { + // Already connected, generate error + $this->setError('Already connected to a server'); + return false; + } + if (empty($port)) { + $port = self::DEFAULT_SMTP_PORT; + } + // Connect to the SMTP server + $this->edebug( + "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true), + self::DEBUG_CONNECTION + ); + $errno = 0; + $errstr = ''; + if ($streamok) { + $socket_context = stream_context_create($options); + set_error_handler(array($this, 'errorHandler')); + $this->smtp_conn = stream_socket_client( + $host . ":" . $port, + $errno, + $errstr, + $timeout, + STREAM_CLIENT_CONNECT, + $socket_context + ); + restore_error_handler(); + } else { + //Fall back to fsockopen which should work in more places, but is missing some features + $this->edebug( + "Connection: stream_socket_client not available, falling back to fsockopen", + self::DEBUG_CONNECTION + ); + set_error_handler(array($this, 'errorHandler')); + $this->smtp_conn = fsockopen( + $host, + $port, + $errno, + $errstr, + $timeout + ); + restore_error_handler(); + } + // Verify we connected properly + if (!is_resource($this->smtp_conn)) { + $this->setError( + 'Failed to connect to server', + $errno, + $errstr + ); + $this->edebug( + 'SMTP ERROR: ' . $this->error['error'] + . ": $errstr ($errno)", + self::DEBUG_CLIENT + ); + return false; + } + $this->edebug('Connection: opened', self::DEBUG_CONNECTION); + // SMTP server can take longer to respond, give longer timeout for first read + // Windows does not have support for this timeout function + if (substr(PHP_OS, 0, 3) != 'WIN') { + $max = ini_get('max_execution_time'); + // Don't bother if unlimited + if ($max != 0 && $timeout > $max) { + @set_time_limit($timeout); + } + stream_set_timeout($this->smtp_conn, $timeout, 0); + } + // Get any announcement + $announce = $this->get_lines(); + $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER); + return true; + } + + /** + * Initiate a TLS (encrypted) session. + * @access public + * @return boolean + */ + public function startTLS() + { + if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { + return false; + } + + //Allow the best TLS version(s) we can + $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; + + //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT + //so add them back in manually if we can + if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { + $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; + $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; + } + + // Begin encrypted connection + if (!stream_socket_enable_crypto( + $this->smtp_conn, + true, + $crypto_method + )) { + return false; + } + return true; + } + + /** + * Perform SMTP authentication. + * Must be run after hello(). + * @see hello() + * @param string $username The user name + * @param string $password The password + * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2) + * @param string $realm The auth realm for NTLM + * @param string $workstation The auth workstation for NTLM + * @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth) + * @return bool True if successfully authenticated.* @access public + */ + public function authenticate( + $username, + $password, + $authtype = null, + $realm = '', + $workstation = '', + $OAuth = null + ) { + if (!$this->server_caps) { + $this->setError('Authentication is not allowed before HELO/EHLO'); + return false; + } + + if (array_key_exists('EHLO', $this->server_caps)) { + // SMTP extensions are available. Let's try to find a proper authentication method + + if (!array_key_exists('AUTH', $this->server_caps)) { + $this->setError('Authentication is not allowed at this stage'); + // 'at this stage' means that auth may be allowed after the stage changes + // e.g. after STARTTLS + return false; + } + + self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL); + self::edebug( + 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), + self::DEBUG_LOWLEVEL + ); + + if (empty($authtype)) { + foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN', 'NTLM', 'XOAUTH2') as $method) { + if (in_array($method, $this->server_caps['AUTH'])) { + $authtype = $method; + break; + } + } + if (empty($authtype)) { + $this->setError('No supported authentication methods found'); + return false; + } + self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL); + } + + if (!in_array($authtype, $this->server_caps['AUTH'])) { + $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); + return false; + } + } elseif (empty($authtype)) { + $authtype = 'LOGIN'; + } + switch ($authtype) { + case 'PLAIN': + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { + return false; + } + // Send encoded username and password + if (!$this->sendCommand( + 'User & Password', + base64_encode("\0" . $username . "\0" . $password), + 235 + ) + ) { + return false; + } + break; + case 'LOGIN': + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { + return false; + } + if (!$this->sendCommand("Username", base64_encode($username), 334)) { + return false; + } + if (!$this->sendCommand("Password", base64_encode($password), 235)) { + return false; + } + break; + case 'XOAUTH2': + //If the OAuth Instance is not set. Can be a case when PHPMailer is used + //instead of PHPMailerOAuth + if (is_null($OAuth)) { + return false; + } + $oauth = $OAuth->getOauth64(); + + // Start authentication + if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { + return false; + } + break; + case 'NTLM': + /* + * ntlm_sasl_client.php + * Bundled with Permission + * + * How to telnet in windows: + * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx + * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication + */ + require_once 'extras/ntlm_sasl_client.php'; + $temp = new stdClass; + $ntlm_client = new ntlm_sasl_client_class; + //Check that functions are available + if (!$ntlm_client->initialize($temp)) { + $this->setError($temp->error); + $this->edebug( + 'You need to enable some modules in your php.ini file: ' + . $this->error['error'], + self::DEBUG_CLIENT + ); + return false; + } + //msg1 + $msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1 + + if (!$this->sendCommand( + 'AUTH NTLM', + 'AUTH NTLM ' . base64_encode($msg1), + 334 + ) + ) { + return false; + } + //Though 0 based, there is a white space after the 3 digit number + //msg2 + $challenge = substr($this->last_reply, 3); + $challenge = base64_decode($challenge); + $ntlm_res = $ntlm_client->NTLMResponse( + substr($challenge, 24, 8), + $password + ); + //msg3 + $msg3 = $ntlm_client->typeMsg3( + $ntlm_res, + $username, + $realm, + $workstation + ); + // send encoded username + return $this->sendCommand('Username', base64_encode($msg3), 235); + case 'CRAM-MD5': + // Start authentication + if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { + return false; + } + // Get the challenge + $challenge = base64_decode(substr($this->last_reply, 4)); + + // Build the response + $response = $username . ' ' . $this->hmac($challenge, $password); + + // send encoded credentials + return $this->sendCommand('Username', base64_encode($response), 235); + default: + $this->setError("Authentication method \"$authtype\" is not supported"); + return false; + } + return true; + } + + /** + * Calculate an MD5 HMAC hash. + * Works like hash_hmac('md5', $data, $key) + * in case that function is not available + * @param string $data The data to hash + * @param string $key The key to hash with + * @access protected + * @return string + */ + protected function hmac($data, $key) + { + if (function_exists('hash_hmac')) { + return hash_hmac('md5', $data, $key); + } + + // The following borrowed from + // http://php.net/manual/en/function.mhash.php#27225 + + // RFC 2104 HMAC implementation for php. + // Creates an md5 HMAC. + // Eliminates the need to install mhash to compute a HMAC + // by Lance Rushing + + $bytelen = 64; // byte length for md5 + if (strlen($key) > $bytelen) { + $key = pack('H*', md5($key)); + } + $key = str_pad($key, $bytelen, chr(0x00)); + $ipad = str_pad('', $bytelen, chr(0x36)); + $opad = str_pad('', $bytelen, chr(0x5c)); + $k_ipad = $key ^ $ipad; + $k_opad = $key ^ $opad; + + return md5($k_opad . pack('H*', md5($k_ipad . $data))); + } + + /** + * Check connection state. + * @access public + * @return boolean True if connected. + */ + public function connected() + { + if (is_resource($this->smtp_conn)) { + $sock_status = stream_get_meta_data($this->smtp_conn); + if ($sock_status['eof']) { + // The socket is valid but we are not connected + $this->edebug( + 'SMTP NOTICE: EOF caught while checking if connected', + self::DEBUG_CLIENT + ); + $this->close(); + return false; + } + return true; // everything looks good + } + return false; + } + + /** + * Close the socket and clean up the state of the class. + * Don't use this function without first trying to use QUIT. + * @see quit() + * @access public + * @return void + */ + public function close() + { + $this->setError(''); + $this->server_caps = null; + $this->helo_rply = null; + if (is_resource($this->smtp_conn)) { + // close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = null; //Makes for cleaner serialization + $this->edebug('Connection: closed', self::DEBUG_CONNECTION); + } + } + + /** + * Send an SMTP DATA command. + * Issues a data command and sends the msg_data to the server, + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a with the message headers + * and the message body being separated by and additional . + * Implements rfc 821: DATA + * @param string $msg_data Message data to send + * @access public + * @return boolean + */ + public function data($msg_data) + { + //This will use the standard timelimit + if (!$this->sendCommand('DATA', 'DATA', 354)) { + return false; + } + + /* The server is ready to accept data! + * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF) + * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into + * smaller lines to fit within the limit. + * We will also look for lines that start with a '.' and prepend an additional '.'. + * NOTE: this does not count towards line-length limit. + */ + + // Normalize line breaks before exploding + $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data)); + + /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field + * of the first line (':' separated) does not contain a space then it _should_ be a header and we will + * process all lines before a blank line as headers. + */ + + $field = substr($lines[0], 0, strpos($lines[0], ':')); + $in_headers = false; + if (!empty($field) && strpos($field, ' ') === false) { + $in_headers = true; + } + + foreach ($lines as $line) { + $lines_out = array(); + if ($in_headers and $line == '') { + $in_headers = false; + } + //Break this line up into several smaller lines if it's too long + //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len), + while (isset($line[self::MAX_LINE_LENGTH])) { + //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on + //so as to avoid breaking in the middle of a word + $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' '); + //Deliberately matches both false and 0 + if (!$pos) { + //No nice break found, add a hard break + $pos = self::MAX_LINE_LENGTH - 1; + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos); + } else { + //Break at the found point + $lines_out[] = substr($line, 0, $pos); + //Move along by the amount we dealt with + $line = substr($line, $pos + 1); + } + //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1 + if ($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + //Send the lines to the server + foreach ($lines_out as $line_out) { + //RFC2821 section 4.5.2 + if (!empty($line_out) and $line_out[0] == '.') { + $line_out = '.' . $line_out; + } + $this->client_send($line_out . self::CRLF); + } + } + + //Message data has been sent, complete the command + //Increase timelimit for end of DATA command + $savetimelimit = $this->Timelimit; + $this->Timelimit = $this->Timelimit * 2; + $result = $this->sendCommand('DATA END', '.', 250); + //Restore timelimit + $this->Timelimit = $savetimelimit; + return $result; + } + + /** + * Send an SMTP HELO or EHLO command. + * Used to identify the sending server to the receiving server. + * This makes sure that client and server are in a known state. + * Implements RFC 821: HELO + * and RFC 2821 EHLO. + * @param string $host The host name or IP to connect to + * @access public + * @return boolean + */ + public function hello($host = '') + { + //Try extended hello first (RFC 2821) + return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host)); + } + + /** + * Send an SMTP HELO or EHLO command. + * Low-level implementation used by hello() + * @see hello() + * @param string $hello The HELO string + * @param string $host The hostname to say we are + * @access protected + * @return boolean + */ + protected function sendHello($hello, $host) + { + $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250); + $this->helo_rply = $this->last_reply; + if ($noerror) { + $this->parseHelloFields($hello); + } else { + $this->server_caps = null; + } + return $noerror; + } + + /** + * Parse a reply to HELO/EHLO command to discover server extensions. + * In case of HELO, the only parameter that can be discovered is a server name. + * @access protected + * @param string $type - 'HELO' or 'EHLO' + */ + protected function parseHelloFields($type) + { + $this->server_caps = array(); + $lines = explode("\n", $this->helo_rply); + + foreach ($lines as $n => $s) { + //First 4 chars contain response code followed by - or space + $s = trim(substr($s, 4)); + if (empty($s)) { + continue; + } + $fields = explode(' ', $s); + if (!empty($fields)) { + if (!$n) { + $name = $type; + $fields = $fields[0]; + } else { + $name = array_shift($fields); + switch ($name) { + case 'SIZE': + $fields = ($fields ? $fields[0] : 0); + break; + case 'AUTH': + if (!is_array($fields)) { + $fields = array(); + } + break; + default: + $fields = true; + } + } + $this->server_caps[$name] = $fields; + } + } + } + + /** + * Send an SMTP MAIL command. + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. + * Implements rfc 821: MAIL FROM: + * @param string $from Source address of this message + * @access public + * @return boolean + */ + public function mail($from) + { + $useVerp = ($this->do_verp ? ' XVERP' : ''); + return $this->sendCommand( + 'MAIL FROM', + 'MAIL FROM:<' . $from . '>' . $useVerp, + 250 + ); + } + + /** + * Send an SMTP QUIT command. + * Closes the socket if there is no error or the $close_on_error argument is true. + * Implements from rfc 821: QUIT + * @param boolean $close_on_error Should the connection close if an error occurs? + * @access public + * @return boolean + */ + public function quit($close_on_error = true) + { + $noerror = $this->sendCommand('QUIT', 'QUIT', 221); + $err = $this->error; //Save any error + if ($noerror or $close_on_error) { + $this->close(); + $this->error = $err; //Restore any error from the quit command + } + return $noerror; + } + + /** + * Send an SMTP RCPT command. + * Sets the TO argument to $toaddr. + * Returns true if the recipient was accepted false if it was rejected. + * Implements from rfc 821: RCPT TO: + * @param string $address The address the message is being sent to + * @access public + * @return boolean + */ + public function recipient($address) + { + return $this->sendCommand( + 'RCPT TO', + 'RCPT TO:<' . $address . '>', + array(250, 251) + ); + } + + /** + * Send an SMTP RSET command. + * Abort any transaction that is currently in progress. + * Implements rfc 821: RSET + * @access public + * @return boolean True on success. + */ + public function reset() + { + return $this->sendCommand('RSET', 'RSET', 250); + } + + /** + * Send a command to an SMTP server and check its return code. + * @param string $command The command name - not sent to the server + * @param string $commandstring The actual command to send + * @param integer|array $expect One or more expected integer success codes + * @access protected + * @return boolean True on success. + */ + protected function sendCommand($command, $commandstring, $expect) + { + if (!$this->connected()) { + $this->setError("Called $command without being connected"); + return false; + } + //Reject line breaks in all commands + if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) { + $this->setError("Command '$command' contained line breaks"); + return false; + } + $this->client_send($commandstring . self::CRLF); + + $this->last_reply = $this->get_lines(); + // Fetch SMTP code and possible error code explanation + $matches = array(); + if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) { + $code = $matches[1]; + $code_ex = (count($matches) > 2 ? $matches[2] : null); + // Cut off error code from each response line + $detail = preg_replace( + "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m", + '', + $this->last_reply + ); + } else { + // Fall back to simple parsing if regex fails + $code = substr($this->last_reply, 0, 3); + $code_ex = null; + $detail = substr($this->last_reply, 4); + } + + $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); + + if (!in_array($code, (array)$expect)) { + $this->setError( + "$command command failed", + $detail, + $code, + $code_ex + ); + $this->edebug( + 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, + self::DEBUG_CLIENT + ); + return false; + } + + $this->setError(''); + return true; + } + + /** + * Send an SMTP SAML command. + * Starts a mail transaction from the email address specified in $from. + * Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more recipient + * commands may be called followed by a data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * Implements rfc 821: SAML FROM: + * @param string $from The address the message is from + * @access public + * @return boolean + */ + public function sendAndMail($from) + { + return $this->sendCommand('SAML', "SAML FROM:$from", 250); + } + + /** + * Send an SMTP VRFY command. + * @param string $name The name to verify + * @access public + * @return boolean + */ + public function verify($name) + { + return $this->sendCommand('VRFY', "VRFY $name", array(250, 251)); + } + + /** + * Send an SMTP NOOP command. + * Used to keep keep-alives alive, doesn't actually do anything + * @access public + * @return boolean + */ + public function noop() + { + return $this->sendCommand('NOOP', 'NOOP', 250); + } + + /** + * Send an SMTP TURN command. + * This is an optional command for SMTP that this class does not support. + * This method is here to make the RFC821 Definition complete for this class + * and _may_ be implemented in future + * Implements from rfc 821: TURN + * @access public + * @return boolean + */ + public function turn() + { + $this->setError('The SMTP TURN command is not implemented'); + $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); + return false; + } + + /** + * Send raw data to the server. + * @param string $data The data to send + * @access public + * @return integer|boolean The number of bytes sent to the server or false on error + */ + public function client_send($data) + { + $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT); + return fwrite($this->smtp_conn, $data); + } + + /** + * Get the latest error. + * @access public + * @return array + */ + public function getError() + { + return $this->error; + } + + /** + * Get SMTP extensions available on the server + * @access public + * @return array|null + */ + public function getServerExtList() + { + return $this->server_caps; + } + + /** + * A multipurpose method + * The method works in three ways, dependent on argument value and current state + * 1. HELO/EHLO was not sent - returns null and set up $this->error + * 2. HELO was sent + * $name = 'HELO': returns server name + * $name = 'EHLO': returns boolean false + * $name = any string: returns null and set up $this->error + * 3. EHLO was sent + * $name = 'HELO'|'EHLO': returns server name + * $name = any string: if extension $name exists, returns boolean True + * or its options. Otherwise returns boolean False + * In other words, one can use this method to detect 3 conditions: + * - null returned: handshake was not or we don't know about ext (refer to $this->error) + * - false returned: the requested feature exactly not exists + * - positive value returned: the requested feature exists + * @param string $name Name of SMTP extension or 'HELO'|'EHLO' + * @return mixed + */ + public function getServerExt($name) + { + if (!$this->server_caps) { + $this->setError('No HELO/EHLO was sent'); + return null; + } + + // the tight logic knot ;) + if (!array_key_exists($name, $this->server_caps)) { + if ($name == 'HELO') { + return $this->server_caps['EHLO']; + } + if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) { + return false; + } + $this->setError('HELO handshake was used. Client knows nothing about server extensions'); + return null; + } + + return $this->server_caps[$name]; + } + + /** + * Get the last reply from the server. + * @access public + * @return string + */ + public function getLastReply() + { + return $this->last_reply; + } + + /** + * Read the SMTP server's response. + * Either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * @access protected + * @return string + */ + protected function get_lines() + { + // If the connection is bad, give up straight away + if (!is_resource($this->smtp_conn)) { + return ''; + } + $data = ''; + $endtime = 0; + stream_set_timeout($this->smtp_conn, $this->Timeout); + if ($this->Timelimit > 0) { + $endtime = time() + $this->Timelimit; + } + while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { + $str = @fgets($this->smtp_conn, 515); + $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL); + $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL); + $data .= $str; + // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen + if ((isset($str[3]) and $str[3] == ' ')) { + break; + } + // Timed-out? Log and break + $info = stream_get_meta_data($this->smtp_conn); + if ($info['timed_out']) { + $this->edebug( + 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)', + self::DEBUG_LOWLEVEL + ); + break; + } + // Now check if reads took too long + if ($endtime and time() > $endtime) { + $this->edebug( + 'SMTP -> get_lines(): timelimit reached ('. + $this->Timelimit . ' sec)', + self::DEBUG_LOWLEVEL + ); + break; + } + } + return $data; + } + + /** + * Enable or disable VERP address generation. + * @param boolean $enabled + */ + public function setVerp($enabled = false) + { + $this->do_verp = $enabled; + } + + /** + * Get VERP address generation mode. + * @return boolean + */ + public function getVerp() + { + return $this->do_verp; + } + + /** + * Set error messages and codes. + * @param string $message The error message + * @param string $detail Further detail on the error + * @param string $smtp_code An associated SMTP error code + * @param string $smtp_code_ex Extended SMTP code + */ + protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') + { + $this->error = array( + 'error' => $message, + 'detail' => $detail, + 'smtp_code' => $smtp_code, + 'smtp_code_ex' => $smtp_code_ex + ); + } + + /** + * Set debug output method. + * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it. + */ + public function setDebugOutput($method = 'echo') + { + $this->Debugoutput = $method; + } + + /** + * Get debug output method. + * @return string + */ + public function getDebugOutput() + { + return $this->Debugoutput; + } + + /** + * Set debug output level. + * @param integer $level + */ + public function setDebugLevel($level = 0) + { + $this->do_debug = $level; + } + + /** + * Get debug output level. + * @return integer + */ + public function getDebugLevel() + { + return $this->do_debug; + } + + /** + * Set SMTP timeout. + * @param integer $timeout + */ + public function setTimeout($timeout = 0) + { + $this->Timeout = $timeout; + } + + /** + * Get SMTP timeout. + * @return integer + */ + public function getTimeout() + { + return $this->Timeout; + } + + /** + * Reports an error number and string. + * @param integer $errno The error number returned by PHP. + * @param string $errmsg The error message returned by PHP. + */ + protected function errorHandler($errno, $errmsg) + { + $notice = 'Connection: Failed to connect to server.'; + $this->setError( + $notice, + $errno, + $errmsg + ); + $this->edebug( + $notice . ' Error number ' . $errno . '. "Error notice: ' . $errmsg, + self::DEBUG_CONNECTION + ); + } + + /** + * Will return the ID of the last smtp transaction based on a list of patterns provided + * in SMTP::$smtp_transaction_id_patterns. + * If no reply has been received yet, it will return null. + * If no pattern has been matched, it will return false. + * @return bool|null|string + */ + public function getLastTransactionID() + { + $reply = $this->getLastReply(); + + if (empty($reply)) { + return null; + } + + foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { + if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) { + return $matches[1]; + } + } + + return false; + } } From d11ddd910f2e24b66a0fb625b7ccc97806330f78 Mon Sep 17 00:00:00 2001 From: Christian Becker Date: Mon, 2 Jan 2017 03:06:18 +0100 Subject: [PATCH 027/179] fix hsts removal links without a protocol, they are treated relative which is annoying --- lng/english.lng.php | 2 +- lng/german.lng.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lng/english.lng.php b/lng/english.lng.php index 45996cd0..e3b96eda 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2061,7 +2061,7 @@ $lng['admin']['domain_hsts_maxage']['description'] = 'Specify the max-age value $lng['admin']['domain_hsts_incsub']['title'] = 'Include HSTS for any subdomain'; $lng['admin']['domain_hsts_incsub']['description'] = 'The optional "includeSubDomains" directive, if present, signals the UA that the HSTS Policy applies to this HSTS Host as well as any subdomains of the host\'s domain name.'; $lng['admin']['domain_hsts_preload']['title'] = 'Include domain in HSTS preload list'; -$lng['admin']['domain_hsts_preload']['description'] = 'If you would like this domain to be included in the HSTS preload list maintained by Chrome (and used by Firefox and Safari), then use activate this.
Sending the preload directive from your site can have PERMANENT CONSEQUENCES and prevent users from accessing your site and any of its subdomains.
Please read the details at hstspreload.appspot.com/#removal before sending the header with "preload".'; +$lng['admin']['domain_hsts_preload']['description'] = 'If you would like this domain to be included in the HSTS preload list maintained by Chrome (and used by Firefox and Safari), then use activate this.
Sending the preload directive from your site can have PERMANENT CONSEQUENCES and prevent users from accessing your site and any of its subdomains.
Please read the details at hstspreload.appspot.com/#removal before sending the header with "preload".'; $lng['serversettings']['nginx_http2_support']['title'] = 'Nginx HTTP2 Support'; $lng['serversettings']['nginx_http2_support']['description'] = 'enable http2 support for ssl. ENABLE ONLY IF YOUR Nginx SUPPORT THIS FEATURE. (version 1.9.5+)'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 490d2651..b31b713e 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1712,4 +1712,4 @@ $lng['admin']['domain_hsts_maxage']['description'] = '"max-age" Wert für den St $lng['admin']['domain_hsts_incsub']['title'] = 'Inkludiere HSTS für jede Subdomain'; $lng['admin']['domain_hsts_incsub']['description'] = 'Die optionale "includeSubDomains" Direktive, wenn vorhanden, signalisiert dem UA, dass die HSTS Regel für diese Domain und auch jede Subdomain dieser gilt.'; $lng['admin']['domain_hsts_preload']['title'] = 'Füge Domain in die HSTS preload Liste hinzu'; -$lng['admin']['domain_hsts_preload']['description'] = 'Wenn die Domain in die HSTS preload Liste, verwaltet von Chrome (und genutzt von Firefox und Safari), hinzugefügt werden soll, dann aktiviere diese Einstellung.
Die preload-Direktive zu senden kann PERMANTENTE KONSEQUENZEN haben und dazu führen, dass Benutzer auf diese Domain und auch Subdomains nicht zugreifen können.
Beachte Details unter hstspreload.appspot.com/#removal bevor ein Header mit "preload" gesendet wird.'; +$lng['admin']['domain_hsts_preload']['description'] = 'Wenn die Domain in die HSTS preload Liste, verwaltet von Chrome (und genutzt von Firefox und Safari), hinzugefügt werden soll, dann aktiviere diese Einstellung.
Die preload-Direktive zu senden kann PERMANTENTE KONSEQUENZEN haben und dazu führen, dass Benutzer auf diese Domain und auch Subdomains nicht zugreifen können.
Beachte Details unter hstspreload.appspot.com/#removal bevor ein Header mit "preload" gesendet wird.'; From 1ebde2e6a44dd49a749c5684a14ab402107ba7c1 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 5 Jan 2017 11:58:11 +0100 Subject: [PATCH 028/179] return correct default redirectCode when none is set, thx to J-BBB Signed-off-by: Michael Kaufmann (d00p) --- lib/functions/output/function.RedirectCode.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/functions/output/function.RedirectCode.php b/lib/functions/output/function.RedirectCode.php index 37bd10e1..c5df262c 100644 --- a/lib/functions/output/function.RedirectCode.php +++ b/lib/functions/output/function.RedirectCode.php @@ -77,7 +77,7 @@ function getDomainRedirectCode($domainid = 0, $default = '') { if (is_array($result) && isset($result['redirect']) ) { - $code = ($result['redirect'] == '---') ? '' : $result['redirect']; + $code = ($result['redirect'] == '---') ? $default : $result['redirect']; } } return $code; From c795cd3320e2fe0ac4e2ff7afb7adc2b37a55cb8 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 10 Jan 2017 08:37:50 +0100 Subject: [PATCH 029/179] check for ownership of certificate when deleting as customer, fixes #1699 Signed-off-by: Michael Kaufmann (d00p) --- ssl_certificates.php | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/ssl_certificates.php b/ssl_certificates.php index 5a8547d7..365b2172 100644 --- a/ssl_certificates.php +++ b/ssl_certificates.php @@ -23,14 +23,32 @@ if (! defined('AREA')) $del_stmt = Database::prepare("DELETE FROM `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` WHERE id = :id"); $success_message = ""; -// do the delete and then just showa success-message and the certificates list again +// do the delete and then just show a success-message and the certificates list again if ($action == 'delete') { $id = isset($_GET['id']) ? (int) $_GET['id'] : 0; if ($id > 0) { - Database::pexecute($del_stmt, array( - 'id' => $id - )); - $success_message = sprintf($lng['domains']['ssl_certificate_removed'], $id); + if (AREA == 'customer') { + $chk_stmt = Database::prepare(" + SELECT d.domain FROM `".TABLE_PANEL_DOMAINS."` d + LEFT JOIN `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` s ON s.domainid = d.id + WHERE s.`id` = :id AND d.`customerid` = :cid + "); + $chk = Database::pexecute_first($chk_stmt, array( + 'id' => $id, + 'cid' => $userinfo['customerid'] + )); + if ($chk !== false) { + Database::pexecute($del_stmt, array( + 'id' => $id + )); + $success_message = sprintf($lng['domains']['ssl_certificate_removed'], $id); + } + } else { + Database::pexecute($del_stmt, array( + 'id' => $id + )); + $success_message = sprintf($lng['domains']['ssl_certificate_removed'], $id); + } } } From 02c6545c94fff745e2ea5fa912adcdee4ae6bb80 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 10 Jan 2017 19:11:01 +0100 Subject: [PATCH 030/179] update download url for libnss-mysql for debian jessie, fixies #1700 Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/jessie.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/configfiles/jessie.xml b/lib/configfiles/jessie.xml index d6613020..ae7e3912 100644 --- a/lib/configfiles/jessie.xml +++ b/lib/configfiles/jessie.xml @@ -4469,9 +4469,9 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin From d574233f491d27f34efef49684f2bb343123ab8a Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 13 Jan 2017 19:21:34 +0100 Subject: [PATCH 031/179] also reseller/admins who can't see all customers were able to delete arbitrary ssl certificates, refs #1699 Signed-off-by: Michael Kaufmann (d00p) --- ssl_certificates.php | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/ssl_certificates.php b/ssl_certificates.php index 365b2172..875b903e 100644 --- a/ssl_certificates.php +++ b/ssl_certificates.php @@ -27,9 +27,10 @@ $success_message = ""; if ($action == 'delete') { $id = isset($_GET['id']) ? (int) $_GET['id'] : 0; if ($id > 0) { + $chk = (AREA == 'admin' && $userinfo['customers_see_all'] == '1') ? true : false; if (AREA == 'customer') { $chk_stmt = Database::prepare(" - SELECT d.domain FROM `".TABLE_PANEL_DOMAINS."` d + SELECT d.domain FROM `" . TABLE_PANEL_DOMAINS . "` d LEFT JOIN `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` s ON s.domainid = d.id WHERE s.`id` = :id AND d.`customerid` = :cid "); @@ -37,13 +38,18 @@ if ($action == 'delete') { 'id' => $id, 'cid' => $userinfo['customerid'] )); - if ($chk !== false) { - Database::pexecute($del_stmt, array( - 'id' => $id - )); - $success_message = sprintf($lng['domains']['ssl_certificate_removed'], $id); - } - } else { + } elseif (AREA == 'admin' && $userinfo['customers_see_all'] == '0') { + $chk_stmt = Database::prepare(" + SELECT d.domain FROM `" . TABLE_PANEL_DOMAINS . "` d + LEFT JOIN `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` s ON s.domainid = d.id + WHERE s.`id` = :id AND d.`adminid` = :aid + "); + $chk = Database::pexecute_first($chk_stmt, array( + 'id' => $id, + 'aid' => $userinfo['adminid'] + )); + } + if ($chk !== false) { Database::pexecute($del_stmt, array( 'id' => $id )); @@ -90,7 +96,9 @@ $certificates = ""; if (count($all_certs) == 0) { $message = $lng['domains']['no_ssl_certificates']; $sortcode = ""; - $arrowcode = array('d.domain' => ''); + $arrowcode = array( + 'd.domain' => '' + ); $searchcode = ""; $pagingcode = ""; eval("\$certificates.=\"" . getTemplate("ssl_certificates/certs_error", true) . "\";"); @@ -145,13 +153,13 @@ if (count($all_certs) == 0) { } $san_list = ""; - if (isset($cert_data['extensions']['subjectAltName']) && !empty($cert_data['extensions']['subjectAltName'])) { + if (isset($cert_data['extensions']['subjectAltName']) && ! empty($cert_data['extensions']['subjectAltName'])) { $SANs = explode(",", $cert_data['extensions']['subjectAltName']); $SANs = array_map('trim', $SANs); foreach ($SANs as $san) { $san = str_replace("DNS:", "", $san); if ($san != $cert_data['subject']['CN'] && strpos($san, "othername:") === false) { - $san_list .= $san."
"; + $san_list .= $san . "
"; } } } From 044ce6662ad5239f01e7d6a5b5999992af8d6bdd Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 13 Jan 2017 19:45:17 +0100 Subject: [PATCH 032/179] set version to 0.9.38.5 for upcoming release Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 8 +++++++- lib/version.inc.php | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index 5c75be4f..456a06fd 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -581,7 +581,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.38.4'), + ('panel', 'version', '0.9.38.5'), ('panel', 'db_version', '201612110'); diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 8cc422dc..c75af54f 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3570,6 +3570,12 @@ if (isDatabaseVersion('201611180')) { showUpdateStep("Adding unique key to ipsandports table"); Database::query("ALTER TABLE `" . TABLE_PANEL_IPSANDPORTS . "` ADD UNIQUE KEY `ip_port` (`ip`,`port`)"); lastStepStatus(0); - + updateToDbVersion('201612110'); } + +if (isFroxlorVersion('0.9.38.4')) { + + showUpdateStep("Updating from 0.9.38.4 to 0.9.38.5", false); + updateToVersion('0.9.38.5'); +} diff --git a/lib/version.inc.php b/lib/version.inc.php index 52765f8d..113b065d 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.38.4'; +$version = '0.9.38.5'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201612110'; From 338cf161d253e2599376e5d11a3984b24f426863 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 14 Jan 2017 18:06:04 +0100 Subject: [PATCH 033/179] fix undefined index if let's encrypt is used for the froxlor-vhost Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/ssl/class.lescript.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index 2acd0934..a87f5bc8 100644 --- a/lib/classes/ssl/class.lescript.php +++ b/lib/classes/ssl/class.lescript.php @@ -63,7 +63,7 @@ class lescript { // Let's see if we have the private accountkey $this->accountKey = $certrow['leprivatekey']; - $this->customerId = $certrow['customerid']; + $this->customerId = (!$isFroxlorVhost ? $certrow['customerid'] : null); $this->isFroxlorVhost = $isFroxlorVhost; $this->isLeProduction = (Settings::Get('system.letsencryptca') == 'production'); From 9fdcd090894095d48bdf445e68a8618140724d17 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 15 Jan 2017 07:44:58 +0100 Subject: [PATCH 034/179] fix install class, set version to 0.9.38.6 Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/lib/class.FroxlorInstall.php | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 6 ++++++ lib/version.inc.php | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index 456a06fd..e27409e4 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -581,7 +581,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.38.5'), + ('panel', 'version', '0.9.38.6'), ('panel', 'db_version', '201612110'); diff --git a/install/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index 37acfc7c..ac9fb7f4 100644 --- a/install/lib/class.FroxlorInstall.php +++ b/install/lib/class.FroxlorInstall.php @@ -181,7 +181,7 @@ class FroxlorInstall $this->_data['servername'] = ''; } - if (empty($this->_data['serverip'] || $this->_validate_ip($this->_data['serverip']) == false)) { + if (empty($this->_data['serverip']) || $this->_validate_ip($this->_data['serverip']) == false) { return false; } diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index c75af54f..a759879f 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3579,3 +3579,9 @@ if (isFroxlorVersion('0.9.38.4')) { showUpdateStep("Updating from 0.9.38.4 to 0.9.38.5", false); updateToVersion('0.9.38.5'); } + +if (isFroxlorVersion('0.9.38.5')) { + + showUpdateStep("Updating from 0.9.38.5 to 0.9.38.6", false); + updateToVersion('0.9.38.6'); +} diff --git a/lib/version.inc.php b/lib/version.inc.php index 113b065d..cf3170c3 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.38.5'; +$version = '0.9.38.6'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201612110'; From c6962b0992391c86da6e29aaf9b7fc489f6551e6 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 16 Jan 2017 08:43:54 +0100 Subject: [PATCH 035/179] fix variable-typo to make phpenabled-flag work when adding new domains, thx to micw Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index bb4fe9a3..8a28364c 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -455,7 +455,7 @@ if ($page == 'domains' || $page == 'overview') { if ($userinfo['caneditphpsettings'] == '1' || $userinfo['change_serversettings'] == '1') { - $phpenabled = isset($POST_['phpenabled']) ? intval($_POST['phpenabled']) : 0; + $phpenabled = isset($_POST['phpenabled']) ? intval($_POST['phpenabled']) : 0; $openbasedir = isset($_POST['openbasedir']) ? intval($_POST['openbasedir']) : 0; if ((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) { @@ -496,7 +496,7 @@ if ($page == 'domains' || $page == 'overview') { } } else { - $phpenabled = '1'; + $phpenabled = '1'; $openbasedir = '1'; if ((int) Settings::Get('phpfpm.enabled') == 1) { @@ -693,8 +693,8 @@ if ($page == 'domains' || $page == 'overview') { if (count($ipandports) == 0) { standard_error('noipportgiven'); } - - if($phpenabled != '1') { + + if ($phpenabled != '1') { $phpenabled = '0'; } @@ -1485,7 +1485,7 @@ if ($page == 'domains' || $page == 'overview') { if (! preg_match('/^https?\:\/\//', $documentroot)) { $documentroot = makeCorrectDir($documentroot); } - + if ($phpenabled != '1') { $phpenabled = '0'; } From 5e0270e6a83e63284e43101c5883ba51371a1595 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laurens=20St=C3=B6tzel?= Date: Tue, 17 Jan 2017 10:18:52 +0100 Subject: [PATCH 036/179] Disable SSLCompression (CRIME attack) https://raymii.org/s/tutorials/Strong_SSL_Security_On_Apache2.html#SSL_Compression_(CRIME_attack) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 174ae623..d7e793fb 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -422,6 +422,8 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLEngine On' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; + $this->virtualhosts_data[$vhosts_filename] .= ' SSLCompression Off' . "\n"; + // this makes it more secure, thx to Marcel (08/2013) $this->virtualhosts_data[$vhosts_filename] .= ' SSLHonorCipherOrder On' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; From ab18d9405325856c0b7eae6eb441de0245e8f984 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 17 Jan 2017 11:29:40 +0100 Subject: [PATCH 037/179] fix PR #407 - only works for apache-2.4 and missed the entry for customer-vhosts Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index d7e793fb..47be4431 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -422,8 +422,9 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLEngine On' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; - $this->virtualhosts_data[$vhosts_filename] .= ' SSLCompression Off' . "\n"; - + if (Settings::Get('system.apache24') == '1') { + $this->virtualhosts_data[$vhosts_filename] .= ' SSLCompression Off' . "\n"; + } // this makes it more secure, thx to Marcel (08/2013) $this->virtualhosts_data[$vhosts_filename] .= ' SSLHonorCipherOrder On' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; @@ -842,6 +843,9 @@ class apache extends HttpConfigBase if ($domain['ssl_cert_file'] != '') { $vhost_content .= ' SSLEngine On' . "\n"; $vhost_content .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; + if (Settings::Get('system.apache24') == '1') { + $vhost_content .= ' SSLCompression Off' . "\n"; + } // this makes it more secure, thx to Marcel (08/2013) $vhost_content .= ' SSLHonorCipherOrder On' . "\n"; $vhost_content .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; From 1033f502b1b7307b216187a50838760427e819be Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 19 Jan 2017 14:09:51 +0100 Subject: [PATCH 038/179] add missing language strings, fixes #1705 Signed-off-by: Michael Kaufmann (d00p) --- lng/english.lng.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lng/english.lng.php b/lng/english.lng.php index e3b96eda..c8c7313f 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2065,3 +2065,5 @@ $lng['admin']['domain_hsts_preload']['description'] = 'If you would like this do $lng['serversettings']['nginx_http2_support']['title'] = 'Nginx HTTP2 Support'; $lng['serversettings']['nginx_http2_support']['description'] = 'enable http2 support for ssl. ENABLE ONLY IF YOUR Nginx SUPPORT THIS FEATURE. (version 1.9.5+)'; + +$lng['error']['noipportgiven'] = 'No IP/port given'; From afb2bce16dbf43e179d2b4e0b03c4ba0ac74b7f6 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 23 Jan 2017 08:05:48 +0100 Subject: [PATCH 039/179] fix missing german language strings, refs #1705 Signed-off-by: Michael Kaufmann (d00p) --- lng/german.lng.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lng/german.lng.php b/lng/german.lng.php index b31b713e..64d501b5 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1713,3 +1713,8 @@ $lng['admin']['domain_hsts_incsub']['title'] = 'Inkludiere HSTS für jede Subdom $lng['admin']['domain_hsts_incsub']['description'] = 'Die optionale "includeSubDomains" Direktive, wenn vorhanden, signalisiert dem UA, dass die HSTS Regel für diese Domain und auch jede Subdomain dieser gilt.'; $lng['admin']['domain_hsts_preload']['title'] = 'Füge Domain in die HSTS preload Liste hinzu'; $lng['admin']['domain_hsts_preload']['description'] = 'Wenn die Domain in die HSTS preload Liste, verwaltet von Chrome (und genutzt von Firefox und Safari), hinzugefügt werden soll, dann aktiviere diese Einstellung.
Die preload-Direktive zu senden kann PERMANTENTE KONSEQUENZEN haben und dazu führen, dass Benutzer auf diese Domain und auch Subdomains nicht zugreifen können.
Beachte Details unter hstspreload.appspot.com/#removal bevor ein Header mit "preload" gesendet wird.'; + +$lng['serversettings']['nginx_http2_support']['title'] = 'Nginx HTTP2 Unterstützung'; +$lng['serversettings']['nginx_http2_support']['description'] = 'Aktiviere http2 Unterstützung für SSL. NUR AKTIVIEREN, WENN nginx DIESE FUNKTION UNTERSTÜTZT (version 1.9.5+)'; + +$lng['error']['noipportgiven'] = 'Keine IP/Port angegeben'; From e00cb8926dfe0e5c581b1eec38f3ed237bf41726 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 23 Jan 2017 08:12:44 +0100 Subject: [PATCH 040/179] set mail-sender to customer mail address when using mod_php, fixes #1707 Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 47be4431..51e42c55 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -502,7 +502,9 @@ class apache extends HttpConfigBase if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { // This vHost has PHP enabled and we are using the regular mod_php - + $cmail = getCustomerDetail($domain['customerid'], 'email'); + $php_options_text .= ' php_admin_value sendmail_path "/usr/sbin/sendmail -t -f '.$cmail.'"' . PHP_EOL; + if ($domain['openbasedir'] == '1') { if ($domain['openbasedir_path'] == '1' || strstr($domain['documentroot'], ":") !== false) { $_phpappendopenbasedir = appendOpenBasedirPath($domain['customerroot'], true); From c2b864a20fee5403db7c3c910e8683dc87762151 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 23 Jan 2017 08:14:14 +0100 Subject: [PATCH 041/179] enable/disable php for standard-subdomain when adding a new customer according to the customer-phpenabled value, fixes #1708 Signed-off-by: Michael Kaufmann (d00p) --- admin_customers.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/admin_customers.php b/admin_customers.php index f73bfb6c..dd663ddd 100644 --- a/admin_customers.php +++ b/admin_customers.php @@ -910,7 +910,8 @@ if ($page == 'customers' 'customerid' => $customerid, 'adminid' => $userinfo['adminid'], 'docroot' => $documentroot, - 'adddate' => date('Y-m-d') + 'adddate' => date('Y-m-d'), + 'phpenabled' => $phpenabled ); $ins_stmt = Database::prepare(" INSERT INTO `" . TABLE_PANEL_DOMAINS . "` SET @@ -928,6 +929,7 @@ if ($page == 'customers' `dkim_id` = '0', `dkim_privkey` = '', `dkim_pubkey` = '', + `phpenabled` = :phpenabled, `add_date` = :adddate" ); Database::pexecute($ins_stmt, $ins_data); From 0eaa81b5037335b88d22c5d7056bc0dcf7593a52 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 23 Jan 2017 08:17:18 +0100 Subject: [PATCH 042/179] use libnss-mysl deb package from froxlor repo as debians 1.5-5 package is not suitable for jessie Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/jessie.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/configfiles/jessie.xml b/lib/configfiles/jessie.xml index ae7e3912..a0eba1c9 100644 --- a/lib/configfiles/jessie.xml +++ b/lib/configfiles/jessie.xml @@ -4469,9 +4469,9 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin From 8030aae37a31cda6f718d96b3a5f933d36b0cc0c Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 23 Jan 2017 23:53:01 +0100 Subject: [PATCH 043/179] fix directory options for deactivated users, fixes #1704 Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 51e42c55..7b1f48d5 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -597,6 +597,16 @@ class apache extends HttpConfigBase if ($domain['deactivated'] == '1' && Settings::Get('system.deactivateddocroot') != '') { $webroot_text .= ' # Using docroot for deactivated users...' . "\n"; $webroot_text .= ' DocumentRoot "' . makeCorrectDir(Settings::Get('system.deactivateddocroot')) . "\"\n"; + $webroot_text .= ' ' . "\n"; + // >=apache-2.4 enabled? + if (Settings::Get('system.apache24') == '1') { + $webroot_text .= ' Require all granted' . "\n"; + $webroot_text .= ' AllowOverride All' . "\n"; + } else { + $webroot_text .= ' Order allow,deny' . "\n"; + $webroot_text .= ' allow from all' . "\n"; + } + $webroot_text .= ' ' . "\n"; $this->_deactivated = true; } else { $webroot_text .= ' DocumentRoot "' . $domain['documentroot'] . "\"\n"; From 95a18be5c588d137a51d3555f5490b49cf08add4 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 24 Jan 2017 09:41:45 +0100 Subject: [PATCH 044/179] do not use HTTP_HOST variable if mod_rewrite is not used Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 7b1f48d5..c3de7b5a 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -810,6 +810,7 @@ class apache extends HttpConfigBase $vhost_content .= '' . "\n"; $vhost_content .= $this->getServerNames($domain); + $domain['documentroot_norewrite'] = $domain['documentroot']; if (($ssl_vhost == false && $domain['ssl'] == '1' && $domain['ssl_redirect'] == '1')) { // We must not check if our port differs from port 443, // but if there is a destination-port != 443 @@ -833,6 +834,7 @@ class apache extends HttpConfigBase } $domain['documentroot'] = 'https://%{HTTP_HOST}' . $_sslport . '/'; + $domain['documentroot_norewrite'] = 'https://' . $domain['domain'] . $_sslport . '/'; } if ($ssl_vhost === true && $domain['ssl'] == '1' && Settings::Get('system.use_ssl') == '1') { @@ -921,7 +923,7 @@ class apache extends HttpConfigBase $vhost_content .= ' RewriteRule ^/(.*) ' . $corrected_docroot . '$1' . $modrew_red . "\n"; $vhost_content .= ' ' . "\n"; $vhost_content .= ' ' . "\n"; - $vhost_content .= ' Redirect ' . $code . ' / ' . $corrected_docroot . "\n"; + $vhost_content .= ' Redirect ' . $code . ' / ' . $domain['documentroot_norewrite'] . "\n"; $vhost_content .= ' ' . "\n"; } else { From 3e6c3d725b8f6a58d56931e192bbb3cc93ece679 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 24 Jan 2017 09:43:20 +0100 Subject: [PATCH 045/179] set version to 0.9.38.7 for upcoming bugfix release Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 6 ++++++ lib/version.inc.php | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index e27409e4..d8d600a0 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -581,7 +581,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.38.6'), + ('panel', 'version', '0.9.38.7'), ('panel', 'db_version', '201612110'); diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index a759879f..a917a7b5 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3585,3 +3585,9 @@ if (isFroxlorVersion('0.9.38.5')) { showUpdateStep("Updating from 0.9.38.5 to 0.9.38.6", false); updateToVersion('0.9.38.6'); } + +if (isFroxlorVersion('0.9.38.6')) { + + showUpdateStep("Updating from 0.9.38.6 to 0.9.38.7", false); + updateToVersion('0.9.38.7'); +} diff --git a/lib/version.inc.php b/lib/version.inc.php index cf3170c3..3ce16650 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.38.6'; +$version = '0.9.38.7'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201612110'; From 8f4da0638e333d62d401879fb914b1f3945e94ae Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 25 Jan 2017 10:42:18 +0100 Subject: [PATCH 046/179] allow underscore in dns labels, fixes #1697 Signed-off-by: Michael Kaufmann (d00p) --- dns_editor.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/dns_editor.php b/dns_editor.php index 15687b10..98e3a373 100644 --- a/dns_editor.php +++ b/dns_editor.php @@ -57,12 +57,16 @@ if ($action == 'add_record' && ! empty($_POST)) { $errors[] = $lng['error']['domain_nopunycode']; } else { $record = $idna_convert->encode($record); + /* + * see https://redmine.froxlor.org/issues/1697 + * if ($type != 'SRV' && $type != 'TXT') { $check_dom = $record . '.example.com'; if (! validateDomain($check_dom)) { $errors[] = sprintf($lng['error']['subdomainiswrong'], $idna_convert->decode($record)); } } + */ if (strlen($record) > 63) { $errors[] = $lng['error']['dns_record_toolong']; } From 01a363456eab2d3808c024258eaaa303ca671c1a Mon Sep 17 00:00:00 2001 From: Vengance Date: Sat, 28 Jan 2017 15:47:19 +0100 Subject: [PATCH 047/179] Fix libnss config (#412) * Fix libnss config --- lib/configfiles/jessie.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/configfiles/jessie.xml b/lib/configfiles/jessie.xml index a0eba1c9..c9ac50af 100644 --- a/lib/configfiles/jessie.xml +++ b/lib/configfiles/jessie.xml @@ -4469,9 +4469,9 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin From 202eb0931f4b70a0f49e2e4ba6e36891c5a91749 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 28 Jan 2017 21:20:37 +0100 Subject: [PATCH 048/179] fix auto-update of database in cronjob if activated Signed-off-by: Michael Kaufmann (d00p) --- install/updates/froxlor/0.9/update_0.9.inc.php | 8 +++++--- install/updatesql.php | 16 +++++++++------- lib/cron_init.php | 1 + 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index a917a7b5..d8aa8735 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -14,9 +14,11 @@ * @package Install * */ -if (! defined('AREA') || (defined('AREA') && AREA != 'admin') || ! isset($userinfo['loginname']) || (isset($userinfo['loginname']) && $userinfo['loginname'] == '')) { - header('Location: ../../../../index.php'); - exit(); +if (!defined('_CRON_UPDATE')) { + if (! defined('AREA') || (defined('AREA') && AREA != 'admin') || ! isset($userinfo['loginname']) || (isset($userinfo['loginname']) && $userinfo['loginname'] == '')) { + header('Location: ../../../../index.php'); + exit(); + } } if (isFroxlorVersion('0.9-r0')) { diff --git a/install/updatesql.php b/install/updatesql.php index 86fe204e..4cc7417f 100644 --- a/install/updatesql.php +++ b/install/updatesql.php @@ -17,13 +17,15 @@ * */ -if (!defined('AREA') - || (defined('AREA') && AREA != 'admin') - || !isset($userinfo['loginname']) - || (isset($userinfo['loginname']) && $userinfo['loginname'] == '') -) { - header('Location: ../index.php'); - exit; +if (!defined('_CRON_UPDATE')) { + if (!defined('AREA') + || (defined('AREA') && AREA != 'admin') + || !isset($userinfo['loginname']) + || (isset($userinfo['loginname']) && $userinfo['loginname'] == '') + ) { + header('Location: ../index.php'); + exit; + } } $updatelog = FroxlorLogger::getInstanceOf(array('loginname' => 'updater')); diff --git a/lib/cron_init.php b/lib/cron_init.php index 68166f5e..a432c593 100644 --- a/lib/cron_init.php +++ b/lib/cron_init.php @@ -205,6 +205,7 @@ if (hasUpdates($version) || hasDbUpdates($dbversion) fwrite($debugHandler, '*** WARNING *** - all new settings etc. will be stored with the default value, that might not always be right for your system!' . "\n"); fwrite($debugHandler, "*** WARNING *** - If you don't want this to happen in the future consider removing the --allow-autoupdate flag from the cronjob\n"); // including update procedures + define('_CRON_UPDATE', 1); include_once FROXLOR_INSTALL_DIR.'/install/updatesql.php'; // pew - everything went better than expected $cronlog->logAction(CRON_ACTION, LOG_WARNING, 'Automatic update done - you should check your settings to be sure everything is fine'); From 2d59e569df709caf7ca5af441235348d6abbc941 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 30 Jan 2017 22:46:53 +0100 Subject: [PATCH 049/179] fix phpenabled flag for new subdomains added by customers Signed-off-by: Michael Kaufmann (d00p) --- customer_domains.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/customer_domains.php b/customer_domains.php index cc2a637e..849eb69b 100644 --- a/customer_domains.php +++ b/customer_domains.php @@ -415,6 +415,7 @@ if ($page == 'overview') { `wwwserveralias` = :wwwserveralias, `isemaildomain` = :isemaildomain, `iswildcarddomain` = :iswildcarddomain, + `phpenabled` = :phpenabled, `openbasedir` = :openbasedir, `openbasedir_path` = :openbasedir_path, `speciallogfile` = :speciallogfile, @@ -437,6 +438,7 @@ if ($page == 'overview') { "isemaildomain" => $domain_check['subcanemaildomain'] == '3' ? '1' : '0', "openbasedir" => $domain_check['openbasedir'], "openbasedir_path" => $openbasedir_path, + "phpenabled" => $domain_check['phpenabled'], "speciallogfile" => $domain_check['speciallogfile'], "specialsettings" => $domain_check['specialsettings'], "ssl_redirect" => $ssl_redirect, From 8ef315014cd786a55e1b8e87918a44fde22fee82 Mon Sep 17 00:00:00 2001 From: Douks08 Date: Thu, 9 Feb 2017 10:19:32 +0100 Subject: [PATCH 050/179] Update french.lng.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Modification de "billets" en "tickets" qui est plus fréquemment utilisé --- lng/french.lng.php | 94 +++++++++++++++++++++++----------------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/lng/french.lng.php b/lng/french.lng.php index aea6d93c..9375aa18 100644 --- a/lng/french.lng.php +++ b/lng/french.lng.php @@ -569,18 +569,18 @@ $lng['serversettings']['webalizer_quiet']['description'] = 'Verbosité du progra $lng['ticket']['admin_email'] = 'root@localhost'; $lng['ticket']['noreply_email'] = 'billets@froxlor'; -$lng['admin']['ticketsystem'] = 'Système de billets'; -$lng['menue']['ticket']['ticket'] = 'Billets de support'; +$lng['admin']['ticketsystem'] = 'Système de tickets'; +$lng['menue']['ticket']['ticket'] = 'Tickets support'; $lng['menue']['ticket']['categories'] = 'Catégories de support'; -$lng['menue']['ticket']['archive'] = 'Archives de billets'; +$lng['menue']['ticket']['archive'] = 'Archives de tickets'; $lng['ticket']['description'] = 'Entrez une description !'; -$lng['ticket']['ticket_new'] = 'Ouvrir un nouveau billet'; -$lng['ticket']['ticket_reply'] = 'Réponse au billet'; -$lng['ticket']['ticket_reopen'] = 'Réouvrir le billet'; +$lng['ticket']['ticket_new'] = 'Ouvrir un nouveau ticket'; +$lng['ticket']['ticket_reply'] = 'Réponse au ticket'; +$lng['ticket']['ticket_reopen'] = 'Réouvrir le ticket'; $lng['ticket']['ticket_newcateory'] = 'Créer une nouvelle catégorie'; $lng['ticket']['ticket_editcateory'] = 'Editer la catégorie'; -$lng['ticket']['ticket_view'] = 'Voir l\'historique du billet'; -$lng['ticket']['ticketcount'] = 'Billets'; +$lng['ticket']['ticket_view'] = 'Voir l\'historique du ticket'; +$lng['ticket']['ticketcount'] = 'Tickets'; $lng['ticket']['ticket_answers'] = 'Réponses'; // $lng['ticket']['lastchange'] = 'Dernière action'; $lng['ticket']['lastchange'] = 'Dernier changement'; @@ -601,8 +601,8 @@ $lng['ticket']['answer'] = 'Répondre'; $lng['ticket']['close'] = 'Fermer'; $lng['ticket']['reopen'] = 'Réouvrir'; $lng['ticket']['archive'] = 'Archive'; -$lng['ticket']['ticket_delete'] = 'Effacer le billet'; -$lng['ticket']['lastarchived'] = 'Billets récemment archivés'; +$lng['ticket']['ticket_delete'] = 'Effacer le ticket'; +$lng['ticket']['lastarchived'] = 'Tickets récemment archivés'; $lng['ticket']['archivedtime'] = 'Archivé'; $lng['ticket']['open'] = 'Ouvert'; $lng['ticket']['wait_reply'] = 'Attente d\'une réponse'; @@ -610,43 +610,43 @@ $lng['ticket']['replied'] = 'Répondu'; $lng['ticket']['closed'] = 'Fermé'; $lng['ticket']['staff'] = 'L\'équipe'; $lng['ticket']['customer'] = 'Client'; -$lng['ticket']['old_tickets'] = 'Messages du billet'; +$lng['ticket']['old_tickets'] = 'Messages du ticket'; $lng['ticket']['search'] = 'Rechercher dans les archives'; $lng['ticket']['nocustomer'] = 'Aucun choix'; $lng['ticket']['archivesearch'] = 'Résultat de la recherche dans les archives'; -$lng['ticket']['noresults'] = 'Aucun billet trouvé'; -$lng['ticket']['notmorethanxopentickets'] = 'Pour éviter les abus, vous ne pouvez avoir plus de %s billets ouverts'; +$lng['ticket']['noresults'] = 'Aucun ticket trouvé'; +$lng['ticket']['notmorethanxopentickets'] = 'Pour éviter les abus, vous ne pouvez avoir plus de %s tickets ouverts'; $lng['ticket']['supportstatus'] = 'Etat du support'; $lng['ticket']['supportavailable'] = 'Nos équipes de support sont disponibles et prètes à vous assister.'; $lng['ticket']['supportnotavailable'] = 'Nos équipes de support ne sont actuellement pas disponibles.'; -$lng['admin']['templates']['ticket'] = 'E-mail de notification pour les billets de support'; -$lng['admin']['templates']['SUBJECT'] = 'Sera remplacé par le sujet du billet de support.'; -$lng['admin']['templates']['new_ticket_for_customer'] = 'Informe le client que le billet a été envoyé'; -$lng['admin']['templates']['new_ticket_by_customer'] = 'Notifie l\'administrateur qu\'un nouveau billet a été ouvert par un client'; -$lng['admin']['templates']['new_reply_ticket_by_customer'] = 'Notifie l\'administrateur d\'une réponse du client au billet'; -$lng['admin']['templates']['new_ticket_by_staff'] = 'Informe le client qu\'un billet a été ouvert par l\'équipe de support'; -$lng['admin']['templates']['new_reply_ticket_by_staff'] = 'Informe le client d\'une réponse de l\'équipe de support au billet'; -$lng['mails']['new_ticket_for_customer']['mailbody'] = 'Bonjour {FIRSTNAME} {NAME},\n\nVotre demande de billet de support ayant comme sujet "{SUBJECT}" a été envoyé.\n\nVous receverez une notification lorsque votre billet aura une réponse.\n\nMerci,\nL\'équipe Froxlor.'; -$lng['mails']['new_ticket_for_customer']['subject'] = 'Votre billet de support a été envoyé'; -$lng['mails']['new_ticket_by_customer']['mailbody'] = 'Bonjour administrateur,\n\nUn nouveau billet de support ayant comme sujet "{SUBJECT}" a été ouvert.\n\nVeuillez vous connecter pour consulter le billet.\n\nMerci,\nl\'équipe Froxlor.'; -$lng['mails']['new_ticket_by_customer']['subject'] = 'Nouveau billet de support soumis'; -$lng['mails']['new_reply_ticket_by_customer']['mailbody'] = 'Bonjour administrateur,\n\nLe billet de support "{SUBJECT}" a reçu une réponse de la part du client.\n\nVeuillez vous connecter pour consulter le billet.\n\nMerci,\nL\'équipe Froxlor.'; -$lng['mails']['new_reply_ticket_by_customer']['subject'] = 'Nouvelle réponse au billet de support'; -$lng['mails']['new_ticket_by_staff']['mailbody'] = 'Bonjour {FIRSTNAME} {NAME},\n\nUn billet de support ayant comme sujet "{SUBJECT}" a été ouvert pour vous par notre équipe.\n\nVeuillez vous connecter pour consulter le billet.\n\nMerci,\nL\'équipe Froxlor.'; +$lng['admin']['templates']['ticket'] = 'E-mail de notification pour les tickets de support'; +$lng['admin']['templates']['SUBJECT'] = 'Sera remplacé par le sujet du ticket de support.'; +$lng['admin']['templates']['new_ticket_for_customer'] = 'Informe le client que le ticket a été envoyé'; +$lng['admin']['templates']['new_ticket_by_customer'] = 'Notifie l\'administrateur qu\'un nouveau ticket a été ouvert par un client'; +$lng['admin']['templates']['new_reply_ticket_by_customer'] = 'Notifie l\'administrateur d\'une réponse du client au ticket'; +$lng['admin']['templates']['new_ticket_by_staff'] = 'Informe le client qu\'un ticket a été ouvert par l\'équipe de support'; +$lng['admin']['templates']['new_reply_ticket_by_staff'] = 'Informe le client d\'une réponse de l\'équipe de support au ticket'; +$lng['mails']['new_ticket_for_customer']['mailbody'] = 'Bonjour {FIRSTNAME} {NAME},\n\nVotre demande de ticket de support ayant comme sujet "{SUBJECT}" a été envoyé.\n\nVous receverez une notification lorsque votre billet aura une réponse.\n\nMerci,\nL\'équipe Froxlor.'; +$lng['mails']['new_ticket_for_customer']['subject'] = 'Votre ticket de support a été envoyé'; +$lng['mails']['new_ticket_by_customer']['mailbody'] = 'Bonjour administrateur,\n\nUn nouveau ticket de support ayant comme sujet "{SUBJECT}" a été ouvert.\n\nVeuillez vous connecter pour consulter le billet.\n\nMerci,\nl\'équipe Froxlor.'; +$lng['mails']['new_ticket_by_customer']['subject'] = 'Nouveau ticket de support soumis'; +$lng['mails']['new_reply_ticket_by_customer']['mailbody'] = 'Bonjour administrateur,\n\nLe ticket de support "{SUBJECT}" a reçu une réponse de la part du client.\n\nVeuillez vous connecter pour consulter le billet.\n\nMerci,\nL\'équipe Froxlor.'; +$lng['mails']['new_reply_ticket_by_customer']['subject'] = 'Nouvelle réponse au ticket de support'; +$lng['mails']['new_ticket_by_staff']['mailbody'] = 'Bonjour {FIRSTNAME} {NAME},\n\nUn ticket de support ayant comme sujet "{SUBJECT}" a été ouvert pour vous par notre équipe.\n\nVeuillez vous connecter pour consulter le billet.\n\nMerci,\nL\'équipe Froxlor.'; $lng['mails']['new_ticket_by_staff']['subject'] = 'Nouvelle demande de support soumise'; -$lng['mails']['new_reply_ticket_by_staff']['mailbody'] = 'Bonjour {FIRSTNAME} {NAME},\n\nLe billet de support ayant comme sujet "{SUBJECT}" a reçu une réponse par notre équipe.\n\nVeuillez vous connecter pour consulter le billet.\n\nMerci,\nL\équipe Froxlor.'; -$lng['mails']['new_reply_ticket_by_staff']['subject'] = 'Nouvelle réponse au billet de support'; -$lng['question']['ticket_reallyclose'] = 'Etes-vous sûr de vouloir clôturer le billet "%s" ?'; -$lng['question']['ticket_reallydelete'] = 'Etes-vous sûr de vouloir supprimer le billet "%s" ?'; +$lng['mails']['new_reply_ticket_by_staff']['mailbody'] = 'Bonjour {FIRSTNAME} {NAME},\n\nLe ticket de support ayant comme sujet "{SUBJECT}" a reçu une réponse par notre équipe.\n\nVeuillez vous connecter pour consulter le billet.\n\nMerci,\nL\équipe Froxlor.'; +$lng['mails']['new_reply_ticket_by_staff']['subject'] = 'Nouvelle réponse au ticket de support'; +$lng['question']['ticket_reallyclose'] = 'Etes-vous sûr de vouloir clôturer le ticket "%s" ?'; +$lng['question']['ticket_reallydelete'] = 'Etes-vous sûr de vouloir supprimer le ticket "%s" ?'; $lng['question']['ticket_reallydeletecat'] = 'Etes-vous sûr de vouloir supprimer la catégorie "%s" ?'; -$lng['question']['ticket_reallyarchive'] = 'Etes-vous sûr de vouloir archiver le billet "%s" ?'; -$lng['error']['nomoreticketsavailable'] = 'Vous n\'avez plus de billets de disponibles. Veuillez contacter votre administrateur.'; -$lng['error']['nocustomerforticket'] = 'Ne peut créer de billet sans client'; -$lng['error']['categoryhastickets'] = 'La catégorie possède des billets.
Veuillez d\'abord supprimer tous les billets de cette catégorie.'; -$lng['admin']['ticketsettings'] = 'Paramètres des billets de support'; -$lng['admin']['archivelastrun'] = 'Derniers billets archivés'; +$lng['question']['ticket_reallyarchive'] = 'Etes-vous sûr de vouloir archiver le ticket "%s" ?'; +$lng['error']['nomoreticketsavailable'] = 'Vous n\'avez plus de tickets de disponibles. Veuillez contacter votre administrateur.'; +$lng['error']['nocustomerforticket'] = 'Impossible de créer un ticket sans clients dans la base'; +$lng['error']['categoryhastickets'] = 'La catégorie possède des tickets.
Veuillez d\'abord supprimer tous les tickets de cette catégorie.'; +$lng['admin']['ticketsettings'] = 'Paramètres des tickets de support'; +$lng['admin']['archivelastrun'] = 'Derniers tickets archivés'; $lng['serversettings']['ticket']['noreply_email']['title'] = 'Adresse e-mail de non réponse'; -$lng['serversettings']['ticket']['noreply_email']['description'] = 'L\'adresse e-mail de l\'expéditeur de notification pour les billets de support, quelque chose du type no-reply@domaine.com'; +$lng['serversettings']['ticket']['noreply_email']['description'] = 'L\'adresse e-mail de l\'expéditeur de notification pour les tickets de support, quelque chose du type no-reply@domaine.com'; $lng['serversettings']['ticket']['worktime_begin']['title'] = 'Début du support (hh:mm)'; $lng['serversettings']['ticket']['worktime_begin']['description'] = 'Horaire de début du support'; $lng['serversettings']['ticket']['worktime_end']['title'] = 'Fin du support (hh:mm)'; @@ -655,21 +655,21 @@ $lng['serversettings']['ticket']['worktime_sat'] = 'Support disponible le samedi $lng['serversettings']['ticket']['worktime_sun'] = 'Support disponible le dimanche ?'; $lng['serversettings']['ticket']['worktime_all']['title'] = 'Aucune limite horaire pour le support'; $lng['serversettings']['ticket']['worktime_all']['description'] = 'Si "Oui", les options pour le début et la fin du support seront écrasés.'; -$lng['serversettings']['ticket']['archiving_days'] = 'Après combien de jours un billet fermé sera automatiquement archivé ?'; -$lng['customer']['tickets'] = 'Billet de support'; +$lng['serversettings']['ticket']['archiving_days'] = 'Après combien de jours un ticket fermé sera automatiquement archivé ?'; +$lng['customer']['tickets'] = 'Ticket de support'; // ADDED IN 1.2.18-svn4 $lng['admin']['domain_nocustomeraddingavailable'] = 'Il n\'est acutellement pas possible d\'ajouter de domaines. Vous devez d\'abord ajouter un client.'; -$lng['serversettings']['ticket']['enable'] = 'Activer le système de billets'; -$lng['serversettings']['ticket']['concurrentlyopen'] = 'Combien de billets peuvent être ouverts au même moment ?'; +$lng['serversettings']['ticket']['enable'] = 'Activer le système de tickets'; +$lng['serversettings']['ticket']['concurrentlyopen'] = 'Combien de tickets peuvent être ouverts au même moment ?'; $lng['error']['norepymailiswrong'] = 'L\'adresse de "non réponse" n\'est pas bonne. Une adresse e-mail valide doit être entrée.'; -$lng['error']['tadminmailiswrong'] = 'L\'adresse de "l\'administrateur de billets" n\'est pas bonne. Une adresse e-mail valide doit être entrée.'; -$lng['ticket']['awaitingticketreply'] = 'Vous avez %s billet(s) de support non répondu(s).'; +$lng['error']['tadminmailiswrong'] = 'L\'adresse de "l\'administrateur de tickets" n\'est pas bonne. Une adresse e-mail valide doit être entrée.'; +$lng['ticket']['awaitingticketreply'] = 'Vous avez %s ticket(s) de support non répondu(s).'; // ADDED IN 1.2.18-svn5 -$lng['serversettings']['ticket']['noreply_name'] = 'Nom de l\'expéditeur e-mail des billets'; +$lng['serversettings']['ticket']['noreply_name'] = 'Nom de l\'expéditeur e-mail des tickets'; // ADDED IN 1.2.19-svn1 @@ -679,8 +679,8 @@ $lng['serversettings']['mod_fcgid']['tmpdir']['title'] = 'Dossier temporaire pou // ADDED IN 1.2.19-svn3 -$lng['serversettings']['ticket']['reset_cycle']['title'] = 'Intervalle de réinitialisation des billets utilisés'; -$lng['serversettings']['ticket']['reset_cycle']['description'] = 'Remettre le compteur de billets à 0 dans le temps imparti'; +$lng['serversettings']['ticket']['reset_cycle']['title'] = 'Intervalle de réinitialisation des tickets utilisés'; +$lng['serversettings']['ticket']['reset_cycle']['description'] = 'Remettre le compteur de tickets à 0 dans le temps imparti'; $lng['admin']['tickets']['daily'] = 'Journalière'; $lng['admin']['tickets']['weekly'] = 'Hebdomadaire'; $lng['admin']['tickets']['monthly'] = 'Mensuelle'; From a4f72cbb408bdb4172a3925535b4f37ece8f63c3 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 12 Feb 2017 16:33:00 +0100 Subject: [PATCH 051/179] do not show full path of file on php-error; fixes #1720 Signed-off-by: Michael Kaufmann (d00p) --- lib/functions/froxlor/function.phpErrHandler.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/functions/froxlor/function.phpErrHandler.php b/lib/functions/froxlor/function.phpErrHandler.php index 862230a2..90664e63 100644 --- a/lib/functions/froxlor/function.phpErrHandler.php +++ b/lib/functions/froxlor/function.phpErrHandler.php @@ -25,6 +25,8 @@ function phpErrHandler($errno, $errstr, $errfile, $errline, $errcontext) { if (empty($theme)) { $theme = "Sparkle"; } + // prevent possible file-path-disclosure + $errfile = str_replace(FROXLOR_INSTALL_DIR, "", $errfile); // if we're not on the shell, output a nicer error-message $err_hint = file_get_contents(FROXLOR_INSTALL_DIR.'/templates/'.$theme.'/misc/phperrornice.tpl'); // replace values From 2284706e0c2551a00a90129f325ec56abc22b311 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 2 Mar 2017 07:57:47 +0100 Subject: [PATCH 052/179] do not load mod_vroot in proftpd on centos Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/rhel_centos.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/configfiles/rhel_centos.xml b/lib/configfiles/rhel_centos.xml index ebe4cb2c..7b8be4b8 100644 --- a/lib/configfiles/rhel_centos.xml +++ b/lib/configfiles/rhel_centos.xml @@ -2089,7 +2089,7 @@ LoadModule mod_ctrls_admin.c # (http://www.castaglia.org/proftpd/modules/mod_vroot.html) # Using this module rather than the kernel's chroot() system call works # around issues with PAM and chroot (http://bugzilla.redhat.com/506735) -LoadModule mod_vroot.c +# LoadModule mod_vroot.c # # Provide a flexible way of specifying that certain configuration directives # only apply to certain sessions, based on credentials such as connection From c0fddbce8117b55ec6807dd511d47b20be9510d2 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 8 Mar 2017 14:04:40 +0100 Subject: [PATCH 053/179] use correct pagination in admin-log/customer-log, fixes #1726 Signed-off-by: Michael Kaufmann (d00p) --- admin_logger.php | 15 ++-- customer_logger.php | 119 +++++++++++++--------------- lib/classes/output/class.paging.php | 11 ++- 3 files changed, 75 insertions(+), 70 deletions(-) diff --git a/admin_logger.php b/admin_logger.php index a409c021..8aba34c8 100644 --- a/admin_logger.php +++ b/admin_logger.php @@ -30,11 +30,12 @@ if ($page == 'log' 'user' => $lng['logger']['user'], 'text' => $lng['logger']['action'] ); - $paging = new paging($userinfo, TABLE_PANEL_LOG, $fields, null, null, 0, 'desc'); - $result_stmt = Database::query(' - SELECT * FROM `' . TABLE_PANEL_LOG . '` ' . $paging->getSqlWhere(false) . ' ' . $paging->getSqlOrderBy() . ' ' . $paging->getSqlLimit() - ); - $logs_count = Database::num_rows(); + $paging = new paging($userinfo, TABLE_PANEL_LOG, $fields, null, null, 0, 'desc', 30); + $query = 'SELECT * FROM `' . TABLE_PANEL_LOG . '` ' . $paging->getSqlWhere(false) . ' ' . $paging->getSqlOrderBy(); + $result_stmt = Database::query($query . ' ' . $paging->getSqlLimit()); + $result_cnt_stmt = Database::query($query); + $res_cnt = $result_cnt_stmt->fetch(PDO::FETCH_ASSOC); + $logs_count = $res_cnt['resultrows']; $paging->setEntries($logs_count); $sortcode = $paging->getHtmlSortCode($lng); $arrowcode = $paging->getHtmlArrowCode($filename . '?page=' . $page . '&s=' . $s); @@ -67,7 +68,7 @@ if ($page == 'log' foreach ($clog as $action => $logrows) { $_action = 0; foreach ($logrows as $row) { - if ($paging->checkDisplay($i)) { + // if ($paging->checkDisplay($i)) { $row = htmlentities_array($row); $row['date'] = date("d.m.y H:i:s", $row['date']); @@ -105,7 +106,7 @@ if ($page == 'log' eval("\$log.=\"" . getTemplate('logger/logger_log') . "\";"); $count++; $_action = $action; - } + // } $i++; } $i++; diff --git a/customer_logger.php b/customer_logger.php index 07e3f8e2..e3290296 100644 --- a/customer_logger.php +++ b/customer_logger.php @@ -16,17 +16,15 @@ * @package Panel * */ - define('AREA', 'customer'); require './lib/init.php'; // redirect if this customer page is hidden via settings -if (Settings::IsInList('panel.customer_hide_options','extras.logger')) { +if (Settings::IsInList('panel.customer_hide_options', 'extras.logger')) { redirectTo('customer_index.php'); } -if ($page == 'log' -) { +if ($page == 'log') { if ($action == '') { $fields = array( 'date' => $lng['logger']['date'], @@ -34,89 +32,86 @@ if ($page == 'log' 'user' => $lng['logger']['user'], 'text' => $lng['logger']['action'] ); - $paging = new paging($userinfo, TABLE_PANEL_LOG, $fields, null, null, 0, 'desc'); - $result_stmt = Database::prepare(' - SELECT * FROM `' . TABLE_PANEL_LOG . '` WHERE `user` = :loginname ' . $paging->getSqlWhere(true) . ' ' . $paging->getSqlOrderBy() . ' ' . $paging->getSqlLimit() - ); - Database::pexecute($result_stmt, array("loginname" => $userinfo['loginname'])); - $logs_count = Database::num_rows(); + $paging = new paging($userinfo, TABLE_PANEL_LOG, $fields, null, null, 0, 'desc', 30); + $query = 'SELECT * FROM `' . TABLE_PANEL_LOG . '` WHERE `user` = :loginname ' . $paging->getSqlWhere(true) . ' ' . $paging->getSqlOrderBy(); + $result_stmt = Database::prepare($query . ' ' . $paging->getSqlLimit()); + Database::pexecute($result_stmt, array( + "loginname" => $userinfo['loginname'] + )); + $result_cnt_stmt = Database::query($query); + $res_cnt = $result_cnt_stmt->fetch(PDO::FETCH_ASSOC); + $logs_count = $res_cnt['resultrows']; $paging->setEntries($logs_count); $sortcode = $paging->getHtmlSortCode($lng); $arrowcode = $paging->getHtmlArrowCode($filename . '?page=' . $page . '&s=' . $s); $searchcode = $paging->getHtmlSearchCode($lng); $pagingcode = $paging->getHtmlPagingCode($filename . '?page=' . $page . '&s=' . $s); $clog = array(); - + while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) { - - if (!isset($clog[$row['action']]) - || !is_array($clog[$row['action']]) - ) { + + if (! isset($clog[$row['action']]) || ! is_array($clog[$row['action']])) { $clog[$row['action']] = array(); } $clog[$row['action']][$row['logid']] = $row; } - - if ($paging->sortfield == 'date' - && $paging->sortorder == 'desc' - ) { + + if ($paging->sortfield == 'date' && $paging->sortorder == 'desc') { krsort($clog); } else { ksort($clog); } - + $i = 0; $count = 0; $log_count = 0; $log = ''; foreach ($clog as $action => $logrows) { - $_action = 0; foreach ($logrows as $row) { - if ($paging->checkDisplay($i)) { - $row = htmlentities_array($row); - $row['date'] = date("d.m.y H:i:s", $row['date']); - - if ($_action != $action) { - switch ($action) { - case USR_ACTION: - $_action = $lng['admin']['customer']; - break; - case RES_ACTION: - $_action = $lng['logger']['reseller']; - break; - case ADM_ACTION: - $_action = $lng['logger']['admin']; - break; - case CRON_ACTION: - $_action = $lng['logger']['cron']; - break; - case LOGIN_ACTION: - $_action = $lng['logger']['login']; - break; - case LOG_ERROR: - $_action = $lng['logger']['intern']; - break; - default: - $_action = $lng['logger']['unknown']; - break; - } - - $row['action'] = $_action; - eval("\$log.=\"" . getTemplate('logger/logger_action') . "\";"); + // if ($paging->checkDisplay($i)) { + $row = htmlentities_array($row); + $row['date'] = date("d.m.y H:i:s", $row['date']); + + if ($_action != $action) { + switch ($action) { + case USR_ACTION: + $_action = $lng['admin']['customer']; + break; + case RES_ACTION: + $_action = $lng['logger']['reseller']; + break; + case ADM_ACTION: + $_action = $lng['logger']['admin']; + break; + case CRON_ACTION: + $_action = $lng['logger']['cron']; + break; + case LOGIN_ACTION: + $_action = $lng['logger']['login']; + break; + case LOG_ERROR: + $_action = $lng['logger']['intern']; + break; + default: + $_action = $lng['logger']['unknown']; + break; } - - $log_count++; - $row['type'] = getLogLevelDesc($row['type']); - eval("\$log.=\"" . getTemplate('logger/logger_log') . "\";"); - $count++; - $_action = $action; + + $row['action'] = $_action; + eval("\$log.=\"" . getTemplate('logger/logger_action') . "\";"); } - $i++; + + $log_count ++; + $row['type'] = getLogLevelDesc($row['type']); + eval("\$log.=\"" . getTemplate('logger/logger_log') . "\";"); + $count ++; + $_action = $action; + // } + $i ++; } - $i++; + $i ++; } - + eval("echo \"" . getTemplate('logger/logger') . "\";"); - } } diff --git a/lib/classes/output/class.paging.php b/lib/classes/output/class.paging.php index 62384248..8ee2bc25 100644 --- a/lib/classes/output/class.paging.php +++ b/lib/classes/output/class.paging.php @@ -88,6 +88,8 @@ class paging { * @var bool */ private $natSorting = false; + + private $_limit = 0; /** * Class constructor. Loads settings from request or from userdata and saves them to session. @@ -101,7 +103,7 @@ class paging { * @param string $default_order default sorting order 'asc' or 'desc' * */ - public function __construct($userinfo, $table, $fields, $entriesperpage = 0, $natSorting = false, $default_field = 0, $default_order = 'asc') { + public function __construct($userinfo, $table, $fields, $entriesperpage = 0, $natSorting = false, $default_field = 0, $default_order = 'asc', $limit = 0) { // entries per page and natsorting-flag are not // passed as parameter anymore, because these are @@ -230,6 +232,8 @@ class paging { 'adminsession' => $userinfo['adminsession'] ); Database::pexecute($upd_stmt, $upd_data); + + $this->_limit = $limit; } /** @@ -378,6 +382,11 @@ class paging { * @return string always empty */ public function getSqlLimit() { + + if ($this->_limit > 0) { + $_offset = ($this->pageno - 1) * $this->_limit; + return ' LIMIT '.$_offset.','.$this->_limit; + } /** * currently not in use */ From 541ab1fe6ee510542f714e2e0a638ea28cbad489 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 11 Mar 2017 07:34:13 +0100 Subject: [PATCH 054/179] clearify field label for domain termination date; fixes #1728 Signed-off-by: Michael Kaufmann (d00p) --- lng/english.lng.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lng/english.lng.php b/lng/english.lng.php index c8c7313f..1f45fd0c 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -1972,7 +1972,7 @@ $lng['error']['autoupdate_9'] = 'The downloaded file did not pass the integrity $lng['admin']['server_php'] = 'PHP'; $lng['domains']['termination_date'] = 'Date of termination'; -$lng['domains']['termination_date_overview'] = 'canceled until '; +$lng['domains']['termination_date_overview'] = 'terminated as of '; $lng['panel']['set'] = 'Apply'; $lng['customer']['selectserveralias_addinfo'] = 'This option can be set when editing the domain. Its initial value is inherited from the parent-domain.'; $lng['error']['mailaccistobedeleted'] = "Another account with the same name (%s) is currently being deleted and can therefore not be added at this moment."; From 398d45deae5232ea70f86b805da92f6b817747f5 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 14 Mar 2017 13:46:07 +0100 Subject: [PATCH 055/179] fix typo Signed-off-by: Michael Kaufmann (d00p) --- lng/english.lng.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lng/english.lng.php b/lng/english.lng.php index 1f45fd0c..94e5e343 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2038,8 +2038,8 @@ $lng['serversettings']['le_froxlor_enabled']['description'] = "If activated, the $lng['serversettings']['le_froxlor_redirect']['title'] = "Enable SSL-redirect for the froxlor vhost"; $lng['serversettings']['le_froxlor_redirect']['description'] = "If activated, all http requests to your froxlor will be redirected to the corresponding SSL site."; $lng['admin']['froxlorvhost'] = 'Froxlor VirtualHost settings'; -$lng['serversettings']['option_unavailable_websrv'] = '
Availble only for: %s'; -$lng['serversettings']['option_unavailable'] = '
Option not availble due to other settings.'; +$lng['serversettings']['option_unavailable_websrv'] = '
Available only for: %s'; +$lng['serversettings']['option_unavailable'] = '
Option not available due to other settings.'; $lng['serversettings']['letsencryptacmeconf']['title'] = "Path to the acme.conf snippet"; $lng['serversettings']['letsencryptacmeconf']['description'] = "File name of the config snippet which allows the web server to serve the acme challenge."; $lng['admin']['hostname'] = 'Hostname'; From ad7cf52f21b8cc1d0dde5ecdbcb9fb50e7be56e3 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 17 Mar 2017 13:05:39 +0100 Subject: [PATCH 056/179] Fix rowcount value for logger Signed-off-by: Michael Kaufmann (d00p) --- admin_logger.php | 3 +-- customer_logger.php | 6 ++++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/admin_logger.php b/admin_logger.php index 8aba34c8..9c344702 100644 --- a/admin_logger.php +++ b/admin_logger.php @@ -34,8 +34,7 @@ if ($page == 'log' $query = 'SELECT * FROM `' . TABLE_PANEL_LOG . '` ' . $paging->getSqlWhere(false) . ' ' . $paging->getSqlOrderBy(); $result_stmt = Database::query($query . ' ' . $paging->getSqlLimit()); $result_cnt_stmt = Database::query($query); - $res_cnt = $result_cnt_stmt->fetch(PDO::FETCH_ASSOC); - $logs_count = $res_cnt['resultrows']; + $logs_count = $result_cnt_stmt->rowCount(); $paging->setEntries($logs_count); $sortcode = $paging->getHtmlSortCode($lng); $arrowcode = $paging->getHtmlArrowCode($filename . '?page=' . $page . '&s=' . $s); diff --git a/customer_logger.php b/customer_logger.php index e3290296..65c1db01 100644 --- a/customer_logger.php +++ b/customer_logger.php @@ -38,9 +38,11 @@ if ($page == 'log') { Database::pexecute($result_stmt, array( "loginname" => $userinfo['loginname'] )); - $result_cnt_stmt = Database::query($query); + $result_cnt_stmt = Database::query($query, array( + "loginname" => $userinfo['loginname'] + )); $res_cnt = $result_cnt_stmt->fetch(PDO::FETCH_ASSOC); - $logs_count = $res_cnt['resultrows']; + $logs_count = $result_cnt_stmt->rowCount(); $paging->setEntries($logs_count); $sortcode = $paging->getHtmlSortCode($lng); $arrowcode = $paging->getHtmlArrowCode($filename . '?page=' . $page . '&s=' . $s); From d9e8f432986fc463aa5cdffe75f20519eb7fdf68 Mon Sep 17 00:00:00 2001 From: Vengance Date: Mon, 3 Apr 2017 20:21:44 +0200 Subject: [PATCH 057/179] Correct Wiki links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Correct the links of the no longer existing redmine to Github´s inbuild Wiki --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 423e16d4..e8cec20d 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Developed by experienced server administrators, this panel simplifies the effort 9. Have fun! ### Detailed installation -http://redmine.froxlor.org/projects/froxlor/wiki/Installationtarball +https://github.com/Froxlor/Froxlor/wiki ## Help @@ -35,7 +35,7 @@ The community is located on http://forum.froxlor.org ### Wiki More documentation may be found in the froxlor - wiki: -http://redmine.froxlor.org/projects/froxlor/wiki +https://github.com/Froxlor/Froxlor/wiki ## License @@ -48,14 +48,14 @@ http://files.froxlor.org/releases/froxlor-latest.tar.gz [MD5](http://files.froxl ### Debian repository -[HowTo](http://redmine.froxlor.org/projects/froxlor/wiki/Installationdebian) +[HowTo](https://github.com/Froxlor/Froxlor/wiki/Install-froxlor-on-debian) /etc/apt/sources.list.d/froxlor.list > deb http://debian.froxlor.org {wheezy|jessie} main ### Gentoo repository -[HowTo](http://redmine.froxlor.org/projects/froxlor/wiki/Installationgentoo) +[HowTo](https://github.com/Froxlor/Froxlor/wiki/Install-froxlor-on-gentoo) http://files.froxlor.org/gentoo/repositories.xml From 9cc69e5b3da1743af350910f488e89257b46ea09 Mon Sep 17 00:00:00 2001 From: Vengance Date: Mon, 3 Apr 2017 20:31:50 +0200 Subject: [PATCH 058/179] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e8cec20d..8f6dd272 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Developed by experienced server administrators, this panel simplifies the effort 9. Have fun! ### Detailed installation -https://github.com/Froxlor/Froxlor/wiki +https://github.com/Froxlor/Froxlor/wiki/Install-froxlor-from-tarball ## Help From d4cd827284ed00888267314465773a369e3aa068 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 9 Apr 2017 10:25:39 +0200 Subject: [PATCH 059/179] update wiki-urls in language files Signed-off-by: Michael Kaufmann (d00p) --- lng/dutch.lng.php | 4 ++-- lng/english.lng.php | 8 ++++---- lng/german.lng.php | 8 ++++---- lng/italian.lng.php | 10 +++++----- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/lng/dutch.lng.php b/lng/dutch.lng.php index fa5d87d3..ec195ec7 100644 --- a/lng/dutch.lng.php +++ b/lng/dutch.lng.php @@ -1031,7 +1031,7 @@ $lng['dkim']['dkim_notes']['description'] = 'Notities die van belang kunnen zijn $lng['dkim']['dkim_add_adsp']['title'] = 'DKIM ADSP toevoegen'; $lng['dkim']['dkim_add_adsp']['description'] = 'Indien u niet weet wat dit is, laat het op "actief" staan.'; $lng['dkim']['dkim_add_adsppolicy']['title'] = 'ADSP beleid'; -$lng['dkim']['dkim_add_adsppolicy']['description'] = 'Voor meer informatie inzake deze instelling zie DKIM ADSP policies'; +$lng['dkim']['dkim_add_adsppolicy']['description'] = 'Voor meer informatie inzake deze instelling zie DKIM ADSP policies'; $lng['admin']['cron']['cronsettings'] = 'Instellingen cron-taken'; $lng['cron']['cronname'] = 'naam cron-taak'; @@ -1146,7 +1146,7 @@ $lng['serversettings']['perl_path']['description'] = 'Alleen relevant voor light // ADDED IN FROXLOR 0.9.12-svn1 $lng['admin']['fcgid_settings'] = 'FCGID'; $lng['serversettings']['mod_fcgid_ownvhost']['title'] = 'FCGID inschakelen voor de VHost voor Froxlor'; -$lng['serversettings']['mod_fcgid_ownvhost']['description'] = 'Indien ingeschakeld wordt Froxlor ook uitgevoerd onder een lokale gebruiker
Let op:Dit vereist handmatige configuratie, zie FCGID - handbook'; +$lng['serversettings']['mod_fcgid_ownvhost']['description'] = 'Indien ingeschakeld wordt Froxlor ook uitgevoerd onder een lokale gebruiker
Let op:Dit vereist handmatige configuratie, zie FCGID - handbook'; $lng['admin']['mod_fcgid_user'] = 'Lokale gebruiker voor FCGID (Froxlor vhost)'; $lng['admin']['mod_fcgid_group'] = 'Lokale groep voor FCGID (Froxlor vhost)'; diff --git a/lng/english.lng.php b/lng/english.lng.php index 94e5e343..59765e15 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -534,7 +534,7 @@ $lng['panel']['back'] = 'Back'; // ADDED IN 1.2.16-svn12 $lng['serversettings']['mod_fcgid']['title'] = 'Enable FCGID'; -$lng['serversettings']['mod_fcgid']['description'] = 'Use this to run PHP with the corresponding useraccount.

This needs a special webserver configuration for Apache, see FCGID - handbook'; +$lng['serversettings']['mod_fcgid']['description'] = 'Use this to run PHP with the corresponding useraccount.

This needs a special webserver configuration for Apache, see FCGID - handbook'; $lng['serversettings']['sendalternativemail']['title'] = 'Use alternative email-address'; $lng['serversettings']['sendalternativemail']['description'] = 'Send the password-email to a different address during email-account-creation'; $lng['emails']['alternative_emailaddress'] = 'Alternative e-mail-address'; @@ -1102,7 +1102,7 @@ $lng['dkim']['dkim_notes']['description'] = 'Notes that might be of interest to $lng['dkim']['dkim_add_adsp']['title'] = 'Add DKIM ADSP entry'; $lng['dkim']['dkim_add_adsp']['description'] = 'If you don\'t know what this is, leave it "enabled"'; $lng['dkim']['dkim_add_adsppolicy']['title'] = 'ADSP policy'; -$lng['dkim']['dkim_add_adsppolicy']['description'] = 'For more information about this setting see DKIM ADSP policies'; +$lng['dkim']['dkim_add_adsppolicy']['description'] = 'For more information about this setting see DKIM ADSP policies'; $lng['admin']['cron']['cronsettings'] = 'Cronjob settings'; $lng['cron']['cronname'] = 'cronjob-name'; @@ -1293,7 +1293,7 @@ $lng['error']['intvaluetoolow'] = 'The given number is too low (field %s)'; $lng['error']['intvaluetoohigh'] = 'The given number is too high (field %s)'; $lng['admin']['phpfpm_settings'] = 'PHP-FPM'; $lng['serversettings']['phpfpm']['title'] = 'Enable php-fpm'; -$lng['serversettings']['phpfpm']['description'] = 'This needs a special webserver configuration see FPM-handbook for Apache2 or nginx'; +$lng['serversettings']['phpfpm']['description'] = 'This needs a special webserver configuration see FPM-handbook for Apache2 or nginx'; $lng['serversettings']['phpfpm_settings']['configdir'] = 'Configuration directory of php-fpm'; $lng['serversettings']['phpfpm_settings']['aliasconfigdir'] = 'Configuration Alias-directory of php-fpm'; $lng['serversettings']['phpfpm_settings']['reload'] = 'php-fpm restart command'; @@ -1840,7 +1840,7 @@ $lng['domains']['import_file'] = 'CSV-File'; $lng['success']['domain_import_successfully'] = 'Successfully imported %s domains.'; $lng['error']['domain_import_error'] = 'Following error occurred while importing domains: %s'; $lng['admin']['note'] = 'Note'; -$lng['domains']['import_description'] = 'Detailed information about the structure of the import-file and how to import successfully, please visit http://redmine.froxlor.org/projects/froxlor/wiki/DomainBulkActionDoc'; +$lng['domains']['import_description'] = 'Detailed information about the structure of the import-file and how to import successfully, please visit https://github.com/Froxlor/Froxlor/wiki/Domain-import-documenation'; $lng['usersettings']['custom_notes']['title'] = 'Custom notes'; $lng['usersettings']['custom_notes']['description'] = 'Feel free to put any notes you want/need in here. They will show up in the admin/customer overview for the corresponding user.'; $lng['usersettings']['custom_notes']['show'] = 'Show your notes on the dashboard of the user'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 64d501b5..af0b418a 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -529,7 +529,7 @@ $lng['panel']['back'] = 'Zurück'; // ADDED IN 1.2.16-svn12 $lng['serversettings']['mod_fcgid']['title'] = 'PHP über mod_fcgid/suexec einbinden'; -$lng['serversettings']['mod_fcgid']['description'] = 'PHP wird unter dem Benutzer des Kunden ausgeführt.

Dies benötigt eine spezielle Webserver-Konfiguration für Apache, siehe FCGID-Handbuch.'; +$lng['serversettings']['mod_fcgid']['description'] = 'PHP wird unter dem Benutzer des Kunden ausgeführt.

Dies benötigt eine spezielle Webserver-Konfiguration für Apache, siehe FCGID-Handbuch.'; $lng['serversettings']['sendalternativemail']['title'] = 'Alternative E-Mail-Adresse benutzen'; $lng['serversettings']['sendalternativemail']['description'] = 'Während des Erstellens eines Accounts das Passwort an eine andere E-Mail-Adresse senden'; $lng['emails']['alternative_emailaddress'] = 'Alternative E-Mail-Adresse'; @@ -1075,7 +1075,7 @@ $lng['dkim']['dkim_notes']['description'] = 'Eine Notiz, welche für Menschen in $lng['dkim']['dkim_add_adsp']['title'] = 'DKIM-ADSP Eintrag hinzufügen'; $lng['dkim']['dkim_add_adsp']['description'] = 'Wenn unsicher oder unbekannt, belassen sie es auf "aktiviert"'; $lng['dkim']['dkim_add_adsppolicy']['title'] = 'ADSP-Richtlinie'; -$lng['dkim']['dkim_add_adsppolicy']['description'] = 'Mehr Informationen zu dieser Einstellung (englisch) DKIM-ADSP-Policies'; +$lng['dkim']['dkim_add_adsppolicy']['description'] = 'Mehr Informationen zu dieser Einstellung (englisch) DKIM-ADSP-Policies'; $lng['admin']['cron']['cronsettings'] = 'Cronjob-Einstellungen'; $lng['cron']['cronname'] = 'Cronjob-Name'; @@ -1271,7 +1271,7 @@ $lng['error']['intvaluetoolow'] = 'Die angegebene Zahl ist zu klein (Feld "%s")' $lng['error']['intvaluetoohigh'] = 'Die angegebene Zahl ist zu groß (Feld "%s")'; $lng['admin']['phpfpm_settings'] = 'PHP-FPM'; $lng['serversettings']['phpfpm']['title'] = 'Aktiviere PHP-FPM'; -$lng['serversettings']['phpfpm']['description'] = 'Dies benötigt eine spezielle Webserver-Konfiguration, siehe FPM-Handbuch für Apache2 oder nginx'; +$lng['serversettings']['phpfpm']['description'] = 'Dies benötigt eine spezielle Webserver-Konfiguration, siehe FPM-Handbuch für Apache2 oder nginx'; $lng['serversettings']['phpfpm_settings']['configdir'] = 'Pfad zu php-fpm-Konfigurationen'; $lng['serversettings']['phpfpm_settings']['aliasconfigdir'] = 'Alias-Ordner der php-fpm Konfiguration'; $lng['serversettings']['phpfpm_settings']['reload'] = 'Kommando zum Neustarten von php-fpm'; @@ -1565,7 +1565,7 @@ $lng['domains']['import_file'] = 'CSV-Datei'; $lng['success']['domain_import_successfully'] = 'Erfolgreich %s Domains importiert.'; $lng['error']['domain_import_error'] = 'Der folgende Fehler trat beim Importieren der Domains auf: %s'; $lng['admin']['note'] = 'Hinweis'; -$lng['domains']['import_description'] = 'Detaillierte Informationen über den Aufbau der Importdatei und einen erfolgreichen Import gibt es hier: http://redmine.froxlor.org/projects/froxlor/wiki/DomainBulkActionDoc (englisch)'; +$lng['domains']['import_description'] = 'Detaillierte Informationen über den Aufbau der Importdatei und einen erfolgreichen Import gibt es hier: https://github.com/Froxlor/Froxlor/wiki/Domain-import-documenation (englisch)'; $lng['usersettings']['custom_notes']['title'] = 'Eigene Notizen'; $lng['usersettings']['custom_notes']['description'] = 'Hier können Notizen je nach Lust und Laune eingetragen werden. Diese werden in der Administrator/Kunden-Übersicht bei dem jeweiligen Benutzer angezeigt.'; $lng['usersettings']['custom_notes']['show'] = 'Zeige die Notizen auf dem Dashboard des Benutzers'; diff --git a/lng/italian.lng.php b/lng/italian.lng.php index c636e70e..7962e250 100644 --- a/lng/italian.lng.php +++ b/lng/italian.lng.php @@ -435,7 +435,7 @@ $lng['panel']['translator'] = 'Traduttore'; $lng['error']['stringformaterror'] = 'Il valore per il campo "%s" non è nel formato atteso.'; // ADDED IN 1.2.15-rc1 -// Translated by marone42@googlemail.com on 03/15/2007 (see https://trac.froxlor.org/ticket/126#comment:21) +// Translated by marone42@googlemail.com on 03/15/2007 $lng['admin']['phpversion'] = 'Versione PHP'; $lng['admin']['mysqlserverversion'] = 'Versione MySQL Server'; @@ -1050,7 +1050,7 @@ $lng['dkim']['dkim_notes']['description'] = 'Nota potrebbe essere di interesse, $lng['dkim']['dkim_add_adsp']['title'] = 'Aggiungi un valore DKIM ADSP'; $lng['dkim']['dkim_add_adsp']['description'] = 'Se non si sa di cosa si tratta, lasciare "enabled"'; $lng['dkim']['dkim_add_adsppolicy']['title'] = 'Regola ADSP'; -$lng['dkim']['dkim_add_adsppolicy']['description'] = 'Per ulteriori informazioni su questa impostazione leggere DKIM ADSP policies'; +$lng['dkim']['dkim_add_adsppolicy']['description'] = 'Per ulteriori informazioni su questa impostazione leggere DKIM ADSP policies'; $lng['admin']['cron']['cronsettings'] = 'Impostazioni Cronjob'; $lng['cron']['cronname'] = 'Nome cronjob'; @@ -1171,7 +1171,7 @@ $lng['serversettings']['perl_path']['description'] = 'Rilevante solo se si utili // ADDED IN FROXLOR 0.9.12-svn1 $lng['admin']['fcgid_settings'] = 'FCGID'; $lng['serversettings']['mod_fcgid_ownvhost']['title'] = 'Abilita FCGID per i vhost Froxlor'; -$lng['serversettings']['mod_fcgid_ownvhost']['description'] = 'Se attivato, Froxlor verrà eseguito con un utente locale
ATTENZIONE:Questo richiede una configurazione manuale, vedi FCGID - handbook'; +$lng['serversettings']['mod_fcgid_ownvhost']['description'] = 'Se attivato, Froxlor verrà eseguito con un utente locale
ATTENZIONE:Questo richiede una configurazione manuale, vedi FCGID - handbook'; $lng['admin']['mod_fcgid_user'] = 'Utente locale per FCGID (Froxlor vhost)'; $lng['admin']['mod_fcgid_group'] = 'Gruppo locale per FCGID (Froxlor vhost)'; @@ -1361,7 +1361,7 @@ $lng['admin']['store_defaultindex'] = 'Archivio del file indice predefinito al p $lng['admin']['ipsandports']['ssl_cert_chainfile']['title'] = 'Percorso al file catena dei certificati SSL'; $lng['admin']['ipsandports']['ssl_cert_chainfile']['description'] = 'Principalmente Bundle CA, o similare, presubilmente vuoi impostare questo se hai acquistato un certificato SSL.'; $lng['serversettings']['phpfpm']['title'] = 'Abilita php-fpm'; -$lng['serversettings']['phpfpm']['description'] = 'Questa impostazione richiede una configurazione speciale del server web. Vedi il manuale FPM per Apache2 o nginx'; +$lng['serversettings']['phpfpm']['description'] = 'Questa impostazione richiede una configurazione speciale del server web. Vedi il manuale FPM per Apache2 o nginx'; $lng['serversettings']['phpfpm_settings']['aliasconfigdir'] = 'Configurazione cartella Alias per php-fpm'; $lng['gender']['title'] = 'Titolo'; $lng['gender']['male'] = 'Sig.'; @@ -1795,7 +1795,7 @@ $lng['domains']['import_file'] = 'File CSV'; $lng['success']['domain_import_successfully'] = 'Importato %s dominii con successo.'; $lng['error']['domain_import_error'] = 'Il seguente errore è occorsonell \'importazione di dominii: %s'; $lng['admin']['note'] = 'Nota'; -$lng['domains']['import_description'] = 'Per ottenere informazioni dettagliate sulla struttura del file di importazione e su come importare con successo, visita http://redmine.froxlor.org/projects/froxlor/wiki/DomainBulkActionDoc'; +$lng['domains']['import_description'] = 'Per ottenere informazioni dettagliate sulla struttura del file di importazione e su come importare con successo, visita https://github.com/Froxlor/Froxlor/wiki/Domain-import-documenation'; $lng['usersettings']['custom_notes']['title'] = 'Note personali'; $lng['usersettings']['custom_notes']['description'] = 'Sentiti libero di inserire qualsi nota vuoi o necessiti qui. Apparirano nel riepilogo dell\'amministratore/cliente perl \'utente corrispondente.'; $lng['usersettings']['custom_notes']['show'] = 'Mostra le tue note nel cruscotto dell\'utente'; From ec1bd6e19a3b8c68a1aa2be1bc521d63fea92f71 Mon Sep 17 00:00:00 2001 From: Daniel Reichelt Date: Tue, 11 Apr 2017 17:09:34 +0200 Subject: [PATCH 060/179] add OCSP stapling support for apache2 and nginx --- actions/admin/settings/131.ssl.php | 12 ++++ admin_domains.php | 56 +++++++++++++++++-- install/froxlor.sql | 4 +- .../updates/froxlor/0.9/update_0.9.inc.php | 14 +++++ lib/classes/webserver/class.WebserverBase.php | 3 +- .../admin/domains/formfield.domains_add.php | 19 ++++++- .../admin/domains/formfield.domains_edit.php | 21 ++++++- lib/version.inc.php | 2 +- lng/english.lng.php | 7 +++ lng/german.lng.php | 7 +++ .../jobs/cron_tasks.inc.http.10.apache.php | 19 ++++++- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 8 +++ 12 files changed, 160 insertions(+), 12 deletions(-) diff --git a/actions/admin/settings/131.ssl.php b/actions/admin/settings/131.ssl.php index 56c27cd5..7a73da85 100644 --- a/actions/admin/settings/131.ssl.php +++ b/actions/admin/settings/131.ssl.php @@ -79,6 +79,18 @@ return array( 'default' => '', 'save_method' => 'storeSettingField' ), + 'system_apache24_ocsp_cache_path' => array( + 'label' => $lng['serversettings']['ssl']['apache24_ocsp_cache_path'], + 'settinggroup' => 'system', + 'varname' => 'apache24_ocsp_cache_path', + 'type' => 'string', + 'string_type' => 'string', + 'string_emptyallowed' => false, + 'default' => '', + 'visible' => Settings::Get('system.webserver') == "apache2" && + Settings::Get('system.apache24') == 1, + 'save_method' => 'storeSettingField' + ), 'system_leenabled' => array( 'label' => $lng['serversettings']['leenabled'], 'settinggroup' => 'system', diff --git a/admin_domains.php b/admin_domains.php index 8a28364c..f2a877aa 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -595,6 +595,9 @@ if ($page == 'domains' || $page == 'overview') { $hsts_sub = isset($_POST['hsts_sub']) && (int)$_POST['hsts_sub'] == 1 ? 1 : 0; $hsts_preload = isset($_POST['hsts_preload']) && (int)$_POST['hsts_preload'] == 1 ? 1 : 0; + // OCSP stapling + $ocsp_stapling = isset($_POST['ocsp_stapling']) && (int)$_POST['ocsp_stapling'] == 1 ? 1 : 0; + } else { $ssl_redirect = 0; $letsencrypt = 0; @@ -606,6 +609,9 @@ if ($page == 'domains' || $page == 'overview') { $hsts_maxage = 0; $hsts_sub = 0; $hsts_preload = 0; + + // OCSP stapling + $ocsp_stapling = 0; } } else { $ssl_redirect = 0; @@ -618,6 +624,9 @@ if ($page == 'domains' || $page == 'overview') { $hsts_maxage = 0; $hsts_sub = 0; $hsts_preload = 0; + + // OCSP stapling + $ocsp_stapling = 0; } // We can't enable let's encrypt for wildcard - domains @@ -789,7 +798,8 @@ if ($page == 'domains' || $page == 'overview') { 'letsencrypt' => $letsencrypt, 'hsts_maxage' => $hsts_maxage, 'hsts_sub' => $hsts_sub, - 'hsts_preload' => $hsts_preload + 'hsts_preload' => $hsts_preload, + 'ocsp_stapling' => $ocsp_stapling, ); $security_questions = array( @@ -841,7 +851,8 @@ if ($page == 'domains' || $page == 'overview') { 'letsencrypt' => $letsencrypt, 'hsts' => $hsts_maxage, 'hsts_sub' => $hsts_sub, - 'hsts_preload' => $hsts_preload + 'hsts_preload' => $hsts_preload, + 'ocsp_stapling' => $ocsp_stapling, ); $ins_stmt = Database::prepare(" @@ -878,7 +889,8 @@ if ($page == 'domains' || $page == 'overview') { `letsencrypt` = :letsencrypt, `hsts` = :hsts, `hsts_sub` = :hsts_sub, - `hsts_preload` = :hsts_preload + `hsts_preload` = :hsts_preload, + `ocsp_stapling` = :ocsp_stapling "); Database::pexecute($ins_stmt, $ins_data); $domainid = Database::lastInsertId(); @@ -1421,6 +1433,9 @@ if ($page == 'domains' || $page == 'overview') { $hsts_sub = isset($_POST['hsts_sub']) && (int)$_POST['hsts_sub'] == 1 ? 1 : 0; $hsts_preload = isset($_POST['hsts_preload']) && (int)$_POST['hsts_preload'] == 1 ? 1 : 0; + // OCSP stapling + $ocsp_stapling = isset($_POST['ocsp_stapling']) && (int)$_POST['ocsp_stapling'] == 1 ? 1 : 0; + $ssl_ipandports = array(); if (isset($_POST['ssl_ipandport']) && ! is_array($_POST['ssl_ipandport'])) { $_POST['ssl_ipandport'] = unserialize($_POST['ssl_ipandport']); @@ -1458,6 +1473,9 @@ if ($page == 'domains' || $page == 'overview') { $hsts_maxage = 0; $hsts_sub = 0; $hsts_preload = 0; + + // OCSP stapling + $ocsp_stapling = 0; } } else { $ssl_redirect = 0; @@ -1470,6 +1488,9 @@ if ($page == 'domains' || $page == 'overview') { $hsts_maxage = 0; $hsts_sub = 0; $hsts_preload = 0; + + // OCSP stapling + $ocsp_stapling = 0; } // We can't enable let's encrypt for wildcard domains @@ -1615,7 +1636,8 @@ if ($page == 'domains' || $page == 'overview') { 'letsencrypt' => $letsencrypt, 'hsts_maxage' => $hsts_maxage, 'hsts_sub' => $hsts_sub, - 'hsts_preload' => $hsts_preload + 'hsts_preload' => $hsts_preload, + 'ocsp_stapling' => $ocsp_stapling, ); $security_questions = array( @@ -1634,7 +1656,27 @@ if ($page == 'domains' || $page == 'overview') { $wwwserveralias = ($serveraliasoption == '1') ? '1' : '0'; $iswildcarddomain = ($serveraliasoption == '0') ? '1' : '0'; - if ($documentroot != $result['documentroot'] || $ssl_redirect != $result['ssl_redirect'] || $wwwserveralias != $result['wwwserveralias'] || $iswildcarddomain != $result['iswildcarddomain'] || $phpenabled != $result['phpenabled'] || $openbasedir != $result['openbasedir'] || $phpsettingid != $result['phpsettingid'] || $mod_fcgid_starter != $result['mod_fcgid_starter'] || $mod_fcgid_maxrequests != $result['mod_fcgid_maxrequests'] || $specialsettings != $result['specialsettings'] || $aliasdomain != $result['aliasdomain'] || $issubof != $result['ismainbutsubto'] || $email_only != $result['email_only'] || ($speciallogfile != $result['speciallogfile'] && $speciallogverified == '1') || $letsencrypt != $result['letsencrypt'] || $hsts_maxage != $result['hsts'] || $hsts_sub != $result['hsts_sub'] || $hsts_preload != $result['hsts_preload']) { + if ( + $documentroot != $result['documentroot'] || + $ssl_redirect != $result['ssl_redirect'] || + $wwwserveralias != $result['wwwserveralias'] || + $iswildcarddomain != $result['iswildcarddomain'] || + $phpenabled != $result['phpenabled'] || + $openbasedir != $result['openbasedir'] || + $phpsettingid != $result['phpsettingid'] || + $mod_fcgid_starter != $result['mod_fcgid_starter'] || + $mod_fcgid_maxrequests != $result['mod_fcgid_maxrequests'] || + $specialsettings != $result['specialsettings'] || + $aliasdomain != $result['aliasdomain'] || + $issubof != $result['ismainbutsubto'] || + $email_only != $result['email_only'] || + ($speciallogfile != $result['speciallogfile'] && $speciallogverified == '1') || + $letsencrypt != $result['letsencrypt'] || + $hsts_maxage != $result['hsts'] || + $hsts_sub != $result['hsts_sub'] || + $hsts_preload != $result['hsts_preload'] || + $ocsp_stapling != $result['ocsp_stapling'] + ) { inserttask('1'); } @@ -1789,6 +1831,7 @@ if ($page == 'domains' || $page == 'overview') { $update_data['hsts'] = $hsts_maxage; $update_data['hsts_sub'] = $hsts_sub; $update_data['hsts_preload'] = $hsts_preload; + $update_data['ocsp_stapling'] = $ocsp_stapling; $update_data['id'] = $id; $update_stmt = Database::prepare(" @@ -1820,7 +1863,8 @@ if ($page == 'domains' || $page == 'overview') { `letsencrypt` = :letsencrypt, `hsts` = :hsts, `hsts_sub` = :hsts_sub, - `hsts_preload` = :hsts_preload + `hsts_preload` = :hsts_preload, + `ocsp_stapling` = :ocsp_stapling WHERE `id` = :id "); Database::pexecute($update_stmt, $update_data); diff --git a/install/froxlor.sql b/install/froxlor.sql index d8d600a0..fa352c50 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -257,6 +257,7 @@ CREATE TABLE `panel_domains` ( `hsts` varchar(10) NOT NULL default '0', `hsts_sub` tinyint(1) NOT NULL default '0', `hsts_preload` tinyint(1) NOT NULL default '0', + `ocsp_stapling` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `customerid` (`customerid`), KEY `parentdomain` (`parentdomainid`), @@ -503,6 +504,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('system', 'perl_server', 'unix:/var/run/nginx/cgiwrap-dispatch.sock'), ('system', 'phpreload_command', ''), ('system', 'apache24', '0'), + ('system', 'apache24_ocsp_cache_path', 'shmcb:/var/run/apache2/ocsp-stapling.cache(131072)'), ('system', 'documentroot_use_default_value', '0'), ('system', 'passwordcryptfunc', '3'), ('system', 'axfrservers', ''), @@ -582,7 +584,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.7'), - ('panel', 'db_version', '201612110'); + ('panel', 'db_version', '201704100'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index d8aa8735..10a2ef19 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3593,3 +3593,17 @@ if (isFroxlorVersion('0.9.38.6')) { showUpdateStep("Updating from 0.9.38.6 to 0.9.38.7", false); updateToVersion('0.9.38.7'); } + +if (isDatabaseVersion('201612110')) { + + showUpdateStep("Adding field for OCSP stapling"); + Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . + "` ADD `ocsp_stapling` TINYINT(1) NOT NULL DEFAULT '0';"); + lastStepStatus(0); + + showUpdateStep("Adding default setting for Apache 2.4 OCSP cache path"); + Settings::AddNew('system.apache24_ocsp_cache_path', 'shmcb:/var/run/apache2/ocsp-stapling.cache(131072)'); + lastStepStatus(0); + + updateToDbVersion('201704100'); +} diff --git a/lib/classes/webserver/class.WebserverBase.php b/lib/classes/webserver/class.WebserverBase.php index b827f04c..8f7c27c5 100644 --- a/lib/classes/webserver/class.WebserverBase.php +++ b/lib/classes/webserver/class.WebserverBase.php @@ -33,7 +33,8 @@ class WebserverBase { `c`.`documentroot` AS `customerroot`, `c`.`deactivated`, `c`.`phpenabled` AS `phpenabled_customer`, `d`.`phpenabled` AS `phpenabled_vhost`, - `d`.`mod_fcgid_starter`,`d`.`mod_fcgid_maxrequests` + `d`.`mod_fcgid_starter`,`d`.`mod_fcgid_maxrequests`, + `d`.`ocsp_stapling` FROM `".TABLE_PANEL_DOMAINS."` `d` LEFT JOIN `".TABLE_PANEL_CUSTOMERS."` `c` USING(`customerid`) diff --git a/lib/formfields/admin/domains/formfield.domains_add.php b/lib/formfields/admin/domains/formfield.domains_add.php index 8482123e..988c496f 100644 --- a/lib/formfields/admin/domains/formfield.domains_add.php +++ b/lib/formfields/admin/domains/formfield.domains_add.php @@ -213,7 +213,24 @@ return array( ) ), 'value' => array() - ) + ), + 'ocsp_stapling' => array( + 'visible' => ($ssl_ipsandports != '' ? true : false) && + Settings::Get('system.webserver') != 'lighttpd', + 'label' => $lng['admin']['domain_ocsp_stapling']['title'], + 'desc' => $lng['admin']['domain_ocsp_stapling']['description'] . + (Settings::Get('system.webserver') == 'nginx' ? + $lng['admin']['domain_ocsp_stapling']['nginx_version_warning'] : + ""), + 'type' => 'checkbox', + 'values' => array( + array ( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array() + ), ) ), 'section_c' => array( diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index 22a293cc..e351c8da 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -251,7 +251,26 @@ return array( 'value' => array( $result['hsts_preload'] ) - ) + ), + 'ocsp_stapling' => array( + 'visible' => ($ssl_ipsandports != '' ? true : false) && + Settings::Get('system.webserver') != 'lighttpd', + 'label' => $lng['admin']['domain_ocsp_stapling']['title'], + 'desc' => $lng['admin']['domain_ocsp_stapling']['description'] . + (Settings::Get('system.webserver') == 'nginx' ? + $lng['admin']['domain_ocsp_stapling']['nginx_version_warning'] : + ""), + 'type' => 'checkbox', + 'values' => array( + array ( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + $result['ocsp_stapling'] + ) + ), ) ), 'section_c' => array( diff --git a/lib/version.inc.php b/lib/version.inc.php index 3ce16650..db028f51 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.7'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201612110'; +$dbversion = '201704100'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index 59765e15..8ed89fd8 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2067,3 +2067,10 @@ $lng['serversettings']['nginx_http2_support']['title'] = 'Nginx HTTP2 Support'; $lng['serversettings']['nginx_http2_support']['description'] = 'enable http2 support for ssl. ENABLE ONLY IF YOUR Nginx SUPPORT THIS FEATURE. (version 1.9.5+)'; $lng['error']['noipportgiven'] = 'No IP/port given'; + +// Added in froxlor 0.9.38.8 +$lng['admin']['domain_ocsp_stapling']['title'] = 'OCSP stapling'; +$lng['admin']['domain_ocsp_stapling']['description'] = 'See Wikipedia for a detailed explanation of OCSP stapling'; +$lng['admin']['domain_ocsp_stapling']['nginx_version_warning'] = '
WARNING: Nginx version 1.3.7 or above is required for OCSP stapling. If your version is older, the webserver will NOT start correctly while OCSP stapling is enabled!'; +$lng['serversettings']['ssl']['apache24_ocsp_cache_path']['title'] = 'Apache 2.4: path to the OCSP stapling cache'; +$lng['serversettings']['ssl']['apache24_ocsp_cache_path']['description'] = 'Configures the cache used to store OCSP responses which get included in TLS handshakes.'; diff --git a/lng/german.lng.php b/lng/german.lng.php index af0b418a..57e9476c 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1718,3 +1718,10 @@ $lng['serversettings']['nginx_http2_support']['title'] = 'Nginx HTTP2 Unterstüt $lng['serversettings']['nginx_http2_support']['description'] = 'Aktiviere http2 Unterstützung für SSL. NUR AKTIVIEREN, WENN nginx DIESE FUNKTION UNTERSTÜTZT (version 1.9.5+)'; $lng['error']['noipportgiven'] = 'Keine IP/Port angegeben'; + +// Added in froxlor 0.9.38.8 +$lng['admin']['domain_ocsp_stapling']['title'] = 'OCSP stapling'; +$lng['admin']['domain_ocsp_stapling']['description'] = 'Siehe Wikipedia für eine ausführliche Beschreibung von OCSP-Stapling'; +$lng['admin']['domain_ocsp_stapling']['nginx_version_warning'] = '
WARNUNG: Nginx unterstützt OCSP-Stapling erst ab Version 1.3.7. Wenn Ihre Version älter ist, wird der Webserver bei aktiviertem OCSP-Stapling NICHT korrekt starten.'; +$lng['serversettings']['ssl']['apache24_ocsp_cache_path']['title'] = 'Apache 2.4: Pfad zum OCSP-Stapling-Cache'; +$lng['serversettings']['ssl']['apache24_ocsp_cache_path']['description'] = 'Konfiguriert den Cache-Pfad zum Zwischenspeichern der OCSP-Antworten,
die an TLS-Handshakes angehängt werden.'; diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index c3de7b5a..85ef9bac 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -107,6 +107,17 @@ class apache extends HttpConfigBase } $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; } + + $ocsp_cache_filename = makeCorrectFile($vhosts_folder . '/03_froxlor_ocsp_cache.conf'); + if (Settings::Get('system.use_ssl') == '1' && Settings::Get('system.apache24') == 1) { + $this->virtualhosts_data[$ocsp_cache_filename] = 'SSLStaplingCache ' . + Settings::Get('system.apache24_ocsp_cache_path') . "\n"; + } else { + if (file_exists($ocsp_cache_filename)) { + $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::_createStandardDirectoryEntry: unlinking ' . basename($ocsp_cache_filename)); + unlink(makeCorrectFile($ocsp_cache_filename)); + } + } } /** @@ -504,7 +515,7 @@ class apache extends HttpConfigBase // This vHost has PHP enabled and we are using the regular mod_php $cmail = getCustomerDetail($domain['customerid'], 'email'); $php_options_text .= ' php_admin_value sendmail_path "/usr/sbin/sendmail -t -f '.$cmail.'"' . PHP_EOL; - + if ($domain['openbasedir'] == '1') { if ($domain['openbasedir_path'] == '1' || strstr($domain['documentroot'], ":") !== false) { $_phpappendopenbasedir = appendOpenBasedirPath($domain['customerroot'], true); @@ -878,6 +889,12 @@ class apache extends HttpConfigBase $vhost_content .= ' SSLCertificateChainFile ' . makeCorrectFile($domain['ssl_cert_chainfile']) . "\n"; } + if (Settings::Get('system.apache24') == '1' && isset($domain['ocsp_stapling']) && + $domain['ocsp_stapling'] == '1') + { + $vhost_content .= ' SSLUseStapling on' . PHP_EOL; + } + if ($domain['hsts'] >= 0) { $vhost_content .= ' ' . "\n"; $vhost_content .= ' Header always set Strict-Transport-Security "max-age=' . $domain['hsts']; diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index 551d43b9..9e282193 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -634,6 +634,14 @@ class nginx extends HttpConfigBase } $sslsettings .= '";' . "\n"; } + + if ((isset($domain_or_ip['ocsp_stapling']) && $domain_or_ip['ocsp_stapling'] == "1") || + (isset($domain_or_ip['letsencrypt']) && $domain_or_ip['letsencrypt'] == "1") ) { + $sslsettings .= "\t" . 'ssl_stapling on;' . "\n"; + $sslsettings .= "\t" . 'ssl_stapling_verify on;' . "\n"; + $sslsettings .= "\t" . 'ssl_trusted_certificate ' . + makeCorrectFile($domain_or_ip['ssl_cert_file']) . ';' . "\n"; + } } } From b11b423217c5cffa4369cd206145498853ed1695 Mon Sep 17 00:00:00 2001 From: Daniel Reichelt Date: Thu, 13 Apr 2017 16:38:17 +0200 Subject: [PATCH 061/179] readme: add section about contributing --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 8f6dd272..a6874147 100644 --- a/README.md +++ b/README.md @@ -72,3 +72,15 @@ This has 2 known side-effects at the moment: It may be possible to fix these issues, but they are not a priority at the moment +## Contributing + +Before you start working on a PR, contact us via IRC or the forum to get a +clue whether someone else isn't already working on it or if we don't want to +invest the effort in favour of working on Froxlor 2.0. +Of course, bug fixes are always welcome. +However, at this stage of the 0.9.x branch, we are not looking for new +features or refactoring, especially not the kind which requires changes to a +lot of files. +Currently, we are working on a complete re-write, which, at this point in +time, is not yet public to keep delays due to discussions about internal +details to a minimum. \ No newline at end of file From 872928fb38854e213002cbdc55e56c9582508a23 Mon Sep 17 00:00:00 2001 From: Max Khon Date: Sat, 15 Apr 2017 15:58:50 +0700 Subject: [PATCH 062/179] Fix customer logs: - SQLSTATE[HY000]: General error: mode must be an integer - customer_logger.php:78 Undefined variable $_actions --- customer_logger.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/customer_logger.php b/customer_logger.php index 65c1db01..366b9735 100644 --- a/customer_logger.php +++ b/customer_logger.php @@ -38,7 +38,8 @@ if ($page == 'log') { Database::pexecute($result_stmt, array( "loginname" => $userinfo['loginname'] )); - $result_cnt_stmt = Database::query($query, array( + $result_cnt_stmt = Database::prepare($query); + Database::pexecute($result_cnt_stmt, array( "loginname" => $userinfo['loginname'] )); $res_cnt = $result_cnt_stmt->fetch(PDO::FETCH_ASSOC); @@ -69,6 +70,7 @@ if ($page == 'log') { $log_count = 0; $log = ''; foreach ($clog as $action => $logrows) { + $_action = 0; foreach ($logrows as $row) { // if ($paging->checkDisplay($i)) { $row = htmlentities_array($row); From 95b7b57fc6dd008e3a2cc8b5086334ee26a177fa Mon Sep 17 00:00:00 2001 From: Max Khon Date: Sat, 15 Apr 2017 16:12:29 +0700 Subject: [PATCH 063/179] Skip views when altering table charsets. --- lib/classes/integrity/class.IntegrityCheck.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/classes/integrity/class.IntegrityCheck.php b/lib/classes/integrity/class.IntegrityCheck.php index bae1c2b3..1f8a3fb7 100644 --- a/lib/classes/integrity/class.IntegrityCheck.php +++ b/lib/classes/integrity/class.IntegrityCheck.php @@ -85,11 +85,10 @@ class IntegrityCheck { // fix database Database::query('ALTER DATABASE `' . Database::getDbName() . '` CHARACTER SET utf8 COLLATE utf8_general_ci'); // fix all tables - $handle = Database::query('SHOW TABLES'); - while ($row = $handle->fetch(PDO::FETCH_ASSOC)) { - foreach ($row as $table) { - Database::query('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;'); - } + $handle = Database::query('SHOW FULL TABLES WHERE Table_type != "VIEW"'); + while ($row = $handle->fetch(PDO::FETCH_BOTH)) { + $table = $row[0]; + Database::query('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;'); } $this->_log->logAction(ADM_ACTION, LOG_WARNING, "database charset was different from UTF-8, integrity-check fixed that"); } else { From 3870cc10026bc116dcb4da3ce326383f24de2556 Mon Sep 17 00:00:00 2001 From: Max Khon Date: Mon, 17 Apr 2017 15:55:49 +0700 Subject: [PATCH 064/179] Add default value for apache24_ocsp_cache_path, otherwise saving SSL settings for !apache24 fails on apache24_ocsp_cache_path validation. --- actions/admin/settings/131.ssl.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actions/admin/settings/131.ssl.php b/actions/admin/settings/131.ssl.php index 7a73da85..9028ac45 100644 --- a/actions/admin/settings/131.ssl.php +++ b/actions/admin/settings/131.ssl.php @@ -86,7 +86,7 @@ return array( 'type' => 'string', 'string_type' => 'string', 'string_emptyallowed' => false, - 'default' => '', + 'default' => 'shmcb:/var/run/apache2/ocsp-stapling.cache(131072)', 'visible' => Settings::Get('system.webserver') == "apache2" && Settings::Get('system.apache24') == 1, 'save_method' => 'storeSettingField' From 5930ab1c9db2e23d42afb4251b8fbc5f6cffb8d5 Mon Sep 17 00:00:00 2001 From: Soner Sayakci Date: Mon, 17 Apr 2017 12:34:20 +0200 Subject: [PATCH 065/179] Fixed MySQL Warning while creating a new user --- admin_customers.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/admin_customers.php b/admin_customers.php index dd663ddd..09e938a9 100644 --- a/admin_customers.php +++ b/admin_customers.php @@ -910,7 +910,7 @@ if ($page == 'customers' 'customerid' => $customerid, 'adminid' => $userinfo['adminid'], 'docroot' => $documentroot, - 'adddate' => date('Y-m-d'), + 'adddate' => time(), 'phpenabled' => $phpenabled ); $ins_stmt = Database::prepare(" @@ -1283,7 +1283,7 @@ if ($page == 'customers' 'customerid' => $result['customerid'], 'adminid' => $userinfo['adminid'], 'docroot' => $result['documentroot'], - 'adddate' => date('Y-m-d') + 'adddate' => time() ); $ins_stmt = Database::prepare(" INSERT INTO `" . TABLE_PANEL_DOMAINS . "` SET From 9db743487618c72cf8b38d9c86e343b5dcf108c4 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 18 Apr 2017 16:55:55 +0200 Subject: [PATCH 066/179] add letsencrypt, HSTS settings, oscp-stapling and phpenabled-flag to Domain-import; fixes #416 Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/bulk/class.DomainBulkAction.php | 38 ++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/lib/classes/bulk/class.DomainBulkAction.php b/lib/classes/bulk/class.DomainBulkAction.php index 9523c5a9..a5dac417 100644 --- a/lib/classes/bulk/class.DomainBulkAction.php +++ b/lib/classes/bulk/class.DomainBulkAction.php @@ -93,6 +93,12 @@ class DomainBulkAction /* 16 */ 'use_ssl', /* 17 */ 'registration_date', /* 18 */ 'ips', +/* 19 */ 'letsencrypt', +/* 20 */ 'hsts', +/* 21 */ 'hsts_sub', +/* 22 */ 'hsts_preload', +/* 23 */ 'ocsp_stapling', +/* 24 */ 'phpenabled', /* automatically added */ 'adminid', 'customerid', @@ -200,7 +206,13 @@ class DomainBulkAction `specialsettings` = :specialsettings, `ssl_redirect` = :ssl_redirect, `registration_date` = :registration_date, - `add_date` = :add_date + `add_date` = :add_date, + `letsencrypt` = :letsencrypt, + `hsts` = :hsts, + `hsts_sub` = :hsts_sub, + `hsts_preload` = :hsts_preload, + `ocsp_stapling` = :ocsp_stapling, + `phpenabled` = :phpenabled "); // prepare insert statement for ip/port <> domain @@ -335,6 +347,30 @@ class DomainBulkAction $domain_data['ssl_redirect'] = 0; } + // only check for letsencrypt, hsts and oscp-stapling if ssl is enabled + if ($domain_data['use_ssl'] == 1) { + //lets encrypt + if ($domain_data['letsencrypt'] != 1 || $domain_data['iswildcarddomain'] == 1) { + $domain_data['letsencrypt'] = 0; + } + } else { + $domain_data['letsencrypt'] = 0; + } + + // hsts + if ($domain_data['hsts'] != 1) { + $domain_data['hsts'] = 0; + } + if ($domain_data['hsts_sub'] != 1) { + $domain_data['hsts_sub'] = 0; + } + if ($domain_data['hsts_preload'] != 1) { + $domain_data['hsts_preload'] = 0; + } + if ($domain_data['ocsp_stapling'] != 1) { + $domain_data['ocsp_stapling'] = 0; + } + // add to known domains $this->_knownDomains[] = $domain_data['domain']; From 22414096ade9fa592b2bdcdbcdafb4457568a1ff Mon Sep 17 00:00:00 2001 From: Daniel Reichelt Date: Mon, 1 May 2017 21:24:48 +0200 Subject: [PATCH 067/179] doc: extend notes about contributing; add issue template --- .github/CONTRIBUTING.md | 58 +++++++++++++++++++++++++++++++++++ .github/ISSUE_TEMPLATE.md | 64 +++++++++++++++++++++++++++++++++++++++ README.md | 11 +------ 3 files changed, 123 insertions(+), 10 deletions(-) create mode 100644 .github/CONTRIBUTING.md create mode 100644 .github/ISSUE_TEMPLATE.md diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 00000000..ffa292ae --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,58 @@ +# Contributing + +Before you start working on a PR, contact us via IRC in #froxlor on Freenode or +the forum at https://forum.froxlor.org to get a clue whether someone else isn't +already working on it or if we don't want to invest the effort in favour of +working on Froxlor 2.0. +Of course, bug fixes are always welcome. +However, at this stage of the 0.9.x branch, we are not looking for new +features or refactoring, especially not the kind which requires changes to a +lot of files. +Currently, we are working on a complete re-write, which, at this point in +time, is not yet public to keep delays due to discussions about internal +details to a minimum. + + + + +## Checklist + +General rules for PRs are: +* Please save us all some trouble and unnecessary round-trips by _testing_ your +changes. + +* Re-write your commit history to provide a CLEAN history! + + * i.e. do not provide PRs which contain a commit that changes something, + the next changes it back, a third one changes it again, only a little + differently... + + +Thanks! + + + + +### Webserver changes +If you make changes to the functionality of webserver configuration, please +make sure your implementation covers both apache **and** nginx. + + + + +### l10n + +If you add new language strings, please make sure you add the english fallback +strings in + +* `lng/english.lng.php` +* `install/lng/english.lng.php` (if applicable) + + + + +### New settings +If you add new settings, please make sure you add the default values to + +* `install/froxlor.sql` +* handle the update (see `install/updates/froxlor/0.9/update_0.9.inc.php`) diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..ff27e343 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,64 @@ +# Bug report vs. support request +If you're unsure of whether your problem is a bug or a configuration error +* contact us via IRC in #froxlor on freenode +* or post a thread in our forum at https://forum.froxlor.org + +As a rule of thumb: before reporting an issue +* see if it hasn't been [reported](https://github.com/Froxlor/froxlor/issues) (and possibly already been [fixed](https://github.com/Froxlor/froxlor/issues?utf8=✓&q=is:issue%20is:closed)) first +* try with the git master + + + + + +# Summary + +Please provide a concise summary of the problem you're experiencing... + + + + +# System information +* Froxlor version: $version/$gitSHA1 +* Web server: apache2/nginx/lighttpd +* DNS server: Bind/PowerDNS (standalone)/PowerDNS (Bind-backend) +* POP/IMAP server: Courier/Dovecot +* SMTP server: postfix/exim +* FTP server: proftpd/pureftpd +* OS/Version: ... + + + + +# Steps to reproduce + +1. +2. +3. + + + + +# Expected behavior + +1. +2. +3. + + + + +# Actual behavior + +1. +2. +3. + + + + +# Log files/log entries +syslog: +
+example
+
diff --git a/README.md b/README.md index a6874147..35d9a624 100644 --- a/README.md +++ b/README.md @@ -74,13 +74,4 @@ It may be possible to fix these issues, but they are not a priority at the momen ## Contributing -Before you start working on a PR, contact us via IRC or the forum to get a -clue whether someone else isn't already working on it or if we don't want to -invest the effort in favour of working on Froxlor 2.0. -Of course, bug fixes are always welcome. -However, at this stage of the 0.9.x branch, we are not looking for new -features or refactoring, especially not the kind which requires changes to a -lot of files. -Currently, we are working on a complete re-write, which, at this point in -time, is not yet public to keep delays due to discussions about internal -details to a minimum. \ No newline at end of file +[see here](.github/CONTRIBUTING.md) From a2e0de23e1ed19a8c174b09edcdf559d98b1b5d0 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 5 May 2017 09:35:06 +0200 Subject: [PATCH 068/179] add libnss-extrausers for debian/ubuntu users Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 3 +- .../updates/froxlor/0.9/update_0.9.inc.php | 10 +++ .../preconfig/0.9/preconfig_0.9.inc.php | 8 +++ lib/configfiles/jessie.xml | 36 ++++++++++ lib/configfiles/precise.xml | 36 ++++++++++ lib/configfiles/trusty.xml | 36 ++++++++++ lib/configfiles/wheezy.xml | 36 ++++++++++ lib/version.inc.php | 2 +- scripts/classes/class.Extrausers.php | 72 +++++++++++++++++++ scripts/froxlor_master_cronjob.php | 18 +++++ scripts/jobs/cron_tasks.php | 7 ++ 11 files changed, 262 insertions(+), 2 deletions(-) create mode 100644 scripts/classes/class.Extrausers.php diff --git a/install/froxlor.sql b/install/froxlor.sql index fa352c50..fbdabcd5 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -552,6 +552,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('system', 'hsts_incsub', '0'), ('system', 'hsts_preload', '0'), ('system', 'leregistered', '0'), + ('system', 'nssextrausers', '0'), ('panel', 'decimal_places', '4'), ('panel', 'adminmail', 'admin@SERVERNAME'), ('panel', 'phpmyadmin_url', ''), @@ -584,7 +585,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.7'), - ('panel', 'db_version', '201704100'); + ('panel', 'db_version', '201705050'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 10a2ef19..1701f8be 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3607,3 +3607,13 @@ if (isDatabaseVersion('201612110')) { updateToDbVersion('201704100'); } + +if (isDatabaseVersion('201704100')) { + + showUpdateStep("Adding new setting for libnss-extrausers"); + $system_nssextrausers= isset($_POST['system_nssextrausers']) ? (int) $_POST['system_nssextrausers'] : 0; + Settings::AddNew('system.nssextrausers', $system_nssextrausers); + lastStepStatus(0); + + updateToDbVersion('201705050'); +} diff --git a/install/updates/preconfig/0.9/preconfig_0.9.inc.php b/install/updates/preconfig/0.9/preconfig_0.9.inc.php index a25b78fc..a528c322 100644 --- a/install/updates/preconfig/0.9/preconfig_0.9.inc.php +++ b/install/updates/preconfig/0.9/preconfig_0.9.inc.php @@ -709,4 +709,12 @@ function parseAndOutputPreconfig(&$has_preconfig, &$return, $current_version, $c $question .= '
'; eval("\$return.=\"" . getTemplate("update/preconfigitem") . "\";"); } + + if (versionInUpdate($current_db_version, '201705050')) { + $has_preconfig = true; + $description = 'DEBIAN/UBUNTU ONLY: Enable usage of libnss-extrausers as alternative to libnss-mysql (NOTE: if enabled, go through the configuration steps right after the update!!!)

'; + $question = 'Enable usage of libnss-extrausers?
'; + $question .= makeyesno('system_nssextrausers', '1', '0', '0') . '
'; + eval("\$return.=\"" . getTemplate("update/preconfigitem") . "\";"); + } } diff --git a/lib/configfiles/jessie.xml b/lib/configfiles/jessie.xml index c9ac50af..ccdbe9a3 100644 --- a/lib/configfiles/jessie.xml +++ b/lib/configfiles/jessie.xml @@ -4634,6 +4634,42 @@ aliases: files
+ + + + + + + + + + + + + + + diff --git a/lib/configfiles/precise.xml b/lib/configfiles/precise.xml index c985a38e..24d6967b 100644 --- a/lib/configfiles/precise.xml +++ b/lib/configfiles/precise.xml @@ -1624,6 +1624,42 @@ netmasks: files netgroup: files bootparams: files +automount: files +aliases: files +]]> + +
+ + + +
+ + + + + + + + + diff --git a/lib/configfiles/trusty.xml b/lib/configfiles/trusty.xml index 7a7aeb8d..44500921 100644 --- a/lib/configfiles/trusty.xml +++ b/lib/configfiles/trusty.xml @@ -1642,6 +1642,42 @@ aliases: files + + + + + + + + + + + + + + + diff --git a/lib/configfiles/wheezy.xml b/lib/configfiles/wheezy.xml index 6e286017..b6fe5698 100644 --- a/lib/configfiles/wheezy.xml +++ b/lib/configfiles/wheezy.xml @@ -5433,6 +5433,42 @@ netmasks: files netgroup: files bootparams: files +automount: files +aliases: files +]]> + +
+ + + +
+ + + + + + + + + diff --git a/lib/version.inc.php b/lib/version.inc.php index db028f51..7d67b9da 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.7'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201704100'; +$dbversion = '201705050'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/scripts/classes/class.Extrausers.php b/scripts/classes/class.Extrausers.php new file mode 100644 index 00000000..4b979a79 --- /dev/null +++ b/scripts/classes/class.Extrausers.php @@ -0,0 +1,72 @@ + (2017-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Cron + * + */ +class Extrausers +{ + + public static function generateFiles(&$cronlog) + { + // passwd + $passwd = '/var/lib/extrausers/passwd'; + $sql = "SELECT username,'x' as password,uid,gid,'Froxlor User' as comment,homedir,shell FROM ftp_users WHERE login_enabled = 'Y' ORDER BY uid ASC"; + self::_generateFile($passwd, $sql, $cronlog); + + // group + $group = '/var/lib/extrausers/group'; + $sql = "SELECT groupname,'x' as password,gid,members FROM ftp_groups ORDER BY gid ASC"; + self::_generateFile($group, $sql, $cronlog); + + // shadow + $shadow = '/var/lib/extrausers/shadow'; + $sql = "SELECT username,password FROM ftp_users ORDER BY gid ASC"; + self::_generateFile($shadow, $sql, $cronlog); + } + + private static function _generateFile($file, $query, &$cronlog) + { + $type = basename($file); + $cronlog->logAction(CRON_ACTION, LOG_NOTICE, 'Creating ' . $type . ' file'); + + if (! file_exists($file)) { + $cronlog->logAction(CRON_ACTION, LOG_NOTICE, $type . ' file does not yet exist'); + @mkdir(dirname($file), 0750, true); + touch($file); + } + + $data_sel_stmt = Database::query($query); + $data_content = ""; + $cronlog->logAction(CRON_ACTION, LOG_NOTICE, 'Writing ' . $data_sel_stmt->rowCount() . ' entries to ' . $type . ' file'); + while ($u = $data_sel_stmt->fetch(PDO::FETCH_ASSOC)) { + switch ($type) { + case 'passwd': + $line = $u['username'] . ':' . $u['password'] . ':' . $u['uid'] . ':' . $u['gid'] . ':' . $u['comment'] . ':' . $u['homedir'] . ':' . $u['shell'] . PHP_EOL; + break; + case 'group': + $line = $u['groupname'] . ':' . $u['password'] . ':' . $u['gid'] . ':' . $u['members'] . PHP_EOL; + break; + case 'shadow': + $line = $u['username'] . ':' . $u['password'] . ':' . floor(time() / 86400 - 1) . ':0:99999:7:::' . PHP_EOL; + break; + } + $data_content .= $line; + } + if (file_put_contents($file, $data_content) !== false) { + $cronlog->logAction(CRON_ACTION, LOG_NOTICE, 'Succesfully wrote ' . $type . ' file'); + } else { + $cronlog->logAction(CRON_ACTION, LOG_NOTICE, 'Error when writing ' . $type . ' file entries'); + } + } +} diff --git a/scripts/froxlor_master_cronjob.php b/scripts/froxlor_master_cronjob.php index 3e4923d4..d00926c6 100644 --- a/scripts/froxlor_master_cronjob.php +++ b/scripts/froxlor_master_cronjob.php @@ -68,6 +68,9 @@ for ($x = 1; $x < count($argv); $x++) { $cronlog->setCronDebugFlag(defined('CRON_DEBUG_FLAG')); +$tasks_cnt_stmt = Database::query("SELECT COUNT(*) as jobcnt FROM `panel_tasks`"); +$tasks_cnt = $tasks_cnt_stmt->fetch(PDO::FETCH_ASSOC); + // do we have anything to include? if (count($jobs_to_run) > 0) { // include all jobs we want to execute @@ -76,6 +79,21 @@ if (count($jobs_to_run) > 0) { $cronfile = getCronFile($cron); require_once $cronfile; } + + if ($tasks_cnt['jobcnt'] > 0) + { + if (Settings::Get('system.nssextrausers') == 1) + { + include_once makeCorrectFile(FROXLOR_INSTALL_DIR.'/scripts/classes/class.Extrausers.php'); + Extrausers::generateFiles($cronlog); + } + + // clear NSCD cache if using fcgid or fpm, #1570 + if (Settings::Get('system.mod_fcgid') == 1 || (int)Settings::Get('phpfpm.enabled') == 1) { + $false_val = false; + safe_exec('nscd -i group 1> /dev/null', $false_val, array('>')); + } + } } fwrite($debugHandler, 'Cronfiles have been included' . "\n"); diff --git a/scripts/jobs/cron_tasks.php b/scripts/jobs/cron_tasks.php index dd7a754f..cd9bb294 100644 --- a/scripts/jobs/cron_tasks.php +++ b/scripts/jobs/cron_tasks.php @@ -168,6 +168,13 @@ while ($row = $result_tasks_stmt->fetch(PDO::FETCH_ASSOC)) { $cronlog->logAction(CRON_ACTION, LOG_NOTICE, 'Running: chown -R ' . (int)Settings::Get('system.vmail_uid') . ':' . (int)Settings::Get('system.vmail_gid') . ' ' . escapeshellarg($usermaildir)); safe_exec('chown -R ' . (int)Settings::Get('system.vmail_uid') . ':' . (int)Settings::Get('system.vmail_gid') . ' ' . escapeshellarg($usermaildir)); + if (Settings::Get('system.nssextrausers') == 1) + { + // explicitly create files after user has been created to avoid unknown user issues for apache/php-fpm when task#1 runs after this + include_once makeCorrectFile(FROXLOR_INSTALL_DIR.'/scripts/classes/class.Extrausers.php'); + Extrausers::generateFiles($cronlog); + } + // clear NSCD cache if using fcgid or fpm, #1570 if (Settings::Get('system.mod_fcgid') == 1 || (int)Settings::Get('phpfpm.enabled') == 1) { $false_val = false; From bea1677d5d657089bfe37f857f45ac078ae293f9 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 5 May 2017 09:44:37 +0200 Subject: [PATCH 069/179] Add setting for libnss-extrausers to frontend Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/135.fcgid.php | 8 ++++++++ actions/admin/settings/136.phpfpm.php | 8 ++++++++ lng/english.lng.php | 2 ++ lng/german.lng.php | 2 ++ 4 files changed, 20 insertions(+) diff --git a/actions/admin/settings/135.fcgid.php b/actions/admin/settings/135.fcgid.php index 050ede3b..d57e4241 100644 --- a/actions/admin/settings/135.fcgid.php +++ b/actions/admin/settings/135.fcgid.php @@ -105,6 +105,14 @@ return array( 'default' => 30, 'save_method' => 'storeSettingField' ), + 'system_nssextrausers' => array( + 'label' => $lng['serversettings']['nssextrausers'], + 'settinggroup' => 'system', + 'varname' => 'nssextrausers', + 'type' => 'bool', + 'default' => false, + 'save_method' => 'storeSettingField' + ), ) ) ) diff --git a/actions/admin/settings/136.phpfpm.php b/actions/admin/settings/136.phpfpm.php index 750a4660..45fc5e71 100644 --- a/actions/admin/settings/136.phpfpm.php +++ b/actions/admin/settings/136.phpfpm.php @@ -160,6 +160,14 @@ return array( 'visible' => Settings::Get('system.apache24'), 'save_method' => 'storeSettingField' ), + 'system_nssextrausers' => array( + 'label' => $lng['serversettings']['nssextrausers'], + 'settinggroup' => 'system', + 'varname' => 'nssextrausers', + 'type' => 'bool', + 'default' => false, + 'save_method' => 'storeSettingField' + ), ), ), ), diff --git a/lng/english.lng.php b/lng/english.lng.php index 8ed89fd8..5361073f 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2074,3 +2074,5 @@ $lng['admin']['domain_ocsp_stapling']['description'] = 'See Date: Tue, 9 May 2017 13:17:50 +0200 Subject: [PATCH 070/179] fix sql_mode=only_full_group_by in admin_admins.php; fix wrong webserver-user when using FCGID Signed-off-by: Michael Kaufmann (d00p) --- admin_admins.php | 2 +- scripts/jobs/cron_tasks.inc.http.10.apache.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/admin_admins.php b/admin_admins.php index 32e5de12..de104c34 100644 --- a/admin_admins.php +++ b/admin_admins.php @@ -846,7 +846,7 @@ if ($page == 'admins' $ipaddress = makeoption($lng['admin']['allips'], "-1", $result['ip']); $ipsandports_stmt = Database::query(" - SELECT `id`, `ip` FROM `" . TABLE_PANEL_IPSANDPORTS . "` GROUP BY `ip` ORDER BY `ip`, `port` ASC + SELECT `id`, `ip` FROM `" . TABLE_PANEL_IPSANDPORTS . "` GROUP BY `id`, `ip` ORDER BY `ip`, `port` ASC "); while ($row = $ipsandports_stmt->fetch(PDO::FETCH_ASSOC)) { diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 85ef9bac..a7ad40f7 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -253,7 +253,7 @@ class apache extends HttpConfigBase 'adminid' => 1, /* first admin-user (superadmin) */ 'mod_fcgid_starter' => - 1, 'mod_fcgid_maxrequests' => - 1, - 'guid' => Settings::Get('phpfpm.vhost_httpuser'), + 'guid' => Settings::Get('system.mod_fcgid_httpuser'), 'openbasedir' => 0, 'email' => Settings::Get('panel.adminmail'), 'loginname' => 'froxlor.panel', From 434f202832008ed427b5b38827b5737dd62d33c3 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 12 May 2017 12:22:04 +0200 Subject: [PATCH 071/179] minor fixes in traffic cron Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_traffic.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/scripts/jobs/cron_traffic.php b/scripts/jobs/cron_traffic.php index 282985e5..d5e077d4 100644 --- a/scripts/jobs/cron_traffic.php +++ b/scripts/jobs/cron_traffic.php @@ -115,7 +115,7 @@ while ($row_database = $databases_stmt->fetch(PDO::FETCH_ASSOC)) { Database::needRoot(true, $row_database['dbserver']); $last_dbserver = $row_database['dbserver']; - $database_list = array(); + $databases_list = array(); $databases_list_result_stmt = Database::query("SHOW DATABASES"); while ($databases_list_row = $databases_list_result_stmt->fetch(PDO::FETCH_ASSOC)) { $databases_list[] = strtolower($databases_list_row['Database']); @@ -501,9 +501,7 @@ while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) { Database::pexecute($result_quota_stmt, array('customerid' => $row['customerid'])); // get correct user - if (Settings::Get('system.mod_fcgid') == 1 - && $row['deactivated'] == '0' - ) { + if ((Settings::Get('system.mod_fcgid') == 1 || Settings::Get('phpfpm.enabled') == 1) && $row['deactivated'] == '0') { $user = $row['loginname']; $group = $row['loginname']; } else { From 9aa2cc269bf184bd7f81c0d723e563db6b3c51c3 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 12 May 2017 12:23:14 +0200 Subject: [PATCH 072/179] rename MYSQL_PASSWORD replacer to FROXLOR_MYSQL_PASSWORD in config-templates to avoid false replacement of couriers authmysqlrc, fixes #438 Signed-off-by: Michael Kaufmann (d00p) --- admin_configfiles.php | 2 +- lng/english.lng.php | 2 +- lng/german.lng.php | 2 +- templates/Sparkle/admin/configfiles/configfiles.tpl | 2 +- templates/Sparkle/assets/js/main.js | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/admin_configfiles.php b/admin_configfiles.php index c5e38a88..29ae9437 100644 --- a/admin_configfiles.php +++ b/admin_configfiles.php @@ -45,7 +45,7 @@ if ($userinfo['change_serversettings'] == '1') { $replace_arr = Array( '' => $sql['user'], - '' => 'MYSQL_PASSWORD', + '' => 'FROXLOR_MYSQL_PASSWORD', '' => $sql['db'], '' => $sql['host'], '' => isset($sql['socket']) ? $sql['socket'] : null, diff --git a/lng/english.lng.php b/lng/english.lng.php index 5361073f..bfd981f8 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -1849,7 +1849,7 @@ $lng['error']['fcgidandphpfpmnogoodtogether'] = 'FCGID and PHP-FPM cannot be act // Added in Froxlor 0.9.34 $lng['admin']['configfiles']['legend'] = 'You are about to configure a service/daemon. The following legend explains the nomenclature.'; $lng['admin']['configfiles']['commands'] = 'Commands: These commands are to be executed line by line as root-user in a shell. It is safe to copy the whole block and paste it into the shell.'; -$lng['admin']['configfiles']['files'] = 'Configfiles: This is an example of the contents of a configuration file. The commands before these textfields should open an editor with the target file. Just copy and paste the contents into the editor and save the file.

Please note: The MySQL-password has not been replaced for security reasons. Please replace "MYSQL_PASSWORD" on your own. If you forgot your MySQL-password you\'ll find it in "lib/userdata.inc.php"'; +$lng['admin']['configfiles']['files'] = 'Configfiles: This is an example of the contents of a configuration file. The commands before these textfields should open an editor with the target file. Just copy and paste the contents into the editor and save the file.

Please note: The MySQL-password has not been replaced for security reasons. Please replace "FROXLOR_MYSQL_PASSWORD" on your own. If you forgot your MySQL-password you\'ll find it in "lib/userdata.inc.php"'; $lng['serversettings']['apache_itksupport']['title'] = 'Use modifications for Apache ITK-MPM'; $lng['serversettings']['apache_itksupport']['description'] = 'ATTENTION: use only if you acutally have apache itk-mpm enabled
otherwise your webserver will not be able to start'; $lng['integrity_check']['DatabaseCharset'] = 'Characterset of database (should be UTF-8)'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 7c2f182e..761fdac5 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1574,7 +1574,7 @@ $lng['error']['fcgidandphpfpmnogoodtogether'] = 'FCGID und PHP-FPM können nicht // Added in Froxlor 0.9.34 $lng['admin']['configfiles']['legend'] = 'Du konfigurierst nun einen Service/Daemon. Die folgende Legende zeigt unsere Nomenklatur.'; $lng['admin']['configfiles']['commands'] = 'Kommandos: Die angezeigten Befehle müssen als Benutzer root in einer Shell ausgeführt werden. Es kann auch problemlos der ganze Block kopiert und in die Shell eingefügt werden.'; -$lng['admin']['configfiles']['files'] = 'Konfigurationsdateien: Dies ist der Inhalt einer Konfigurationsdatei. Der Befehl direkt vor dem Textfeld sollte einen Editor mit der Zieldatei öffnen. Der Inhalt kann nun einfach kopiert und in den Editor eingefügt und die Datei gespeichert werden.

Beachten Sie: Das MySQL-Passwort wurde aus Sicherheitsgründen nicht ersetzt. Bitte ersetzen Sie "MYSQL_PASSWORD" manuell durch das entsprechende Passwort. Falls Sie es vergessen haben sollten, finden Sie es in der Datei "lib/userdata.inc.php".'; +$lng['admin']['configfiles']['files'] = 'Konfigurationsdateien: Dies ist der Inhalt einer Konfigurationsdatei. Der Befehl direkt vor dem Textfeld sollte einen Editor mit der Zieldatei öffnen. Der Inhalt kann nun einfach kopiert und in den Editor eingefügt und die Datei gespeichert werden.

Beachten Sie: Das MySQL-Passwort wurde aus Sicherheitsgründen nicht ersetzt. Bitte ersetzen Sie "FROXLOR_MYSQL_PASSWORD" manuell durch das entsprechende Passwort. Falls Sie es vergessen haben sollten, finden Sie es in der Datei "lib/userdata.inc.php".'; $lng['serversettings']['apache_itksupport']['title'] = 'Anpassungen für Apache ITK-MPM verwenden'; $lng['serversettings']['apache_itksupport']['description'] = '
Achtung: Bitte nur verwenden, wenn wirklich Apache itk-mpm verwendet wird, ansonsten wird der Webserver nicht starten.
'; $lng['integrity_check']['DatabaseCharset'] = 'Characterset der Datenbank (sollte UTF-8 sein)'; diff --git a/templates/Sparkle/admin/configfiles/configfiles.tpl b/templates/Sparkle/admin/configfiles/configfiles.tpl index f35b4051..cab16fb1 100644 --- a/templates/Sparkle/admin/configfiles/configfiles.tpl +++ b/templates/Sparkle/admin/configfiles/configfiles.tpl @@ -27,7 +27,7 @@ eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

- MYSQL_PASSWORD: + FROXLOR_MYSQL_PASSWORD:
diff --git a/templates/Sparkle/assets/js/main.js b/templates/Sparkle/assets/js/main.js index 3d0ec460..3ea7cc4f 100644 --- a/templates/Sparkle/assets/js/main.js +++ b/templates/Sparkle/assets/js/main.js @@ -205,12 +205,12 @@ $(document).ready(function() { // Config files var configfileTextareas = $("textarea.filecontent, textarea.shell"); - var lastPw = "MYSQL_PASSWORD"; + var lastPw = "FROXLOR_MYSQL_PASSWORD"; $("#configfiles_setmysqlpw").submit(function(event) { event.preventDefault(); var inputVal = $("#configfiles_mysqlpw").val(); if (!inputVal.trim()) { - inputVal = "MYSQL_PASSWORD"; + inputVal = "FROXLOR_MYSQL_PASSWORD"; } configfileTextareas.each(function() { this.value = this.value.replace(lastPw, inputVal); From dae233dd05fd93fe4cb251f9dc6e875f63bf036f Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 4 Jun 2017 09:17:31 +0200 Subject: [PATCH 073/179] allow adding domains with multiple dashes, that are NOT punycode (xn--) Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 2 +- customer_domains.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index f2a877aa..5b2b31a5 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -306,7 +306,7 @@ if ($page == 'domains' || $page == 'overview') { standard_error('admin_domain_emailsystemhostname'); } - if (strpos($_POST['domain'], '--') !== false) { + if (substr($_POST['domain'], 0, 4) == 'xn--') { standard_error('domain_nopunycode'); } diff --git a/customer_domains.php b/customer_domains.php index 849eb69b..f492ee8a 100644 --- a/customer_domains.php +++ b/customer_domains.php @@ -260,7 +260,7 @@ if ($page == 'overview') { if ($userinfo['subdomains_used'] < $userinfo['subdomains'] || $userinfo['subdomains'] == '-1') { if (isset($_POST['send']) && $_POST['send'] == 'send') { - if (strpos($_POST['subdomain'], '--') !== false) { + if (substr($_POST['subdomain'], 0, 4) == 'xn--') { standard_error('domain_nopunycode'); } From a3201481f6984f2d0f7db4e5d315ac3c41b54f13 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 4 Jun 2017 09:30:32 +0200 Subject: [PATCH 074/179] beatufication in generated vhost configs Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index a7ad40f7..8440d005 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -869,7 +869,7 @@ class apache extends HttpConfigBase $vhost_content .= ' SSLEngine On' . "\n"; $vhost_content .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; if (Settings::Get('system.apache24') == '1') { - $vhost_content .= ' SSLCompression Off' . "\n"; + $vhost_content .= ' SSLCompression Off' . "\n"; } // this makes it more secure, thx to Marcel (08/2013) $vhost_content .= ' SSLHonorCipherOrder On' . "\n"; From 332e6270075ea8f4507a40b1a404e6774908a3fe Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 4 Jun 2017 09:31:55 +0200 Subject: [PATCH 075/179] fix wildcard entries in dns editor, fixes #447; do not add extra dot at the end of SRV entries, fixes #446 Signed-off-by: Michael Kaufmann (d00p) --- dns_editor.php | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/dns_editor.php b/dns_editor.php index 98e3a373..0d6b437e 100644 --- a/dns_editor.php +++ b/dns_editor.php @@ -56,7 +56,19 @@ if ($action == 'add_record' && ! empty($_POST)) { if (strpos($record, '--') !== false) { $errors[] = $lng['error']['domain_nopunycode']; } else { + // check for wildcard-record + $add_wildcard_again = false; + if (substr($record, 0, 2) == '*.') { + $record = substr($record, 2); + $add_wildcard_again = true; + } + // convert entry $record = $idna_convert->encode($record); + + if ($add_wildcard_again) { + $record = '*.'.$record; + } + /* * see https://redmine.froxlor.org/issues/1697 * @@ -175,8 +187,8 @@ if ($action == 'add_record' && ! empty($_POST)) { } } } - // append trailing dot (again) - if ($target != '.') { + // append trailing dot if there's none + if (substr($content, - 1) != '.') { $content .= '.'; } } From e95a9178123904df01538d54433f9c170f9a6794 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 4 Jun 2017 11:29:21 +0200 Subject: [PATCH 076/179] allow non fqdn CNAME entries (froxlor appends zone's domain automatically if there's no trailing dot), fixes #434 Signed-off-by: Michael Kaufmann (d00p) --- dns_editor.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dns_editor.php b/dns_editor.php index 0d6b437e..98a4d683 100644 --- a/dns_editor.php +++ b/dns_editor.php @@ -128,6 +128,9 @@ if ($action == 'add_record' && ! empty($_POST)) { if (substr($content, - 1) == '.') { // remove it for checks $content = substr($content, 0, - 1); + } else { + // add domain name + $content .= '.' . $domain; } if (! validateDomain($content)) { $errors[] = $lng['error']['dns_cname_invaliddom']; From aa8a7ee0a98f0c4bced104cec5972cb2387bb704 Mon Sep 17 00:00:00 2001 From: Oliver Rahner Date: Sat, 10 Jun 2017 10:59:41 +0200 Subject: [PATCH 077/179] nginx: add index directive to path options for secured directories `index` directives are now created for secured directory locations. --- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index 9e282193..20d3dbc8 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -719,6 +719,11 @@ class nginx extends HttpConfigBase if ($single['path'] == '/') { $path_options .= "\t\t" . 'auth_basic "' . $single['authname'] . '";' . "\n"; $path_options .= "\t\t" . 'auth_basic_user_file ' . makeCorrectFile($single['usrf']) . ';' . "\n"; + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { + $path_options .= "\t\t" . 'index index.php index.html index.htm;' . "\n"; + } else { + $path_options .= "\t\t" . 'index index.html index.htm;' . "\n"; + } $path_options .= "\t\t" . 'location ~ ^(.+?\.php)(/.*)?$ {' . "\n"; $path_options .= "\t\t\t" . 'try_files ' . $domain['nonexistinguri'] . ' @php;' . "\n"; $path_options .= "\t\t" . '}' . "\n"; @@ -776,6 +781,11 @@ class nginx extends HttpConfigBase $path_options .= "\t" . 'location ' . makeCorrectDir($single['path']) . ' {' . "\n"; $path_options .= "\t\t" . 'auth_basic "' . $single['authname'] . '";' . "\n"; $path_options .= "\t\t" . 'auth_basic_user_file ' . makeCorrectFile($single['usrf']) . ';' . "\n"; + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { + $path_options .= "\t\t" . 'index index.php index.html index.htm;' . "\n"; + } else { + $path_options .= "\t\t" . 'index index.html index.htm;' . "\n"; + } $path_options .= "\t\t" . 'location ~ ^(.+?\.php)(/.*)?$ {' . "\n"; $path_options .= "\t\t\t" . 'try_files ' . $domain['nonexistinguri'] . ' @php;' . "\n"; $path_options .= "\t\t" . '}' . "\n"; From dc22ff6aa35f955258833989c51a226b89049d2a Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 20 Jun 2017 16:48:11 +0200 Subject: [PATCH 078/179] fix rebuild of libnss-extrausers files when editing/deleting ftp account, fixes #454 Signed-off-by: Michael Kaufmann (d00p) --- customer_ftp.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/customer_ftp.php b/customer_ftp.php index 27f90864..46cd71f4 100644 --- a/customer_ftp.php +++ b/customer_ftp.php @@ -134,6 +134,12 @@ if ($page == 'overview') { // refs #293 if (isset($_POST['delete_userfiles']) && (int)$_POST['delete_userfiles'] == 1) { inserttask('8', $userinfo['loginname'], $result['homedir']); + } else { + if (Settings::Get('system.nssextrausers') == 1) + { + // this is used so that the libnss-extrausers cron is fired + inserttask(5); + } } $stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` @@ -431,6 +437,7 @@ if ($page == 'overview') { } $log->logAction(USR_ACTION, LOG_INFO, "edited ftp-account '" . $result['username'] . "'"); + inserttask(5); $description = validate($_POST['ftp_description'], 'description'); $stmt = Database::prepare("UPDATE `" . TABLE_FTP_USERS . "` SET `description` = :desc, `shell` = :shell From 82c719d7864660c152694e85fc4ec18760c6c842 Mon Sep 17 00:00:00 2001 From: Pascal Querner Date: Fri, 7 Jul 2017 22:50:39 +0200 Subject: [PATCH 079/179] dont send uri to challenge, if no valid token could be fetched --- lib/classes/ssl/class.lescript.php | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index a87f5bc8..6d9ca5a3 100644 --- a/lib/classes/ssl/class.lescript.php +++ b/lib/classes/ssl/class.lescript.php @@ -238,6 +238,7 @@ class lescript } @unlink($tokenPath); $this->logger->logAction(CRON_ACTION, LOG_ERR, "letsencrypt Please check $uri - token not available" . $errmsg); + continue; } $this->log("Sending request to challenge"); From 47cd30a45ecb6ec9d3779f15259f2b3edb1b722f Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 19 Jul 2017 12:06:36 +0200 Subject: [PATCH 080/179] use correct logging-level in customer_mail, thx to priority Signed-off-by: Michael Kaufmann (d00p) --- customer_email.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/customer_email.php b/customer_email.php index 22a4685d..1076832a 100644 --- a/customer_email.php +++ b/customer_email.php @@ -164,7 +164,7 @@ if ($page == 'overview') { Database::pexecute($stmt, array("customerid" => $userinfo['customerid'], "id" => $result['popaccountid'])); $update_users_query_addon .= " , `email_accounts_used` = `email_accounts_used` - 1 "; $number_forwarders-= 1; - $log->logAction(USR_ACTION, LOG_NOTICE, "deleted forwarder for email address '" . $result['email'] . "'"); + $log->logAction(USR_ACTION, LOG_INFO, "deleted forwarder for email address '" . $result['email'] . "'"); } } else { $number_forwarders = 0; @@ -652,7 +652,7 @@ if ($page == 'overview') { $password = validatePassword($password); - $log->logAction(USR_ACTION, LOG_NOTICE, "changed email password for '" . $result['email_full'] . "'"); + $log->logAction(USR_ACTION, LOG_INFO, "changed email password for '" . $result['email_full'] . "'"); $cryptPassword = makeCryptPassword($password); $stmt = Database::prepare("UPDATE `" . TABLE_MAIL_USERS . "` SET " . (Settings::Get('system.mailpwcleartext') == '1' ? "`password` = :password, " : '') . " @@ -699,7 +699,7 @@ if ($page == 'overview') { if ($userinfo['email_quota'] != '-1' && ($quota == 0 || ($quota + $userinfo['email_quota_used'] - $result['quota']) > $userinfo['email_quota'])) { standard_error('allocatetoomuchquota', $quota); } else { - $log->logAction(USR_ACTION, LOG_NOTICE, "updated quota for email address '" . $result['email'] . "' to " . $quota . " MB"); + $log->logAction(USR_ACTION, LOG_INFO, "updated quota for email address '" . $result['email'] . "' to " . $quota . " MB"); $stmt = Database::prepare("UPDATE `" . TABLE_MAIL_USERS . "` SET `quota` = :quota WHERE `id` = :id @@ -834,7 +834,7 @@ if ($page == 'overview') { ); Database::pexecute($stmt, array("cid" => $userinfo['customerid'])); - $log->logAction(USR_ACTION, LOG_NOTICE, "added email forwarder for '" . $result['email_full'] . "'"); + $log->logAction(USR_ACTION, LOG_INFO, "added email forwarder for '" . $result['email_full'] . "'"); redirectTo($filename, array('page' => 'emails', 'action' => 'edit', 'id' => $id, 's' => $s)); } } else { @@ -895,7 +895,7 @@ if ($page == 'overview') { ); Database::pexecute($stmt, array("cid" => $userinfo['customerid'])); - $log->logAction(USR_ACTION, LOG_NOTICE, "deleted email forwarder for '" . $result['email_full'] . "'"); + $log->logAction(USR_ACTION, LOG_INFO, "deleted email forwarder for '" . $result['email_full'] . "'"); redirectTo($filename, array('page' => 'emails', 'action' => 'edit', 'id' => $id, 's' => $s)); } else { ask_yesno('email_reallydelete_forwarder', $filename, array('id' => $id, 'forwarderid' => $forwarderid, 'page' => $page, 'action' => $action), $idna_convert->decode($result['email_full']) . ' -> ' . $idna_convert->decode($forwarder)); From 56e8e32965d19990aa494e0857ed2bf708d77c26 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 26 Jul 2017 07:30:14 +0200 Subject: [PATCH 081/179] set correct permissions for extrausers files/folder, fixes #465 Signed-off-by: Michael Kaufmann (d00p) --- scripts/classes/class.Extrausers.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/scripts/classes/class.Extrausers.php b/scripts/classes/class.Extrausers.php index 4b979a79..17b312af 100644 --- a/scripts/classes/class.Extrausers.php +++ b/scripts/classes/class.Extrausers.php @@ -33,6 +33,13 @@ class Extrausers $shadow = '/var/lib/extrausers/shadow'; $sql = "SELECT username,password FROM ftp_users ORDER BY gid ASC"; self::_generateFile($shadow, $sql, $cronlog); + + // set correct permissions + @chmod('/var/lib/extrausers/', 0755); + @chmod('/var/lib/extrausers/passwd', 0644); + @chmod('/var/lib/extrausers/group', 0644); + @chmod('/var/lib/extrausers/shadow', 0640); + } private static function _generateFile($file, $query, &$cronlog) From c2c517883196ae2ddc5eb5ae5d60fcb9717eda9c Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 23 Aug 2017 14:03:39 +0200 Subject: [PATCH 082/179] remove superfluous character in froxlor.sql file, fixes #471 Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- templates/misc/standardcustomer/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index fbdabcd5..d3069621 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -771,7 +771,7 @@ CREATE TABLE `panel_phpconfigs` ( INSERT INTO `panel_phpconfigs` (`id`, `description`, `binary`, `file_extensions`, `mod_fcgid_starter`, `mod_fcgid_maxrequests`, `phpsettings`) VALUES (1, 'Default Config', '/usr/bin/php-cgi', 'php', '-1', '-1', 'allow_call_time_pass_reference = Off\r\nallow_url_fopen = Off\r\nasp_tags = Off\r\ndisable_classes =\r\ndisable_functions = curl_exec,curl_multi_exec,exec,parse_ini_file,passthru,popen,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,shell_exec,show_source,system\r\ndisplay_errors = Off\r\ndisplay_startup_errors = Off\r\nenable_dl = Off\r\nerror_reporting = E_ALL & ~E_NOTICE\r\nexpose_php = Off\r\nfile_uploads = On\r\ncgi.force_redirect = 1\r\ngpc_order = "GPC"\r\nhtml_errors = Off\r\nignore_repeated_errors = Off\r\nignore_repeated_source = Off\r\ninclude_path = ".:{PEAR_DIR}"\r\nlog_errors = On\r\nlog_errors_max_len = 1024\r\nmagic_quotes_gpc = Off\r\nmagic_quotes_runtime = Off\r\nmagic_quotes_sybase = Off\r\nmax_execution_time = 30\r\nmax_input_time = 60\r\nmemory_limit = 128M\r\n{OPEN_BASEDIR_C}open_basedir = "{OPEN_BASEDIR}"\r\noutput_buffering = 4096\r\npost_max_size = 16M\r\nprecision = 14\r\nregister_argc_argv = Off\r\nregister_globals = Off\r\nreport_memleaks = On\r\nsendmail_path = "/usr/sbin/sendmail -t -i -f {CUSTOMER_EMAIL}"\r\nsession.auto_start = 0\r\nsession.bug_compat_42 = 0\r\nsession.bug_compat_warn = 1\r\nsession.cache_expire = 180\r\nsession.cache_limiter = nocache\r\nsession.cookie_domain =\r\nsession.cookie_lifetime = 0\r\nsession.cookie_path = /\r\nsession.entropy_file = /dev/urandom\r\nsession.entropy_length = 16\r\nsession.gc_divisor = 1000\r\nsession.gc_maxlifetime = 1440\r\nsession.gc_probability = 1\r\nsession.name = PHPSESSID\r\nsession.referer_check =\r\nsession.save_handler = files\r\nsession.save_path = "{TMP_DIR}"\r\nsession.serialize_handler = php\r\nsession.use_cookies = 1\r\nsession.use_trans_sid = 0\r\nshort_open_tag = On\r\nsuhosin.mail.protect = 1\r\nsuhosin.simulation = Off\r\ntrack_errors = Off\r\nupload_max_filesize = 32M\r\nupload_tmp_dir = "{TMP_DIR}"\r\nvariables_order = "GPCS"\r\n;mail.add_x_header = On\r\n;mail.log = "/var/log/phpmail.log"\r\nopcache.restrict_api = "{DOCUMENT_ROOT}"\r\n'), -(2, 'Froxlor Vhost Config', '/usr/bin/php-cgi', 'php', '-1', '-1', 'allow_call_time_pass_reference = Off\r\nallow_url_fopen = On\r\nasp_tags = Off\r\ndisable_classes =\r\ndisable_functions = curl_multi_exec,exec,parse_ini_file,passthru,popen,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,shell_exec,show_source,system\r\ndisplay_errors = Off\r\ndisplay_startup_errors = Off\r\nenable_dl = Off\r\nerror_reporting = E_ALL & ~E_NOTICE\r\nexpose_php = Off\r\nfile_uploads = On\r\ncgi.force_redirect = 1\r\ngpc_order = "GPC"\r\nhtml_errors = Off\r\nignore_repeated_errors = Off\r\nignore_repeated_source = Off\r\ninclude_path = ".:{PEAR_DIR}"\r\nlog_errors = On\r\nlog_errors_max_len = 1024\r\nmagic_quotes_gpc = Off\r\nmagic_quotes_runtime = Off\r\nmagic_quotes_sybase = Off\r\nmax_execution_time = 60\r\nmax_input_time = 60\r\nmemory_limit = 128M\r\nnoutput_buffering = 4096\r\npost_max_size = 16M\r\nprecision = 14\r\nregister_argc_argv = Off\r\nregister_globals = Off\r\nreport_memleaks = On\r\nsendmail_path = "/usr/sbin/sendmail -t -i -f {CUSTOMER_EMAIL}"\r\nsession.auto_start = 0\r\nsession.bug_compat_42 = 0\r\nsession.bug_compat_warn = 1\r\nsession.cache_expire = 180\r\nsession.cache_limiter = nocache\r\nsession.cookie_domain =\r\nsession.cookie_lifetime = 0\r\nsession.cookie_path = /\r\nsession.entropy_file = /dev/urandom\r\nsession.entropy_length = 16\r\nsession.gc_divisor = 1000\r\nsession.gc_maxlifetime = 1440\r\nsession.gc_probability = 1\r\nsession.name = PHPSESSID\r\nsession.referer_check =\r\nsession.save_handler = files\r\nsession.save_path = "{TMP_DIR}"\r\nsession.serialize_handler = php\r\nsession.use_cookies = 1\r\nsession.use_trans_sid = 0\r\nshort_open_tag = On\r\nsuhosin.mail.protect = 1\r\nsuhosin.simulation = Off\r\ntrack_errors = Off\r\nupload_max_filesize = 32M\r\nupload_tmp_dir = "{TMP_DIR}"\r\nvariables_order = "GPCS"\r\n;mail.add_x_header = On\r\n;mail.log = "/var/log/phpmail.log"\r\nopcache.restrict_api = ""\r\n'); +(2, 'Froxlor Vhost Config', '/usr/bin/php-cgi', 'php', '-1', '-1', 'allow_call_time_pass_reference = Off\r\nallow_url_fopen = On\r\nasp_tags = Off\r\ndisable_classes =\r\ndisable_functions = curl_multi_exec,exec,parse_ini_file,passthru,popen,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,shell_exec,show_source,system\r\ndisplay_errors = Off\r\ndisplay_startup_errors = Off\r\nenable_dl = Off\r\nerror_reporting = E_ALL & ~E_NOTICE\r\nexpose_php = Off\r\nfile_uploads = On\r\ncgi.force_redirect = 1\r\ngpc_order = "GPC"\r\nhtml_errors = Off\r\nignore_repeated_errors = Off\r\nignore_repeated_source = Off\r\ninclude_path = ".:{PEAR_DIR}"\r\nlog_errors = On\r\nlog_errors_max_len = 1024\r\nmagic_quotes_gpc = Off\r\nmagic_quotes_runtime = Off\r\nmagic_quotes_sybase = Off\r\nmax_execution_time = 60\r\nmax_input_time = 60\r\nmemory_limit = 128M\r\noutput_buffering = 4096\r\npost_max_size = 16M\r\nprecision = 14\r\nregister_argc_argv = Off\r\nregister_globals = Off\r\nreport_memleaks = On\r\nsendmail_path = "/usr/sbin/sendmail -t -i -f {CUSTOMER_EMAIL}"\r\nsession.auto_start = 0\r\nsession.bug_compat_42 = 0\r\nsession.bug_compat_warn = 1\r\nsession.cache_expire = 180\r\nsession.cache_limiter = nocache\r\nsession.cookie_domain =\r\nsession.cookie_lifetime = 0\r\nsession.cookie_path = /\r\nsession.entropy_file = /dev/urandom\r\nsession.entropy_length = 16\r\nsession.gc_divisor = 1000\r\nsession.gc_maxlifetime = 1440\r\nsession.gc_probability = 1\r\nsession.name = PHPSESSID\r\nsession.referer_check =\r\nsession.save_handler = files\r\nsession.save_path = "{TMP_DIR}"\r\nsession.serialize_handler = php\r\nsession.use_cookies = 1\r\nsession.use_trans_sid = 0\r\nshort_open_tag = On\r\nsuhosin.mail.protect = 1\r\nsuhosin.simulation = Off\r\ntrack_errors = Off\r\nupload_max_filesize = 32M\r\nupload_tmp_dir = "{TMP_DIR}"\r\nvariables_order = "GPCS"\r\n;mail.add_x_header = On\r\n;mail.log = "/var/log/phpmail.log"\r\nopcache.restrict_api = ""\r\n'); DROP TABLE IF EXISTS `cronjobs_run`; diff --git a/templates/misc/standardcustomer/index.html b/templates/misc/standardcustomer/index.html index dbba3f63..de82cf3b 100644 --- a/templates/misc/standardcustomer/index.html +++ b/templates/misc/standardcustomer/index.html @@ -57,7 +57,7 @@
From bab982a0e6d13f3a6671fb578a489f28f0615119 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 24 Aug 2017 13:21:21 +0200 Subject: [PATCH 083/179] add http2 support for froxlor-vhost and per-domain Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/122.froxlorvhost.php | 13 ++++++++++++ actions/admin/settings/130.webserver.php | 11 ---------- admin_domains.php | 21 ++++++++++++++++--- install/froxlor.sql | 5 +++-- .../updates/froxlor/0.9/update_0.9.inc.php | 16 ++++++++++++++ .../admin/domains/formfield.domains_add.php | 13 ++++++++++++ .../admin/domains/formfield.domains_edit.php | 15 +++++++++++++ lib/version.inc.php | 2 +- lng/english.lng.php | 6 ++++-- lng/german.lng.php | 6 ++++-- .../jobs/cron_tasks.inc.http.10.apache.php | 6 ++++++ scripts/jobs/cron_tasks.inc.http.30.nginx.php | 4 ++-- 12 files changed, 95 insertions(+), 23 deletions(-) diff --git a/actions/admin/settings/122.froxlorvhost.php b/actions/admin/settings/122.froxlorvhost.php index 6175bb73..5ddbfc30 100644 --- a/actions/admin/settings/122.froxlorvhost.php +++ b/actions/admin/settings/122.froxlorvhost.php @@ -80,6 +80,19 @@ return array( 'save_method' => 'storeSettingField', 'visible' => Settings::Get('system.use_ssl') ), + 'system_http2_support' => array( + 'label' => $lng['serversettings']['http2_support'], + 'settinggroup' => 'system', + 'varname' => 'http2_support', + 'type' => 'bool', + 'default' => false, + 'save_method' => 'storeSettingField', + 'websrv_avail' => array( + 'apache2', + 'nginx' + ), + 'visible' => Settings::Get('system.use_ssl') + ), /** * FCGID */ diff --git a/actions/admin/settings/130.webserver.php b/actions/admin/settings/130.webserver.php index 8a117d5c..4374b148 100644 --- a/actions/admin/settings/130.webserver.php +++ b/actions/admin/settings/130.webserver.php @@ -179,17 +179,6 @@ return array( 'nginx' ) ), - 'system_nginx_http2_support' => array( - 'label' => $lng['serversettings']['nginx_http2_support'], - 'settinggroup' => 'system', - 'varname' => 'nginx_http2_support', - 'type' => 'bool', - 'default' => false, - 'save_method' => 'storeSettingField', - 'websrv_avail' => array( - 'nginx' - ) - ), 'system_nginx_php_backend' => array( 'label' => $lng['serversettings']['nginx_php_backend'], 'settinggroup' => 'system', diff --git a/admin_domains.php b/admin_domains.php index 5b2b31a5..7c05f08a 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -590,6 +590,8 @@ if ($page == 'domains' || $page == 'overview') { } } + $http2 = isset($_POST['http2']) && (int)$_POST['http2'] == 1 ? 1 : 0; + // HSTS $hsts_maxage = isset($_POST['hsts_maxage']) ? (int)$_POST['hsts_maxage'] : 0; $hsts_sub = isset($_POST['hsts_sub']) && (int)$_POST['hsts_sub'] == 1 ? 1 : 0; @@ -601,6 +603,7 @@ if ($page == 'domains' || $page == 'overview') { } else { $ssl_redirect = 0; $letsencrypt = 0; + $http2 = 0; // we need this for the serialize // if ssl is disabled or no ssl-ip/port exists $ssl_ipandports[] = - 1; @@ -616,6 +619,7 @@ if ($page == 'domains' || $page == 'overview') { } else { $ssl_redirect = 0; $letsencrypt = 0; + $http2 = 0; // we need this for the serialize // if ssl is disabled or no ssl-ip/port exists $ssl_ipandports[] = - 1; @@ -796,10 +800,11 @@ if ($page == 'domains' || $page == 'overview') { 'termination_date' => $termination_date, 'issubof' => $issubof, 'letsencrypt' => $letsencrypt, + 'http2' => $http2, 'hsts_maxage' => $hsts_maxage, 'hsts_sub' => $hsts_sub, 'hsts_preload' => $hsts_preload, - 'ocsp_stapling' => $ocsp_stapling, + 'ocsp_stapling' => $ocsp_stapling ); $security_questions = array( @@ -849,10 +854,11 @@ if ($page == 'domains' || $page == 'overview') { 'mod_fcgid_maxrequests' => $mod_fcgid_maxrequests, 'ismainbutsubto' => $issubof, 'letsencrypt' => $letsencrypt, + 'http2' => $http2, 'hsts' => $hsts_maxage, 'hsts_sub' => $hsts_sub, 'hsts_preload' => $hsts_preload, - 'ocsp_stapling' => $ocsp_stapling, + 'ocsp_stapling' => $ocsp_stapling ); $ins_stmt = Database::prepare(" @@ -887,6 +893,7 @@ if ($page == 'domains' || $page == 'overview') { `mod_fcgid_maxrequests` = :mod_fcgid_maxrequests, `ismainbutsubto` = :ismainbutsubto, `letsencrypt` = :letsencrypt, + `http2` = :http2, `hsts` = :hsts, `hsts_sub` = :hsts_sub, `hsts_preload` = :hsts_preload, @@ -1428,6 +1435,8 @@ if ($page == 'domains' || $page == 'overview') { $letsencrypt = (int) $_POST['letsencrypt']; } + $http2 = isset($_POST['http2']) && (int)$_POST['http2'] == 1 ? 1 : 0; + // HSTS $hsts_maxage = isset($_POST['hsts_maxage']) ? (int)$_POST['hsts_maxage'] : 0; $hsts_sub = isset($_POST['hsts_sub']) && (int)$_POST['hsts_sub'] == 1 ? 1 : 0; @@ -1465,6 +1474,7 @@ if ($page == 'domains' || $page == 'overview') { } else { $ssl_redirect = 0; $letsencrypt = 0; + $http2 = 0; // we need this for the serialize // if ssl is disabled or no ssl-ip/port exists $ssl_ipandports[] = - 1; @@ -1480,6 +1490,7 @@ if ($page == 'domains' || $page == 'overview') { } else { $ssl_redirect = 0; $letsencrypt = 0; + $http2 = 0; // we need this for the serialize // if ssl is disabled or no ssl-ip/port exists $ssl_ipandports[] = - 1; @@ -1634,10 +1645,11 @@ if ($page == 'domains' || $page == 'overview') { 'ipandport' => serialize($ipandports), 'ssl_ipandport' => serialize($ssl_ipandports), 'letsencrypt' => $letsencrypt, + 'http2' => $http2, 'hsts_maxage' => $hsts_maxage, 'hsts_sub' => $hsts_sub, 'hsts_preload' => $hsts_preload, - 'ocsp_stapling' => $ocsp_stapling, + 'ocsp_stapling' => $ocsp_stapling ); $security_questions = array( @@ -1672,6 +1684,7 @@ if ($page == 'domains' || $page == 'overview') { $email_only != $result['email_only'] || ($speciallogfile != $result['speciallogfile'] && $speciallogverified == '1') || $letsencrypt != $result['letsencrypt'] || + $http2 != $result['http2'] || $hsts_maxage != $result['hsts'] || $hsts_sub != $result['hsts_sub'] || $hsts_preload != $result['hsts_preload'] || @@ -1828,6 +1841,7 @@ if ($page == 'domains' || $page == 'overview') { $update_data['termination_date'] = $termination_date; $update_data['ismainbutsubto'] = $issubof; $update_data['letsencrypt'] = $letsencrypt; + $update_data['http2'] = $http2; $update_data['hsts'] = $hsts_maxage; $update_data['hsts_sub'] = $hsts_sub; $update_data['hsts_preload'] = $hsts_preload; @@ -1861,6 +1875,7 @@ if ($page == 'domains' || $page == 'overview') { `termination_date` = :termination_date, `ismainbutsubto` = :ismainbutsubto, `letsencrypt` = :letsencrypt, + `http2` = :http2, `hsts` = :hsts, `hsts_sub` = :hsts_sub, `hsts_preload` = :hsts_preload, diff --git a/install/froxlor.sql b/install/froxlor.sql index d3069621..f1b896da 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -258,6 +258,7 @@ CREATE TABLE `panel_domains` ( `hsts_sub` tinyint(1) NOT NULL default '0', `hsts_preload` tinyint(1) NOT NULL default '0', `ocsp_stapling` tinyint(1) DEFAULT '0', + `http2` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `customerid` (`customerid`), KEY `parentdomain` (`parentdomainid`), @@ -500,7 +501,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('system', 'ssl_cert_chainfile', ''), ('system', 'ssl_cipher_list', 'ECDH+AESGCM:ECDH+AES256:!aNULL:!MD5:!DSS:!DH:!AES128'), ('system', 'nginx_php_backend', '127.0.0.1:8888'), - ('system', 'nginx_http2_support', '0'), + ('system', 'http2_support', '0'), ('system', 'perl_server', 'unix:/var/run/nginx/cgiwrap-dispatch.sock'), ('system', 'phpreload_command', ''), ('system', 'apache24', '0'), @@ -585,7 +586,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.7'), - ('panel', 'db_version', '201705050'); + ('panel', 'db_version', '201708240'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 1701f8be..b8d6f495 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3617,3 +3617,19 @@ if (isDatabaseVersion('201704100')) { updateToDbVersion('201705050'); } + +if (isDatabaseVersion('201705050')) { + + showUpdateStep("Updating HTTP2 setting"); + if (Settings::Get('system.nginx_http2_support') != null) { + Database::query("UPDATE `" . TABLE_PANEL_SETTINGS . "` SET `varname` = 'http2_support' WHERE `varname` = 'nginx_http2_support';"); + } else { + Settings::AddNew('system.http2_support', 0); + } + lastStepStatus(0); + showUpdateStep("Adding domain field for HTTP2 stapling"); + Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `http2` TINYINT(1) NOT NULL DEFAULT '0';"); + lastStepStatus(0); + + updateToDbVersion('201708240'); +} diff --git a/lib/formfields/admin/domains/formfield.domains_add.php b/lib/formfields/admin/domains/formfield.domains_add.php index 988c496f..1976b034 100644 --- a/lib/formfields/admin/domains/formfield.domains_add.php +++ b/lib/formfields/admin/domains/formfield.domains_add.php @@ -173,6 +173,19 @@ return array( ), 'value' => array() ), + 'http2' => array( + 'visible' => ($ssl_ipsandports != '' ? true : false) && Settings::Get('system.webserver') != 'lighttpd', + 'label' => $lng['admin']['domain_http2']['title'], + 'desc' => $lng['admin']['domain_http2']['description'], + 'type' => 'checkbox', + 'values' => array( + array ( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array() + ), 'no_ssl_available_info' => array( 'visible' => ($ssl_ipsandports == '' ? true : false), 'label' => 'SSL', diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index e351c8da..d668aa9d 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -207,6 +207,21 @@ return array( $result['letsencrypt'] ) ), + 'http2' => array( + 'visible' => ($ssl_ipsandports != '' ? true : false) && Settings::Get('system.webserver') != 'lighttpd', + 'label' => $lng['admin']['domain_http2']['title'], + 'desc' => $lng['admin']['domain_http2']['description'], + 'type' => 'checkbox', + 'values' => array( + array ( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + $result['http2'] + ) + ), 'no_ssl_available_info' => array( 'visible' => ($ssl_ipsandports == '' ? true : false), 'label' => 'SSL', diff --git a/lib/version.inc.php b/lib/version.inc.php index 7d67b9da..187d99b3 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.7'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201705050'; +$dbversion = '201708240'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index bfd981f8..1fb24970 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2063,8 +2063,8 @@ $lng['admin']['domain_hsts_incsub']['description'] = 'The optional "includeSubDo $lng['admin']['domain_hsts_preload']['title'] = 'Include domain in HSTS preload list'; $lng['admin']['domain_hsts_preload']['description'] = 'If you would like this domain to be included in the HSTS preload list maintained by Chrome (and used by Firefox and Safari), then use activate this.
Sending the preload directive from your site can have PERMANENT CONSEQUENCES and prevent users from accessing your site and any of its subdomains.
Please read the details at hstspreload.appspot.com/#removal before sending the header with "preload".'; -$lng['serversettings']['nginx_http2_support']['title'] = 'Nginx HTTP2 Support'; -$lng['serversettings']['nginx_http2_support']['description'] = 'enable http2 support for ssl. ENABLE ONLY IF YOUR Nginx SUPPORT THIS FEATURE. (version 1.9.5+)'; +$lng['serversettings']['http2_support']['title'] = 'HTTP2 Support'; +$lng['serversettings']['http2_support']['description'] = 'enable HTTP2 support for ssl.
ENABLE ONLY IF YOUR WEBSERVER SUPPORTS THIS FEATURE (nginx version 1.9.5+, apache2 version 2.4.17+)'; $lng['error']['noipportgiven'] = 'No IP/port given'; @@ -2076,3 +2076,5 @@ $lng['serversettings']['ssl']['apache24_ocsp_cache_path']['title'] = 'Apache 2.4 $lng['serversettings']['ssl']['apache24_ocsp_cache_path']['description'] = 'Configures the cache used to store OCSP responses which get included in TLS handshakes.'; $lng['serversettings']['nssextrausers']['title'] = 'Use libnss-extrausers instead of libnss-mysql'; $lng['serversettings']['nssextrausers']['description'] = 'Do not read users from the database but from files. Please only activate if you have already gone through the required configuration steps (system -> libnss-extrausers).
For Debian/Ubuntu only (or if you have compiled libnss-extrausers yourself!)'; +$lng['admin']['domain_http2']['title'] = 'HTTP2 support'; +$lng['admin']['domain_http2']['description'] = 'See Wikipedia for a detailed explanation of HTTP2'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 761fdac5..df6f0bf6 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1714,8 +1714,8 @@ $lng['admin']['domain_hsts_incsub']['description'] = 'Die optionale "includeSubD $lng['admin']['domain_hsts_preload']['title'] = 'Füge Domain in die HSTS preload Liste hinzu'; $lng['admin']['domain_hsts_preload']['description'] = 'Wenn die Domain in die HSTS preload Liste, verwaltet von Chrome (und genutzt von Firefox und Safari), hinzugefügt werden soll, dann aktiviere diese Einstellung.
Die preload-Direktive zu senden kann PERMANTENTE KONSEQUENZEN haben und dazu führen, dass Benutzer auf diese Domain und auch Subdomains nicht zugreifen können.
Beachte Details unter hstspreload.appspot.com/#removal bevor ein Header mit "preload" gesendet wird.'; -$lng['serversettings']['nginx_http2_support']['title'] = 'Nginx HTTP2 Unterstützung'; -$lng['serversettings']['nginx_http2_support']['description'] = 'Aktiviere http2 Unterstützung für SSL. NUR AKTIVIEREN, WENN nginx DIESE FUNKTION UNTERSTÜTZT (version 1.9.5+)'; +$lng['serversettings']['http2_support']['title'] = 'HTTP2 Unterstützung'; +$lng['serversettings']['http2_support']['description'] = 'Aktiviere HTTP2 Unterstützung für SSL.
NUR AKTIVIEREN, WENN DER WEBSERVER DIESE FUNKTION UNTERSTÜTZT (nginx version 1.9.5+, apache2 version 2.4.17+)'; $lng['error']['noipportgiven'] = 'Keine IP/Port angegeben'; @@ -1727,3 +1727,5 @@ $lng['serversettings']['ssl']['apache24_ocsp_cache_path']['title'] = 'Apache 2.4 $lng['serversettings']['ssl']['apache24_ocsp_cache_path']['description'] = 'Konfiguriert den Cache-Pfad zum Zwischenspeichern der OCSP-Antworten,
die an TLS-Handshakes angehängt werden.'; $lng['serversettings']['nssextrausers']['title'] = 'Verwende libnss-extrausers anstatt libnss-mysql'; $lng['serversettings']['nssextrausers']['description'] = 'Lese Benutzer nicht direkt aus der Datenbank sondern über Dateien, bitte nur aktivieren, wenn die entsprechende Konfiguration vorgenommen wurde (System -> libnss-extrausers).
Nur für Debian/Ubuntu (oder wenn libnss-extrausers manuell kompiliert wurde!)'; +$lng['admin']['domain_http2']['title'] = 'HTTP2 Unterstützung'; +$lng['admin']['domain_http2']['description'] = 'Siehe Wikipedia für eine ausführliche Beschreibung von HTTP2'; diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 8440d005..98d1ed17 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -434,6 +434,9 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLEngine On' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; if (Settings::Get('system.apache24') == '1') { + if (Settings::Get('system.http2_support') == '1') { + $this->virtualhosts_data[$vhosts_filename] .= ' Protocols h2 http/1.1' . "\n"; + } $this->virtualhosts_data[$vhosts_filename] .= ' SSLCompression Off' . "\n"; } // this makes it more secure, thx to Marcel (08/2013) @@ -869,6 +872,9 @@ class apache extends HttpConfigBase $vhost_content .= ' SSLEngine On' . "\n"; $vhost_content .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; if (Settings::Get('system.apache24') == '1') { + if (isset($domain['http2']) && $domain['http2'] == '1') { + $vhost_content .= ' Protocols h2 http/1.1' . "\n"; + } $vhost_content .= ' SSLCompression Off' . "\n"; } // this makes it more secure, thx to Marcel (08/2013) diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index 20d3dbc8..bc7f23fc 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -196,7 +196,7 @@ class nginx extends HttpConfigBase } } - $http2 = $ssl_vhost == true && Settings::Get('system.nginx_http2_support') == '1'; + $http2 = $ssl_vhost == true && Settings::Get('system.http2_support') == '1'; /** * this HAS to be set for the default host in nginx or else no vhost will work @@ -418,7 +418,7 @@ class nginx extends HttpConfigBase $_vhost_content .= $this->processSpecialConfigTemplate($ipandport['default_vhostconf_domain'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } - $http2 = $ssl_vhost == true && Settings::Get('system.nginx_http2_support') == '1'; + $http2 = $ssl_vhost == true && (isset($domain['http2']) && $domain['http2'] == '1'); $vhost_content .= "\t" . 'listen ' . $ipport . ($ssl_vhost == true ? ' ssl' : '') . ($http2 == true ? ' http2' : '') . ';' . "\n"; } From 64ebb0ca3826a3f5afd82b32318ba7d663aaa777 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 24 Aug 2017 15:27:47 +0200 Subject: [PATCH 084/179] also add http2 flag to domain-import Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/bulk/class.DomainBulkAction.php | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/classes/bulk/class.DomainBulkAction.php b/lib/classes/bulk/class.DomainBulkAction.php index a5dac417..0c0a6b09 100644 --- a/lib/classes/bulk/class.DomainBulkAction.php +++ b/lib/classes/bulk/class.DomainBulkAction.php @@ -99,6 +99,7 @@ class DomainBulkAction /* 22 */ 'hsts_preload', /* 23 */ 'ocsp_stapling', /* 24 */ 'phpenabled', +/* 25 */ 'http2', /* automatically added */ 'adminid', 'customerid', @@ -212,7 +213,8 @@ class DomainBulkAction `hsts_sub` = :hsts_sub, `hsts_preload` = :hsts_preload, `ocsp_stapling` = :ocsp_stapling, - `phpenabled` = :phpenabled + `phpenabled` = :phpenabled, + `http2` = :http2 "); // prepare insert statement for ip/port <> domain @@ -371,6 +373,14 @@ class DomainBulkAction $domain_data['ocsp_stapling'] = 0; } + if ($domain_data['phpenabled'] != 1) { + $domain_data['phpenabled'] = 0; + } + + if ($domain_data['http2'] != 1) { + $domain_data['http2'] = 0; + } + // add to known domains $this->_knownDomains[] = $domain_data['domain']; From 1753d2895b833a3a84269975144f19bc85b33191 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 25 Aug 2017 10:34:59 +0200 Subject: [PATCH 085/179] add simple smtp-settings test-page, fixes #464 Signed-off-by: Michael Kaufmann (d00p) --- admin_settings.php | 65 +++++++++++++++++++ lib/navigation/00.froxlor.main.php | 4 ++ lng/english.lng.php | 2 + lng/german.lng.php | 2 + templates/Sparkle/admin/settings/testmail.tpl | 48 ++++++++++++++ 5 files changed, 121 insertions(+) create mode 100644 templates/Sparkle/admin/settings/testmail.tpl diff --git a/admin_settings.php b/admin_settings.php index 18289d28..66abf4aa 100644 --- a/admin_settings.php +++ b/admin_settings.php @@ -290,3 +290,68 @@ if ($page == 'overview' && $userinfo['change_serversettings'] == '1') { } eval("echo \"" . getTemplate("settings/integritycheck") . "\";"); } +elseif ($page == 'testmail') +{ + if (isset($_POST['send']) && $_POST['send'] == 'send') + { + $test_addr = isset($_POST['test_addr']) ? $_POST['test_addr'] : null; + + /** + * Initialize the mailingsystem + */ + $testmail = new PHPMailer(true); + $testmail->CharSet = "UTF-8"; + + if (Settings::Get('system.mail_use_smtp')) { + $testmail->isSMTP(); + $testmail->Host = Settings::Get('system.mail_smtp_host'); + $testmail->SMTPAuth = Settings::Get('system.mail_smtp_auth') == '1' ? true : false; + $testmail->Username = Settings::Get('system.mail_smtp_user'); + $testmail->Password = Settings::Get('system.mail_smtp_passwd'); + if (Settings::Get('system.mail_smtp_usetls')) { + $testmail->SMTPSecure = 'tls'; + } + $testmail->Port = Settings::Get('system.mail_smtp_port'); + } + + $_mailerror = false; + if (PHPMailer::ValidateAddress(Settings::Get('panel.adminmail')) !== false) { + // set return-to address and custom sender-name, see #76 + $testmail->SetFrom(Settings::Get('panel.adminmail'), Settings::Get('panel.adminmail_defname')); + if (Settings::Get('panel.adminmail_return') != '') { + $testmail->AddReplyTo(Settings::Get('panel.adminmail_return'), Settings::Get('panel.adminmail_defname')); + } + + try { + $testmail->Subject = "Froxlor Test-Mail"; + $mail_body = "Yay, this worked :)"; + $testmail->AltBody = $mail_body; + $testmail->MsgHTML(str_replace("\n", "
", $mail_body)); + $testmail->AddAddress($test_addr); + $testmail->Send(); + } catch(phpmailerException $e) { + $mailerr_msg = $e->errorMessage(); + $_mailerror = true; + } catch (Exception $e) { + $mailerr_msg = $e->getMessage(); + $_mailerror = true; + } + + if (!$_mailerror) { + // success + $mail->ClearAddresses(); + standard_success('testmailsent', '', array('filename' => 'admin_settings.php', 'page' => 'testmail')); + } + } else { + // invalid sender e-mail + $mailerr_msg = "Invalid sender e-mail address: ".Settings::Get('panel.adminmail'); + $_mailerror = true; + } + } + + $mail_smtp_user = Settings::Get('system.mail_smtp_user'); + $mail_smtp_host = Settings::Get('system.mail_smtp_host'); + $mail_smtp_port = Settings::Get('system.mail_smtp_port'); + + eval("echo \"" . getTemplate("settings/testmail") . "\";"); +} diff --git a/lib/navigation/00.froxlor.main.php b/lib/navigation/00.froxlor.main.php index faa3feec..18dc74ab 100644 --- a/lib/navigation/00.froxlor.main.php +++ b/lib/navigation/00.froxlor.main.php @@ -313,6 +313,10 @@ return array( array( 'url' => 'admin_message.php?page=message', 'label' => $lng['admin']['message'] + ), + array( + 'url' => 'admin_settings.php?page=testmail', + 'label' => $lng['admin']['testmail'] ) ) ) diff --git a/lng/english.lng.php b/lng/english.lng.php index 1fb24970..51e05ef6 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2078,3 +2078,5 @@ $lng['serversettings']['nssextrausers']['title'] = 'Use libnss-extrausers instea $lng['serversettings']['nssextrausers']['description'] = 'Do not read users from the database but from files. Please only activate if you have already gone through the required configuration steps (system -> libnss-extrausers).
For Debian/Ubuntu only (or if you have compiled libnss-extrausers yourself!)'; $lng['admin']['domain_http2']['title'] = 'HTTP2 support'; $lng['admin']['domain_http2']['description'] = 'See Wikipedia for a detailed explanation of HTTP2'; +$lng['admin']['testmail'] = 'SMTP test'; +$lng['success']['testmailsent'] = 'Test mail sent successfully'; diff --git a/lng/german.lng.php b/lng/german.lng.php index df6f0bf6..22e73ca8 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1729,3 +1729,5 @@ $lng['serversettings']['nssextrausers']['title'] = 'Verwende libnss-extrausers a $lng['serversettings']['nssextrausers']['description'] = 'Lese Benutzer nicht direkt aus der Datenbank sondern über Dateien, bitte nur aktivieren, wenn die entsprechende Konfiguration vorgenommen wurde (System -> libnss-extrausers).
Nur für Debian/Ubuntu (oder wenn libnss-extrausers manuell kompiliert wurde!)'; $lng['admin']['domain_http2']['title'] = 'HTTP2 Unterstützung'; $lng['admin']['domain_http2']['description'] = 'Siehe Wikipedia für eine ausführliche Beschreibung von HTTP2'; +$lng['admin']['testmail'] = 'SMTP Test'; +$lng['success']['testmailsent'] = 'Test E-Mail erfolgreich gesendet'; diff --git a/templates/Sparkle/admin/settings/testmail.tpl b/templates/Sparkle/admin/settings/testmail.tpl new file mode 100644 index 00000000..6b882563 --- /dev/null +++ b/templates/Sparkle/admin/settings/testmail.tpl @@ -0,0 +1,48 @@ +$header +
+
+

+   + {$lng['admin']['testmail']} +

+
+ + +
+
+
{$lng['admin']['warning']}
+
{$mailerr_msg}
+
+
+
+ +
+ + + + + + + + + + + + + + + +
{$lng['serversettings']['mail_smtp_user']}HostPortSMTP AuthTLS
{$mail_smtp_user}{$mail_smtp_host}{$mail_smtp_port}
+
+
+ + + + + + + +
+
+
+$footer From b263b211a5417b1e8e509a7fb36099867465e41a Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 28 Aug 2017 15:35:07 +0200 Subject: [PATCH 086/179] generate multiline txt-record if content is too long, fixes #472 Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/dns/class.DnsEntry.php | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/classes/dns/class.DnsEntry.php b/lib/classes/dns/class.DnsEntry.php index c5bcab79..27f0dd8f 100644 --- a/lib/classes/dns/class.DnsEntry.php +++ b/lib/classes/dns/class.DnsEntry.php @@ -41,7 +41,31 @@ class DnsEntry public function __toString() { - $result = $this->record . "\t" . $this->ttl . "\t" . $this->class . "\t" . $this->type . "\t" . (($this->priority >= 0 && ($this->type == 'MX' || $this->type == 'SRV')) ? $this->priority . "\t" : "") . $this->content . PHP_EOL; + $_content = $this->content; + // check content length for txt records for bind9 (multiline) + if (Settings::Get('system.dns_server') != 'pdns' && $this->type == 'TXT' && strlen($_content) >= 64) { + // split string + $_contentlines = str_split($_content, 63); + // first line + $_l = array_shift($_contentlines); + // check for starting quote + if (substr($_l, 0, 1) == '"') { + $_l = substr($_l, 1); + } + $_content = '( "' . $_l . '"' . PHP_EOL; + $_l = array_pop($_contentlines); + // check for ending quote + if (substr($_l, -1) == '"') { + $_l = substr($_l, 0, -1); + } + foreach ($_contentlines as $_cl) { + // lines in between + $_content .= "\t\t\t\t" . '"' . $_cl . '"' . PHP_EOL; + } + // last line + $_content .= "\t\t\t\t" . '"'.$_l.'" )'; + } + $result = $this->record . "\t" . $this->ttl . "\t" . $this->class . "\t" . $this->type . "\t" . (($this->priority >= 0 && ($this->type == 'MX' || $this->type == 'SRV')) ? $this->priority . "\t" : "") . $_content . PHP_EOL; return $result; } } From 181848290ff89231dbf24a162da6ea028b3ba61d Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 4 Sep 2017 15:28:12 +0200 Subject: [PATCH 087/179] move setting to enable usage of libnss-extrausers to 'system' category as mpm-itk + mod_php users might need this too Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/120.system.php | 8 ++++++++ actions/admin/settings/135.fcgid.php | 10 +--------- actions/admin/settings/136.phpfpm.php | 10 +--------- 3 files changed, 10 insertions(+), 18 deletions(-) diff --git a/actions/admin/settings/120.system.php b/actions/admin/settings/120.system.php index b08ce88e..e1b4c5cd 100644 --- a/actions/admin/settings/120.system.php +++ b/actions/admin/settings/120.system.php @@ -94,6 +94,14 @@ return array( 'plausibility_check_method' => 'checkMysqlAccessHost', 'save_method' => 'storeSettingMysqlAccessHost', ), + 'system_nssextrausers' => array( + 'label' => $lng['serversettings']['nssextrausers'], + 'settinggroup' => 'system', + 'varname' => 'nssextrausers', + 'type' => 'bool', + 'default' => false, + 'save_method' => 'storeSettingField' + ), 'system_index_file_extension' => array( 'label' => $lng['serversettings']['index_file_extension'], 'settinggroup' => 'system', diff --git a/actions/admin/settings/135.fcgid.php b/actions/admin/settings/135.fcgid.php index d57e4241..212c03f7 100644 --- a/actions/admin/settings/135.fcgid.php +++ b/actions/admin/settings/135.fcgid.php @@ -104,15 +104,7 @@ return array( 'type' => 'int', 'default' => 30, 'save_method' => 'storeSettingField' - ), - 'system_nssextrausers' => array( - 'label' => $lng['serversettings']['nssextrausers'], - 'settinggroup' => 'system', - 'varname' => 'nssextrausers', - 'type' => 'bool', - 'default' => false, - 'save_method' => 'storeSettingField' - ), + ) ) ) ) diff --git a/actions/admin/settings/136.phpfpm.php b/actions/admin/settings/136.phpfpm.php index 45fc5e71..90dc742f 100644 --- a/actions/admin/settings/136.phpfpm.php +++ b/actions/admin/settings/136.phpfpm.php @@ -159,15 +159,7 @@ return array( 'default' => false, 'visible' => Settings::Get('system.apache24'), 'save_method' => 'storeSettingField' - ), - 'system_nssextrausers' => array( - 'label' => $lng['serversettings']['nssextrausers'], - 'settinggroup' => 'system', - 'varname' => 'nssextrausers', - 'type' => 'bool', - 'default' => false, - 'save_method' => 'storeSettingField' - ), + ) ), ), ), From 15b62aae043b511a96d873843c907d80b1ed58e0 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 6 Oct 2017 09:29:49 +0200 Subject: [PATCH 088/179] add inserttask for config regeneration and fix aliasdomain NULL value if empty, fixes #478 Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 2 ++ lib/classes/bulk/class.DomainBulkAction.php | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index 7c05f08a..5e410c45 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -2223,6 +2223,8 @@ if ($page == 'domains' || $page == 'overview') { // update customer/admin counters updateCounters(false); + inserttask('1'); + inserttask('4'); $result_str = $result['imported'] . ' / ' . $result['all']; standard_success('domain_import_successfully', $result_str, array( diff --git a/lib/classes/bulk/class.DomainBulkAction.php b/lib/classes/bulk/class.DomainBulkAction.php index 0c0a6b09..1331cec5 100644 --- a/lib/classes/bulk/class.DomainBulkAction.php +++ b/lib/classes/bulk/class.DomainBulkAction.php @@ -187,13 +187,14 @@ class DomainBulkAction } // preapre insert statement as it is used a few times + // leave out aliasdomain for now, cause empty = NULL value which cannot be + // added this easily using prepared statements $this->_ins_stmt = Database::prepare(" INSERT INTO `" . TABLE_PANEL_DOMAINS . "` SET `domain` = :domain, `adminid` = :adminid, `customerid` = :customerid, `documentroot` = :documentroot, - `aliasdomain` = :aliasdomain, `isbinddomain` = :isbinddomain, `isemaildomain` = :isemaildomain, `email_only` = :email_only, @@ -307,6 +308,7 @@ class DomainBulkAction } // check for alias-domain + $hasAlias = false; if (! empty($domain_data['aliasdomain'])) { // format $domain_data['aliasdomain'] = $idna_convert->encode(preg_replace(array( @@ -325,6 +327,7 @@ class DomainBulkAction // - we'd better skip return false; } + $hasAlias = $domain_data['aliasdomain']; } // check for use_ssl and ssl_redirect @@ -462,13 +465,21 @@ class DomainBulkAction $use_ssl = (bool)$domain_data['use_ssl']; // don't need that for the domain-insert-statement unset($domain_data['use_ssl']); - + // don't need alias + unset($domain_data['aliasdomain']); + // finally ADD the domain to panel_domains Database::pexecute($this->_ins_stmt, $domain_data); // get the newly inserted domain-id $domain_id = Database::lastInsertId(); + // add alias if any + if ($hasAlias != false) { + $alias_stmt = Database::prepare("UPDATE `".TABLE_PANEL_DOMAINS."` SET `aliasdomain` = :aliasdomain WHERE `id` = :did"); + Database::pexecute($alias_stmt, array('aliasdomain' => $hasAlias, 'did' => $domain_id)); + } + // insert domain <-> ip/port reference if (empty($iplist)) { $iplist = Settings::Get('system.ipaddress'); From 421c29c4918a1fa193846cede4373b045b5d33f3 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 31 Oct 2017 13:03:06 +0100 Subject: [PATCH 089/179] remove each() keyword as it is deprecated as of php-7.2, fixes #479 Signed-off-by: Michael Kaufmann (d00p) --- admin_admins.php | 4 ++-- admin_customers.php | 4 ++-- admin_index.php | 2 +- admin_templates.php | 4 ++-- customer_email.php | 5 +++-- customer_index.php | 2 +- index.php | 2 +- install/lib/class.FroxlorInstall.php | 2 +- .../phphelpers/function.array_trim.php | 21 +++++++------------ lib/init.php | 3 ++- 10 files changed, 23 insertions(+), 26 deletions(-) diff --git a/admin_admins.php b/admin_admins.php index de104c34..f0ede7de 100644 --- a/admin_admins.php +++ b/admin_admins.php @@ -440,7 +440,7 @@ if ($page == 'admins' } else { $language_options = ''; - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $language_options.= makeoption($language_name, $language_file, $userinfo['language'], true); } @@ -840,7 +840,7 @@ if ($page == 'admins' } $language_options = ''; - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $language_options.= makeoption($language_name, $language_file, $result['def_language'], true); } diff --git a/admin_customers.php b/admin_customers.php index 09e938a9..3a88dd38 100644 --- a/admin_customers.php +++ b/admin_customers.php @@ -1024,7 +1024,7 @@ if ($page == 'customers' } else { $language_options = ''; - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $language_options.= makeoption($language_name, $language_file, Settings::Get('panel.standardlanguage'), true); } @@ -1630,7 +1630,7 @@ if ($page == 'customers' } else { $language_options = ''; - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $language_options.= makeoption($language_name, $language_file, $result['def_language'], true); } diff --git a/admin_index.php b/admin_index.php index 177278bf..dae69d6d 100644 --- a/admin_index.php +++ b/admin_index.php @@ -280,7 +280,7 @@ if ($page == 'overview') { $default_lang = $userinfo['def_language']; } - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $language_options.= makeoption($language_name, $language_file, $default_lang, true); } diff --git a/admin_templates.php b/admin_templates.php index cec93081..5a138fc0 100644 --- a/admin_templates.php +++ b/admin_templates.php @@ -99,7 +99,7 @@ if ($action == '') { } $add = false; - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $templates_done = array(); $result_stmt = Database::prepare(" @@ -328,7 +328,7 @@ if ($action == '') { $language_options = ''; $template_options = ''; - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $templates = array(); $result_stmt = Database::prepare(" SELECT `varname` FROM `" . TABLE_PANEL_TEMPLATES . "` diff --git a/customer_email.php b/customer_email.php index 1076832a..479493d6 100644 --- a/customer_email.php +++ b/customer_email.php @@ -96,7 +96,8 @@ if ($page == 'overview') { $row['destination'] = explode(' ', $row['destination']); uasort($row['destination'], 'strcasecmp'); - while (list($dest_id, $destination) = each($row['destination'])) { + $dest_list = $row['destination']; + foreach ($dest_list as $dest_id => $destination) { $row['destination'][$dest_id] = $idna_convert->decode($row['destination'][$dest_id]); if ($row['destination'][$dest_id] == $row['email_full']) { @@ -323,7 +324,7 @@ if ($page == 'overview') { $forwarders = ''; $forwarders_count = 0; - while (list($dest_id, $destination) = each($result['destination'])) { + foreach ($row['destination'] as $dest_id => $destination) { $destination = $idna_convert->decode($destination); if ($destination != $result['email_full'] && $destination != '') { diff --git a/customer_index.php b/customer_index.php index 5e6c2aaf..bb1305c9 100644 --- a/customer_index.php +++ b/customer_index.php @@ -204,7 +204,7 @@ if ($page == 'overview') { } $language_options = ''; - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $language_options .= makeoption($language_name, $language_file, $default_lang, true); } diff --git a/index.php b/index.php index 423f8fd8..a970c53b 100644 --- a/index.php +++ b/index.php @@ -250,7 +250,7 @@ if ($action == 'login') { $language_options = ''; $language_options .= makeoption($lng['login']['profile_lng'], 'profile', 'profile', true, true); - while (list($language_file, $language_name) = each($languages)) { + foreach ($languages as $language_file => $language_name) { $language_options .= makeoption($language_name, $language_file, 'profile', true); } diff --git a/install/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index ac9fb7f4..5f6ea5e7 100644 --- a/install/lib/class.FroxlorInstall.php +++ b/install/lib/class.FroxlorInstall.php @@ -702,7 +702,7 @@ class FroxlorInstall } // language selection $language_options = ''; - while (list ($language_file, $language_name) = each($this->_languages)) { + foreach ($this->_languages as $language_name => $language_file) { $language_options .= makeoption($language_name, $language_file, $this->_activelng, true, true); } // get language-form-template diff --git a/lib/functions/phphelpers/function.array_trim.php b/lib/functions/phphelpers/function.array_trim.php index ca587c1d..4c64ccfd 100644 --- a/lib/functions/phphelpers/function.array_trim.php +++ b/lib/functions/phphelpers/function.array_trim.php @@ -20,27 +20,22 @@ /** * Returns Array, whose elements have been checked whether thay are empty or not * - * @param array The array to trim + * @param array $source + * The array to trim * @return array The trim'med array * @author Florian Lippert */ - function array_trim($source) { $returnval = array(); - - if(is_array($source)) - { - while(list($var, $val) = each($source)) - { - if($val != ' ' - && $val != '')$returnval[$var] = $val; + if (is_array($source)) { + foreach ($source as $var => $val) { + if ($val != ' ' && $val != '') { + $returnval[$var] = $val; + } } - } - else - { + } else { $returnval = $source; } - return $returnval; } diff --git a/lib/init.php b/lib/init.php index b4e4c018..d5747621 100644 --- a/lib/init.php +++ b/lib/init.php @@ -156,7 +156,8 @@ if (version_compare(PHP_VERSION, "5.4.0", "<")) { if (get_magic_quotes_gpc()) { $in = array(&$_GET, &$_POST, &$_COOKIE); - while (list($k, $v) = each($in)) { + $_in = $in; + foreach ($in as $k => $v) { foreach ($v as $key => $val) { if (!is_array($val)) { $in[$k][$key] = stripslashes($val); From dd3e5e9c6bf2831e3f94939aa19e83807c293619 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 6 Nov 2017 07:36:51 +0100 Subject: [PATCH 090/179] fix wrong variable name typo, fixes #484 Signed-off-by: Michael Kaufmann (d00p) --- customer_email.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/customer_email.php b/customer_email.php index 479493d6..02517fc1 100644 --- a/customer_email.php +++ b/customer_email.php @@ -324,7 +324,7 @@ if ($page == 'overview') { $forwarders = ''; $forwarders_count = 0; - foreach ($row['destination'] as $dest_id => $destination) { + foreach ($result['destination'] as $dest_id => $destination) { $destination = $idna_convert->decode($destination); if ($destination != $result['email_full'] && $destination != '') { From 1e03946df7e0a8aebe8d2c680b9349be81dafda3 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 8 Nov 2017 07:49:40 +0100 Subject: [PATCH 091/179] set sql_mode to disable STRICT_MODE usage for froxlor, thx to albech for the hint Signed-off-by: Michael Kaufmann (d00p) --- install/lib/class.FroxlorInstall.php | 6 +++--- lib/classes/database/class.Database.php | 2 +- scripts/jobs/cron_tasks.inc.dns.20.pdns.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/install/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index 5f6ea5e7..dc8cf74b 100644 --- a/install/lib/class.FroxlorInstall.php +++ b/install/lib/class.FroxlorInstall.php @@ -204,7 +204,7 @@ class FroxlorInstall $content .= $this->_status_message('begin', $this->_lng['install']['testing_mysql']); $options = array( - 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'set names utf8' + 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'SET names utf8,sql_mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' ); $dsn = "mysql:host=" . $this->_data['mysql_host'] . ";"; $fatal_fail = false; @@ -240,7 +240,7 @@ class FroxlorInstall $content .= $this->_importDatabaseData(); // create DB object for new database $options = array( - 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'set names utf8' + 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'SET names utf8,sql_mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' ); $dsn = "mysql:host=" . $this->_data['mysql_host'] . ";dbname=" . $this->_data['mysql_database'] . ";"; $another_fail = false; @@ -511,7 +511,7 @@ class FroxlorInstall $content = ""; $content .= $this->_status_message('begin', $this->_lng['install']['testing_new_db']); $options = array( - 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'set names utf8' + 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'SET names utf8,sql_mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' ); $dsn = "mysql:host=" . $this->_data['mysql_host'] . ";dbname=" . $this->_data['mysql_database'] . ";"; $fatal_fail = false; diff --git a/lib/classes/database/class.Database.php b/lib/classes/database/class.Database.php index 74a655d7..3174c2b3 100644 --- a/lib/classes/database/class.Database.php +++ b/lib/classes/database/class.Database.php @@ -262,7 +262,7 @@ class Database { // build up connection string $driver = 'mysql'; $dsn = $driver.":"; - $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8'); + $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET names utf8,sql_mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"'); $attributes = array('ATTR_ERRMODE' => 'ERRMODE_EXCEPTION'); $dbconf["dsn"] = array( diff --git a/scripts/jobs/cron_tasks.inc.dns.20.pdns.php b/scripts/jobs/cron_tasks.inc.dns.20.pdns.php index 27a63632..cb70417a 100644 --- a/scripts/jobs/cron_tasks.inc.dns.20.pdns.php +++ b/scripts/jobs/cron_tasks.inc.dns.20.pdns.php @@ -227,7 +227,7 @@ class pdns extends DnsBase // build up connection string $driver = 'mysql'; $dsn = $driver.":"; - $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8'); + $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET names utf8,sql_mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"'); $attributes = array('ATTR_ERRMODE' => 'ERRMODE_EXCEPTION'); $dbconf = array(); From 45c0915b59ffe553c17e9d05655a7b1eee09b45c Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 17 Nov 2017 15:15:09 +0100 Subject: [PATCH 092/179] fix ssl integration in lighttpd, thx to black-night for the info Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.20.lighttpd.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php index d1ba5d04..a2d5258b 100644 --- a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php +++ b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php @@ -535,7 +535,8 @@ class lighttpd extends HttpConfigBase if ($domain['ssl_cert_file'] != '') { - $ssl_settings .= 'ssl.engine = "enable"' . "\n"; + // ssl.engine only necessary once in the ip/port vhost (SERVER['socket'] condition) + //$ssl_settings .= 'ssl.engine = "enable"' . "\n"; $ssl_settings .= 'ssl.use-compression = "disable"' . "\n"; $ssl_settings .= 'ssl.use-sslv2 = "disable"' . "\n"; $ssl_settings .= 'ssl.use-sslv3 = "disable"' . "\n"; From e725b48c4c9e19d6cbd4cb9dd4f34a64e283e082 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 27 Nov 2017 07:48:36 +0100 Subject: [PATCH 093/179] add default/global directory options in apache regardless of whether fcgid/fpm is being used or not; fixes #485 Signed-off-by: Michael Kaufmann (d00p) --- .../jobs/cron_tasks.inc.http.10.apache.php | 48 ++++++++----------- 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 98d1ed17..6e9d3277 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -78,36 +78,28 @@ class apache extends HttpConfigBase } $vhosts_filename = makeCorrectFile($vhosts_folder . '/05_froxlor_dirfix_nofcgid.conf'); - if (Settings::Get('system.mod_fcgid') == '1' || Settings::Get('phpfpm.enabled') == '1') { - // if we use fcgid or php-fpm we don't need this file - if (file_exists($vhosts_filename)) { - $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::_createStandardDirectoryEntry: unlinking ' . basename($vhosts_filename)); - unlink(makeCorrectFile($vhosts_filename)); - } - } else { - if (! isset($this->virtualhosts_data[$vhosts_filename])) { - $this->virtualhosts_data[$vhosts_filename] = ''; - } - - $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; - - // check for custom values, see #1638 - $custom_opts = Settings::Get('system.apacheglobaldiropt'); - if (! empty($custom_opts)) { - $this->virtualhosts_data[$vhosts_filename] .= $custom_opts . "\n"; - } else { - // >=apache-2.4 enabled? - if (Settings::Get('system.apache24') == '1') { - $this->virtualhosts_data[$vhosts_filename] .= ' Require all granted' . "\n"; - $this->virtualhosts_data[$vhosts_filename] .= ' AllowOverride All' . "\n"; - } else { - $this->virtualhosts_data[$vhosts_filename] .= ' Order allow,deny' . "\n"; - $this->virtualhosts_data[$vhosts_filename] .= ' allow from all' . "\n"; - } - } - $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; + if (! isset($this->virtualhosts_data[$vhosts_filename])) { + $this->virtualhosts_data[$vhosts_filename] = ''; } + $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; + + // check for custom values, see #1638 + $custom_opts = Settings::Get('system.apacheglobaldiropt'); + if (! empty($custom_opts)) { + $this->virtualhosts_data[$vhosts_filename] .= $custom_opts . "\n"; + } else { + // >=apache-2.4 enabled? + if (Settings::Get('system.apache24') == '1') { + $this->virtualhosts_data[$vhosts_filename] .= ' Require all granted' . "\n"; + $this->virtualhosts_data[$vhosts_filename] .= ' AllowOverride All' . "\n"; + } else { + $this->virtualhosts_data[$vhosts_filename] .= ' Order allow,deny' . "\n"; + $this->virtualhosts_data[$vhosts_filename] .= ' allow from all' . "\n"; + } + } + $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; + $ocsp_cache_filename = makeCorrectFile($vhosts_folder . '/03_froxlor_ocsp_cache.conf'); if (Settings::Get('system.use_ssl') == '1' && Settings::Get('system.apache24') == 1) { $this->virtualhosts_data[$ocsp_cache_filename] = 'SSLStaplingCache ' . From 5540b02e352fc421763d01d4e69beca6fd6ea11d Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 27 Nov 2017 07:54:41 +0100 Subject: [PATCH 094/179] do not remove Let's Encrypt token when self-check fails but rather give out the information as warning. The self-check fails for many users due to different local configurations and might not always be correct; fixes #480 Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/ssl/class.lescript.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index 6d9ca5a3..8645c67b 100644 --- a/lib/classes/ssl/class.lescript.php +++ b/lib/classes/ssl/class.lescript.php @@ -236,9 +236,7 @@ class lescript } else { $errmsg = ""; } - @unlink($tokenPath); - $this->logger->logAction(CRON_ACTION, LOG_ERR, "letsencrypt Please check $uri - token not available" . $errmsg); - continue; + $this->logger->logAction(CRON_ACTION, LOG_WARNING, "[Lets Encrypt self-check] Please check $uri - token seems to be not available. This is just a simple self-check, it might be wrong but consider using this information when Let's Encrypt fails to issue a certificate" . $errmsg); } $this->log("Sending request to challenge"); From cb31c5258daa6220bb607becb0bc536e00c15f37 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 27 Nov 2017 08:09:33 +0100 Subject: [PATCH 095/179] correct setting for php-fpm peardir, fixes #475 Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/136.phpfpm.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/actions/admin/settings/136.phpfpm.php b/actions/admin/settings/136.phpfpm.php index 90dc742f..bcbe153f 100644 --- a/actions/admin/settings/136.phpfpm.php +++ b/actions/admin/settings/136.phpfpm.php @@ -73,6 +73,8 @@ return array( 'varname' => 'peardir', 'type' => 'string', 'string_type' => 'dir', + 'string_delimiter' => ':', + 'string_emptyallowed' => true, 'default' => '/usr/share/php/:/usr/share/php5/', 'save_method' => 'storeSettingField' ), From a5251824ae6862eb86a13e0e47362f17ace8e413 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 27 Nov 2017 08:14:31 +0100 Subject: [PATCH 096/179] try to reduce weird path-values when people are getting creative, fixes #487 Signed-off-by: Michael Kaufmann (d00p) --- customer_domains.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/customer_domains.php b/customer_domains.php index f492ee8a..3bfcd382 100644 --- a/customer_domains.php +++ b/customer_domains.php @@ -327,6 +327,9 @@ if ($page == 'overview') { } if (!preg_match('/^https?\:\/\//', $path) || !validateUrl($path)) { + if (strstr($path, ":") !== FALSE) { + standard_error('pathmaynotcontaincolon'); + } // If path is empty or '/' and 'Use domain name as default value for DocumentRoot path' is enabled in settings, // set default path to subdomain or domain name if ((($path == '') || ($path == '/')) && Settings::Get('system.documentroot_use_default_value') == 1) { @@ -334,9 +337,6 @@ if ($page == 'overview') { } else { $path = makeCorrectDir($userinfo['documentroot'] . '/' . $path); } - if (strstr($path, ":") !== FALSE) { - standard_error('pathmaynotcontaincolon'); - } } else { $_doredirect = true; } @@ -571,6 +571,9 @@ if ($page == 'overview') { } if (!preg_match('/^https?\:\/\//', $path) || !validateUrl($path)) { + if (strstr($path, ":") !== FALSE) { + standard_error('pathmaynotcontaincolon'); + } // If path is empty or '/' and 'Use domain name as default value for DocumentRoot path' is enabled in settings, // set default path to subdomain or domain name if ((($path == '') || ($path == '/')) && Settings::Get('system.documentroot_use_default_value') == 1) { @@ -578,9 +581,6 @@ if ($page == 'overview') { } else { $path = makeCorrectDir($userinfo['documentroot'] . '/' . $path); } - if (strstr($path, ":") !== FALSE) { - standard_error('pathmaynotcontaincolon'); - } } else { $_doredirect = true; } From cf4f15a83c4769347ee3175c6a5d1dc399df89dc Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 19 Dec 2017 08:00:39 +0100 Subject: [PATCH 097/179] explicitly deactivate TLS (and auto-tls) when setting use-tls is OFF; fixes #496 Signed-off-by: Michael Kaufmann (d00p) --- admin_settings.php | 2 ++ lib/functions/output/function.dieWithMail.php | 2 ++ lib/init.php | 2 ++ scripts/jobs/cron_usage_report.php | 2 ++ 4 files changed, 8 insertions(+) diff --git a/admin_settings.php b/admin_settings.php index 66abf4aa..49e2bd8c 100644 --- a/admin_settings.php +++ b/admin_settings.php @@ -310,6 +310,8 @@ elseif ($page == 'testmail') $testmail->Password = Settings::Get('system.mail_smtp_passwd'); if (Settings::Get('system.mail_smtp_usetls')) { $testmail->SMTPSecure = 'tls'; + } else { + $testmail->SMTPAutoTLS = false; } $testmail->Port = Settings::Get('system.mail_smtp_port'); } diff --git a/lib/functions/output/function.dieWithMail.php b/lib/functions/output/function.dieWithMail.php index 21890bdd..d0e5015b 100644 --- a/lib/functions/output/function.dieWithMail.php +++ b/lib/functions/output/function.dieWithMail.php @@ -42,6 +42,8 @@ function dieWithMail($message, $subject = "[froxlor] Cronjob error") { $_mail->Password = Settings::Get('system.mail_smtp_passwd'); if (Settings::Get('system.mail_smtp_usetls')) { $_mail->SMTPSecure = 'tls'; + } else { + $mail->SMTPAutoTLS = false; } $_mail->Port = Settings::Get('system.mail_smtp_port'); } diff --git a/lib/init.php b/lib/init.php index d5747621..3436b237 100644 --- a/lib/init.php +++ b/lib/init.php @@ -564,6 +564,8 @@ if (Settings::Get('system.mail_use_smtp')) { $mail->Password = Settings::Get('system.mail_smtp_passwd'); if (Settings::Get('system.mail_smtp_usetls')) { $mail->SMTPSecure = 'tls'; + } else { + $mail->SMTPAutoTLS = false; } $mail->Port = Settings::Get('system.mail_smtp_port'); } diff --git a/scripts/jobs/cron_usage_report.php b/scripts/jobs/cron_usage_report.php index 2ff94b52..9bc9eea4 100644 --- a/scripts/jobs/cron_usage_report.php +++ b/scripts/jobs/cron_usage_report.php @@ -34,6 +34,8 @@ if (Settings::Get('system.mail_use_smtp')) { $mail->Password = Settings::Get('system.mail_smtp_passwd'); if (Settings::Get('system.mail_smtp_usetls')) { $mail->SMTPSecure = 'tls'; + } else { + $mail->SMTPAutoTLS = false; } $mail->Port = Settings::Get('system.mail_smtp_port'); } From 148b2fc1beaf379a49064732365155647c0167e3 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 27 Dec 2017 10:01:07 +0100 Subject: [PATCH 098/179] validating config-template parameters; avoid URL misuse, thx to hyp3rlinx for noticing this Signed-off-by: Michael Kaufmann (d00p) --- admin_configfiles.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/admin_configfiles.php b/admin_configfiles.php index 29ae9437..949e9417 100644 --- a/admin_configfiles.php +++ b/admin_configfiles.php @@ -82,6 +82,12 @@ if ($userinfo['change_serversettings'] == '1') { $config_dir = makeCorrectDir(FROXLOR_INSTALL_DIR . '/lib/configfiles/'); if ($distribution != "") { + + if (!file_exists($config_dir . '/' . $distribution . ".xml")) { + trigger_error("Unknown distribution, are you playing around with the URL?"); + exit; + } + // create configparser object $configfiles = new ConfigParser($config_dir . '/' . $distribution . ".xml"); @@ -93,6 +99,11 @@ if ($userinfo['change_serversettings'] == '1') { if ($service != "") { + if (!isset($services[$service])) { + trigger_error("Unknown service, are you playing around with the URL?"); + exit; + } + $daemons = $services[$service]->getDaemons(); if ($daemon == "") { @@ -136,6 +147,11 @@ if ($userinfo['change_serversettings'] == '1') { if ($distribution != "" && $service != "" && $daemon != "") { + if (!isset($daemons[$daemon])) { + trigger_error("Unknown daemon, are you playing around with the URL?"); + exit; + } + $confarr = $daemons[$daemon]->getConfig(); $configpage = ''; From 57277eb1e34755bd7f13a7225f5e2d56ad4f6441 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 27 Dec 2017 10:36:10 +0100 Subject: [PATCH 099/179] also add locked users to the passwd file for quota not to rage :P thx J-BBB Signed-off-by: Michael Kaufmann (d00p) --- scripts/classes/class.Extrausers.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/classes/class.Extrausers.php b/scripts/classes/class.Extrausers.php index 17b312af..2ad38b73 100644 --- a/scripts/classes/class.Extrausers.php +++ b/scripts/classes/class.Extrausers.php @@ -21,7 +21,7 @@ class Extrausers { // passwd $passwd = '/var/lib/extrausers/passwd'; - $sql = "SELECT username,'x' as password,uid,gid,'Froxlor User' as comment,homedir,shell FROM ftp_users WHERE login_enabled = 'Y' ORDER BY uid ASC"; + $sql = "SELECT username,'x' as password,uid,gid,'Froxlor User' as comment,homedir,shell, login_enabled FROM ftp_users ORDER BY uid ASC"; self::_generateFile($passwd, $sql, $cronlog); // group @@ -39,7 +39,6 @@ class Extrausers @chmod('/var/lib/extrausers/passwd', 0644); @chmod('/var/lib/extrausers/group', 0644); @chmod('/var/lib/extrausers/shadow', 0640); - } private static function _generateFile($file, $query, &$cronlog) @@ -59,6 +58,11 @@ class Extrausers while ($u = $data_sel_stmt->fetch(PDO::FETCH_ASSOC)) { switch ($type) { case 'passwd': + if ($u['login_enabled'] != 'Y') { + $u['password'] = '*'; + $u['shell'] = '/bin/false'; + $u['comment'] = 'Locked Froxlor User'; + } $line = $u['username'] . ':' . $u['password'] . ':' . $u['uid'] . ':' . $u['gid'] . ':' . $u['comment'] . ':' . $u['homedir'] . ':' . $u['shell'] . PHP_EOL; break; case 'group': From 66a4309fe551e0b2d3540927f74afe84853df928 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 31 Dec 2017 11:18:59 +0100 Subject: [PATCH 100/179] add setting to disable LE self-check; set version to 0.9.38.8 for maintenance/bugfix release Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/131.ssl.php | 8 +++++++ install/froxlor.sql | 5 +++-- .../updates/froxlor/0.9/update_0.9.inc.php | 13 ++++++++++++ .../preconfig/0.9/preconfig_0.9.inc.php | 10 +++++++++ lib/classes/ssl/class.lescript.php | 21 +++++++++++-------- lib/version.inc.php | 4 ++-- lng/english.lng.php | 2 ++ lng/german.lng.php | 2 ++ 8 files changed, 52 insertions(+), 13 deletions(-) diff --git a/actions/admin/settings/131.ssl.php b/actions/admin/settings/131.ssl.php index 9028ac45..68f2a9e8 100644 --- a/actions/admin/settings/131.ssl.php +++ b/actions/admin/settings/131.ssl.php @@ -165,6 +165,14 @@ return array( 'type' => 'bool', 'default' => false, 'save_method' => 'storeSettingField' + ), + 'system_disable_le_selfcheck' => array( + 'label' => $lng['serversettings']['disable_le_selfcheck'], + 'settinggroup' => 'system', + 'varname' => 'disable_le_selfcheck', + 'type' => 'bool', + 'default' => false, + 'save_method' => 'storeSettingField' ) ) ) diff --git a/install/froxlor.sql b/install/froxlor.sql index f1b896da..e90d2112 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -554,6 +554,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('system', 'hsts_preload', '0'), ('system', 'leregistered', '0'), ('system', 'nssextrausers', '0'), + ('system', 'disable_le_selfcheck', '0'), ('panel', 'decimal_places', '4'), ('panel', 'adminmail', 'admin@SERVERNAME'), ('panel', 'phpmyadmin_url', ''), @@ -585,8 +586,8 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.38.7'), - ('panel', 'db_version', '201708240'); + ('panel', 'version', '0.9.38.8'), + ('panel', 'db_version', '201712310'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index b8d6f495..57f57a7d 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3633,3 +3633,16 @@ if (isDatabaseVersion('201705050')) { updateToDbVersion('201708240'); } + +if (isDatabaseVersion('201708240')) { + + showUpdateStep("Adding new 'disable LE self-check' setting"); + $system_disable_le_selfcheck = isset($_POST['system_disable_le_selfcheck']) ? (int) $_POST['system_disable_le_selfcheck'] : 0; + Settings::AddNew('system.disable_le_selfcheck', $system_disable_le_selfcheck); + lastStepStatus(0); + + updateToDbVersion('201712310'); + + showUpdateStep("Updating from 0.9.38.7 to 0.9.38.8", false); + updateToVersion('0.9.38.8'); +} diff --git a/install/updates/preconfig/0.9/preconfig_0.9.inc.php b/install/updates/preconfig/0.9/preconfig_0.9.inc.php index a528c322..ffbf9503 100644 --- a/install/updates/preconfig/0.9/preconfig_0.9.inc.php +++ b/install/updates/preconfig/0.9/preconfig_0.9.inc.php @@ -717,4 +717,14 @@ function parseAndOutputPreconfig(&$has_preconfig, &$return, $current_version, $c $question .= makeyesno('system_nssextrausers', '1', '0', '0') . '
'; eval("\$return.=\"" . getTemplate("update/preconfigitem") . "\";"); } + + if (versionInUpdate($current_db_version, '201712310')) { + if (Settings::Get('system.leenabled') == 1) { + $has_preconfig = true; + $description = 'Chose whether you want to disable the Let\'s Encrypt selfcheck as it causes false positives for some onfigurations.

'; + $question = 'Disable Let\'s Encrypt self-check?
'; + $question .= makeyesno('system_disable_le_selfcheck', '1', '0', '0') . '
'; + eval("\$return.=\"" . getTemplate("update/preconfigitem") . "\";"); + } + } } diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index 8645c67b..9923d5b0 100644 --- a/lib/classes/ssl/class.lescript.php +++ b/lib/classes/ssl/class.lescript.php @@ -227,16 +227,19 @@ class lescript $this->log("Token for $domain saved at $tokenPath and should be available at $uri"); // simple self check - $selfcheckContextOptions = array('http' => array('header' => "User-Agent: Froxlor/".$this->version)); - $selfcheckContext = stream_context_create($selfcheckContextOptions); - if ($payload !== trim(@file_get_contents($uri, false, $selfcheckContext))) { - $errmsg = json_encode(error_get_last()); - if ($errmsg != "null") { - $errmsg = "; PHP error: " . $errmsg; - } else { - $errmsg = ""; + if (Settings::Get('system.disable_le_selfcheck') == '0') + { + $selfcheckContextOptions = array('http' => array('header' => "User-Agent: Froxlor/".$this->version)); + $selfcheckContext = stream_context_create($selfcheckContextOptions); + if ($payload !== trim(@file_get_contents($uri, false, $selfcheckContext))) { + $errmsg = json_encode(error_get_last()); + if ($errmsg != "null") { + $errmsg = "; PHP error: " . $errmsg; + } else { + $errmsg = ""; + } + $this->logger->logAction(CRON_ACTION, LOG_WARNING, "[Lets Encrypt self-check] Please check $uri - token seems to be not available. This is just a simple self-check, it might be wrong but consider using this information when Let's Encrypt fails to issue a certificate" . $errmsg); } - $this->logger->logAction(CRON_ACTION, LOG_WARNING, "[Lets Encrypt self-check] Please check $uri - token seems to be not available. This is just a simple self-check, it might be wrong but consider using this information when Let's Encrypt fails to issue a certificate" . $errmsg); } $this->log("Sending request to challenge"); diff --git a/lib/version.inc.php b/lib/version.inc.php index 187d99b3..f6c42a62 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,10 +16,10 @@ */ // Main version variable -$version = '0.9.38.7'; +$version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201708240'; +$dbversion = '201712310'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index 51e05ef6..da777141 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2080,3 +2080,5 @@ $lng['admin']['domain_http2']['title'] = 'HTTP2 support'; $lng['admin']['domain_http2']['description'] = 'See Wikipedia for a detailed explanation of HTTP2'; $lng['admin']['testmail'] = 'SMTP test'; $lng['success']['testmailsent'] = 'Test mail sent successfully'; +$lng['serversettings']['disable_le_selfcheck']['title'] = "Disable Let's Encrypt local self-check"; +$lng['serversettings']['disable_le_selfcheck']['description'] = "If activated, froxlor will not perform its self-check for token accessability. Needed for NATed IP's or similar."; diff --git a/lng/german.lng.php b/lng/german.lng.php index 22e73ca8..7edda2ca 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1731,3 +1731,5 @@ $lng['admin']['domain_http2']['title'] = 'HTTP2 Unterstützung'; $lng['admin']['domain_http2']['description'] = 'Siehe Wikipedia für eine ausführliche Beschreibung von HTTP2'; $lng['admin']['testmail'] = 'SMTP Test'; $lng['success']['testmailsent'] = 'Test E-Mail erfolgreich gesendet'; +$lng['serversettings']['disable_le_selfcheck']['title'] = "Deaktiviere Let's Encrypt lokale Selbstprüfung"; +$lng['serversettings']['disable_le_selfcheck']['description'] = "Wenn aktiviert wird Froxlor keine Erreichbarkeitsprüfung des Tokens vornehmen. Nötig bei ge-NAT-eten IP's oder Ähnlichem"; From 732c6e3a7820f1b666de5494fa96a312b5cb1952 Mon Sep 17 00:00:00 2001 From: Andreas Grundler Date: Sun, 31 Dec 2017 22:40:19 +0100 Subject: [PATCH 101/179] Added nscd -i passwd to clear user --- scripts/jobs/cron_tasks.php | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/jobs/cron_tasks.php b/scripts/jobs/cron_tasks.php index cd9bb294..b7176a53 100644 --- a/scripts/jobs/cron_tasks.php +++ b/scripts/jobs/cron_tasks.php @@ -178,6 +178,7 @@ while ($row = $result_tasks_stmt->fetch(PDO::FETCH_ASSOC)) { // clear NSCD cache if using fcgid or fpm, #1570 if (Settings::Get('system.mod_fcgid') == 1 || (int)Settings::Get('phpfpm.enabled') == 1) { $false_val = false; + safe_exec('nscd -i passwd 1> /dev/null', $false_val, array('>')); safe_exec('nscd -i group 1> /dev/null', $false_val, array('>')); } } From 64653a2bb11a3529893db93be095d72ffa283708 Mon Sep 17 00:00:00 2001 From: Andreas Grundler Date: Mon, 1 Jan 2018 13:54:32 +0100 Subject: [PATCH 102/179] =?UTF-8?q?nscd=20-i=20passwd=20in=20froxlor=5Fmas?= =?UTF-8?q?ter=5Fcronjob.php=20eingef=C3=BCgt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/froxlor_master_cronjob.php | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/froxlor_master_cronjob.php b/scripts/froxlor_master_cronjob.php index d00926c6..a6d0d817 100644 --- a/scripts/froxlor_master_cronjob.php +++ b/scripts/froxlor_master_cronjob.php @@ -91,6 +91,7 @@ if (count($jobs_to_run) > 0) { // clear NSCD cache if using fcgid or fpm, #1570 if (Settings::Get('system.mod_fcgid') == 1 || (int)Settings::Get('phpfpm.enabled') == 1) { $false_val = false; + safe_exec('nscd -i passwd 1> /dev/null', $false_val, array('>')); safe_exec('nscd -i group 1> /dev/null', $false_val, array('>')); } } From ea96039128989dc55d994a53662a8494edfbf049 Mon Sep 17 00:00:00 2001 From: heavygale Date: Fri, 5 Jan 2018 18:11:23 +0100 Subject: [PATCH 103/179] Update preconfig_0.9.inc.php fixed a typo --- install/updates/preconfig/0.9/preconfig_0.9.inc.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install/updates/preconfig/0.9/preconfig_0.9.inc.php b/install/updates/preconfig/0.9/preconfig_0.9.inc.php index ffbf9503..26b47282 100644 --- a/install/updates/preconfig/0.9/preconfig_0.9.inc.php +++ b/install/updates/preconfig/0.9/preconfig_0.9.inc.php @@ -721,7 +721,7 @@ function parseAndOutputPreconfig(&$has_preconfig, &$return, $current_version, $c if (versionInUpdate($current_db_version, '201712310')) { if (Settings::Get('system.leenabled') == 1) { $has_preconfig = true; - $description = 'Chose whether you want to disable the Let\'s Encrypt selfcheck as it causes false positives for some onfigurations.

'; + $description = 'Chose whether you want to disable the Let\'s Encrypt selfcheck as it causes false positives for some configurations.

'; $question = 'Disable Let\'s Encrypt self-check?
'; $question .= makeyesno('system_disable_le_selfcheck', '1', '0', '0') . '
'; eval("\$return.=\"" . getTemplate("update/preconfigitem") . "\";"); From af55fe5b82593d4fba6f71ed9ad062ec5431c453 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 7 Jan 2018 14:55:25 +0100 Subject: [PATCH 104/179] add possibility to add multiple php-fpm instances Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/136.phpfpm.php | 75 --- admin_phpsettings.php | 546 +++++++++++++----- install/froxlor.sql | 32 +- .../updates/froxlor/0.9/update_0.9.inc.php | 70 +++ .../phpinterface/class.phpinterface_fpm.php | 490 ++++++++-------- lib/classes/webserver/class.ConfigIO.php | 205 +++---- lib/classes/webserver/class.WebserverBase.php | 51 +- .../phpconfig/formfield.fpmconfig_add.php | 89 +++ .../phpconfig/formfield.fpmconfig_edit.php | 91 +++ .../phpconfig/formfield.phpconfig_add.php | 6 + .../phpconfig/formfield.phpconfig_edit.php | 6 + lib/navigation/00.froxlor.main.php | 6 + lib/tables.inc.php | 1 + lib/version.inc.php | 2 +- lng/english.lng.php | 6 +- lng/german.lng.php | 6 +- .../jobs/cron_tasks.inc.http.10.apache.php | 330 +++++------ .../jobs/cron_tasks.inc.http.20.lighttpd.php | 11 +- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 11 +- .../Sparkle/admin/phpconfig/fpmconfig_add.tpl | 24 + .../admin/phpconfig/fpmconfig_edit.tpl | 25 + .../Sparkle/admin/phpconfig/fpmdaemons.tpl | 42 ++ .../admin/phpconfig/fpmdaemons_overview.tpl | 17 + .../Sparkle/admin/phpconfig/overview.tpl | 6 +- .../admin/phpconfig/overview_overview.tpl | 6 +- 25 files changed, 1408 insertions(+), 746 deletions(-) create mode 100644 lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php create mode 100644 lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php create mode 100644 templates/Sparkle/admin/phpconfig/fpmconfig_add.tpl create mode 100644 templates/Sparkle/admin/phpconfig/fpmconfig_edit.tpl create mode 100644 templates/Sparkle/admin/phpconfig/fpmdaemons.tpl create mode 100644 templates/Sparkle/admin/phpconfig/fpmdaemons_overview.tpl diff --git a/actions/admin/settings/136.phpfpm.php b/actions/admin/settings/136.phpfpm.php index bcbe153f..13e733ae 100644 --- a/actions/admin/settings/136.phpfpm.php +++ b/actions/admin/settings/136.phpfpm.php @@ -40,15 +40,6 @@ return array( 'option_options_method' => 'getPhpConfigs', 'save_method' => 'storeSettingField' ), - 'system_phpfpm_configdir' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['configdir'], - 'settinggroup' => 'phpfpm', - 'varname' => 'configdir', - 'type' => 'string', - 'string_type' => 'confdir', - 'default' => '/etc/php-fpm.d/', - 'save_method' => 'storeSettingField' - ), 'system_phpfpm_aliasconfigdir' => array( 'label' => $lng['serversettings']['phpfpm_settings']['aliasconfigdir'], 'settinggroup' => 'phpfpm', @@ -87,72 +78,6 @@ return array( 'default' => '/var/lib/apache2/fastcgi/', 'save_method' => 'storeSettingField' ), - 'system_phpfpm_reload' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['reload'], - 'settinggroup' => 'phpfpm', - 'varname' => 'reload', - 'type' => 'string', - 'default' => '/etc/init.d/php-fpm restart', - 'save_method' => 'storeSettingField' - ), - 'system_phpfpm_pm' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['pm'], - 'settinggroup' => 'phpfpm', - 'varname' => 'pm', - 'type' => 'option', - 'default' => 'static', - 'option_mode' => 'one', - 'option_options' => array('static' => 'static', 'dynamic' => 'dynamic', 'ondemand' => 'ondemand'), - 'save_method' => 'storeSettingField' - ), - 'system_phpfpm_max_children' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['max_children'], - 'settinggroup' => 'phpfpm', - 'varname' => 'max_children', - 'type' => 'int', - 'default' => 1, - 'save_method' => 'storeSettingField' - ), - 'system_phpfpm_start_servers' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['start_servers'], - 'settinggroup' => 'phpfpm', - 'varname' => 'start_servers', - 'type' => 'int', - 'default' => 20, - 'save_method' => 'storeSettingField' - ), - 'system_phpfpm_min_spare_servers' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['min_spare_servers'], - 'settinggroup' => 'phpfpm', - 'varname' => 'min_spare_servers', - 'type' => 'int', - 'default' => 5, - 'save_method' => 'storeSettingField' - ), - 'system_phpfpm_max_spare_servers' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['max_spare_servers'], - 'settinggroup' => 'phpfpm', - 'varname' => 'max_spare_servers', - 'type' => 'int', - 'default' => 35, - 'save_method' => 'storeSettingField' - ), - 'system_phpfpm_max_requests' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['max_requests'], - 'settinggroup' => 'phpfpm', - 'varname' => 'max_requests', - 'type' => 'int', - 'default' => 0, - 'save_method' => 'storeSettingField' - ), - 'system_phpfpm_idle_timeout' => array( - 'label' => $lng['serversettings']['phpfpm_settings']['idle_timeout'], - 'settinggroup' => 'phpfpm', - 'varname' => 'idle_timeout', - 'type' => 'int', - 'default' => 30, - 'save_method' => 'storeSettingField' - ), 'system_phpfpm_use_mod_proxy' => array( 'label' => $lng['phpfpm']['use_mod_proxy'], 'settinggroup' => 'phpfpm', diff --git a/admin_phpsettings.php b/admin_phpsettings.php index 4f7f9824..eb72f741 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -16,7 +16,6 @@ * @package Panel * */ - define('AREA', 'admin'); require './lib/init.php'; @@ -27,102 +26,107 @@ if (isset($_POST['id'])) { } if ($page == 'overview') { - + if ($action == '') { - + $tablecontent = ''; $count = 0; - $result = Database::query("SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "`"); - + $result = Database::query(" + SELECT c.*, fd.description as fpmdesc + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fd ON fd.id = c.fpmsettingid + ORDER BY c.description ASC + "); + while ($row = $result->fetch(PDO::FETCH_ASSOC)) { - + $domainresult = false; - $query_params = array('id' => $row['id']); - - $query = "SELECT * FROM `".TABLE_PANEL_DOMAINS."` + $query_params = array( + 'id' => $row['id'] + ); + + $query = "SELECT * FROM `" . TABLE_PANEL_DOMAINS . "` WHERE `phpsettingid` = :id AND `parentdomainid` = '0'"; - - if ((int)$userinfo['domains_see_all'] == 0) { + + if ((int) $userinfo['domains_see_all'] == 0) { $query .= " AND `adminid` = :adminid"; $query_params['adminid'] = $userinfo['adminid']; } - - if ((int)Settings::Get('panel.phpconfigs_hidestdsubdomain') == 1) { + + if ((int) Settings::Get('panel.phpconfigs_hidestdsubdomain') == 1) { $ssdids_res = Database::query(" - SELECT DISTINCT `standardsubdomain` FROM `".TABLE_PANEL_CUSTOMERS."` - WHERE `standardsubdomain` > 0 ORDER BY `standardsubdomain` ASC;" - ); + SELECT DISTINCT `standardsubdomain` FROM `" . TABLE_PANEL_CUSTOMERS . "` + WHERE `standardsubdomain` > 0 ORDER BY `standardsubdomain` ASC;"); $ssdids = array(); while ($ssd = $ssdids_res->fetch(PDO::FETCH_ASSOC)) { $ssdids[] = $ssd['standardsubdomain']; } if (count($ssdids) > 0) { - $query .= " AND `id` NOT IN (".implode(', ', $ssdids).")"; + $query .= " AND `id` NOT IN (" . implode(', ', $ssdids) . ")"; } } - + $domainresult_stmt = Database::prepare($query); Database::pexecute($domainresult_stmt, $query_params); - + $domains = ''; if (Database::num_rows() > 0) { while ($row2 = $domainresult_stmt->fetch(PDO::FETCH_ASSOC)) { - $domains.= $row2['domain'] . '
'; + $domains .= $row2['domain'] . '
'; } } - + // check whether we use that config as froxor-vhost config - if (Settings::Get('system.mod_fcgid_defaultini_ownvhost') == $row['id'] - || Settings::Get('phpfpm.vhost_defaultini') == $row['id'] - ) { + if (Settings::Get('system.mod_fcgid_defaultini_ownvhost') == $row['id'] || Settings::Get('phpfpm.vhost_defaultini') == $row['id']) { $domains .= Settings::Get('system.hostname'); } - + if ($domains == '') { $domains = $lng['admin']['phpsettings']['notused']; } - + // check whether this is our default config - if ((Settings::Get('system.mod_fcgid') == '1' - && Settings::Get('system.mod_fcgid_defaultini') == $row['id']) - || (Settings::Get('phpfpm.enabled') == '1' - && Settings::Get('phpfpm.defaultini') == $row['id']) - ) { - $row['description'] = ''.$row['description'].''; + if ((Settings::Get('system.mod_fcgid') == '1' && Settings::Get('system.mod_fcgid_defaultini') == $row['id']) || (Settings::Get('phpfpm.enabled') == '1' && Settings::Get('phpfpm.defaultini') == $row['id'])) { + $row['description'] = '' . $row['description'] . ''; } - + $count ++; eval("\$tablecontent.=\"" . getTemplate("phpconfig/overview_overview") . "\";"); } - + $log->logAction(ADM_ACTION, LOG_INFO, "php.ini setting overview has been viewed by '" . $userinfo['loginname'] . "'"); eval("echo \"" . getTemplate("phpconfig/overview") . "\";"); } - + if ($action == 'add') { - - if ((int)$userinfo['change_serversettings'] == 1) { - - if (isset($_POST['send']) - && $_POST['send'] == 'send' - ) { + + if ((int) $userinfo['change_serversettings'] == 1) { + + if (isset($_POST['send']) && $_POST['send'] == 'send') { $description = validate($_POST['description'], 'description'); $phpsettings = validate(str_replace("\r\n", "\n", $_POST['phpsettings']), 'phpsettings', '/^[^\0]*$/'); - + if (Settings::Get('system.mod_fcgid') == 1) { $binary = makeCorrectFile(validate($_POST['binary'], 'binary')); $file_extensions = validate($_POST['file_extensions'], 'file_extensions', '/^[a-zA-Z0-9\s]*$/'); - $mod_fcgid_starter = validate($_POST['mod_fcgid_starter'], 'mod_fcgid_starter', '/^[0-9]*$/', '', array('-1', '')); - $mod_fcgid_maxrequests = validate($_POST['mod_fcgid_maxrequests'], 'mod_fcgid_maxrequests', '/^[0-9]*$/', '', array('-1', '')); + $mod_fcgid_starter = validate($_POST['mod_fcgid_starter'], 'mod_fcgid_starter', '/^[0-9]*$/', '', array( + '-1', + '' + )); + $mod_fcgid_maxrequests = validate($_POST['mod_fcgid_maxrequests'], 'mod_fcgid_maxrequests', '/^[0-9]*$/', '', array( + '-1', + '' + )); $mod_fcgid_umask = validate($_POST['mod_fcgid_umask'], 'mod_fcgid_umask', '/^[0-9]*$/'); // disable fpm stuff + $fpm_config_id = 1; $fpm_enableslowlog = 0; $fpm_reqtermtimeout = 0; $fpm_reqslowtimeout = 0; - } - elseif (Settings::Get('phpfpm.enabled') == 1) { - $fpm_enableslowlog = isset($_POST['phpfpm_enable_slowlog']) ? (int)$_POST['phpfpm_enable_slowlog'] : 0; + } elseif (Settings::Get('phpfpm.enabled') == 1) { + $fpm_config_id = intval($_POST['fpmconfig']); + $fpm_enableslowlog = isset($_POST['phpfpm_enable_slowlog']) ? (int) $_POST['phpfpm_enable_slowlog'] : 0; $fpm_reqtermtimeout = validate($_POST['phpfpm_reqtermtimeout'], 'phpfpm_reqtermtimeout', '/^([0-9]+)(|s|m|h|d)$/'); $fpm_reqslowtimeout = validate($_POST['phpfpm_reqslowtimeout'], 'phpfpm_reqslowtimeout', '/^([0-9]+)(|s|m|h|d)$/'); // disable fcgid stuff @@ -132,13 +136,11 @@ if ($page == 'overview') { $mod_fcgid_maxrequests = 0; $mod_fcgid_umask = "022"; } - - if (strlen($description) == 0 - || strlen($description) > 50 - ) { + + if (strlen($description) == 0 || strlen($description) > 50) { standard_error('descriptioninvalid'); } - + $ins_stmt = Database::prepare(" INSERT INTO `" . TABLE_PANEL_PHPCONFIGS . "` SET `description` = :desc, @@ -150,8 +152,8 @@ if ($page == 'overview') { `fpm_slowlog` = :fpmslow, `fpm_reqterm` = :fpmreqterm, `fpm_reqslow` = :fpmreqslow, - `phpsettings` = :phpsettings" - ); + `phpsettings` = :phpsettings, + `fpmsettingid` = :fpmsettingid"); $ins_data = array( 'desc' => $description, 'binary' => $binary, @@ -162,121 +164,128 @@ if ($page == 'overview') { 'fpmslow' => $fpm_enableslowlog, 'fpmreqterm' => $fpm_reqtermtimeout, 'fpmreqslow' => $fpm_reqslowtimeout, - 'phpsettings' => $phpsettings + 'phpsettings' => $phpsettings, + 'fpmsettingid' => $fpm_config_id ); Database::pexecute($ins_stmt, $ins_data); - + inserttask('1'); $log->logAction(ADM_ACTION, LOG_INFO, "php.ini setting with description '" . $description . "' has been created by '" . $userinfo['loginname'] . "'"); - redirectTo($filename, array('page' => $page, 's' => $s)); - + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); } else { - + $result_stmt = Database::query("SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `id` = 1"); $result = $result_stmt->fetch(PDO::FETCH_ASSOC); - - $phpconfig_add_data = include_once dirname(__FILE__).'/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php'; + + $fpmconfigs = ''; + $configs = Database::query("SELECT * FROM `" . TABLE_PANEL_FPMDAEMONS . "` ORDER BY `description` ASC"); + while ($row = $configs->fetch(PDO::FETCH_ASSOC)) { + $fpmconfigs .= makeoption($row['description'], $row['id'], 1, true, true); + } + + $phpconfig_add_data = include_once dirname(__FILE__) . '/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php'; $phpconfig_add_form = htmlform::genHTMLForm($phpconfig_add_data); - + $title = $phpconfig_add_data['phpconfig_add']['title']; $image = $phpconfig_add_data['phpconfig_add']['image']; - + eval("echo \"" . getTemplate("phpconfig/overview_add") . "\";"); } - } else { standard_error('nopermissionsorinvalidid'); } } - + if ($action == 'delete') { - + $result_stmt = Database::prepare(" - SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `id` = :id" - ); - $result = Database::pexecute_first($result_stmt, array('id' => $id)); - - if ((Settings::Get('system.mod_fcgid') == '1' - && Settings::Get('system.mod_fcgid_defaultini_ownvhost') == $id) - || (Settings::Get('phpfpm.enabled') == '1' - && Settings::Get('phpfpm.vhost_defaultini') == $id) - ) { + SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `id` = :id"); + $result = Database::pexecute_first($result_stmt, array( + 'id' => $id + )); + + if ((Settings::Get('system.mod_fcgid') == '1' && Settings::Get('system.mod_fcgid_defaultini_ownvhost') == $id) || (Settings::Get('phpfpm.enabled') == '1' && Settings::Get('phpfpm.vhost_defaultini') == $id)) { standard_error('cannotdeletehostnamephpconfig'); } - - if ((Settings::Get('system.mod_fcgid') == '1' - && Settings::Get('system.mod_fcgid_defaultini') == $id) - || (Settings::Get('phpfpm.enabled') == '1' - && Settings::Get('phpfpm.defaultini') == $id) - ) { + + if ((Settings::Get('system.mod_fcgid') == '1' && Settings::Get('system.mod_fcgid_defaultini') == $id) || (Settings::Get('phpfpm.enabled') == '1' && Settings::Get('phpfpm.defaultini') == $id)) { standard_error('cannotdeletedefaultphpconfig'); } - - if ($result['id'] != 0 - && $result['id'] == $id - && (int)$userinfo['change_serversettings'] == 1 - && $id != 1 // cannot delete the default php.config - ) { - - if (isset($_POST['send']) - && $_POST['send'] == 'send' - ) { + + if ($result['id'] != 0 && $result['id'] == $id && (int) $userinfo['change_serversettings'] == 1 && $id != 1) // cannot delete the default php.config + { + + if (isset($_POST['send']) && $_POST['send'] == 'send') { // set php-config to default for all domains using the // config that is to be deleted $upd_stmt = Database::prepare(" UPDATE `" . TABLE_PANEL_DOMAINS . "` SET - `phpsettingid` = '1' WHERE `phpsettingid` = :id" - ); - Database::pexecute($upd_stmt, array('id' => $id)); - + `phpsettingid` = '1' WHERE `phpsettingid` = :id"); + Database::pexecute($upd_stmt, array( + 'id' => $id + )); + $del_stmt = Database::prepare(" - DELETE FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `id` = :id" - ); - Database::pexecute($del_stmt, array('id' => $id)); - + DELETE FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `id` = :id"); + Database::pexecute($del_stmt, array( + 'id' => $id + )); + inserttask('1'); - $log->logAction(ADM_ACTION, LOG_INFO, "php.ini setting with id #" . (int)$id . " has been deleted by '" . $userinfo['loginname'] . "'"); - redirectTo($filename, array('page' => $page, 's' => $s)); - + $log->logAction(ADM_ACTION, LOG_INFO, "php.ini setting with id #" . (int) $id . " has been deleted by '" . $userinfo['loginname'] . "'"); + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); } else { - ask_yesno('phpsetting_reallydelete', $filename, array('id' => $id, 'page' => $page, 'action' => $action), $result['description']); + ask_yesno('phpsetting_reallydelete', $filename, array( + 'id' => $id, + 'page' => $page, + 'action' => $action + ), $result['description']); } } else { standard_error('nopermissionsorinvalidid'); } } - + if ($action == 'edit') { - + $result_stmt = Database::prepare(" - SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `id` = :id" - ); - $result = Database::pexecute_first($result_stmt, array('id' => $id)); - - if ($result['id'] != 0 - && $result['id'] == $id - && (int)$userinfo['change_serversettings'] == 1 - ) { - - if (isset($_POST['send']) - && $_POST['send'] == 'send' - ) { + SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `id` = :id"); + $result = Database::pexecute_first($result_stmt, array( + 'id' => $id + )); + + if ($result['id'] != 0 && $result['id'] == $id && (int) $userinfo['change_serversettings'] == 1) { + + if (isset($_POST['send']) && $_POST['send'] == 'send') { $description = validate($_POST['description'], 'description'); $phpsettings = validate(str_replace("\r\n", "\n", $_POST['phpsettings']), 'phpsettings', '/^[^\0]*$/'); - + if (Settings::Get('system.mod_fcgid') == 1) { $binary = makeCorrectFile(validate($_POST['binary'], 'binary')); $file_extensions = validate($_POST['file_extensions'], 'file_extensions', '/^[a-zA-Z0-9\s]*$/'); - $mod_fcgid_starter = validate($_POST['mod_fcgid_starter'], 'mod_fcgid_starter', '/^[0-9]*$/', '', array('-1', '')); - $mod_fcgid_maxrequests = validate($_POST['mod_fcgid_maxrequests'], 'mod_fcgid_maxrequests', '/^[0-9]*$/', '', array('-1', '')); + $mod_fcgid_starter = validate($_POST['mod_fcgid_starter'], 'mod_fcgid_starter', '/^[0-9]*$/', '', array( + '-1', + '' + )); + $mod_fcgid_maxrequests = validate($_POST['mod_fcgid_maxrequests'], 'mod_fcgid_maxrequests', '/^[0-9]*$/', '', array( + '-1', + '' + )); $mod_fcgid_umask = validate($_POST['mod_fcgid_umask'], 'mod_fcgid_umask', '/^[0-9]*$/'); // disable fpm stuff + $fpm_config_id = 1; $fpm_enableslowlog = 0; $fpm_reqtermtimeout = 0; $fpm_reqslowtimeout = 0; - } - elseif (Settings::Get('phpfpm.enabled') == 1) { - $fpm_enableslowlog = isset($_POST['phpfpm_enable_slowlog']) ? (int)$_POST['phpfpm_enable_slowlog'] : 0; + } elseif (Settings::Get('phpfpm.enabled') == 1) { + $fpm_config_id = intval($_POST['fpmconfig']); + $fpm_enableslowlog = isset($_POST['phpfpm_enable_slowlog']) ? (int) $_POST['phpfpm_enable_slowlog'] : 0; $fpm_reqtermtimeout = validate($_POST['phpfpm_reqtermtimeout'], 'phpfpm_reqtermtimeout', '/^([0-9]+)(|s|m|h|d)$/'); $fpm_reqslowtimeout = validate($_POST['phpfpm_reqslowtimeout'], 'phpfpm_reqslowtimeout', '/^([0-9]+)(|s|m|h|d)$/'); // disable fcgid stuff @@ -286,13 +295,11 @@ if ($page == 'overview') { $mod_fcgid_maxrequests = 0; $mod_fcgid_umask = "022"; } - - if (strlen($description) == 0 - || strlen($description) > 50 - ) { + + if (strlen($description) == 0 || strlen($description) > 50) { standard_error('descriptioninvalid'); } - + $upd_stmt = Database::prepare(" UPDATE `" . TABLE_PANEL_PHPCONFIGS . "` SET `description` = :desc, @@ -304,39 +311,284 @@ if ($page == 'overview') { `fpm_slowlog` = :fpmslow, `fpm_reqterm` = :fpmreqterm, `fpm_reqslow` = :fpmreqslow, - `phpsettings` = :phpsettings - WHERE `id` = :id" - ); + `phpsettings` = :phpsettings, + `fpmsettingid` = :fpmsettingid + WHERE `id` = :id"); $upd_data = array( - 'desc' => $description, - 'binary' => $binary, - 'fext' => $file_extensions, - 'starter' => $mod_fcgid_starter, - 'mreq' => $mod_fcgid_maxrequests, - 'umask' => $mod_fcgid_umask, - 'fpmslow' => $fpm_enableslowlog, - 'fpmreqterm' => $fpm_reqtermtimeout, - 'fpmreqslow' => $fpm_reqslowtimeout, - 'phpsettings' => $phpsettings, - 'id' => $id + 'desc' => $description, + 'binary' => $binary, + 'fext' => $file_extensions, + 'starter' => $mod_fcgid_starter, + 'mreq' => $mod_fcgid_maxrequests, + 'umask' => $mod_fcgid_umask, + 'fpmslow' => $fpm_enableslowlog, + 'fpmreqterm' => $fpm_reqtermtimeout, + 'fpmreqslow' => $fpm_reqslowtimeout, + 'phpsettings' => $phpsettings, + 'fpmsettingid' => $fpm_config_id, + 'id' => $id ); Database::pexecute($upd_stmt, $upd_data); - + inserttask('1'); $log->logAction(ADM_ACTION, LOG_INFO, "php.ini setting with description '" . $description . "' has been changed by '" . $userinfo['loginname'] . "'"); - redirectTo($filename, array('page' => $page, 's' => $s)); - + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); } else { - $phpconfig_edit_data = include_once dirname(__FILE__).'/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php'; + $fpmconfigs = ''; + $configs = Database::query("SELECT * FROM `" . TABLE_PANEL_FPMDAEMONS . "` ORDER BY `description` ASC"); + while ($row = $configs->fetch(PDO::FETCH_ASSOC)) { + $fpmconfigs .= makeoption($row['description'], $row['id'], $id, true, true); + } + + $phpconfig_edit_data = include_once dirname(__FILE__) . '/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php'; $phpconfig_edit_form = htmlform::genHTMLForm($phpconfig_edit_data); $title = $phpconfig_edit_data['phpconfig_edit']['title']; $image = $phpconfig_edit_data['phpconfig_edit']['image']; - + eval("echo \"" . getTemplate("phpconfig/overview_edit") . "\";"); } + } else { + standard_error('nopermissionsorinvalidid'); + } + } +} elseif ($page == 'fpmdaemons') { + + if ($action == '') { + + $tablecontent = ''; + $count = 0; + $result = Database::query("SELECT * FROM `" . TABLE_PANEL_FPMDAEMONS . "` ORDER BY `description` ASC"); + + while ($row = $result->fetch(PDO::FETCH_ASSOC)) { + $query_params = array( + 'id' => $row['id'] + ); + + $query = "SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `fpmsettingid` = :id"; + + $configresult_stmt = Database::prepare($query); + Database::pexecute($configresult_stmt, $query_params); + + $configs = ''; + if (Database::num_rows() > 0) { + while ($row2 = $configresult_stmt->fetch(PDO::FETCH_ASSOC)) { + $configs .= $row2['description'] . '
'; + } + } + + if ($configs == '') { + $configs = $lng['admin']['phpsettings']['notused']; + } + + $count ++; + eval("\$tablecontent.=\"" . getTemplate("phpconfig/fpmdaemons_overview") . "\";"); + } + + $log->logAction(ADM_ACTION, LOG_INFO, "fpm daemons setting overview has been viewed by '" . $userinfo['loginname'] . "'"); + eval("echo \"" . getTemplate("phpconfig/fpmdaemons") . "\";"); + } + + if ($action == 'add') { + + if ((int) $userinfo['change_serversettings'] == 1) { + + if (isset($_POST['send']) && $_POST['send'] == 'send') { + $description = validate($_POST['description'], 'description'); + $reload_cmd = validate($_POST['reload_cmd'], 'reload_cmd'); + $config_dir = validate($_POST['config_dir'], 'config_dir'); + $pm = validate($_POST['pm'], 'pm'); + $max_children = isset($_POST['max_children']) ? (int) $_POST['max_children'] : 0; + $start_servers = isset($_POST['start_servers']) ? (int) $_POST['start_servers'] : 0; + $min_spare_servers = isset($_POST['min_spare_servers']) ? (int) $_POST['min_spare_servers'] : 0; + $max_spare_servers = isset($_POST['max_spare_servers']) ? (int) $_POST['max_spare_servers'] : 0; + $max_requests = isset($_POST['max_requests']) ? (int) $_POST['max_requests'] : 0; + $idle_timeout = isset($_POST['idle_timeout']) ? (int) $_POST['idle_timeout'] : 0; + + if (strlen($description) == 0 || strlen($description) > 50) { + standard_error('descriptioninvalid'); + } + + $ins_stmt = Database::prepare(" + INSERT INTO `" . TABLE_PANEL_FPMDAEMONS . "` SET + `description` = :desc, + `reload_cmd` = :reload_cmd, + `config_dir` = :config_dir, + `pm` = :pm, + `max_children` = :max_children, + `start_servers` = :start_servers, + `min_spare_servers` = :min_spare_servers, + `max_spare_servers` = :max_spare_servers, + `max_requests` = :max_requests, + `idle_timeout` = :idle_timeout + "); + $ins_data = array( + 'desc' => $description, + 'reload_cmd' => $reload_cmd, + 'config_dir' => makeCorrectDir($config_dir), + 'pm' => pm, + 'max_children' => $max_children, + 'start_servers' => $start_servers, + 'min_spare_servers' => $min_spare_servers, + 'max_spare_servers' => $max_spare_servers, + 'max_requests' => $max_requests, + 'idle_timeout' => $idle_timeout + ); + Database::pexecute($ins_stmt, $ins_data); + + inserttask('1'); + $log->logAction(ADM_ACTION, LOG_INFO, "fpm-daemon setting with description '" . $description . "' has been created by '" . $userinfo['loginname'] . "'"); + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); + } else { + + $pm_select = makeoption('static', 'static', 'static', true, true); + $pm_select.= makeoption('dynamic', 'dynamic', 'static', true, true); + $pm_select.= makeoption('ondemand', 'ondemand', 'static', true, true); + + $fpmconfig_add_data = include_once dirname(__FILE__) . '/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php'; + $fpmconfig_add_form = htmlform::genHTMLForm($fpmconfig_add_data); + + $title = $fpmconfig_add_data['fpmconfig_add']['title']; + $image = $fpmconfig_add_data['fpmconfig_add']['image']; + + eval("echo \"" . getTemplate("phpconfig/fpmconfig_add") . "\";"); + } + } else { + standard_error('nopermissionsorinvalidid'); + } + } + + if ($action == 'delete') { + + $result_stmt = Database::prepare(" + SELECT * FROM `" . TABLE_PANEL_FPMDAEMONS . "` WHERE `id` = :id"); + $result = Database::pexecute_first($result_stmt, array( + 'id' => $id + )); + + if ($id == 1) { + standard_error('cannotdeletedefaultphpconfig'); + } + + if ($result['id'] != 0 && $result['id'] == $id && (int) $userinfo['change_serversettings'] == 1 && $id != 1) // cannot delete the default php.config + { + + if (isset($_POST['send']) && $_POST['send'] == 'send') { + // set default fpm daemon config for all php-config that use this config that is to be deleted + $upd_stmt = Database::prepare(" + UPDATE `" . TABLE_PANEL_PHPCONFIGS . "` SET + `phpsettingid` = '1' WHERE `phpsettingid` = :id"); + Database::pexecute($upd_stmt, array( + 'id' => $id + )); + + $del_stmt = Database::prepare(" + DELETE FROM `" . TABLE_PANEL_FPMDAEMONS . "` WHERE `id` = :id"); + Database::pexecute($del_stmt, array( + 'id' => $id + )); + + inserttask('1'); + $log->logAction(ADM_ACTION, LOG_INFO, "fpm-daemon setting with id #" . (int) $id . " has been deleted by '" . $userinfo['loginname'] . "'"); + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); + } else { + ask_yesno('fpmsetting_reallydelete', $filename, array( + 'id' => $id, + 'page' => $page, + 'action' => $action + ), $result['description']); + } + } else { + standard_error('nopermissionsorinvalidid'); + } + } + + if ($action == 'edit') { + + $result_stmt = Database::prepare(" + SELECT * FROM `" . TABLE_PANEL_FPMDAEMONS . "` WHERE `id` = :id"); + $result = Database::pexecute_first($result_stmt, array( + 'id' => $id + )); + + if ($result['id'] != 0 && $result['id'] == $id && (int) $userinfo['change_serversettings'] == 1) { + + if (isset($_POST['send']) && $_POST['send'] == 'send') { + $description = validate($_POST['description'], 'description'); + $reload_cmd = validate($_POST['reload_cmd'], 'reload_cmd'); + $config_dir = validate($_POST['config_dir'], 'config_dir'); + $pm = validate($_POST['pm'], 'pm'); + $max_children = isset($_POST['max_children']) ? (int) $_POST['max_children'] : $result['max_children']; + $start_servers = isset($_POST['start_servers']) ? (int) $_POST['start_servers'] : $result['start_servers']; + $min_spare_servers = isset($_POST['min_spare_servers']) ? (int) $_POST['min_spare_servers'] : $result['min_spare_servers']; + $max_spare_servers = isset($_POST['max_spare_servers']) ? (int) $_POST['max_spare_servers'] : $result['max_spare_servers']; + $max_requests = isset($_POST['max_requests']) ? (int) $_POST['max_requests'] : $result['max_requests']; + $idle_timeout = isset($_POST['idle_timeout']) ? (int) $_POST['idle_timeout'] : $result['idle_timeout']; + + if (strlen($description) == 0 || strlen($description) > 50) { + standard_error('descriptioninvalid'); + } + + $upd_stmt = Database::prepare(" + UPDATE `" . TABLE_PANEL_PHPCONFIGS . "` SET + `description` = :desc, + `reload_cmd` = :reload_cmd, + `config_dir` = :config_dir, + `pm` = :pm, + `max_children` = :max_children, + `start_servers` = :start_servers, + `min_spare_servers` = :min_spare_servers, + `max_spare_servers` = :max_spare_servers, + `max_requests` = :max_requests, + `idle_timeout` = :idle_timeout + WHERE `id` = :id + "); + $upd_data = array( + 'desc' => $description, + 'reload_cmd' => $reload_cmd, + 'config_dir' => makeCorrectDir($config_dir), + 'pm' => pm, + 'max_children' => $max_children, + 'start_servers' => $start_servers, + 'min_spare_servers' => $min_spare_servers, + 'max_spare_servers' => $max_spare_servers, + 'max_requests' => $max_requests, + 'idle_timeout' => $idle_timeout, + 'id' => $id + ); + Database::pexecute($upd_stmt, $upd_data); + + inserttask('1'); + $log->logAction(ADM_ACTION, LOG_INFO, "fpm-daemon setting with description '" . $description . "' has been changed by '" . $userinfo['loginname'] . "'"); + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); + } else { + + $pm_select = makeoption('static', 'static', $result['pm'], true, true); + $pm_select.= makeoption('dynamic', 'dynamic', $result['pm'], true, true); + $pm_select.= makeoption('ondemand', 'ondemand', $result['pm'], true, true); + + $fpmconfig_edit_data = include_once dirname(__FILE__) . '/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php'; + $fpmconfig_edit_form = htmlform::genHTMLForm($fpmconfig_edit_data); + + $title = $fpmconfig_edit_data['fpmconfig_edit']['title']; + $image = $fpmconfig_edit_data['fpmconfig_edit']['image']; + + eval("echo \"" . getTemplate("phpconfig/fpmconfig_edit") . "\";"); + } } else { standard_error('nopermissionsorinvalidid'); } diff --git a/install/froxlor.sql b/install/froxlor.sql index e90d2112..4883fe14 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -587,7 +587,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.8'), - ('panel', 'db_version', '201712310'); + ('panel', 'db_version', '201801070'); DROP TABLE IF EXISTS `panel_tasks`; @@ -753,6 +753,32 @@ CREATE TABLE IF NOT EXISTS `panel_syslog` ( ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; + +DROP TABLE IF EXISTS `panel_fpmdaemons`; +CREATE TABLE `panel_fpmdaemons` ( + `id` int(11) unsigned NOT NULL auto_increment, + `description` varchar(50) NOT NULL, + `reload_cmd` varchar(255) NOT NULL, + `config_dir` varchar(255) NOT NULL, + `pm` varchar(15) NOT NULL DEFAULT 'static', + `max_children` int(4) NOT NULL DEFAULT '1', + `start_servers` int(4) NOT NULL DEFAULT '20', + `min_spare_servers` int(4) NOT NULL DEFAULT '5', + `max_spare_servers` int(4) NOT NULL DEFAULT '35', + `max_requests` int(4) NOT NULL DEFAULT '0', + `idle_timeout` int(4) NOT NULL DEFAULT '30', + PRIMARY KEY (`id`), + UNIQUE KEY `reload` (`reload_cmd`), + UNIQUE KEY `config` (`config_dir`) +) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; + + + +INSERT INTO `panel_fpmdaemons` (`id`, `description`, `reload_cmd`, `config_dir`) VALUES +(1, 'System default', 'service php7.0-fpm restart', '/etc/php/7.0/fpm/pool.d/'); + + + DROP TABLE IF EXISTS `panel_phpconfigs`; CREATE TABLE `panel_phpconfigs` ( `id` int(11) unsigned NOT NULL auto_increment, @@ -766,7 +792,9 @@ CREATE TABLE `panel_phpconfigs` ( `fpm_reqterm` varchar(15) NOT NULL default '60s', `fpm_reqslow` varchar(15) NOT NULL default '5s', `phpsettings` text NOT NULL, - PRIMARY KEY (`id`) + `fpmsettingid` int(11) NOT NULL DEFAULT '1', + PRIMARY KEY (`id`), + KEY `fpmsettingid` (`fpmsettingid`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 57f57a7d..8ae1c344 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3646,3 +3646,73 @@ if (isDatabaseVersion('201708240')) { showUpdateStep("Updating from 0.9.38.7 to 0.9.38.8", false); updateToVersion('0.9.38.8'); } + +if (isDatabaseVersion('201712310')) { + + showUpdateStep("Adding field for fpm-daemon configs"); + Database::query("ALTER TABLE `" . TABLE_PANEL_PHPCONFIGS . "` ADD `fpmsettingid` int(11) NOT NULL DEFAULT '1';"); + lastStepStatus(0); + + showUpdateStep("Adding new fpm-daemons table"); + Database::query("DROP TABLE IF EXISTS `panel_fpmdaemons`;"); + $sql = "CREATE TABLE `panel_fpmdaemons` ( + `id` int(11) unsigned NOT NULL auto_increment, + `description` varchar(50) NOT NULL, + `reload_cmd` varchar(255) NOT NULL, + `config_dir` varchar(255) NOT NULL, + `pm` varchar(15) NOT NULL DEFAULT 'static', + `max_children` int(4) NOT NULL DEFAULT '1', + `start_servers` int(4) NOT NULL DEFAULT '20', + `min_spare_servers` int(4) NOT NULL DEFAULT '5', + `max_spare_servers` int(4) NOT NULL DEFAULT '35', + `max_requests` int(4) NOT NULL DEFAULT '0', + `idle_timeout` int(4) NOT NULL DEFAULT '30', + PRIMARY KEY (`id`), + UNIQUE KEY `reload` (`reload_cmd`), + UNIQUE KEY `config` (`config_dir`) + ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci;"; + Database::query($sql); + lastStepStatus(0); + + showUpdateStep("Converting php-fpm settings to new layout"); + $ins_stmt = Database::prepare(" + INSERT INTO `panel_fpmdaemons` SET + `id` = 1, + `description` = 'System default', + `reload_cmd` = :reloadcmd, + `config_dir` = :confdir, + `pm` = :pm, + `max_children` = :maxc, + `start_servers` = :starts, + `min_spare_servers` = :minss, + `max_spare_servers` = :maxss, + `max_requests` = :maxr, + `idle_timeout` = :it + "); + Database::pexecute($ins_stmt, array( + 'reloadcmd' => Settings::Get('phpfpm.reload'), + 'confdir' => Settings::Get('phpfpm.configdir'), + 'pm' => Settings::Get('phpfpm.pm'), + 'maxc' => Settings::Get('phpfpm.max_children'), + 'starts' => Settings::Get('phpfpm.start_servers'), + 'minss' => Settings::Get('phpfpm.min_spare_servers'), + 'maxss' => Settings::Get('phpfpm.max_spare_servers'), + 'maxr' => Settings::Get('phpfpm.max_requests'), + 'it' => Settings::Get('phpfpm.idle_timeout') + )); + lastStepStatus(0); + + showUpdateStep("Deleting unneeded settings"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'reload'"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'configdir'"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'pm'"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'max_children'"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'start_servers'"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'min_spare_servers'"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'max_spare_servers'"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'max_requests'"); + Database::query("DELETE FROM `".TABLE_PANEL_SETTINGS."` WHERE `settinggroup` = 'phpfpm' AND `varname` = 'idle_timeout'"); + lastStepStatus(0); + + updateToDbVersion('201801070'); +} diff --git a/lib/classes/phpinterface/class.phpinterface_fpm.php b/lib/classes/phpinterface/class.phpinterface_fpm.php index 5c39d00b..b4a577ac 100644 --- a/lib/classes/phpinterface/class.phpinterface_fpm.php +++ b/lib/classes/phpinterface/class.phpinterface_fpm.php @@ -18,19 +18,28 @@ * @since 0.9.16 * */ - -class phpinterface_fpm { +class phpinterface_fpm +{ /** * Domain-Data array + * * @var array - */ + */ private $_domain = array(); /** - * Admin-Date cache array + * fpm config + * * @var array - */ + */ + private $_fpm_cfg = array(); + + /** + * Admin-Date cache array + * + * @var array + */ private $_admin_cache = array(); /** @@ -38,119 +47,129 @@ class phpinterface_fpm { * Mostly taken from http://php.net/manual/en/ini.list.php * * @var array - */ + */ private $_ini = array( - 'php_value' => array( - 'auto_append_file', - 'auto_prepend_file', - 'date.timezone', - 'default_charset', - 'error_reporting', - 'include_path', - 'log_errors_max_len', - 'mail.log', - 'max_execution_time', - 'session.cookie_domain', - 'session.cookie_lifetime', - 'session.cookie_path', - 'session.name', - 'session.serialize_handler', - 'upload_max_filesize', - 'xmlrpc_error_number', - 'session.auto_start', - 'always_populate_raw_post_data', - 'suhosin.session.cryptkey', - 'suhosin.session.cryptraddr', - 'suhosin.session.checkraddr', - 'suhosin.cookie.cryptkey', - 'suhosin.cookie.plainlist', - 'suhosin.cookie.cryptraddr', - 'suhosin.cookie.checkraddr', - 'suhosin.executor.func.blacklist', - 'suhosin.executor.eval.whitelist' - ), - 'php_flag' => array( - 'asp_tags', - 'display_errors', - 'display_startup_errors', - 'html_errors', - 'log_errors', - 'magic_quotes_gpc', - 'magic_quotes_runtime', - 'magic_quotes_sybase', - 'mail.add_x_header', - 'session.cookie_secure', - 'session.use_cookies', - 'short_open_tag', - 'track_errors', - 'xmlrpc_errors', - 'suhosin.simulation', - 'suhosin.session.encrypt', - 'suhosin.session.cryptua', - 'suhosin.session.cryptdocroot', - 'suhosin.cookie.encrypt', - 'suhosin.cookie.cryptua', - 'suhosin.cookie.cryptdocroot', - 'suhosin.executor.disable_eval', - 'mbstring.func_overload' - ), - 'php_admin_value' => array( - 'cgi.redirect_status_env', - 'date.timezone', - 'disable_classes', - 'disable_functions', - 'error_log', - 'gpc_order', - 'max_input_time', - 'max_input_vars', - 'memory_limit', - 'open_basedir', - 'output_buffering', - 'post_max_size', - 'precision', - 'sendmail_path', - 'session.gc_divisor', - 'session.gc_probability', - 'variables_order', - 'opcache.log_verbosity_level', - 'opcache.restrict_api', - 'opcache.revalidate_freq', - 'opcache.max_accelerated_files', - 'opcache.memory_consumption', - 'opcache.interned_strings_buffer' - ), - 'php_admin_flag' => array( - 'allow_call_time_pass_reference', - 'allow_url_fopen', - 'allow_url_include', - 'auto_detect_line_endings', - 'cgi.fix_pathinfo', - 'cgi.force_redirect', - 'enable_dl', - 'expose_php', - 'file_uploads', - 'ignore_repeated_errors', - 'ignore_repeated_source', - 'log_errors', - 'register_argc_argv', - 'report_memleaks', - 'opcache.enable', - 'opcache.consistency_checks', - 'opcache.dups_fix', - 'opcache.load_comments', - 'opcache.revalidate_path', - 'opcache.save_comments', - 'opcache.use_cwd', - 'opcache.validate_timestamps', - 'opcache.fast_shutdown' - ) + 'php_value' => array( + 'auto_append_file', + 'auto_prepend_file', + 'date.timezone', + 'default_charset', + 'error_reporting', + 'include_path', + 'log_errors_max_len', + 'mail.log', + 'max_execution_time', + 'session.cookie_domain', + 'session.cookie_lifetime', + 'session.cookie_path', + 'session.name', + 'session.serialize_handler', + 'upload_max_filesize', + 'xmlrpc_error_number', + 'session.auto_start', + 'always_populate_raw_post_data', + 'suhosin.session.cryptkey', + 'suhosin.session.cryptraddr', + 'suhosin.session.checkraddr', + 'suhosin.cookie.cryptkey', + 'suhosin.cookie.plainlist', + 'suhosin.cookie.cryptraddr', + 'suhosin.cookie.checkraddr', + 'suhosin.executor.func.blacklist', + 'suhosin.executor.eval.whitelist' + ), + 'php_flag' => array( + 'asp_tags', + 'display_errors', + 'display_startup_errors', + 'html_errors', + 'log_errors', + 'magic_quotes_gpc', + 'magic_quotes_runtime', + 'magic_quotes_sybase', + 'mail.add_x_header', + 'session.cookie_secure', + 'session.use_cookies', + 'short_open_tag', + 'track_errors', + 'xmlrpc_errors', + 'suhosin.simulation', + 'suhosin.session.encrypt', + 'suhosin.session.cryptua', + 'suhosin.session.cryptdocroot', + 'suhosin.cookie.encrypt', + 'suhosin.cookie.cryptua', + 'suhosin.cookie.cryptdocroot', + 'suhosin.executor.disable_eval', + 'mbstring.func_overload' + ), + 'php_admin_value' => array( + 'cgi.redirect_status_env', + 'date.timezone', + 'disable_classes', + 'disable_functions', + 'error_log', + 'gpc_order', + 'max_input_time', + 'max_input_vars', + 'memory_limit', + 'open_basedir', + 'output_buffering', + 'post_max_size', + 'precision', + 'sendmail_path', + 'session.gc_divisor', + 'session.gc_probability', + 'variables_order', + 'opcache.log_verbosity_level', + 'opcache.restrict_api', + 'opcache.revalidate_freq', + 'opcache.max_accelerated_files', + 'opcache.memory_consumption', + 'opcache.interned_strings_buffer' + ), + 'php_admin_flag' => array( + 'allow_call_time_pass_reference', + 'allow_url_fopen', + 'allow_url_include', + 'auto_detect_line_endings', + 'cgi.fix_pathinfo', + 'cgi.force_redirect', + 'enable_dl', + 'expose_php', + 'file_uploads', + 'ignore_repeated_errors', + 'ignore_repeated_source', + 'log_errors', + 'register_argc_argv', + 'report_memleaks', + 'opcache.enable', + 'opcache.consistency_checks', + 'opcache.dups_fix', + 'opcache.load_comments', + 'opcache.revalidate_path', + 'opcache.save_comments', + 'opcache.use_cwd', + 'opcache.validate_timestamps', + 'opcache.fast_shutdown' + ) ); /** * main constructor - */ - public function __construct($domain) { + */ + public function __construct($domain) + { $this->_domain = $domain; + $this->_readFpmConfig($domain['fpm_config_id']); + } + + private function _readFpmConfig($fpm_config_id) + { + $stmt = Database::prepare("SELECT * FROM `" . TABLE_PANEL_FPMDAEMONS . "` WHERE `id` = :id"); + $this->_fpm_cfg = Database::pexecute_first($stmt, array( + 'id' => $fpm_config_id + )); } /** @@ -158,47 +177,47 @@ class phpinterface_fpm { * * @param array $phpconfig */ - public function createConfig($phpconfig) { - + public function createConfig($phpconfig) + { $fh = @fopen($this->getConfigFile(), 'w'); - + if ($fh) { - $fpm_pm = Settings::Get('phpfpm.pm'); - $fpm_children = (int)Settings::Get('phpfpm.max_children'); - $fpm_start_servers = (int)Settings::Get('phpfpm.start_servers'); - $fpm_min_spare_servers = (int)Settings::Get('phpfpm.min_spare_servers'); - $fpm_max_spare_servers = (int)Settings::Get('phpfpm.max_spare_servers'); - $fpm_requests = (int)Settings::Get('phpfpm.max_requests'); - $fpm_process_idle_timeout = (int)Settings::Get('phpfpm.idle_timeout'); - + $fpm_pm = $this->_fpm_cfg['pm']; + $fpm_children = (int) $this->_fpm_cfg['max_children']; + $fpm_start_servers = (int) $this->_fpm_cfg['start_servers']; + $fpm_min_spare_servers = (int) $this->_fpm_cfg['min_spare_servers']; + $fpm_max_spare_servers = (int) $this->_fpm_cfg['max_spare_servers']; + $fpm_requests = (int) $this->_fpm_cfg['max_requests']; + $fpm_process_idle_timeout = (int) $this->_fpm_cfg['idle_timeout']; + if ($fpm_children == 0) { $fpm_children = 1; } - - $fpm_config = ';PHP-FPM configuration for "'.$this->_domain['domain'].'" created on ' . date("Y.m.d H:i:s") . "\n"; - $fpm_config.= '['.$this->_domain['domain'].']'."\n"; - $fpm_config.= 'listen = '.$this->getSocketFile()."\n"; + + $fpm_config = ';PHP-FPM configuration for "' . $this->_domain['domain'] . '" created on ' . date("Y.m.d H:i:s") . "\n"; + $fpm_config .= '[' . $this->_domain['domain'] . ']' . "\n"; + $fpm_config .= 'listen = ' . $this->getSocketFile() . "\n"; if ($this->_domain['loginname'] == 'froxlor.panel') { - $fpm_config.= 'listen.owner = '.$this->_domain['guid']."\n"; - $fpm_config.= 'listen.group = '.$this->_domain['guid']."\n"; + $fpm_config .= 'listen.owner = ' . $this->_domain['guid'] . "\n"; + $fpm_config .= 'listen.group = ' . $this->_domain['guid'] . "\n"; } else { - $fpm_config.= 'listen.owner = '.$this->_domain['loginname']."\n"; - $fpm_config.= 'listen.group = '.$this->_domain['loginname']."\n"; + $fpm_config .= 'listen.owner = ' . $this->_domain['loginname'] . "\n"; + $fpm_config .= 'listen.group = ' . $this->_domain['loginname'] . "\n"; } // see #1418 why this is 0660 - $fpm_config.= 'listen.mode = 0660'."\n"; - + $fpm_config .= 'listen.mode = 0660' . "\n"; + if ($this->_domain['loginname'] == 'froxlor.panel') { - $fpm_config.= 'user = '.$this->_domain['guid']."\n"; - $fpm_config.= 'group = '.$this->_domain['guid']."\n"; + $fpm_config .= 'user = ' . $this->_domain['guid'] . "\n"; + $fpm_config .= 'group = ' . $this->_domain['guid'] . "\n"; } else { - $fpm_config.= 'user = '.$this->_domain['loginname']."\n"; - $fpm_config.= 'group = '.$this->_domain['loginname']."\n"; + $fpm_config .= 'user = ' . $this->_domain['loginname'] . "\n"; + $fpm_config .= 'group = ' . $this->_domain['loginname'] . "\n"; } - - $fpm_config.= 'pm = '.$fpm_pm."\n"; - $fpm_config.= 'pm.max_children = '.$fpm_children."\n"; - + + $fpm_config .= 'pm = ' . $fpm_pm . "\n"; + $fpm_config .= 'pm.max_children = ' . $fpm_children . "\n"; + if ($fpm_pm == 'dynamic') { // honor max_children if ($fpm_children < $fpm_min_spare_servers) { @@ -214,35 +233,35 @@ class phpinterface_fpm { if ($fpm_start_servers > $fpm_max_spare_servers) { $fpm_start_servers = $fpm_max_spare_servers; } - $fpm_config.= 'pm.start_servers = '.$fpm_start_servers."\n"; - $fpm_config.= 'pm.min_spare_servers = '.$fpm_min_spare_servers."\n"; - $fpm_config.= 'pm.max_spare_servers = '.$fpm_max_spare_servers."\n"; + $fpm_config .= 'pm.start_servers = ' . $fpm_start_servers . "\n"; + $fpm_config .= 'pm.min_spare_servers = ' . $fpm_min_spare_servers . "\n"; + $fpm_config .= 'pm.max_spare_servers = ' . $fpm_max_spare_servers . "\n"; } elseif ($fpm_pm == 'ondemand') { - $fpm_config.= 'pm.process_idle_timeout = '.$fpm_process_idle_timeout."\n"; + $fpm_config .= 'pm.process_idle_timeout = ' . $fpm_process_idle_timeout . "\n"; } - - $fpm_config.= 'pm.max_requests = '.$fpm_requests."\n"; - + + $fpm_config .= 'pm.max_requests = ' . $fpm_requests . "\n"; + // possible slowlog configs if ($phpconfig['fpm_slowlog'] == '1') { - $fpm_config.= 'request_terminate_timeout = ' . $phpconfig['fpm_reqterm'] . "\n"; - $fpm_config.= 'request_slowlog_timeout = ' . $phpconfig['fpm_reqslow'] . "\n"; + $fpm_config .= 'request_terminate_timeout = ' . $phpconfig['fpm_reqterm'] . "\n"; + $fpm_config .= 'request_slowlog_timeout = ' . $phpconfig['fpm_reqslow'] . "\n"; $slowlog = makeCorrectFile(Settings::Get('system.logfiles_directory') . '/' . $this->_domain['loginname'] . '-php-slow.log'); - $fpm_config.= 'slowlog = ' . $slowlog . "\n"; - $fpm_config.= 'catch_workers_output = yes' . "\n"; + $fpm_config .= 'slowlog = ' . $slowlog . "\n"; + $fpm_config .= 'catch_workers_output = yes' . "\n"; } - - $fpm_config.= ';chroot = '.makeCorrectDir($this->_domain['documentroot'])."\n"; - + + $fpm_config .= ';chroot = ' . makeCorrectDir($this->_domain['documentroot']) . "\n"; + $tmpdir = makeCorrectDir(Settings::Get('phpfpm.tmpdir') . '/' . $this->_domain['loginname'] . '/'); - if (!is_dir($tmpdir)) { + if (! is_dir($tmpdir)) { $this->getTempDir(); } - - $fpm_config.= 'env[TMP] = '.$tmpdir."\n"; - $fpm_config.= 'env[TMPDIR] = '.$tmpdir."\n"; - $fpm_config.= 'env[TEMP] = '.$tmpdir."\n"; - + + $fpm_config .= 'env[TMP] = ' . $tmpdir . "\n"; + $fpm_config .= 'env[TMPDIR] = ' . $tmpdir . "\n"; + $fpm_config .= 'env[TEMP] = ' . $tmpdir . "\n"; + $openbasedir = ''; if ($this->_domain['loginname'] != 'froxlor.panel') { if ($this->_domain['openbasedir'] == '1') { @@ -251,47 +270,45 @@ class phpinterface_fpm { foreach ($_custom_openbasedir as $cobd) { $_phpappendopenbasedir .= appendOpenBasedirPath($cobd); } - + $_custom_openbasedir = explode(':', Settings::Get('system.phpappendopenbasedir')); foreach ($_custom_openbasedir as $cobd) { $_phpappendopenbasedir .= appendOpenBasedirPath($cobd); } - - if ($this->_domain['openbasedir_path'] == '0' - && strstr($this->_domain['documentroot'], ":") === false - ) { + + if ($this->_domain['openbasedir_path'] == '0' && strstr($this->_domain['documentroot'], ":") === false) { $openbasedir = appendOpenBasedirPath($this->_domain['documentroot'], true); } else { $openbasedir = appendOpenBasedirPath($this->_domain['customerroot'], true); } - + $openbasedir .= appendOpenBasedirPath($this->getTempDir()); $openbasedir .= $_phpappendopenbasedir; } } - $fpm_config.= 'php_admin_value[session.save_path] = ' . makeCorrectDir(Settings::Get('phpfpm.tmpdir') . '/' . $this->_domain['loginname'] . '/') . "\n"; - $fpm_config.= 'php_admin_value[upload_tmp_dir] = ' . makeCorrectDir(Settings::Get('phpfpm.tmpdir') . '/' . $this->_domain['loginname'] . '/') . "\n"; - + $fpm_config .= 'php_admin_value[session.save_path] = ' . makeCorrectDir(Settings::Get('phpfpm.tmpdir') . '/' . $this->_domain['loginname'] . '/') . "\n"; + $fpm_config .= 'php_admin_value[upload_tmp_dir] = ' . makeCorrectDir(Settings::Get('phpfpm.tmpdir') . '/' . $this->_domain['loginname'] . '/') . "\n"; + $admin = $this->_getAdminData($this->_domain['adminid']); $php_ini_variables = array( - 'SAFE_MODE' => 'Off', // keep this for compatibility, just in case - 'PEAR_DIR' => Settings::Get('phpfpm.peardir'), - 'TMP_DIR' => $this->getTempDir(), - 'CUSTOMER_EMAIL' => $this->_domain['email'], - 'ADMIN_EMAIL' => $admin['email'], - 'DOMAIN' => $this->_domain['domain'], - 'CUSTOMER' => $this->_domain['loginname'], - 'ADMIN' => $admin['loginname'], - 'OPEN_BASEDIR' => $openbasedir, - 'OPEN_BASEDIR_C' => '', - 'OPEN_BASEDIR_GLOBAL' => Settings::Get('system.phpappendopenbasedir'), - 'DOCUMENT_ROOT' => makeCorrectDir($this->_domain['documentroot']) + 'SAFE_MODE' => 'Off', // keep this for compatibility, just in case + 'PEAR_DIR' => Settings::Get('phpfpm.peardir'), + 'TMP_DIR' => $this->getTempDir(), + 'CUSTOMER_EMAIL' => $this->_domain['email'], + 'ADMIN_EMAIL' => $admin['email'], + 'DOMAIN' => $this->_domain['domain'], + 'CUSTOMER' => $this->_domain['loginname'], + 'ADMIN' => $admin['loginname'], + 'OPEN_BASEDIR' => $openbasedir, + 'OPEN_BASEDIR_C' => '', + 'OPEN_BASEDIR_GLOBAL' => Settings::Get('system.phpappendopenbasedir'), + 'DOCUMENT_ROOT' => makeCorrectDir($this->_domain['documentroot']) ); - + $phpini = replace_variables($phpconfig['phpsettings'], $php_ini_variables); $phpini_array = explode("\n", $phpini); - - $fpm_config.= "\n\n"; + + $fpm_config .= "\n\n"; foreach ($phpini_array as $inisection) { $is = explode("=", $inisection); foreach ($this->_ini as $sec => $possibles) { @@ -300,17 +317,17 @@ class phpinterface_fpm { if (trim($is[0]) == 'open_basedir' && $openbasedir == '') { continue; } - $fpm_config.= $sec.'['.trim($is[0]).'] = ' . trim($is[1]) . "\n"; + $fpm_config .= $sec . '[' . trim($is[0]) . '] = ' . trim($is[1]) . "\n"; } } } - + // now check if 'sendmail_path' has not beed set in the custom-php.ini // if not we use our fallback-default as usual if (strpos($fpm_config, 'php_admin_value[sendmail_path]') === false) { - $fpm_config.= 'php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f '.$this->_domain['email']."\n"; + $fpm_config .= 'php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f ' . $this->_domain['email'] . "\n"; } - + fwrite($fh, $fpm_config, strlen($fpm_config)); fclose($fh); } @@ -322,108 +339,117 @@ class phpinterface_fpm { * * @param string $phpconfig */ - public function createIniFile($phpconfig) { + public function createIniFile($phpconfig) + { return; } /** * fpm-config file * - * @param boolean $createifnotexists create the directory if it does not exist - * + * @param boolean $createifnotexists + * create the directory if it does not exist + * * @return string the full path to the file */ - public function getConfigFile($createifnotexists = true) { - - $configdir = makeCorrectDir(Settings::Get('phpfpm.configdir')); - $config = makeCorrectFile($configdir.'/'.$this->_domain['domain'].'.conf'); - - if (!is_dir($configdir) && $createifnotexists) { + public function getConfigFile($createifnotexists = true) + { + $configdir = $this->_fpm_cfg['config_path']; + $config = makeCorrectFile($configdir . '/' . $this->_domain['domain'] . '.conf'); + + if (! is_dir($configdir) && $createifnotexists) { safe_exec('mkdir -p ' . escapeshellarg($configdir)); } - + return $config; } /** * return path of fpm-socket file * - * @param boolean $createifnotexists create the directory if it does not exist - * + * @param boolean $createifnotexists + * create the directory if it does not exist + * * @return string the full path to the socket */ - public function getSocketFile($createifnotexists = true) { - + public function getSocketFile($createifnotexists = true) + { $socketdir = makeCorrectDir(Settings::Get('phpfpm.fastcgi_ipcdir')); - $socket = strtolower(makeCorrectFile($socketdir.'/'.$this->_domain['loginname'].'-'.$this->_domain['domain'].'-php-fpm.socket')); - - if (!is_dir($socketdir) && $createifnotexists) { - safe_exec('mkdir -p '.escapeshellarg($socketdir)); - safe_exec('chown -R '.Settings::Get('system.httpuser').':'.Settings::Get('system.httpgroup').' '.escapeshellarg($socketdir)); + // add fpm-config-id to filename so it's unique for the fpm-daemon and doesn't interfere with running configs when reuilding + $socket = strtolower(makeCorrectFile($socketdir . '/' . $this->_domain['fpm_config_id'] . '-' . $this->_domain['loginname'] . '-' . $this->_domain['domain'] . '-php-fpm.socket')); + + if (! is_dir($socketdir) && $createifnotexists) { + safe_exec('mkdir -p ' . escapeshellarg($socketdir)); + safe_exec('chown -R ' . Settings::Get('system.httpuser') . ':' . Settings::Get('system.httpgroup') . ' ' . escapeshellarg($socketdir)); } - + return $socket; } /** * fpm-temp directory * - * @param boolean $createifnotexists create the directory if it does not exist - * + * @param boolean $createifnotexists + * create the directory if it does not exist + * * @return string the directory */ - public function getTempDir($createifnotexists = true) { - + public function getTempDir($createifnotexists = true) + { $tmpdir = makeCorrectDir(Settings::Get('phpfpm.tmpdir') . '/' . $this->_domain['loginname'] . '/'); - - if (!is_dir($tmpdir) && $createifnotexists) { + + if (! is_dir($tmpdir) && $createifnotexists) { safe_exec('mkdir -p ' . escapeshellarg($tmpdir)); safe_exec('chown -R ' . $this->_domain['guid'] . ':' . $this->_domain['guid'] . ' ' . escapeshellarg($tmpdir)); safe_exec('chmod 0750 ' . escapeshellarg($tmpdir)); } - + return $tmpdir; } /** * fastcgi-fakedirectory directory * - * @param boolean $createifnotexists create the directory if it does not exist - * + * @param boolean $createifnotexists + * create the directory if it does not exist + * * @return string the directory */ - public function getAliasConfigDir($createifnotexists = true) { - + public function getAliasConfigDir($createifnotexists = true) + { + // ensure default... if (Settings::Get('phpfpm.aliasconfigdir') == null) { Settings::Set('phpfpm.aliasconfigdir', '/var/www/php-fpm'); } - + $configdir = makeCorrectDir(Settings::Get('phpfpm.aliasconfigdir') . '/' . $this->_domain['loginname'] . '/' . $this->_domain['domain'] . '/'); - if (!is_dir($configdir) && $createifnotexists) { + if (! is_dir($configdir) && $createifnotexists) { safe_exec('mkdir -p ' . escapeshellarg($configdir)); safe_exec('chown ' . $this->_domain['guid'] . ':' . $this->_domain['guid'] . ' ' . escapeshellarg($configdir)); } - + return $configdir; } /** * return the admin-data of a specific admin * - * @param int $adminid id of the admin-user - * + * @param int $adminid + * id of the admin-user + * * @return array */ - private function _getAdminData($adminid) { - + private function _getAdminData($adminid) + { $adminid = intval($adminid); - - if (!isset($this->_admin_cache[$adminid])) { + + if (! isset($this->_admin_cache[$adminid])) { $stmt = Database::prepare(" - SELECT `email`, `loginname` FROM `" . TABLE_PANEL_ADMINS . "` WHERE `adminid` = :id" - ); - $this->_admin_cache[$adminid] = Database::pexecute_first($stmt, array('id' => $adminid)); + SELECT `email`, `loginname` FROM `" . TABLE_PANEL_ADMINS . "` WHERE `adminid` = :id"); + $this->_admin_cache[$adminid] = Database::pexecute_first($stmt, array( + 'id' => $adminid + )); } return $this->_admin_cache[$adminid]; } diff --git a/lib/classes/webserver/class.ConfigIO.php b/lib/classes/webserver/class.ConfigIO.php index cbe79b10..10fe1b50 100644 --- a/lib/classes/webserver/class.ConfigIO.php +++ b/lib/classes/webserver/class.ConfigIO.php @@ -17,13 +17,14 @@ * @since 0.9.29 * */ - -class ConfigIO { +class ConfigIO +{ /** * constructor */ - public function __construct() {} + public function __construct() + {} /** * clean up former created configs, including (if enabled) @@ -32,39 +33,40 @@ class ConfigIO { * * @return null */ - public function cleanUp() { - + public function cleanUp() + { + // old error logs $this->_cleanErrLogs(); - + // awstats files $this->_cleanAwstatsFiles(); - + // fcgid files $this->_cleanFcgidFiles(); - + // php-fpm files $this->_cleanFpmFiles(); - + // clean webserver-configs $this->_cleanWebserverConfigs(); - + // old htpasswd files $this->_cleanHtpasswdFiles(); - + // customer-specified ssl-certificates $this->_cleanCustomerSslCerts(); } - private function _cleanErrLogs() { - - $err_dir = makeCorrectDir(FROXLOR_INSTALL_DIR."/logs/"); - if (@is_dir($err_dir)) { - // now get rid of old stuff - //(but append /*.log so we don't delete the directory) - $err_dir.='/*.log'; - safe_exec('rm -rf '. makeCorrectFile($err_dir)); - } + private function _cleanErrLogs() + { + $err_dir = makeCorrectDir(FROXLOR_INSTALL_DIR . "/logs/"); + if (@is_dir($err_dir)) { + // now get rid of old stuff + // (but append /*.log so we don't delete the directory) + $err_dir .= '/*.log'; + safe_exec('rm -rf ' . makeCorrectFile($err_dir)); + } } /** @@ -73,8 +75,9 @@ class ConfigIO { * * @return null */ - private function _cleanCustomerSslCerts() { - + private function _cleanCustomerSslCerts() + { + /* * only clean up if we're actually using SSL */ @@ -82,14 +85,14 @@ class ConfigIO { // get correct directory $configdir = $this->_getFile('system', 'customer_ssl_path'); if ($configdir !== false) { - + $configdir = makeCorrectDir($configdir); - + if (@is_dir($configdir)) { // now get rid of old stuff - //(but append /* so we don't delete the directory) - $configdir.='/*'; - safe_exec('rm -rf '. makeCorrectFile($configdir)); + // (but append /* so we don't delete the directory) + $configdir .= '/*'; + safe_exec('rm -rf ' . makeCorrectFile($configdir)); } } } @@ -100,39 +103,38 @@ class ConfigIO { * * @return null */ - private function _cleanWebserverConfigs() { - + private function _cleanWebserverConfigs() + { + // get directories $configdirs = array(); $dir = $this->_getFile('system', 'apacheconf_vhost'); if ($dir !== false) $configdirs[] = makeCorrectDir($dir); - + $dir = $this->_getFile('system', 'apacheconf_diroptions'); if ($dir !== false) $configdirs[] = makeCorrectDir($dir); - + // file pattern $pattern = "/^([0-9]){2}_(froxlor|syscp)_(.+)\.conf$/"; - + // check ALL the folders foreach ($configdirs as $config_dir) { - + // check directory if (@is_dir($config_dir)) { - + // create directory iterator - $its = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($config_dir) - ); - + $its = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($config_dir)); + // iterate through all subdirs, // look for vhost/diroption files // and delete them - foreach ($its as $fullFileName => $it ) { + foreach ($its as $fullFileName => $it) { if ($it->isFile() && preg_match($pattern, $it->getFilename())) { // remove file - safe_exec('rm -f '. escapeshellarg(makeCorrectFile($its->getPathname()))); + safe_exec('rm -f ' . escapeshellarg(makeCorrectFile($its->getPathname()))); } } } @@ -144,19 +146,20 @@ class ConfigIO { * * @return null */ - private function _cleanHtpasswdFiles() { - + private function _cleanHtpasswdFiles() + { + // get correct directory $configdir = $this->_getFile('system', 'apacheconf_htpasswddir'); - + if ($configdir !== false) { $configdir = makeCorrectDir($configdir); - + if (@is_dir($configdir)) { // now get rid of old stuff - //(but append /* so we don't delete the directory) - $configdir.='/*'; - safe_exec('rm -rf '. makeCorrectFile($configdir)); + // (but append /* so we don't delete the directory) + $configdir .= '/*'; + safe_exec('rm -rf ' . makeCorrectFile($configdir)); } } } @@ -166,37 +169,36 @@ class ConfigIO { * * @return null */ - private function _cleanAwstatsFiles() { - + private function _cleanAwstatsFiles() + { if (Settings::Get('system.awstats_enabled') == '0') { return; } - - //dhr: cleanout froxlor-generated awstats configs prior to re-creation + + // dhr: cleanout froxlor-generated awstats configs prior to re-creation $awstatsclean['header'] = "## GENERATED BY FROXLOR\n"; $awstatsclean['headerold'] = "## GENERATED BY SYSCP\n"; $awstatsclean['path'] = $this->_getFile('system', 'awstats_conf'); - + /** * don't do anything if the directory does not exist - * (e.g. awstats not installed yet or whatever) + * (e.g. + * awstats not installed yet or whatever) * fixes #45 - */ + */ if ($awstatsclean['path'] !== false && is_dir($awstatsclean['path'])) { $awstatsclean['dir'] = dir($awstatsclean['path']); while ($awstatsclean['entry'] = $awstatsclean['dir']->read()) { - $awstatsclean['fullentry'] = makeCorrectFile($awstatsclean['path'].'/'.$awstatsclean['entry']); + $awstatsclean['fullentry'] = makeCorrectFile($awstatsclean['path'] . '/' . $awstatsclean['entry']); /** * don't do anything if the file does not exist - */ + */ if (@file_exists($awstatsclean['fullentry'])) { $awstatsclean['fh'] = fopen($awstatsclean['fullentry'], 'r'); - $awstatsclean['headerRead'] = fgets($awstatsclean['fh'], strlen($awstatsclean['header'])+1); + $awstatsclean['headerRead'] = fgets($awstatsclean['fh'], strlen($awstatsclean['header']) + 1); fclose($awstatsclean['fh']); - - if ($awstatsclean['headerRead'] == $awstatsclean['header'] - || $awstatsclean['headerRead'] == $awstatsclean['headerold'] - ) { + + if ($awstatsclean['headerRead'] == $awstatsclean['header'] || $awstatsclean['headerRead'] == $awstatsclean['headerold']) { $awstats_conf_file = makeCorrectFile($awstatsclean['fullentry']); @unlink($awstats_conf_file); } @@ -204,7 +206,7 @@ class ConfigIO { } } unset($awstatsclean); - //end dhr + // end dhr } /** @@ -212,39 +214,37 @@ class ConfigIO { * * @return null */ - private function _cleanFcgidFiles() { - + private function _cleanFcgidFiles() + { if (Settings::Get('system.mod_fcgid') == '0') { return; } - + // get correct directory $configdir = $this->_getFile('system', 'mod_fcgid_configdir'); if ($configdir !== false) { - + $configdir = makeCorrectDir($configdir); - + if (@is_dir($configdir)) { // create directory iterator - $its = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator($configdir) - ); - + $its = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configdir)); + // iterate through all subdirs, // look for php-fcgi-starter files // and take immutable-flag away from them // so we can delete them :) - foreach ($its as $fullFileName => $it ) { + foreach ($its as $fullFileName => $it) { if ($it->isFile() && $it->getFilename() == 'php-fcgi-starter') { // set chattr -i removeImmutable($its->getPathname()); } } - + // now get rid of old stuff - //(but append /* so we don't delete the directory) - $configdir.='/*'; - safe_exec('rm -rf '. makeCorrectFile($configdir)); + // (but append /* so we don't delete the directory) + $configdir .= '/*'; + safe_exec('rm -rf ' . makeCorrectFile($configdir)); } } } @@ -254,33 +254,36 @@ class ConfigIO { * * @return null */ - private function _cleanFpmFiles() { - + private function _cleanFpmFiles() + { if (Settings::Get('phpfpm.enabled') == '0') { return; } - - // get correct directory - $configdir = $this->_getFile('phpfpm', 'configdir'); - if ($configdir !== false) { - - $configdir = makeCorrectDir($configdir); - + + // get all fpm config paths + $fpmconf_sel = Database::prepare("SELECT config_dir FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); + Database::pexecute($fpmconf_sel); + $fpmconf_paths = $fpmconf_sel->fetchAll(PDO::FETCH_ASSOC); + // clean all php-fpm config-dirs + foreach ($fpmconf_paths as $configdir) { + $configdir = makeCorrectDir($configdir['config_dir']); if (@is_dir($configdir)) { // now get rid of old stuff - //(but append /* so we don't delete the directory) - $configdir.='/*'; - safe_exec('rm -rf '. makeCorrectFile($configdir)); + // (but append /* so we don't delete the directory) + $configdir .= '/*'; + safe_exec('rm -rf ' . makeCorrectFile($configdir)); + } else { + safe_exec('mkdir -p ' . $configdir); } } - + // also remove aliasconfigdir #1273 $aliasconfigdir = $this->_getFile('phpfpm', 'aliasconfigdir'); if ($aliasconfigdir !== false) { $aliasconfigdir = makeCorrectDir($aliasconfigdir); if (@is_dir($aliasconfigdir)) { - $aliasconfigdir.='/*'; - safe_exec('rm -rf '. makeCorrectFile($aliasconfigdir)); + $aliasconfigdir .= '/*'; + safe_exec('rm -rf ' . makeCorrectFile($aliasconfigdir)); } } } @@ -288,17 +291,21 @@ class ConfigIO { /** * returns a file/direcotry from the settings and checks whether it exists * - * @param string $group settings-group - * @param string $varname var-name - * @param boolean $check_exists check if the file exists - * + * @param string $group + * settings-group + * @param string $varname + * var-name + * @param boolean $check_exists + * check if the file exists + * * @return string|boolean complete path including filename if any or false on error */ - private function _getFile($group, $varname, $check_exists = true) { - + private function _getFile($group, $varname, $check_exists = true) + { + // read from settings - $file = Settings::Get($group.'.'.$varname); - + $file = Settings::Get($group . '.' . $varname); + // check whether it exists if ($check_exists && @file_exists($file) == false) { return false; diff --git a/lib/classes/webserver/class.WebserverBase.php b/lib/classes/webserver/class.WebserverBase.php index 8f7c27c5..5181bd25 100644 --- a/lib/classes/webserver/class.WebserverBase.php +++ b/lib/classes/webserver/class.WebserverBase.php @@ -17,8 +17,8 @@ * @since 0.9.31 * */ - -class WebserverBase { +class WebserverBase +{ /** * returns an array with all entries required for all @@ -26,8 +26,8 @@ class WebserverBase { * * @return array */ - public static function getVhostsToCreate() { - + public static function getVhostsToCreate() + { $query = "SELECT `d`.*, `pd`.`domain` AS `parentdomain`, `c`.`loginname`, `d`.`phpsettingid`, `c`.`adminid`, `c`.`guid`, `c`.`email`, `c`.`documentroot` AS `customerroot`, `c`.`deactivated`, @@ -35,20 +35,20 @@ class WebserverBase { `d`.`phpenabled` AS `phpenabled_vhost`, `d`.`mod_fcgid_starter`,`d`.`mod_fcgid_maxrequests`, `d`.`ocsp_stapling` - FROM `".TABLE_PANEL_DOMAINS."` `d` + FROM `" . TABLE_PANEL_DOMAINS . "` `d` - LEFT JOIN `".TABLE_PANEL_CUSTOMERS."` `c` USING(`customerid`) - LEFT JOIN `".TABLE_PANEL_DOMAINS."` `pd` ON (`pd`.`id` = `d`.`parentdomainid`) + LEFT JOIN `" . TABLE_PANEL_CUSTOMERS . "` `c` USING(`customerid`) + LEFT JOIN `" . TABLE_PANEL_DOMAINS . "` `pd` ON (`pd`.`id` = `d`.`parentdomainid`) WHERE `d`.`aliasdomain` IS NULL AND `d`.`email_only` <> '1' ORDER BY `d`.`parentdomainid` DESC, `d`.`iswildcarddomain`, `d`.`domain` ASC; "; - + $result_domains_stmt = Database::query($query); - + $domains = array(); while ($domain = $result_domains_stmt->fetch(PDO::FETCH_ASSOC)) { - + // set whole domain $domains[$domain['domain']] = $domain; // set empty-defaults for non-ssl @@ -57,31 +57,46 @@ class WebserverBase { $domains[$domain['domain']]['ssl_key_file'] = ''; $domains[$domain['domain']]['ssl_ca_file'] = ''; $domains[$domain['domain']]['ssl_cert_chainfile'] = ''; - + // now, if the domain has an ssl ip/port assigned, get // the corresponding information from the db if (domainHasSslIpPort($domain['id'])) { - + $ip_stmt = Database::prepare(" SELECT `di`.`id_domain` , `p`.`ssl`, `p`.`ssl_cert_file`, `p`.`ssl_key_file`, `p`.`ssl_ca_file`, `p`.`ssl_cert_chainfile` - FROM `".TABLE_DOMAINTOIP."` `di`, `".TABLE_PANEL_IPSANDPORTS."` `p` + FROM `" . TABLE_DOMAINTOIP . "` `di`, `" . TABLE_PANEL_IPSANDPORTS . "` `p` WHERE `p`.`id` = `di`.`id_ipandports` AND `di`.`id_domain` = :domainid AND `p`.`ssl` = '1' "); - $ssl_ip = Database::pexecute_first($ip_stmt, array('domainid' => $domain['id'])); - + $ssl_ip = Database::pexecute_first($ip_stmt, array( + 'domainid' => $domain['id'] + )); + // set ssl info for domain $domains[$domain['domain']]['ssl'] = '1'; $domains[$domain['domain']]['ssl_cert_file'] = $ssl_ip['ssl_cert_file']; $domains[$domain['domain']]['ssl_key_file'] = $ssl_ip['ssl_key_file']; $domains[$domain['domain']]['ssl_ca_file'] = $ssl_ip['ssl_ca_file']; $domains[$domain['domain']]['ssl_cert_chainfile'] = $ssl_ip['ssl_cert_chainfile']; - + } + + // read fpm-config-id if using fpm + if ((int) Settings::Get('phpfpm.enabled') == 1) { + $fpm_sel_stmt = Database::prepare(" + SELECT f.id FROM `" . TABLE_PANEL_FPMDAEMONS . "` f + LEFT JOIN `" . TABLE_PANEL_PHPCONFIGS . "` p ON p.fpmsettingid = f.id + WHERE p.id = :phpconfigid + "); + $fpm_config = Database::pexecute_first($fpm_sel_stmt, array( + 'phpconfigid' => $domain['phpsettingid'] + )); + if ($fpm_config) { + $domains[$domain['domain']]['fpm_config_id'] = $fpm_config['id']; + } } } - + return $domains; } - } diff --git a/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php b/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php new file mode 100644 index 00000000..88a1bb8b --- /dev/null +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php @@ -0,0 +1,89 @@ + (2010-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Formfields + * + */ + +return array( + 'fpmconfig_add' => array( + 'title' => $lng['admin']['phpsettings']['addsettings'], + 'image' => 'icons/phpsettings_add.png', + 'sections' => array( + 'section_a' => array( + 'title' => $lng['admin']['phpsettings']['addsettings'], + 'image' => 'icons/phpsettings_add.png', + 'fields' => array( + 'description' => array( + 'label' => $lng['admin']['phpsettings']['description'], + 'type' => 'text', + 'maxlength' => 50 + ), + 'reload_cmd' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['reload'], + 'type' => 'text', + 'maxlength' => 255, + 'value' => 'service php7.0-fpm restart' + ), + 'config_dir' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['configdir'], + 'type' => 'text', + 'maxlength' => 255, + 'value' => '/etc/php/7.0/fpm/pool.d/' + ), + 'pm' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['pm'], + 'type' => 'select', + 'select_var' => $pm_select + ), + 'max_children' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['max_children']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['max_children']['description'], + 'type' => 'int', + 'value' => 1 + ), + 'start_servers' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['start_servers']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['start_servers']['description'], + 'type' => 'int', + 'value' => 20 + ), + 'min_spare_servers' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['min_spare_servers']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['min_spare_servers']['description'], + 'type' => 'int', + 'value' => 5 + ), + 'max_spare_servers' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['max_spare_servers']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['max_spare_servers']['description'], + 'type' => 'int', + 'value' => 35 + ), + 'max_requests' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['max_requests']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['max_requests']['description'], + 'type' => 'int', + 'value' => 0 + ), + 'idle_timeout' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['idle_timeout']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['idle_timeout']['description'], + 'type' => 'int', + 'value' => 30 + ) + ) + ) + ) + ) +); diff --git a/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php new file mode 100644 index 00000000..a06592ed --- /dev/null +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php @@ -0,0 +1,91 @@ + (2010-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Formfields + * + */ + +return array( + 'fpmconfig_edit' => array( + 'title' => $lng['admin']['phpsettings']['editsettings'], + 'image' => 'icons/phpsettings_edit.png', + 'sections' => array( + 'section_a' => array( + 'title' => $lng['admin']['phpsettings']['editsettings'], + 'image' => 'icons/phpsettings_edit.png', + 'fields' => array( + 'description' => array( + 'label' => $lng['admin']['phpsettings']['description'], + 'type' => 'text', + 'maxlength' => 50, + 'value' => $result['description'] + ), + 'reload_cmd' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['reload'], + 'type' => 'text', + 'maxlength' => 255, + 'value' => $result['reload_cmd'] + ), + 'config_dir' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['configdir'], + 'type' => 'text', + 'maxlength' => 255, + 'value' => $result['config_dir'] + ), + 'pm' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['pm'], + 'type' => 'select', + 'select_var' => array('static' => 'static', 'dynamic' => 'dynamic', 'ondemand' => 'ondemand'), + 'value' => $result['pm'] + ), + 'max_children' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['max_children']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['max_children']['description'], + 'type' => 'int', + 'value' => $result['max_children'] + ), + 'start_servers' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['start_servers']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['start_servers']['description'], + 'type' => 'int', + 'value' => $result['start_servers'] + ), + 'min_spare_servers' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['min_spare_servers']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['min_spare_servers']['description'], + 'type' => 'int', + 'value' => $result['min_spare_servers'] + ), + 'max_spare_servers' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['max_spare_servers']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['max_spare_servers']['description'], + 'type' => 'int', + 'value' => $result['max_spare_servers'] + ), + 'max_requests' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['max_requests']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['max_requests']['description'], + 'type' => 'int', + 'value' => $result['max_requests'] + ), + 'idle_timeout' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['idle_timeout']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['idle_timeout']['description'], + 'type' => 'int', + 'value' => $result['idle_timeout'] + ) + ) + ) + ) + ) +); diff --git a/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php b/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php index 3bcc4922..07889120 100644 --- a/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php +++ b/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php @@ -36,6 +36,12 @@ return array( 'maxlength' => 255, 'value' => '/usr/bin/php-cgi' ), + 'fpmconfig' => array( + 'visible' => (Settings::Get('phpfpm.enabled') == 1 ? true : false), + 'label' => $lng['admin']['phpsettings']['fpmdesc'], + 'type' => 'select', + 'select_var' => $fpmconfigs + ), 'file_extensions' => array( 'visible' => (Settings::Get('system.mod_fcgid') == 1 ? true : false), 'label' => $lng['admin']['phpsettings']['file_extensions'], diff --git a/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php b/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php index d3a9828f..9ae736ed 100644 --- a/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php +++ b/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php @@ -37,6 +37,12 @@ return array( 'maxlength' => 255, 'value' => $result['binary'] ), + 'fpmconfig' => array( + 'visible' => (Settings::Get('phpfpm.enabled') == 1 ? true : false), + 'label' => $lng['admin']['phpsettings']['fpmdesc'], + 'type' => 'select', + 'select_var' => $fpmconfigs + ), 'file_extensions' => array( 'visible' => (Settings::Get('system.mod_fcgid') == 1 ? true : false), 'label' => $lng['admin']['phpsettings']['file_extensions'], diff --git a/lib/navigation/00.froxlor.main.php b/lib/navigation/00.froxlor.main.php index 18dc74ab..fd077c3c 100644 --- a/lib/navigation/00.froxlor.main.php +++ b/lib/navigation/00.froxlor.main.php @@ -279,6 +279,12 @@ return array( 'label' => $lng['menue']['phpsettings']['maintitle'], 'show_element' => (Settings::Get('system.mod_fcgid') == true || Settings::Get('phpfpm.enabled') == true) ), + array( + 'url' => 'admin_phpsettings.php?page=fpmdaemons', + 'label' => $lng['menue']['phpsettings']['fpmdaemons'], + 'required_resources' => 'change_serversettings', + 'show_element' => Settings::Get('phpfpm.enabled') == true + ), array( 'url' => 'admin_settings.php?page=phpinfo', 'label' => $lng['admin']['phpinfo'], diff --git a/lib/tables.inc.php b/lib/tables.inc.php index 39b37e24..c9f71112 100644 --- a/lib/tables.inc.php +++ b/lib/tables.inc.php @@ -51,5 +51,6 @@ define('TABLE_PANEL_DOMAINREDIRECTS', 'domain_redirect_codes'); define('TABLE_PANEL_DOMAIN_SSL_SETTINGS', 'domain_ssl_settings'); define('TABLE_DOMAINTOIP', 'panel_domaintoip'); define('TABLE_DOMAIN_DNS', 'domain_dns_entries'); +define('TABLE_PANEL_FPMDAEMONS', 'panel_fpmdaemons'); require dirname(__FILE__).'/version.inc.php'; diff --git a/lib/version.inc.php b/lib/version.inc.php index f6c42a62..f6174b9a 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201712310'; +$dbversion = '201801070'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index da777141..2a850d00 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -940,6 +940,7 @@ $lng['admin']['phpsettings']['phpinisettings'] = 'php.ini settings'; $lng['error']['nopermissionsorinvalidid'] = 'You don\'t have enough permissions to change these settings or an invalid id was given.'; $lng['panel']['view'] = 'view'; $lng['question']['phpsetting_reallydelete'] = 'Do you really want to delete these settings? All domains which use these settings currently will be changed to the default config.'; +$lng['question']['fpmsetting_reallydelete'] = 'Do you really want to delete these php-fpm settings? All php configurations which use these settings currently will be changed to the default config.'; $lng['admin']['phpsettings']['addnew'] = 'Create new settings'; $lng['error']['phpsettingidwrong'] = 'A PHP Configuration with this id doesn\'t exist'; $lng['error']['descriptioninvalid'] = 'The description is too short, too long or contains illegal characters.'; @@ -1001,6 +1002,7 @@ $lng['error']['ipportdoesntexist'] = 'The ip/port combination you have chosen do $lng['admin']['phpserversettings'] = 'PHP Settings'; $lng['admin']['phpsettings']['binary'] = 'PHP Binary'; +$lng['admin']['phpsettings']['fpmdesc'] = 'PHP-FPM config'; $lng['admin']['phpsettings']['file_extensions'] = 'File extensions'; $lng['admin']['phpsettings']['file_extensions_note'] = '(without dot, separated by spaces)'; $lng['admin']['mod_fcgid_maxrequests']['title'] = 'Maximum php requests for this domain (empty for default value)'; @@ -1656,7 +1658,7 @@ $lng['traffic']['mail'] = 'Mail (MiB)'; $lng['serversettings']['mod_fcgid']['idle_timeout']['title'] = 'Idle Timeout'; $lng['serversettings']['mod_fcgid']['idle_timeout']['description'] = 'Timeout setting for Mod FastCGI.'; $lng['serversettings']['phpfpm_settings']['idle_timeout']['title'] = 'Idle Timeout'; -$lng['serversettings']['phpfpm_settings']['idle_timeout']['description'] = 'Timeout setting for PHP5 FPM FastCGI.'; +$lng['serversettings']['phpfpm_settings']['idle_timeout']['description'] = 'Timeout setting for PHP FPM FastCGI.'; // ADDED IN 0.9.27-svn2 $lng['panel']['cancel'] = 'Cancel'; @@ -2082,3 +2084,5 @@ $lng['admin']['testmail'] = 'SMTP test'; $lng['success']['testmailsent'] = 'Test mail sent successfully'; $lng['serversettings']['disable_le_selfcheck']['title'] = "Disable Let's Encrypt local self-check"; $lng['serversettings']['disable_le_selfcheck']['description'] = "If activated, froxlor will not perform its self-check for token accessability. Needed for NATed IP's or similar."; +$lng['menue']['phpsettings']['fpmdaemons'] = 'PHP-FPM versions'; +$lng['admin']['phpsettings']['activephpconfigs'] = 'In use for php-config(s)'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 7edda2ca..f20700ec 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -934,6 +934,7 @@ $lng['admin']['phpsettings']['phpinisettings'] = 'php.ini-Einstellungen'; $lng['error']['nopermissionsorinvalidid'] = 'Entweder fehlen Ihnen die nötigen Rechte diese Einstellung zu ändern oder es wurde eine ungültige ID übergeben'; $lng['panel']['view'] = 'ansehen'; $lng['question']['phpsetting_reallydelete'] = 'Wollen Sie diese PHP-Einstellungen wirklich löschen? Alle Domains die diese Einstellungen bis jetzt verwendet haben, werden dann auf die Standardeinstellungen umgestellt.'; +$lng['question']['fpmsetting_reallydelete'] = 'Wollen Sie diese PHP-FPM Einstellungen wirklich löschen? Alle PHP Konfigurationen die diese Einstellungen bis jetzt verwendet haben, werden dann auf die Standardeinstellungen umgestellt.'; $lng['admin']['phpsettings']['addnew'] = 'Neue Konfiguration erstellen'; $lng['error']['phpsettingidwrong'] = 'Eine PHP-Konfiguration mit dieser ID existiert nicht'; $lng['error']['descriptioninvalid'] = 'Der Beschreibungstext ist zu kurz, zu lang oder enthält ungültige Zeichen'; @@ -997,6 +998,7 @@ $lng['error']['ipportdoesntexist'] = 'Die gewählte IP/Port-Kombination existier $lng['admin']['phpserversettings'] = 'PHP-Einstellungen'; $lng['admin']['phpsettings']['binary'] = 'PHP-Binary'; +$lng['admin']['phpsettings']['fpmdesc'] = 'PHP-FPM Config'; $lng['admin']['phpsettings']['file_extensions'] = 'Dateiendungen'; $lng['admin']['phpsettings']['file_extensions_note'] = '(ohne Punkt, durch Leerzeichen getrennt)'; $lng['admin']['mod_fcgid_maxrequests']['title'] = 'Maximale PHP-Requests für diese Domain (leer für Standardwert)'; @@ -1383,7 +1385,7 @@ $lng['traffic']['mail'] = 'Mail (MiB)'; $lng['serversettings']['mod_fcgid']['idle_timeout']['title'] = 'Idle-Timeout'; $lng['serversettings']['mod_fcgid']['idle_timeout']['description'] = 'Timeout-Einstellung für mod_FastCGI.'; $lng['serversettings']['phpfpm_settings']['idle_timeout']['title'] = 'Idle-Timeout'; -$lng['serversettings']['phpfpm_settings']['idle_timeout']['description'] = 'Timeout-Einstellung für PHP5-FPM FastCGI.'; +$lng['serversettings']['phpfpm_settings']['idle_timeout']['description'] = 'Timeout-Einstellung für PHP-FPM FastCGI.'; // ADDED IN 0.9.27-svn2 $lng['admin']['delete_statistics'] = 'Statistiken Löschen'; @@ -1733,3 +1735,5 @@ $lng['admin']['testmail'] = 'SMTP Test'; $lng['success']['testmailsent'] = 'Test E-Mail erfolgreich gesendet'; $lng['serversettings']['disable_le_selfcheck']['title'] = "Deaktiviere Let's Encrypt lokale Selbstprüfung"; $lng['serversettings']['disable_le_selfcheck']['description'] = "Wenn aktiviert wird Froxlor keine Erreichbarkeitsprüfung des Tokens vornehmen. Nötig bei ge-NAT-eten IP's oder Ähnlichem"; +$lng['menue']['phpsettings']['fpmdaemons'] = 'PHP-FPM Versionen'; +$lng['admin']['phpsettings']['activephpconfigs'] = 'In Verwendung für PHP-Konfiguration(en)'; diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 6e9d3277..f4107512 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -16,7 +16,7 @@ if (! defined('MASTER_CRONJOB')) * @author Froxlor team (2010-) * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt * @package Cron - * + * */ require_once (dirname(__FILE__) . '/../classes/class.HttpConfigBase.php'); @@ -58,8 +58,15 @@ class apache extends HttpConfigBase public function reload() { if ((int) Settings::Get('phpfpm.enabled') == 1) { - $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::reload: reloading php-fpm'); - safe_exec(escapeshellcmd(Settings::Get('phpfpm.reload'))); + // get all start/stop commands + $startstop_sel = Database::prepare("SELECT reload_cmd FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); + Database::pexecute($startstop_sel); + $restart_cmds = $startstop_sel->fetchAll(PDO::FETCH_ASSOC); + // restart all php-fpm instances + foreach ($restart_cmds as $restart_cmd) { + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::reload: running ' . $restart_cmd['reload_cmd']); + safe_exec(escapeshellcmd($restart_cmd['reload_cmd'])); + } } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::reload: reloading apache'); safe_exec(escapeshellcmd(Settings::Get('system.apachereload_command'))); @@ -77,13 +84,13 @@ class apache extends HttpConfigBase $vhosts_folder = makeCorrectDir(dirname(Settings::Get('system.apacheconf_vhost'))); } $vhosts_filename = makeCorrectFile($vhosts_folder . '/05_froxlor_dirfix_nofcgid.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; - + // check for custom values, see #1638 $custom_opts = Settings::Get('system.apacheglobaldiropt'); if (! empty($custom_opts)) { @@ -99,11 +106,10 @@ class apache extends HttpConfigBase } } $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; - + $ocsp_cache_filename = makeCorrectFile($vhosts_folder . '/03_froxlor_ocsp_cache.conf'); if (Settings::Get('system.use_ssl') == '1' && Settings::Get('system.apache24') == 1) { - $this->virtualhosts_data[$ocsp_cache_filename] = 'SSLStaplingCache ' . - Settings::Get('system.apache24_ocsp_cache_path') . "\n"; + $this->virtualhosts_data[$ocsp_cache_filename] = 'SSLStaplingCache ' . Settings::Get('system.apache24_ocsp_cache_path') . "\n"; } else { if (file_exists($ocsp_cache_filename)) { $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::_createStandardDirectoryEntry: unlinking ' . basename($ocsp_cache_filename)); @@ -124,13 +130,13 @@ class apache extends HttpConfigBase } else { $vhosts_folder = makeCorrectDir(dirname(Settings::Get('system.apacheconf_vhost'))); } - + $vhosts_filename = makeCorrectFile($vhosts_folder . '/05_froxlor_default_errorhandler.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + $statusCodes = array( '401', '403', @@ -154,26 +160,26 @@ class apache extends HttpConfigBase public function createIpPort() { $result_ipsandports_stmt = Database::query("SELECT * FROM `" . TABLE_PANEL_IPSANDPORTS . "` ORDER BY `ip` ASC, `port` ASC"); - + while ($row_ipsandports = $result_ipsandports_stmt->fetch(PDO::FETCH_ASSOC)) { if (filter_var($row_ipsandports['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $ipport = '[' . $row_ipsandports['ip'] . ']:' . $row_ipsandports['port']; } else { $ipport = $row_ipsandports['ip'] . ':' . $row_ipsandports['port']; } - + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::createIpPort: creating ip/port settings for ' . $ipport); $vhosts_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/10_froxlor_ipandport_' . trim(str_replace(':', '.', $row_ipsandports['ip']), '.') . '.' . $row_ipsandports['port'] . '.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + if ($row_ipsandports['listen_statement'] == '1') { $this->virtualhosts_data[$vhosts_filename] .= 'Listen ' . $ipport . "\n"; $this->logger->logAction(CRON_ACTION, LOG_DEBUG, $ipport . ' :: inserted listen-statement'); } - + if ($row_ipsandports['namevirtualhost_statement'] == '1') { // >=apache-2.4 enabled? if (Settings::Get('system.apache24') == '1') { @@ -183,22 +189,22 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_DEBUG, $ipport . ' :: inserted namevirtualhost-statement'); } } - + if ($row_ipsandports['vhostcontainer'] == '1') { - + $without_vhost = $this->virtualhosts_data[$vhosts_filename]; $close_vhost = true; - + $this->virtualhosts_data[$vhosts_filename] .= '' . "\n"; - + $mypath = $this->getMyPath($row_ipsandports); - + $this->virtualhosts_data[$vhosts_filename] .= 'DocumentRoot "' . $mypath . '"' . "\n"; - + if ($row_ipsandports['vhostcontainer_servername_statement'] == '1') { $this->virtualhosts_data[$vhosts_filename] .= ' ServerName ' . Settings::Get('system.hostname') . "\n"; } - + $is_redirect = false; // check for SSL redirect if ($row_ipsandports['ssl'] == '0' && Settings::Get('system.le_froxlor_redirect') == '1') { @@ -210,11 +216,11 @@ class apache extends HttpConfigBase $is_redirect = false; } else { $_sslport = $this->checkAlternativeSslPort(); - + $mypath = 'https://' . Settings::Get('system.hostname') . $_sslport . '/'; $code = '301'; $modrew_red = ' [R=' . $code . ';L,NE]'; - + // redirect everything, not only root-directory, #541 $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' RewriteEngine On' . "\n"; @@ -229,7 +235,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; } } - + if (! $is_redirect) { // create fcgid -Part (starter is created in apache_fcgid) if (Settings::Get('system.mod_fcgid_ownvhost') == '1' && Settings::Get('system.mod_fcgid') == '1') { @@ -253,7 +259,7 @@ class apache extends HttpConfigBase ); $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig(Settings::Get('system.mod_fcgid_defaultini_ownvhost')); - + $starter_filename = makeCorrectFile($configdir . '/php-fcgi-starter'); $this->virtualhosts_data[$vhosts_filename] .= ' SuexecUserGroup "' . Settings::Get('system.mod_fcgid_httpuser') . '" "' . Settings::Get('system.mod_fcgid_httpgroup') . '"' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; @@ -280,8 +286,7 @@ class apache extends HttpConfigBase } $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; } - } - elseif (Settings::Get('phpfpm.enabled') == '1') { + } elseif (Settings::Get('phpfpm.enabled') == '1') { // create php-fpm -Part (config is created in apache_fcgid) $domain = array( 'id' => 'none', @@ -295,14 +300,14 @@ class apache extends HttpConfigBase 'loginname' => 'froxlor.panel', 'documentroot' => $mypath ); - + $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig(Settings::Get('phpfpm.vhost_defaultini')); $srvName = substr(md5($ipport), 0, 4) . '.fpm.external'; if ($row_ipsandports['ssl']) { $srvName = substr(md5($ipport), 0, 4) . '.ssl-fpm.external'; } - + // mod_proxy stuff for apache-2.4 if (Settings::Get('system.apache24') == '1' && Settings::Get('phpfpm.use_mod_proxy') == '1') { $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; @@ -347,8 +352,7 @@ class apache extends HttpConfigBase ); } } // end of ssl-redirect check - else - { + else { // fallback of froxlor domain-data for processSpecialConfigTemplate() $domain = array( 'domain' => Settings::Get('system.hostname'), @@ -356,7 +360,7 @@ class apache extends HttpConfigBase 'documentroot' => $mypath ); } - + /** * dirprotection, see #72 * @@ -365,36 +369,36 @@ class apache extends HttpConfigBase * $this->virtualhosts_data[$vhosts_filename] .= "\t\tAllow from all\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tOptions -Indexes\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; - * + * * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tOrder Deny,Allow\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tDeny from All\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; * end of dirprotection */ - + if ($row_ipsandports['specialsettings'] != '') { $this->virtualhosts_data[$vhosts_filename] .= $this->processSpecialConfigTemplate($row_ipsandports['specialsettings'], $domain, $row_ipsandports['ip'], $row_ipsandports['port'], $row_ipsandports['ssl'] == '1') . "\n"; } - + if ($row_ipsandports['ssl'] == '1' && Settings::Get('system.use_ssl') == '1') { if ($row_ipsandports['ssl_cert_file'] == '') { $row_ipsandports['ssl_cert_file'] = Settings::Get('system.ssl_cert_file'); } - + if ($row_ipsandports['ssl_key_file'] == '') { $row_ipsandports['ssl_key_file'] = Settings::Get('system.ssl_key_file'); } - + if ($row_ipsandports['ssl_ca_file'] == '') { $row_ipsandports['ssl_ca_file'] = Settings::Get('system.ssl_ca_file'); } - + // #418 if ($row_ipsandports['ssl_cert_chainfile'] == '') { $row_ipsandports['ssl_cert_chainfile'] = Settings::Get('system.ssl_cert_chainfile'); } - + $domain = array( 'id' => 0, 'domain' => Settings::Get('system.hostname'), @@ -403,26 +407,26 @@ class apache extends HttpConfigBase 'documentroot' => $mypath, 'parentdomainid' => 0 ); - + // override corresponding array values $domain['ssl_cert_file'] = $row_ipsandports['ssl_cert_file']; $domain['ssl_key_file'] = $row_ipsandports['ssl_key_file']; $domain['ssl_ca_file'] = $row_ipsandports['ssl_ca_file']; $domain['ssl_cert_chainfile'] = $row_ipsandports['ssl_cert_chainfile']; - + // SSL STUFF $dssl = new DomainSSL(); // this sets the ssl-related array-indices in the $domain array // if the domain has customer-defined ssl-certificates $dssl->setDomainSSLFilesArray($domain); - + if ($domain['ssl_cert_file'] != '') { - + // check for existence, #1485 if (! file_exists($domain['ssl_cert_file'])) { $this->logger->logAction(CRON_ACTION, LOG_ERR, $ipport . ' :: certificate file "' . $domain['ssl_cert_file'] . '" does not exist! Cannot create ssl-directives'); } else { - + $this->virtualhosts_data[$vhosts_filename] .= ' SSLEngine On' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; if (Settings::Get('system.apache24') == '1') { @@ -436,7 +440,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLVerifyDepth 10' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLCertificateFile ' . makeCorrectFile($domain['ssl_cert_file']) . "\n"; - + if ($domain['ssl_key_file'] != '') { // check for existence, #1485 if (! file_exists($domain['ssl_key_file'])) { @@ -445,7 +449,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCertificateKeyFile ' . makeCorrectFile($domain['ssl_key_file']) . "\n"; } } - + if ($domain['ssl_ca_file'] != '') { // check for existence, #1485 if (! file_exists($domain['ssl_ca_file'])) { @@ -454,7 +458,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCACertificateFile ' . makeCorrectFile($domain['ssl_ca_file']) . "\n"; } } - + // #418 if ($domain['ssl_cert_chainfile'] != '') { // check for existence, #1485 @@ -474,7 +478,7 @@ class apache extends HttpConfigBase $close_vhost = false; } } - + if ($close_vhost) { $this->virtualhosts_data[$vhosts_filename] .= '' . "\n"; } @@ -482,12 +486,12 @@ class apache extends HttpConfigBase } unset($vhosts_filename); } - + /** * bug #32 */ $this->_createStandardDirectoryEntry(); - + /** * bug #unknown-yet */ @@ -505,31 +509,31 @@ class apache extends HttpConfigBase protected function composePhpOptions($domain, $ssl_vhost = false) { $php_options_text = ''; - + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { // This vHost has PHP enabled and we are using the regular mod_php $cmail = getCustomerDetail($domain['customerid'], 'email'); - $php_options_text .= ' php_admin_value sendmail_path "/usr/sbin/sendmail -t -f '.$cmail.'"' . PHP_EOL; - + $php_options_text .= ' php_admin_value sendmail_path "/usr/sbin/sendmail -t -f ' . $cmail . '"' . PHP_EOL; + if ($domain['openbasedir'] == '1') { if ($domain['openbasedir_path'] == '1' || strstr($domain['documentroot'], ":") !== false) { $_phpappendopenbasedir = appendOpenBasedirPath($domain['customerroot'], true); } else { $_phpappendopenbasedir = appendOpenBasedirPath($domain['documentroot'], true); } - + $_custom_openbasedir = explode(':', Settings::Get('system.phpappendopenbasedir')); foreach ($_custom_openbasedir as $cobd) { $_phpappendopenbasedir .= appendOpenBasedirPath($cobd); } - + $php_options_text .= ' php_admin_value open_basedir "' . $_phpappendopenbasedir . '"' . "\n"; } } else { $php_options_text .= ' # PHP is disabled for this vHost' . "\n"; $php_options_text .= ' php_flag engine off' . "\n"; } - + /** * check for apache-itk-support, #1400 * why is this here? Because it only works with mod_php @@ -539,7 +543,7 @@ class apache extends HttpConfigBase $php_options_text .= ' AssignUserID ' . $domain['loginname'] . ' ' . $domain['loginname'] . "\n"; $php_options_text .= ' ' . "\n"; } - + return $php_options_text; } @@ -552,18 +556,18 @@ class apache extends HttpConfigBase protected function getServerNames($domain) { $servernames_text = ' ServerName ' . $domain['domain'] . "\n"; - + $server_alias = ''; if ($domain['iswildcarddomain'] == '1') { $server_alias = '*.' . $domain['domain']; } elseif ($domain['wwwserveralias'] == '1') { $server_alias = 'www.' . $domain['domain']; } - + if (trim($server_alias) != '') { $servernames_text .= ' ServerAlias ' . $server_alias . "\n"; } - + $alias_domains_stmt = Database::prepare(" SELECT `domain`, `iswildcarddomain`, `wwwserveralias` FROM `" . TABLE_PANEL_DOMAINS . "` @@ -572,10 +576,10 @@ class apache extends HttpConfigBase Database::pexecute($alias_domains_stmt, array( 'domainid' => $domain['id'] )); - + while (($alias_domain = $alias_domains_stmt->fetch(PDO::FETCH_ASSOC)) !== false) { $server_alias = ' ServerAlias ' . $alias_domain['domain']; - + if ($alias_domain['iswildcarddomain'] == '1') { $server_alias .= ' *.' . $alias_domain['domain']; } else { @@ -583,10 +587,10 @@ class apache extends HttpConfigBase $server_alias .= ' www.' . $alias_domain['domain']; } } - + $servernames_text .= $server_alias . "\n"; } - + $servernames_text .= ' ServerAdmin ' . $domain['email'] . "\n"; return $servernames_text; } @@ -599,7 +603,7 @@ class apache extends HttpConfigBase $webroot_text = ''; $domain['customerroot'] = makeCorrectDir($domain['customerroot']); $domain['documentroot'] = makeCorrectDir($domain['documentroot']); - + if ($domain['deactivated'] == '1' && Settings::Get('system.deactivateddocroot') != '') { $webroot_text .= ' # Using docroot for deactivated users...' . "\n"; $webroot_text .= ' DocumentRoot "' . makeCorrectDir(Settings::Get('system.deactivateddocroot')) . "\"\n"; @@ -618,7 +622,7 @@ class apache extends HttpConfigBase $webroot_text .= ' DocumentRoot "' . $domain['documentroot'] . "\"\n"; $this->_deactivated = false; } - + return $webroot_text; } @@ -628,7 +632,7 @@ class apache extends HttpConfigBase protected function getStats($domain) { $stats_text = ''; - + if ($domain['speciallogfile'] == '1') { $statDomain = ($domain['parentdomainid'] == '0') ? $domain['domain'] : $domain['parentdomain']; if (Settings::Get('system.awstats_enabled') == '1') { @@ -654,7 +658,7 @@ class apache extends HttpConfigBase $stats_text .= ' Alias /awstats-icon "' . makeCorrectDir(Settings::Get('system.awstats_icons')) . '"' . "\n"; } } - + return $stats_text; } @@ -664,7 +668,7 @@ class apache extends HttpConfigBase protected function getLogfiles($domain) { $logfiles_text = ''; - + if ($domain['speciallogfile'] == '1') { if ($domain['parentdomainid'] == '0') { $speciallogfile = '-' . $domain['domain']; @@ -674,23 +678,23 @@ class apache extends HttpConfigBase } else { $speciallogfile = ''; } - + // The normal access/error - logging is enabled $error_log = makeCorrectFile(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-error.log'); // Create the logfile if it does not exist (fixes #46) touch($error_log); chown($error_log, Settings::Get('system.httpuser')); chgrp($error_log, Settings::Get('system.httpgroup')); - + $access_log = makeCorrectFile(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-access.log'); // Create the logfile if it does not exist (fixes #46) touch($access_log); chown($access_log, Settings::Get('system.httpuser')); chgrp($access_log, Settings::Get('system.httpgroup')); - + $logfiles_text .= ' ErrorLog "' . $error_log . "\"\n"; $logfiles_text .= ' CustomLog "' . $access_log . '" combined' . "\n"; - + if (Settings::Get('system.awstats_enabled') == '1') { if ((int) $domain['parentdomainid'] == 0) { // prepare the aliases and subdomains for stats config files @@ -703,25 +707,25 @@ class apache extends HttpConfigBase Database::pexecute($alias_domains_stmt, array( 'domainid' => $domain['id'] )); - + while (($alias_domain = $alias_domains_stmt->fetch(PDO::FETCH_ASSOC)) !== false) { - + $server_alias .= ' ' . $alias_domain['domain'] . ' '; - + if ($alias_domain['iswildcarddomain'] == '1') { $server_alias .= '*.' . $alias_domain['domain']; } elseif ($alias_domain['wwwserveralias'] == '1') { $server_alias .= 'www.' . $alias_domain['domain']; } } - + $alias = ''; if ($domain['iswildcarddomain'] == '1') { $alias = '*.' . $domain['domain']; } elseif ($domain['wwwserveralias'] == '1') { $alias = 'www.' . $domain['domain']; } - + // After inserting the AWStats information, // be sure to build the awstats conf file as well // and chown it using $awstats_params, #258 @@ -729,7 +733,7 @@ class apache extends HttpConfigBase createAWStatsConf(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-access.log', $domain['domain'], $alias . $server_alias, $domain['customerroot'], $domain); } } - + return $logfiles_text; } @@ -746,13 +750,13 @@ class apache extends HttpConfigBase // number of dots in a domain specifies it's position (and depth of subdomain) starting at 29 going downwards on higher depth $vhost_no = (string) (30 - substr_count($domain['domain'], ".") + 1); } - + if ($ssl_vhost === true) { $vhost_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/' . $vhost_no . '_froxlor_ssl_vhost_' . $domain['domain'] . '.conf'); } else { $vhost_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/' . $vhost_no . '_froxlor_normal_vhost_' . $domain['domain'] . '.conf'); } - + return $vhost_filename; } @@ -764,27 +768,27 @@ class apache extends HttpConfigBase if ($ssl_vhost === true && ($domain['ssl_redirect'] != '1' && $domain['ssl'] != '1')) { return ''; } - + $query = "SELECT * FROM `" . TABLE_PANEL_IPSANDPORTS . "` `i`, `" . TABLE_DOMAINTOIP . "` `dip` WHERE dip.id_domain = :domainid AND i.id = dip.id_ipandports "; - + if ($ssl_vhost === true && ($domain['ssl'] == '1' || $domain['ssl_redirect'] == '1')) { // by ordering by cert-file the row with filled out SSL-Fields will be shown last, thus it is enough to fill out 1 set of SSL-Fields $query .= "AND i.ssl = '1' ORDER BY i.ssl_cert_file ASC;"; } else { $query .= "AND i.ssl = '0';"; } - + $vhost_content = ''; $result_stmt = Database::prepare($query); Database::pexecute($result_stmt, array( 'domainid' => $domain['id'] )); - + $ipportlist = ''; $_vhost_content = ''; while ($ipandport = $result_stmt->fetch(PDO::FETCH_ASSOC)) { - + $ipport = ''; $domain['ip'] = $ipandport['ip']; $domain['port'] = $ipandport['port']; @@ -793,29 +797,29 @@ class apache extends HttpConfigBase $domain['ssl_key_file'] = $ipandport['ssl_key_file']; $domain['ssl_ca_file'] = $ipandport['ssl_ca_file']; $domain['ssl_cert_chainfile'] = $ipandport['ssl_cert_chainfile']; - + // SSL STUFF $dssl = new DomainSSL(); // this sets the ssl-related array-indices in the $domain array // if the domain has customer-defined ssl-certificates $dssl->setDomainSSLFilesArray($domain); } - + if (filter_var($domain['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $ipport = '[' . $domain['ip'] . ']:' . $domain['port'] . ' '; } else { $ipport = $domain['ip'] . ':' . $domain['port'] . ' '; } - + if ($ipandport['default_vhostconf_domain'] != '') { $_vhost_content .= $this->processSpecialConfigTemplate($ipandport['default_vhostconf_domain'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } $ipportlist .= $ipport; } - + $vhost_content .= '' . "\n"; $vhost_content .= $this->getServerNames($domain); - + $domain['documentroot_norewrite'] = $domain['documentroot']; if (($ssl_vhost == false && $domain['ssl'] == '1' && $domain['ssl_redirect'] == '1')) { // We must not check if our port differs from port 443, @@ -834,32 +838,32 @@ class apache extends HttpConfigBase $ssldestport = Database::pexecute_first($ssldestport_stmt, array( 'domainid' => $domain['id'] )); - + if ($ssldestport['port'] != '') { $_sslport = ":" . $ssldestport['port']; } - + $domain['documentroot'] = 'https://%{HTTP_HOST}' . $_sslport . '/'; $domain['documentroot_norewrite'] = 'https://' . $domain['domain'] . $_sslport . '/'; } - + if ($ssl_vhost === true && $domain['ssl'] == '1' && Settings::Get('system.use_ssl') == '1') { if ($domain['ssl_cert_file'] == '') { $domain['ssl_cert_file'] = Settings::Get('system.ssl_cert_file'); } - + if ($domain['ssl_key_file'] == '') { $domain['ssl_key_file'] = Settings::Get('system.ssl_key_file'); } - + if ($domain['ssl_ca_file'] == '') { $domain['ssl_ca_file'] = Settings::Get('system.ssl_ca_file'); } - + if ($domain['ssl_cert_chainfile'] == '') { $domain['ssl_cert_chainfile'] = Settings::Get('system.ssl_cert_chainfile'); } - + if ($domain['ssl_cert_file'] != '') { $vhost_content .= ' SSLEngine On' . "\n"; $vhost_content .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; @@ -874,25 +878,23 @@ class apache extends HttpConfigBase $vhost_content .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; $vhost_content .= ' SSLVerifyDepth 10' . "\n"; $vhost_content .= ' SSLCertificateFile ' . makeCorrectFile($domain['ssl_cert_file']) . "\n"; - + if ($domain['ssl_key_file'] != '') { $vhost_content .= ' SSLCertificateKeyFile ' . makeCorrectFile($domain['ssl_key_file']) . "\n"; } - + if ($domain['ssl_ca_file'] != '') { $vhost_content .= ' SSLCACertificateFile ' . makeCorrectFile($domain['ssl_ca_file']) . "\n"; } - + if ($domain['ssl_cert_chainfile'] != '') { $vhost_content .= ' SSLCertificateChainFile ' . makeCorrectFile($domain['ssl_cert_chainfile']) . "\n"; } - - if (Settings::Get('system.apache24') == '1' && isset($domain['ocsp_stapling']) && - $domain['ocsp_stapling'] == '1') - { + + if (Settings::Get('system.apache24') == '1' && isset($domain['ocsp_stapling']) && $domain['ocsp_stapling'] == '1') { $vhost_content .= ' SSLUseStapling on' . PHP_EOL; } - + if ($domain['hsts'] >= 0) { $vhost_content .= ' ' . "\n"; $vhost_content .= ' Header always set Strict-Transport-Security "max-age=' . $domain['hsts']; @@ -912,20 +914,20 @@ class apache extends HttpConfigBase return '# no ssl-certificate was specified for this domain, therefore no explicit vhost is being generated'; } } - + // avoid using any whitespaces $domain['documentroot'] = trim($domain['documentroot']); - + if (preg_match('/^https?\:\/\//', $domain['documentroot'])) { $corrected_docroot = $domain['documentroot']; - + // Get domain's redirect code $code = getDomainRedirectCode($domain['id'], '301'); $modrew_red = ''; if ($code != '') { $modrew_red = ' [R=' . $code . ';L,NE]'; } - + // redirect everything, not only root-directory, #541 $vhost_content .= ' ' . "\n"; $vhost_content .= ' RewriteEngine On' . "\n"; @@ -941,7 +943,7 @@ class apache extends HttpConfigBase $vhost_content .= ' Redirect ' . $code . ' / ' . $domain['documentroot_norewrite'] . "\n"; $vhost_content .= ' ' . "\n"; } else { - + mkDirWithCorrectOwnership($domain['customerroot'], $domain['documentroot'], $domain['guid'], $domain['guid'], true, true); $vhost_content .= $this->getWebroot($domain); if ($this->_deactivated == false) { @@ -949,22 +951,22 @@ class apache extends HttpConfigBase $vhost_content .= $this->getStats($domain); } $vhost_content .= $this->getLogfiles($domain); - + if ($domain['specialsettings'] != '') { $vhost_content .= $this->processSpecialConfigTemplate($domain['specialsettings'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } - + if ($_vhost_content != '') { $vhost_content .= $_vhost_content; } - + if (Settings::Get('system.default_vhostconf') != '') { $vhost_content .= $this->processSpecialConfigTemplate(Settings::Get('system.default_vhostconf'), $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } } - + $vhost_content .= '' . "\n"; - + return $vhost_content; } @@ -975,17 +977,17 @@ class apache extends HttpConfigBase { $domains = WebserverBase::getVhostsToCreate(); foreach ($domains as $domain) { - + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::createVirtualHosts: creating vhost container for domain ' . $domain['id'] . ', customer ' . $domain['loginname']); $vhosts_filename = $this->getVhostFilename($domain); - + // Apply header $this->virtualhosts_data[$vhosts_filename] = '# Domain ID: ' . $domain['id'] . ' - CustomerID: ' . $domain['customerid'] . ' - CustomerLogin: ' . $domain['loginname'] . "\n"; - + if ($domain['deactivated'] != '1' || Settings::Get('system.deactivateddocroot') != '') { // Create vhost without ssl $this->virtualhosts_data[$vhosts_filename] .= $this->getVhostContent($domain, false); - + if ($domain['ssl'] == '1' || $domain['ssl_redirect'] == '1') { // Adding ssl stuff if enabled $vhosts_filename_ssl = $this->getVhostFilename($domain, true); @@ -1010,27 +1012,27 @@ class apache extends HttpConfigBase ORDER BY `htac`.`path` "); $diroptions = array(); - + while ($row_diroptions = $result_stmt->fetch(PDO::FETCH_ASSOC)) { if ($row_diroptions['customerid'] != 0 && isset($row_diroptions['customerroot']) && $row_diroptions['customerroot'] != '') { $diroptions[$row_diroptions['path']] = $row_diroptions; $diroptions[$row_diroptions['path']]['htpasswds'] = array(); } } - + $result_stmt = Database::query(" SELECT `htpw`.*, `c`.`guid`, `c`.`documentroot` AS `customerroot` FROM `" . TABLE_PANEL_HTPASSWDS . "` `htpw` LEFT JOIN `" . TABLE_PANEL_CUSTOMERS . "` `c` USING (`customerid`) ORDER BY `htpw`.`path`, `htpw`.`username` "); - + while ($row_htpasswds = $result_stmt->fetch(PDO::FETCH_ASSOC)) { if ($row_htpasswds['customerid'] != 0 && isset($row_htpasswds['customerroot']) && $row_htpasswds['customerroot'] != '') { if (! isset($diroptions[$row_htpasswds['path']]) || ! is_array($diroptions[$row_htpasswds['path']])) { $diroptions[$row_htpasswds['path']] = array(); } - + $diroptions[$row_htpasswds['path']]['path'] = $row_htpasswds['path']; $diroptions[$row_htpasswds['path']]['guid'] = $row_htpasswds['guid']; $diroptions[$row_htpasswds['path']]['customerroot'] = $row_htpasswds['customerroot']; @@ -1038,24 +1040,24 @@ class apache extends HttpConfigBase $diroptions[$row_htpasswds['path']]['htpasswds'][] = $row_htpasswds; } } - + foreach ($diroptions as $row_diroptions) { $row_diroptions['path'] = makeCorrectDir($row_diroptions['path']); mkDirWithCorrectOwnership($row_diroptions['customerroot'], $row_diroptions['path'], $row_diroptions['guid'], $row_diroptions['guid']); $diroptions_filename = makeCorrectFile(Settings::Get('system.apacheconf_diroptions') . '/40_froxlor_diroption_' . md5($row_diroptions['path']) . '.conf'); - + if (! isset($this->diroptions_data[$diroptions_filename])) { $this->diroptions_data[$diroptions_filename] = ''; } - + if (is_dir($row_diroptions['path'])) { $cperlenabled = customerHasPerlEnabled($row_diroptions['customerid']); - + $this->diroptions_data[$diroptions_filename] .= '' . "\n"; - + if (isset($row_diroptions['options_indexes']) && $row_diroptions['options_indexes'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' Options +Indexes'; - + // add perl options if enabled if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' +ExecCGI -MultiViews +SymLinksIfOwnerMatch +FollowSymLinks' . "\n"; @@ -1064,10 +1066,10 @@ class apache extends HttpConfigBase } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Setting Options +Indexes for ' . $row_diroptions['path']); } - + if (isset($row_diroptions['options_indexes']) && $row_diroptions['options_indexes'] == '0') { $this->diroptions_data[$diroptions_filename] .= ' Options -Indexes'; - + // add perl options if enabled if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' +ExecCGI -MultiViews +SymLinksIfOwnerMatch +FollowSymLinks' . "\n"; @@ -1076,7 +1078,7 @@ class apache extends HttpConfigBase } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Setting Options -Indexes for ' . $row_diroptions['path']); } - + $statusCodes = array( '404', '403', @@ -1093,7 +1095,7 @@ class apache extends HttpConfigBase $this->diroptions_data[$diroptions_filename] .= ' ErrorDocument ' . $statusCode . ' ' . $defhandler . "\n"; } } - + if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' AllowOverride None' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AddHandler cgi-script .cgi .pl' . "\n"; @@ -1111,18 +1113,18 @@ class apache extends HttpConfigBase $this->diroptions_data[$diroptions_filename] .= ' Allow from all' . "\n"; } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Enabling perl execution for ' . $row_diroptions['path']); - + // check for suexec-workaround, #319 if ((int) Settings::Get('perl.suexecworkaround') == 1) { // symlink this directory to suexec-safe-path $loginname = getCustomerDetail($row_diroptions['customerid'], 'loginname'); $suexecpath = makeCorrectDir(Settings::Get('perl.suexecpath') . '/' . $loginname . '/' . md5($row_diroptions['path']) . '/'); - + if (! file_exists($suexecpath)) { safe_exec('mkdir -p ' . escapeshellarg($suexecpath)); safe_exec('chown -R ' . escapeshellarg($row_diroptions['guid']) . ':' . escapeshellarg($row_diroptions['guid']) . ' ' . escapeshellarg($suexecpath)); } - + // symlink to {$givenpath}/cgi-bin // NOTE: symlinks are FILES, so do not append a / here $perlsymlink = makeCorrectFile($row_diroptions['path'] . '/cgi-bin'); @@ -1138,7 +1140,7 @@ class apache extends HttpConfigBase $loginname = getCustomerDetail($row_diroptions['customerid'], 'loginname'); $suexecpath = makeCorrectDir(Settings::Get('perl.suexecpath') . '/' . $loginname . '/' . md5($row_diroptions['path']) . '/'); $perlsymlink = makeCorrectFile($row_diroptions['path'] . '/cgi-bin'); - + // remove symlink if (file_exists($perlsymlink)) { safe_exec('rm -f ' . escapeshellarg($perlsymlink)); @@ -1149,24 +1151,24 @@ class apache extends HttpConfigBase } } } - + if (count($row_diroptions['htpasswds']) > 0) { $htpasswd_filename = makeCorrectFile(Settings::Get('system.apacheconf_htpasswddir') . '/' . $row_diroptions['customerid'] . '-' . md5($row_diroptions['path']) . '.htpasswd'); - + if (! isset($this->htpasswds_data[$htpasswd_filename])) { $this->htpasswds_data[$htpasswd_filename] = ''; } - + foreach ($row_diroptions['htpasswds'] as $row_htpasswd) { $this->htpasswds_data[$htpasswd_filename] .= $row_htpasswd['username'] . ':' . $row_htpasswd['password'] . "\n"; } - + $this->diroptions_data[$diroptions_filename] .= ' AuthType Basic' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AuthName "' . $row_htpasswd['authname'] . '"' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AuthUserFile ' . $htpasswd_filename . "\n"; $this->diroptions_data[$diroptions_filename] .= ' require valid-user' . "\n"; } - + $this->diroptions_data[$diroptions_filename] .= '' . "\n"; } } @@ -1179,19 +1181,19 @@ class apache extends HttpConfigBase { // Write diroptions $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_diroptions')); - + if (count($this->diroptions_data) > 0) { $optsDir = new frxDirectory(Settings::Get('system.apacheconf_diroptions')); if (! $optsDir->isConfigDir()) { // Save one big file $diroptions_file = ''; - + foreach ($this->diroptions_data as $diroptions_filename => $diroptions_content) { $diroptions_file .= $diroptions_content . "\n\n"; } - + $diroptions_filename = Settings::Get('system.apacheconf_diroptions'); - + // Apply header $diroptions_file = '# ' . basename($diroptions_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $diroptions_file; $diroptions_file_handler = fopen($diroptions_filename, 'w'); @@ -1202,11 +1204,11 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::writeConfigs: mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_diroptions')))); safe_exec('mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_diroptions')))); } - + // Write a single file for every diroption foreach ($this->diroptions_data as $diroptions_filename => $diroptions_file) { $this->known_diroptionsfilenames[] = basename($diroptions_filename); - + // Apply header $diroptions_file = '# ' . basename($diroptions_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $diroptions_file; $diroptions_file_handler = fopen($diroptions_filename, 'w'); @@ -1215,10 +1217,10 @@ class apache extends HttpConfigBase } } } - + // Write htpasswds $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_htpasswddir')); - + if (count($this->htpasswds_data) > 0) { if (! file_exists(Settings::Get('system.apacheconf_htpasswddir'))) { $umask = umask(); @@ -1226,7 +1228,7 @@ class apache extends HttpConfigBase mkdir(Settings::Get('system.apacheconf_htpasswddir'), 0751); umask($umask); } - + $htpasswdDir = new frxDirectory(Settings::Get('system.apacheconf_htpasswddir')); if ($htpasswdDir->isConfigDir(true)) { foreach ($this->htpasswds_data as $htpasswd_filename => $htpasswd_file) { @@ -1239,34 +1241,34 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_WARNING, 'WARNING!!! ' . Settings::Get('system.apacheconf_htpasswddir') . ' is not a directory. htpasswd directory protection is disabled!!!'); } } - + // Write virtualhosts $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_vhost')); - + if (count($this->virtualhosts_data) > 0) { $vhostDir = new frxDirectory(Settings::Get('system.apacheconf_vhost')); if (! $vhostDir->isConfigDir()) { // Save one big file $vhosts_file = ''; - + // sort by filename so the order is: // 1. subdomains x-29 // 2. subdomains as main-domains 30 // 3. main-domains 35 // #437 ksort($this->virtualhosts_data); - + foreach ($this->virtualhosts_data as $vhosts_filename => $vhost_content) { $vhosts_file .= $vhost_content . "\n\n"; } - + // Include diroptions file in case it exists if (file_exists(Settings::Get('system.apacheconf_diroptions'))) { $vhosts_file .= "\n" . 'Include ' . Settings::Get('system.apacheconf_diroptions') . "\n\n"; } - + $vhosts_filename = Settings::Get('system.apacheconf_vhost'); - + // Apply header $vhosts_file = '# ' . basename($vhosts_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $vhosts_file; $vhosts_file_handler = fopen($vhosts_filename, 'w'); @@ -1277,11 +1279,11 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::writeConfigs: mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_vhost')))); safe_exec('mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_vhost')))); } - + // Write a single file for every vhost foreach ($this->virtualhosts_data as $vhosts_filename => $vhosts_file) { $this->known_vhostfilenames[] = basename($vhosts_filename); - + // Apply header $vhosts_file = '# ' . basename($vhosts_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $vhosts_file; $vhosts_file_handler = fopen($vhosts_filename, 'w'); diff --git a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php index a2d5258b..3525a471 100644 --- a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php +++ b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php @@ -58,8 +58,15 @@ class lighttpd extends HttpConfigBase public function reload() { if ((int) Settings::Get('phpfpm.enabled') == 1) { - $this->logger->logAction(CRON_ACTION, LOG_INFO, 'lighttpd::reload: reloading php-fpm'); - safe_exec(escapeshellcmd(Settings::Get('phpfpm.reload'))); + // get all start/stop commands + $startstop_sel = Database::prepare("SELECT reload_cmd FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); + Database::pexecute($startstop_sel); + $restart_cmds = $startstop_sel->fetchAll(PDO::FETCH_ASSOC); + // restart all php-fpm instances + foreach ($restart_cmds as $restart_cmd) { + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'lighttpd::reload: running ' . $restart_cmd['reload_cmd']); + safe_exec(escapeshellcmd($restart_cmd['reload_cmd'])); + } } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'lighttpd::reload: reloading lighttpd'); safe_exec(escapeshellcmd(Settings::Get('system.apachereload_command'))); diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index bc7f23fc..2bf53daa 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -73,8 +73,15 @@ class nginx extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_INFO, 'nginx::reload: restarting php processes'); safe_exec(Settings::Get('system.phpreload_command')); } elseif ((int) Settings::Get('phpfpm.enabled') == 1) { - $this->logger->logAction(CRON_ACTION, LOG_INFO, 'nginx::reload: reloading php-fpm'); - safe_exec(escapeshellcmd(Settings::Get('phpfpm.reload'))); + // get all start/stop commands + $startstop_sel = Database::prepare("SELECT reload_cmd FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); + Database::pexecute($startstop_sel); + $restart_cmds = $startstop_sel->fetchAll(PDO::FETCH_ASSOC); + // restart all php-fpm instances + foreach ($restart_cmds as $restart_cmd) { + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'nginx::reload: running ' . $restart_cmd['reload_cmd']); + safe_exec(escapeshellcmd($restart_cmd['reload_cmd'])); + } } } diff --git a/templates/Sparkle/admin/phpconfig/fpmconfig_add.tpl b/templates/Sparkle/admin/phpconfig/fpmconfig_add.tpl new file mode 100644 index 00000000..51a31dfd --- /dev/null +++ b/templates/Sparkle/admin/phpconfig/fpmconfig_add.tpl @@ -0,0 +1,24 @@ +$header +
+
+

+ {$title}  + {$title} +

+
+ +
+ +
+ + + + + + + {$fpmconfig_add_form} +
+
+
+
+$footer diff --git a/templates/Sparkle/admin/phpconfig/fpmconfig_edit.tpl b/templates/Sparkle/admin/phpconfig/fpmconfig_edit.tpl new file mode 100644 index 00000000..c1383a9b --- /dev/null +++ b/templates/Sparkle/admin/phpconfig/fpmconfig_edit.tpl @@ -0,0 +1,25 @@ +$header +
+
+

+ {$title}  + {$title} +

+
+ +
+ +
+ + + + + + + + {$fpmconfig_edit_form} +
+
+
+
+$footer diff --git a/templates/Sparkle/admin/phpconfig/fpmdaemons.tpl b/templates/Sparkle/admin/phpconfig/fpmdaemons.tpl new file mode 100644 index 00000000..9f4f95b9 --- /dev/null +++ b/templates/Sparkle/admin/phpconfig/fpmdaemons.tpl @@ -0,0 +1,42 @@ +$header +
+
+

+   + {$lng['menue']['phpsettings']['maintitle']} +

+
+ +
+ + + + + + + + + + + + + + + $tablecontent + +
{$lng['admin']['phpsettings']['description']}{$lng['admin']['phpsettings']['activephpconfigs']}{$lng['serversettings']['phpfpm_settings']['reload']}{$lng['serversettings']['phpfpm_settings']['configdir']}{$lng['serversettings']['phpfpm_settings']['pm']}{$lng['panel']['options']}
+ + + + + +
+ +
+$footer diff --git a/templates/Sparkle/admin/phpconfig/fpmdaemons_overview.tpl b/templates/Sparkle/admin/phpconfig/fpmdaemons_overview.tpl new file mode 100644 index 00000000..fe2d894a --- /dev/null +++ b/templates/Sparkle/admin/phpconfig/fpmdaemons_overview.tpl @@ -0,0 +1,17 @@ + + {$row['description']} + {$configs} + {$row['reload_cmd']} + {$row['config_dir']} + {$row['pm']} + + + {$lng['panel']['edit']} + + +   + {$lng['panel']['delete']} + + + + diff --git a/templates/Sparkle/admin/phpconfig/overview.tpl b/templates/Sparkle/admin/phpconfig/overview.tpl index 6fcfc428..aac895ac 100644 --- a/templates/Sparkle/admin/phpconfig/overview.tpl +++ b/templates/Sparkle/admin/phpconfig/overview.tpl @@ -19,7 +19,11 @@ $header {$lng['admin']['phpsettings']['description']} {$lng['admin']['phpsettings']['activedomains']} - {$lng['admin']['phpsettings']['binary']} + + {$lng['admin']['phpsettings']['fpmdesc']} + + {$lng['admin']['phpsettings']['binary']} + {$lng['admin']['phpsettings']['file_extensions']} {$lng['panel']['options']} diff --git a/templates/Sparkle/admin/phpconfig/overview_overview.tpl b/templates/Sparkle/admin/phpconfig/overview_overview.tpl index 2df5fd6f..0ccc9f58 100644 --- a/templates/Sparkle/admin/phpconfig/overview_overview.tpl +++ b/templates/Sparkle/admin/phpconfig/overview_overview.tpl @@ -1,7 +1,11 @@ {$row['description']} {$domains} - {$row['binary']} + + {$row['fpmdesc']} + + {$row['binary']} + {$row['file_extensions']} From 73868b794774567bbd8e5f3bc1c07a7cd6a95b14 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 7 Jan 2018 23:31:39 +0100 Subject: [PATCH 105/179] soften the file cleaning to reduce risk Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/webserver/class.ConfigIO.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/classes/webserver/class.ConfigIO.php b/lib/classes/webserver/class.ConfigIO.php index 10fe1b50..14e95085 100644 --- a/lib/classes/webserver/class.ConfigIO.php +++ b/lib/classes/webserver/class.ConfigIO.php @@ -65,7 +65,7 @@ class ConfigIO // now get rid of old stuff // (but append /*.log so we don't delete the directory) $err_dir .= '/*.log'; - safe_exec('rm -rf ' . makeCorrectFile($err_dir)); + safe_exec('rm -f ' . makeCorrectFile($err_dir)); } } @@ -92,7 +92,7 @@ class ConfigIO // now get rid of old stuff // (but append /* so we don't delete the directory) $configdir .= '/*'; - safe_exec('rm -rf ' . makeCorrectFile($configdir)); + safe_exec('rm -f ' . makeCorrectFile($configdir)); } } } @@ -159,7 +159,7 @@ class ConfigIO // now get rid of old stuff // (but append /* so we don't delete the directory) $configdir .= '/*'; - safe_exec('rm -rf ' . makeCorrectFile($configdir)); + safe_exec('rm -f ' . makeCorrectFile($configdir)); } } } @@ -269,9 +269,9 @@ class ConfigIO $configdir = makeCorrectDir($configdir['config_dir']); if (@is_dir($configdir)) { // now get rid of old stuff - // (but append /* so we don't delete the directory) - $configdir .= '/*'; - safe_exec('rm -rf ' . makeCorrectFile($configdir)); + // (but append /*.conf so we don't delete the directory) + $configdir .= '/*.conf'; + safe_exec('rm -f ' . makeCorrectFile($configdir)); } else { safe_exec('mkdir -p ' . $configdir); } From 07caf55f79ed0f9d39738dbe5c55b7a63568bc2f Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 8 Jan 2018 09:16:00 +0100 Subject: [PATCH 106/179] fixes to multi-fpm in cron Signed-off-by: Michael Kaufmann (d00p) --- .../phpinterface/class.phpinterface_fpm.php | 5 ++- lib/classes/webserver/class.WebserverBase.php | 34 ++++++++++++------- .../jobs/cron_tasks.inc.http.10.apache.php | 12 ++++++- .../cron_tasks.inc.http.15.apache_fcgid.php | 13 ++++++- 4 files changed, 48 insertions(+), 16 deletions(-) diff --git a/lib/classes/phpinterface/class.phpinterface_fpm.php b/lib/classes/phpinterface/class.phpinterface_fpm.php index b4a577ac..2f84a2a2 100644 --- a/lib/classes/phpinterface/class.phpinterface_fpm.php +++ b/lib/classes/phpinterface/class.phpinterface_fpm.php @@ -160,6 +160,9 @@ class phpinterface_fpm */ public function __construct($domain) { + if (!isset($domain['fpm_config_id']) || empty($domain['fpm_config_id'])) { + $domain['fpm_config_id'] = 1; + } $this->_domain = $domain; $this->_readFpmConfig($domain['fpm_config_id']); } @@ -354,7 +357,7 @@ class phpinterface_fpm */ public function getConfigFile($createifnotexists = true) { - $configdir = $this->_fpm_cfg['config_path']; + $configdir = $this->_fpm_cfg['config_dir']; $config = makeCorrectFile($configdir . '/' . $this->_domain['domain'] . '.conf'); if (! is_dir($configdir) && $createifnotexists) { diff --git a/lib/classes/webserver/class.WebserverBase.php b/lib/classes/webserver/class.WebserverBase.php index 5181bd25..f16073c8 100644 --- a/lib/classes/webserver/class.WebserverBase.php +++ b/lib/classes/webserver/class.WebserverBase.php @@ -46,6 +46,22 @@ class WebserverBase $result_domains_stmt = Database::query($query); + // prepare IP statement + $ip_stmt = Database::prepare(" + SELECT `di`.`id_domain` , `p`.`ssl`, `p`.`ssl_cert_file`, `p`.`ssl_key_file`, `p`.`ssl_ca_file`, `p`.`ssl_cert_chainfile` + FROM `" . TABLE_DOMAINTOIP . "` `di`, `" . TABLE_PANEL_IPSANDPORTS . "` `p` + WHERE `p`.`id` = `di`.`id_ipandports` + AND `di`.`id_domain` = :domainid + AND `p`.`ssl` = '1' + "); + + // prepare fpm-config select query + $fpm_sel_stmt = Database::prepare(" + SELECT f.id FROM `" . TABLE_PANEL_FPMDAEMONS . "` f + LEFT JOIN `" . TABLE_PANEL_PHPCONFIGS . "` p ON p.fpmsettingid = f.id + WHERE p.id = :phpconfigid + "); + $domains = array(); while ($domain = $result_domains_stmt->fetch(PDO::FETCH_ASSOC)) { @@ -61,14 +77,7 @@ class WebserverBase // now, if the domain has an ssl ip/port assigned, get // the corresponding information from the db if (domainHasSslIpPort($domain['id'])) { - - $ip_stmt = Database::prepare(" - SELECT `di`.`id_domain` , `p`.`ssl`, `p`.`ssl_cert_file`, `p`.`ssl_key_file`, `p`.`ssl_ca_file`, `p`.`ssl_cert_chainfile` - FROM `" . TABLE_DOMAINTOIP . "` `di`, `" . TABLE_PANEL_IPSANDPORTS . "` `p` - WHERE `p`.`id` = `di`.`id_ipandports` - AND `di`.`id_domain` = :domainid - AND `p`.`ssl` = '1' - "); + $ssl_ip = Database::pexecute_first($ip_stmt, array( 'domainid' => $domain['id'] )); @@ -83,16 +92,15 @@ class WebserverBase // read fpm-config-id if using fpm if ((int) Settings::Get('phpfpm.enabled') == 1) { - $fpm_sel_stmt = Database::prepare(" - SELECT f.id FROM `" . TABLE_PANEL_FPMDAEMONS . "` f - LEFT JOIN `" . TABLE_PANEL_PHPCONFIGS . "` p ON p.fpmsettingid = f.id - WHERE p.id = :phpconfigid - "); + $fpm_config = Database::pexecute_first($fpm_sel_stmt, array( 'phpconfigid' => $domain['phpsettingid'] )); if ($fpm_config) { $domains[$domain['domain']]['fpm_config_id'] = $fpm_config['id']; + } else { + // fallback + $domains[$domain['domain']]['fpm_config_id'] = 1; } } } diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index f4107512..c594e6d3 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -287,6 +287,15 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; } } elseif (Settings::Get('phpfpm.enabled') == '1') { + // get fpm config + $fpm_sel_stmt = Database::prepare(" + SELECT f.id FROM `" . TABLE_PANEL_FPMDAEMONS . "` f + LEFT JOIN `" . TABLE_PANEL_PHPCONFIGS . "` p ON p.fpmsettingid = f.id + WHERE p.id = :phpconfigid + "); + $fpm_config = Database::pexecute_first($fpm_sel_stmt, array( + 'phpconfigid' => Settings::Get('phpfpm.vhost_defaultini') + )); // create php-fpm -Part (config is created in apache_fcgid) $domain = array( 'id' => 'none', @@ -298,7 +307,8 @@ class apache extends HttpConfigBase 'openbasedir' => 0, 'email' => Settings::Get('panel.adminmail'), 'loginname' => 'froxlor.panel', - 'documentroot' => $mypath + 'documentroot' => $mypath, + 'fpm_config_id' => isset($fpm_config['id']) ? $fpm_config['id'] : 1 ); $php = new phpinterface($domain); diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index 6c9bd2a2..ab53539c 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -155,6 +155,16 @@ class apache_fcgid extends apache ) { $user = Settings::Get('phpfpm.vhost_httpuser'); $group = Settings::Get('phpfpm.vhost_httpgroup'); + + // get fpm config + $fpm_sel_stmt = Database::prepare(" + SELECT f.id FROM `" . TABLE_PANEL_FPMDAEMONS . "` f + LEFT JOIN `" . TABLE_PANEL_PHPCONFIGS . "` p ON p.fpmsettingid = f.id + WHERE p.id = :phpconfigid + "); + $fpm_config = Database::pexecute_first($fpm_sel_stmt, array( + 'phpconfigid' => Settings::Get('phpfpm.vhost_defaultini') + )); } $domain = array( @@ -167,7 +177,8 @@ class apache_fcgid extends apache 'openbasedir' => 0, 'email' => Settings::Get('panel.adminmail'), 'loginname' => 'froxlor.panel', - 'documentroot' => $mypath + 'documentroot' => $mypath, + 'fpm_config_id' => isset($fpm_config['id']) ? $fpm_config['id'] : 1 ); // all the files and folders have to belong to the local user From ebd636494a4d35115f5204ec560a6c8374fe6e5f Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 8 Jan 2018 10:11:38 +0100 Subject: [PATCH 107/179] fix wrong table constant Signed-off-by: Michael Kaufmann (d00p) --- admin_phpsettings.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/admin_phpsettings.php b/admin_phpsettings.php index eb72f741..52809867 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -541,7 +541,7 @@ if ($page == 'overview') { } $upd_stmt = Database::prepare(" - UPDATE `" . TABLE_PANEL_PHPCONFIGS . "` SET + UPDATE `" . TABLE_PANEL_FPMDAEMONS . "` SET `description` = :desc, `reload_cmd` = :reload_cmd, `config_dir` = :config_dir, From 3dc6a64252b5cc38c2283600bebfcd7cdd6793f0 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 8 Jan 2018 10:22:09 +0100 Subject: [PATCH 108/179] fix pm select when editing fpmdaemon; fix saving of pm value Signed-off-by: Michael Kaufmann (d00p) --- admin_phpsettings.php | 8 ++++---- .../admin/phpconfig/formfield.fpmconfig_edit.php | 3 +-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/admin_phpsettings.php b/admin_phpsettings.php index 52809867..2b2e33b7 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -402,7 +402,7 @@ if ($page == 'overview') { $description = validate($_POST['description'], 'description'); $reload_cmd = validate($_POST['reload_cmd'], 'reload_cmd'); $config_dir = validate($_POST['config_dir'], 'config_dir'); - $pm = validate($_POST['pm'], 'pm'); + $pm = $_POST['pm']; $max_children = isset($_POST['max_children']) ? (int) $_POST['max_children'] : 0; $start_servers = isset($_POST['start_servers']) ? (int) $_POST['start_servers'] : 0; $min_spare_servers = isset($_POST['min_spare_servers']) ? (int) $_POST['min_spare_servers'] : 0; @@ -431,7 +431,7 @@ if ($page == 'overview') { 'desc' => $description, 'reload_cmd' => $reload_cmd, 'config_dir' => makeCorrectDir($config_dir), - 'pm' => pm, + 'pm' => $pm, 'max_children' => $max_children, 'start_servers' => $start_servers, 'min_spare_servers' => $min_spare_servers, @@ -528,7 +528,7 @@ if ($page == 'overview') { $description = validate($_POST['description'], 'description'); $reload_cmd = validate($_POST['reload_cmd'], 'reload_cmd'); $config_dir = validate($_POST['config_dir'], 'config_dir'); - $pm = validate($_POST['pm'], 'pm'); + $pm = $_POST['pm']; $max_children = isset($_POST['max_children']) ? (int) $_POST['max_children'] : $result['max_children']; $start_servers = isset($_POST['start_servers']) ? (int) $_POST['start_servers'] : $result['start_servers']; $min_spare_servers = isset($_POST['min_spare_servers']) ? (int) $_POST['min_spare_servers'] : $result['min_spare_servers']; @@ -558,7 +558,7 @@ if ($page == 'overview') { 'desc' => $description, 'reload_cmd' => $reload_cmd, 'config_dir' => makeCorrectDir($config_dir), - 'pm' => pm, + 'pm' => $pm, 'max_children' => $max_children, 'start_servers' => $start_servers, 'min_spare_servers' => $min_spare_servers, diff --git a/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php index a06592ed..d5e8c17f 100644 --- a/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php @@ -45,8 +45,7 @@ return array( 'pm' => array( 'label' => $lng['serversettings']['phpfpm_settings']['pm'], 'type' => 'select', - 'select_var' => array('static' => 'static', 'dynamic' => 'dynamic', 'ondemand' => 'ondemand'), - 'value' => $result['pm'] + 'select_var' => $pm_select ), 'max_children' => array( 'label' => $lng['serversettings']['phpfpm_settings']['max_children']['title'], From b849a5f29a066e7c8a613edbbc9d5eac5e247989 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 8 Jan 2018 13:59:30 +0100 Subject: [PATCH 109/179] preparations for php-config select for customers Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 20 +++++-- customer_domains.php | 58 ++++++++++++++++++- install/froxlor.sql | 3 +- .../updates/froxlor/0.9/update_0.9.inc.php | 9 +++ .../domains/formfield.domains_add.php | 6 ++ .../domains/formfield.domains_edit.php | 6 ++ lib/version.inc.php | 2 +- 7 files changed, 97 insertions(+), 7 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index 5e410c45..9eb1934e 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -1077,11 +1077,15 @@ if ($page == 'domains' || $page == 'overview') { } $phpconfigs = ''; - $configs = Database::query("SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "`"); + $configs = Database::query(" + SELECT c.*, fc.description as interpreter + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid + "); while ($row = $configs->fetch(PDO::FETCH_ASSOC)) { if ((int) Settings::Get('phpfpm.enabled') == 1) { - $phpconfigs .= makeoption($row['description'], $row['id'], Settings::Get('phpfpm.defaultini'), true, true); + $phpconfigs .= makeoption($row['description'] . " [".$row['interpreter']."]", $row['id'], Settings::Get('phpfpm.defaultini'), true, true); } else { $phpconfigs .= makeoption($row['description'], $row['id'], Settings::Get('system.mod_fcgid_defaultini'), true, true); } @@ -2180,10 +2184,18 @@ if ($page == 'domains' || $page == 'overview') { $result['add_date'] = date('Y-m-d', $result['add_date']); $phpconfigs = ''; - $phpconfigs_result_stmt = Database::query("SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "`"); + $phpconfigs_result_stmt = Database::query(" + SELECT c.*, fc.description as interpreter + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid + "); while ($phpconfigs_row = $phpconfigs_result_stmt->fetch(PDO::FETCH_ASSOC)) { - $phpconfigs .= makeoption($phpconfigs_row['description'], $phpconfigs_row['id'], $result['phpsettingid'], true, true); + if ((int) Settings::Get('phpfpm.enabled') == 1) { + $phpconfigs .= makeoption($phpconfigs_row['description'] . " [".$phpconfigs_row['interpreter']."]", $phpconfigs_row['id'], $result['phpsettingid'], true, true); + } else { + $phpconfigs .= makeoption($phpconfigs_row['description'], $phpconfigs_row['id'], $result['phpsettingid'], true, true); + } } $result = htmlentities_array($result); diff --git a/customer_domains.php b/customer_domains.php index 3bfcd382..f14b69a7 100644 --- a/customer_domains.php +++ b/customer_domains.php @@ -405,6 +405,10 @@ if ($page == 'overview') { // assign default config $phpsid_result['phpsettingid'] = 1; } + // check whether the customer has chosen its own php-config + if (isset($_POST['phpsettingid']) && intval($_POST['phpsettingid']) != $phpsid_result['phpsettingid']) { + $phpsid_result['phpsettingid'] = intval($_POST['phpsettingid']); + } $stmt = Database::prepare("INSERT INTO `" . TABLE_PANEL_DOMAINS . "` SET `customerid` = :customerid, @@ -534,6 +538,27 @@ if ($page == 'overview') { $openbasedir = makeoption($lng['domain']['docroot'], 0, NULL, true) . makeoption($lng['domain']['homedir'], 1, NULL, true); $pathSelect = makePathfield($userinfo['documentroot'], $userinfo['guid'], $userinfo['guid']); + $phpconfigs = ''; + $has_phpconfigs = false; + if (isset($userinfo['allowed_phpconfigs']) && !empty($userinfo['allowed_phpconfigs'])) + { + $has_phpconfigs = true; + $allowed_cfg = json_decode($userinfo['allowed_phpconfigs'], JSON_OBJECT_AS_ARRAY); + $phpconfigs_result_stmt = Database::query(" + SELECT c.*, fc.description as interpreter + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid + WHERE c.id IN (".implode(", ", $allowed_cfg).") + "); + while ($phpconfigs_row = $phpconfigs_result_stmt->fetch(PDO::FETCH_ASSOC)) { + if ((int) Settings::Get('phpfpm.enabled') == 1) { + $phpconfigs .= makeoption($phpconfigs_row['description'] . " [".$phpconfigs_row['interpreter']."]", $phpconfigs_row['id'], Settings::Get('phpfpm.defaultini'), true, true); + } else { + $phpconfigs .= makeoption($phpconfigs_row['description'], $phpconfigs_row['id'], Settings::Get('system.mod_fcgid_defaultini'), true, true); + } + } + } + $subdomain_add_data = include_once dirname(__FILE__).'/lib/formfields/customer/domains/formfield.domains_add.php'; $subdomain_add_form = htmlform::genHTMLForm($subdomain_add_data); @@ -624,6 +649,13 @@ if ($page == 'overview') { $openbasedir_path = '0'; } + // check whether the customer has chosen its own php-config + if (isset($_POST['phpsettingid'])) { + $phpsettingid = intval($_POST['phpsettingid']); + } else { + $phpsettingid = $result['phpsettingid']; + } + if (isset($_POST['ssl_redirect']) && $_POST['ssl_redirect'] == '1') { // a ssl-redirect only works if there actually is a // ssl ip/port assigned to the domain @@ -692,6 +724,7 @@ if ($page == 'overview') { || $hsts_maxage != $result['hsts'] || $hsts_sub != $result['hsts_sub'] || $hsts_preload != $result['hsts_preload'] + || $phpsettingid != $result['phpsettingid'] ) { $log->logAction(USR_ACTION, LOG_INFO, "edited domain '" . $idna_convert->decode($result['domain']) . "'"); @@ -706,7 +739,8 @@ if ($page == 'overview') { `letsencrypt`= :letsencrypt, `hsts` = :hsts, `hsts_sub` = :hsts_sub, - `hsts_preload` = :hsts_preload + `hsts_preload` = :hsts_preload, + `phpsettingid` = :phpsettingid WHERE `customerid`= :customerid AND `id`= :id" ); @@ -722,6 +756,7 @@ if ($page == 'overview') { "hsts" => $hsts_maxage, "hsts_sub" => $hsts_sub, "hsts_preload" => $hsts_preload, + "phpsettingid" => $phpsettingid, "customerid" => $userinfo['customerid'], "id" => $id ); @@ -846,6 +881,27 @@ if ($page == 'overview') { $result_ipandport['ip'] .= $rowip['ip'] . "
"; } + $phpconfigs = ''; + $has_phpconfigs = false; + if (isset($userinfo['allowed_phpconfigs']) && !empty($userinfo['allowed_phpconfigs'])) + { + $has_phpconfigs = true; + $allowed_cfg = json_decode($userinfo['allowed_phpconfigs'], JSON_OBJECT_AS_ARRAY); + $phpconfigs_result_stmt = Database::query(" + SELECT c.*, fc.description as interpreter + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid + WHERE c.id IN (".implode(", ", $allowed_cfg).") + "); + while ($phpconfigs_row = $phpconfigs_result_stmt->fetch(PDO::FETCH_ASSOC)) { + if ((int) Settings::Get('phpfpm.enabled') == 1) { + $phpconfigs .= makeoption($phpconfigs_row['description'] . " [".$phpconfigs_row['interpreter']."]", $phpconfigs_row['id'], $result['phpsettingid'], true, true); + } else { + $phpconfigs .= makeoption($phpconfigs_row['description'], $phpconfigs_row['id'], $result['phpsettingid'], true, true); + } + } + } + $domainip = $result_ipandport['ip']; $result = htmlentities_array($result); diff --git a/install/froxlor.sql b/install/froxlor.sql index 4883fe14..3fdc57dd 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -198,6 +198,7 @@ CREATE TABLE `panel_customers` ( `lepublickey` mediumtext default NULL, `leprivatekey` mediumtext default NULL, `leregistered` tinyint(1) NOT NULL default '0', + `allowed_phpconfigs` varchar(500) NOT NULL default '', PRIMARY KEY (`customerid`), UNIQUE KEY `loginname` (`loginname`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; @@ -587,7 +588,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.8'), - ('panel', 'db_version', '201801070'); + ('panel', 'db_version', '201801080'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 8ae1c344..0483ba44 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3716,3 +3716,12 @@ if (isDatabaseVersion('201712310')) { updateToDbVersion('201801070'); } + +if (isDatabaseVersion('201801070')) { + + showUpdateStep("Adding field allowed_phpconfigs for customers"); + Database::query("ALTER TABLE `" . TABLE_PANEL_CUSTOMERS . "` ADD `allowed_phpconfigs` varchar(500) NOT NULL default '';"); + lastStepStatus(0); + + updateToDbVersion('201801080'); +} diff --git a/lib/formfields/customer/domains/formfield.domains_add.php b/lib/formfields/customer/domains/formfield.domains_add.php index 238adfff..ad660098 100644 --- a/lib/formfields/customer/domains/formfield.domains_add.php +++ b/lib/formfields/customer/domains/formfield.domains_add.php @@ -70,6 +70,12 @@ return array( 'label' => $lng['domain']['openbasedirpath'], 'type' => 'select', 'select_var' => $openbasedir + ), + 'phpsettingid' => array( + 'visible' => (((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) && $has_phpconfigs ? true : false), + 'label' => $lng['admin']['phpsettings']['title'], + 'type' => 'select', + 'select_var' => $phpconfigs ) ) ), diff --git a/lib/formfields/customer/domains/formfield.domains_edit.php b/lib/formfields/customer/domains/formfield.domains_edit.php index 6ac6d186..31910123 100644 --- a/lib/formfields/customer/domains/formfield.domains_edit.php +++ b/lib/formfields/customer/domains/formfield.domains_edit.php @@ -81,6 +81,12 @@ return array( 'label' => $lng['domain']['openbasedirpath'], 'type' => 'select', 'select_var' => $openbasedir + ), + 'phpsettingid' => array( + 'visible' => (((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) && $has_phpconfigs ? true : false), + 'label' => $lng['admin']['phpsettings']['title'], + 'type' => 'select', + 'select_var' => $phpconfigs ) ) ), diff --git a/lib/version.inc.php b/lib/version.inc.php index f6174b9a..5f433e8b 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201801070'; +$dbversion = '201801080'; // Distribution branding-tag (used for Debian etc.) $branding = ''; From c434249616c5c3b57c7504eed8cec903b44d65fc Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 8 Jan 2018 14:45:00 +0100 Subject: [PATCH 110/179] allow admin to set php-configs that can be used by customers Signed-off-by: Michael Kaufmann (d00p) --- admin_customers.php | 60 ++++++++++ .../admin/customer/formfield.customer_add.php | 112 +++++++++++++----- .../customer/formfield.customer_edit.php | 8 ++ 3 files changed, 149 insertions(+), 31 deletions(-) diff --git a/admin_customers.php b/admin_customers.php index 3a88dd38..74dc10b8 100644 --- a/admin_customers.php +++ b/admin_customers.php @@ -532,6 +532,14 @@ if ($page == 'customers' $phpenabled = intval($_POST['phpenabled']); } + $allowed_phpconfigs = array(); + if (isset($_POST['allowed_phpconfigs']) && is_array($_POST['allowed_phpconfigs'])) { + foreach ($_POST['allowed_phpconfigs'] as $allowed_phpconfig) { + $allowed_phpconfig = intval($allowed_phpconfig); + $allowed_phpconfigs[] = $allowed_phpconfig; + } + } + $perlenabled = 0; if (isset($_POST['perlenabled'])) { $perlenabled = intval($_POST['perlenabled']); @@ -693,6 +701,7 @@ if ($page == 'customers' 'tickets' => $tickets, 'mysqls' => $mysqls, 'phpenabled' => $phpenabled, + 'allowed_phpconfigs' => empty($allowed_phpconfigs) ? "" : json_encode($allowed_phpconfigs), 'imap' => $email_imap, 'pop3' => $email_pop3, 'perlenabled' => $perlenabled, @@ -733,6 +742,7 @@ if ($page == 'customers' `mysqls` = :mysqls, `standardsubdomain` = '0', `phpenabled` = :phpenabled, + `allowed_phpconfigs` = :allowed_phpconfigs, `imap` = :imap, `pop3` = :pop3, `perlenabled` = :perlenabled, @@ -1043,6 +1053,26 @@ if ($page == 'customers' $gender_options .= makeoption($lng['gender']['male'], 1, null, true, true); $gender_options .= makeoption($lng['gender']['female'], 2, null, true, true); + $phpconfigs = array(); + $configs = Database::query(" + SELECT c.*, fc.description as interpreter + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid + "); + while ($row = $configs->fetch(PDO::FETCH_ASSOC)) { + if ((int) Settings::Get('phpfpm.enabled') == 1) { + $phpconfigs[] = array( + 'label' => $row['description'] . " [".$row['interpreter']."]
", + 'value' => $row['id'] + ); + } else { + $phpconfigs[] = array( + 'label' => $row['description']."
", + 'value' => $row['id'] + ); + } + } + $customer_add_data = include_once dirname(__FILE__).'/lib/formfields/admin/customer/formfield.customer_add.php'; $customer_add_form = htmlform::genHTMLForm($customer_add_data); @@ -1205,6 +1235,14 @@ if ($page == 'customers' $phpenabled = intval($_POST['phpenabled']); } + $allowed_phpconfigs = array(); + if (isset($_POST['allowed_phpconfigs']) && is_array($_POST['allowed_phpconfigs'])) { + foreach ($_POST['allowed_phpconfigs'] as $allowed_phpconfig) { + $allowed_phpconfig = intval($allowed_phpconfig); + $allowed_phpconfigs[] = $allowed_phpconfig; + } + } + $perlenabled = 0; if (isset($_POST['perlenabled'])) { $perlenabled = intval($_POST['perlenabled']); @@ -1457,6 +1495,7 @@ if ($page == 'customers' 'mysqls' => $mysqls, 'deactivated' => $deactivated, 'phpenabled' => $phpenabled, + 'allowed_phpconfigs' => empty($allowed_phpconfigs) ? "" : json_encode($allowed_phpconfigs), 'imap' => $email_imap, 'pop3' => $email_pop3, 'perlenabled' => $perlenabled, @@ -1490,6 +1529,7 @@ if ($page == 'customers' `mysqls` = :mysqls, `deactivated` = :deactivated, `phpenabled` = :phpenabled, + `allowed_phpconfigs` = :allowed_phpconfigs, `email_quota` = :email_quota, `imap` = :imap, `pop3` = :pop3, @@ -1695,6 +1735,26 @@ if ($page == 'customers' $gender_options .= makeoption($lng['gender']['male'], 1, ($result['gender'] == '1' ? true : false), true, true); $gender_options .= makeoption($lng['gender']['female'], 2, ($result['gender'] == '2' ? true : false), true, true); + $phpconfigs = array(); + $configs = Database::query(" + SELECT c.*, fc.description as interpreter + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid + "); + while ($row = $configs->fetch(PDO::FETCH_ASSOC)) { + if ((int) Settings::Get('phpfpm.enabled') == 1) { + $phpconfigs[] = array( + 'label' => $row['description'] . " [".$row['interpreter']."]
", + 'value' => $row['id'] + ); + } else { + $phpconfigs[] = array( + 'label' => $row['description']."
", + 'value' => $row['id'] + ); + } + } + $customer_edit_data = include_once dirname(__FILE__).'/lib/formfields/admin/customer/formfield.customer_edit.php'; $customer_edit_form = htmlform::genHTMLForm($customer_edit_data); diff --git a/lib/formfields/admin/customer/formfield.customer_add.php b/lib/formfields/admin/customer/formfield.customer_add.php index eaa408aa..9d3d26ef 100644 --- a/lib/formfields/admin/customer/formfield.customer_add.php +++ b/lib/formfields/admin/customer/formfield.customer_add.php @@ -14,7 +14,6 @@ * @package Formfields * */ - return array( 'customer_add' => array( 'title' => $lng['admin']['customer_add'], @@ -29,20 +28,30 @@ return array( 'type' => 'text' ), 'createstdsubdomain' => array( - 'label' => $lng['admin']['stdsubdomain_add'].'?', + 'label' => $lng['admin']['stdsubdomain_add'] . '?', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), - 'value' => array('1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + '1' + ) ), 'store_defaultindex' => array( - 'label' => $lng['admin']['store_defaultindex'].'?', + 'label' => $lng['admin']['store_defaultindex'] . '?', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), - 'value' => array('1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + '1' + ) ), 'new_customer_password' => array( 'label' => $lng['login']['password'], @@ -53,15 +62,20 @@ return array( 'label' => $lng['customer']['generated_pwd'], 'type' => 'text', 'visible' => (Settings::Get('panel.password_regex') == ''), - 'value' => generatePassword(), + 'value' => generatePassword() ), 'sendpassword' => array( 'label' => $lng['admin']['sendpassword'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), - 'value' => array('1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + '1' + ) ), 'def_language' => array( 'label' => $lng['login']['language'], @@ -135,7 +149,10 @@ return array( 'label' => $lng['usersettings']['custom_notes']['show'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), 'value' => array() ) @@ -206,18 +223,28 @@ return array( 'label' => $lng['customer']['email_imap'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), - 'value' => array('1'), + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + '1' + ), 'mandatory' => true ), 'email_pop3' => array( 'label' => $lng['customer']['email_pop3'], 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), - 'value' => array('1'), + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + '1' + ), 'mandatory' => true ), 'ftps' => array( @@ -244,28 +271,51 @@ return array( 'ul_field' => $mysqls_ul ), 'phpenabled' => array( - 'label' => $lng['admin']['phpenabled'].'?', + 'label' => $lng['admin']['phpenabled'] . '?', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), - 'value' => array('1') + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + '1' + ) + ), + 'allowed_phpconfigs' => array( + 'visible' => (((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) ? true : false), + 'label' => $lng['admin']['phpsettings']['title'], + 'type' => 'checkbox', + 'values' => $phpconfigs, + 'value' => ((int) Settings::Get('system.mod_fcgid') == 1 ? array( + Settings::Get('system.mod_fcgid_defaultini') + ) : (int) Settings::Get('phpfpm.enabled') == 1) ? array( + Settings::Get('phpfpm.defaultini') + ) : array(), + 'is_array' => 1 ), 'perlenabled' => array( - 'label' => $lng['admin']['perlenabled'].'?', + 'label' => $lng['admin']['perlenabled'] . '?', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ) + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ) ), 'dnsenabled' => array( - 'label' => $lng['admin']['dnsenabled'].'?', + 'label' => $lng['admin']['dnsenabled'] . '?', 'type' => 'checkbox', 'values' => array( - array ('label' => $lng['panel']['yes'], 'value' => '1') - ), + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), 'visible' => (Settings::Get('system.dnsenabled') == '1' ? true : false) - ), + ) ) ) ) diff --git a/lib/formfields/admin/customer/formfield.customer_edit.php b/lib/formfields/admin/customer/formfield.customer_edit.php index b099651f..c5f74d74 100644 --- a/lib/formfields/admin/customer/formfield.customer_edit.php +++ b/lib/formfields/admin/customer/formfield.customer_edit.php @@ -260,6 +260,14 @@ return array( ), 'value' => array($result['phpenabled']) ), + 'allowed_phpconfigs' => array( + 'visible' => (((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) ? true : false), + 'label' => $lng['admin']['phpsettings']['title'], + 'type' => 'checkbox', + 'values' => $phpconfigs, + 'value' => isset($result['allowed_phpconfigs']) && !empty($result['allowed_phpconfigs']) ? json_decode($result['allowed_phpconfigs'], JSON_OBJECT_AS_ARRAY) : array(), + 'is_array' => 1 + ), 'perlenabled' => array( 'label' => $lng['admin']['perlenabled'].'?', 'type' => 'checkbox', From eaa10ce6a5387d19c3d6ab16a573d0e37286631a Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 8 Jan 2018 15:31:27 +0100 Subject: [PATCH 111/179] add option to update php-configs for all subdomains when editing a domain as admin (default: yes) Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 16 +++++++++++++--- .../admin/domains/formfield.domains_edit.php | 15 +++++++++++++++ lng/english.lng.php | 2 ++ lng/german.lng.php | 2 ++ 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index 9eb1934e..0faa8854 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -1363,6 +1363,7 @@ if ($page == 'domains' || $page == 'overview') { $phpenabled = isset($_POST['phpenabled']) ? intval($_POST['phpenabled']) : 0; $openbasedir = isset($_POST['openbasedir']) ? intval($_POST['openbasedir']) : 0; + $phpfs = (isset($_POST['phpsettingsforsubdomains']) && intval($_POST['phpsettingsforsubdomains']) == 1) ? 1 : 0; if ((int) Settings::Get('system.mod_fcgid') == 1 || (int) Settings::Get('phpfpm.enabled') == 1) { $phpsettingid = (int) $_POST['phpsettingid']; @@ -1392,6 +1393,7 @@ if ($page == 'domains' || $page == 'overview') { } } else { $phpsettingid = $result['phpsettingid']; + $phpfs = 1; $mod_fcgid_starter = $result['mod_fcgid_starter']; $mod_fcgid_maxrequests = $result['mod_fcgid_maxrequests']; } @@ -1399,6 +1401,7 @@ if ($page == 'domains' || $page == 'overview') { $phpenabled = $result['phpenabled']; $openbasedir = $result['openbasedir']; $phpsettingid = $result['phpsettingid']; + $phpfs = 1; $mod_fcgid_starter = $result['mod_fcgid_starter']; $mod_fcgid_maxrequests = $result['mod_fcgid_maxrequests']; } @@ -1637,6 +1640,7 @@ if ($page == 'domains' || $page == 'overview') { 'phpenabled' => $phpenabled, 'openbasedir' => $openbasedir, 'phpsettingid' => $phpsettingid, + 'phpsettingsforsubdomains' => $phpfs, 'mod_fcgid_starter' => $mod_fcgid_starter, 'mod_fcgid_maxrequests' => $mod_fcgid_maxrequests, 'specialsettings' => $specialsettings, @@ -1892,11 +1896,18 @@ if ($page == 'domains' || $page == 'overview') { $_update_data['adminid'] = $adminid; $_update_data['phpenabled'] = $phpenabled; $_update_data['openbasedir'] = $openbasedir; - $_update_data['phpsettingid'] = $phpsettingid; $_update_data['mod_fcgid_starter'] = $mod_fcgid_starter; $_update_data['mod_fcgid_maxrequests'] = $mod_fcgid_maxrequests; $_update_data['parentdomainid'] = $id; + // if php config is to be set for all subdomains, check here + $update_phpconfig = ''; + $phpfs = isset($_POST['phpsettingsforsubdomains']) ? 1 : 0; + if ($phpfs == 1) { + $_update_data['phpsettingid'] = $phpsettingid; + $update_phpconfig = ", `phpsettingid` = :phpsettingid"; + } + // if we have no more ssl-ip's for this domain, // all its subdomains must have "ssl-redirect = 0" // and disable let's encrypt @@ -1911,10 +1922,9 @@ if ($page == 'domains' || $page == 'overview') { `adminid` = :adminid, `phpenabled` = :phpenabled, `openbasedir` = :openbasedir, - `phpsettingid` = :phpsettingid, `mod_fcgid_starter` = :mod_fcgid_starter, `mod_fcgid_maxrequests` = :mod_fcgid_maxrequests - " . $upd_specialsettings . $updatechildren . $update_sslredirect . " + " . $update_phpconfig . $upd_specialsettings . $updatechildren . $update_sslredirect . " WHERE `parentdomainid` = :parentdomainid "); Database::pexecute($_update_stmt, $_update_data); diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index d668aa9d..5588ab69 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -325,6 +325,21 @@ return array( 'type' => 'select', 'select_var' => $phpconfigs ), + 'phpsettingsforsubdomains' => array( + 'visible' => ($userinfo['change_serversettings'] == '1' ? true : false), + 'label' => $lng['admin']['phpsettingsforsubdomains'], + 'desc' => $lng['serversettings']['phpsettingsforsubdomains']['description'], + 'type' => 'checkbox', + 'values' => array( + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + '1' + ) + ), 'mod_fcgid_starter' => array( 'visible' => ((int) Settings::Get('system.mod_fcgid') == 1 ? true : false), 'label' => $lng['admin']['mod_fcgid_starter']['title'], diff --git a/lng/english.lng.php b/lng/english.lng.php index 2a850d00..039073ff 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2086,3 +2086,5 @@ $lng['serversettings']['disable_le_selfcheck']['title'] = "Disable Let's Encrypt $lng['serversettings']['disable_le_selfcheck']['description'] = "If activated, froxlor will not perform its self-check for token accessability. Needed for NATed IP's or similar."; $lng['menue']['phpsettings']['fpmdaemons'] = 'PHP-FPM versions'; $lng['admin']['phpsettings']['activephpconfigs'] = 'In use for php-config(s)'; +$lng['admin']['phpsettingsforsubdomains'] = 'Apply php-config to all subdomains:'; +$lng['serversettings']['phpsettingsforsubdomains']['description'] = 'If yes the chosen php-config will be updated to all subdomains'; diff --git a/lng/german.lng.php b/lng/german.lng.php index f20700ec..941ebf82 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1737,3 +1737,5 @@ $lng['serversettings']['disable_le_selfcheck']['title'] = "Deaktiviere Let's Enc $lng['serversettings']['disable_le_selfcheck']['description'] = "Wenn aktiviert wird Froxlor keine Erreichbarkeitsprüfung des Tokens vornehmen. Nötig bei ge-NAT-eten IP's oder Ähnlichem"; $lng['menue']['phpsettings']['fpmdaemons'] = 'PHP-FPM Versionen'; $lng['admin']['phpsettings']['activephpconfigs'] = 'In Verwendung für PHP-Konfiguration(en)'; +$lng['admin']['phpsettingsforsubdomains'] = 'PHP-Config für alle Subdomains übernehmen:'; +$lng['serversettings']['phpsettingsforsubdomains']['description'] = 'Wenn ja, wird die gewählte PHP-Config für alle Subdomains übernommen'; From d8abe30c449c3471ca5c3d698fc0e9a8fdd02a97 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 09:25:56 +0100 Subject: [PATCH 112/179] create dummy pool-config whenever a fpm-daemons configdir is empty so it still restarts Signed-off-by: Michael Kaufmann (d00p) --- .../phpinterface/class.phpinterface_fpm.php | 21 +++++++++++++++++++ .../jobs/cron_tasks.inc.http.10.apache.php | 9 +++++++- .../jobs/cron_tasks.inc.http.20.lighttpd.php | 9 +++++++- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 9 +++++++- 4 files changed, 45 insertions(+), 3 deletions(-) diff --git a/lib/classes/phpinterface/class.phpinterface_fpm.php b/lib/classes/phpinterface/class.phpinterface_fpm.php index 2f84a2a2..2622b090 100644 --- a/lib/classes/phpinterface/class.phpinterface_fpm.php +++ b/lib/classes/phpinterface/class.phpinterface_fpm.php @@ -435,6 +435,27 @@ class phpinterface_fpm return $configdir; } + /** + * create a dummy fpm pool config with minimal configuration + * (this is used whenever a config directory is empty but needs at least one pool to startup/restart) + * + * @param string $configdir + */ + public static function createDummyPool($configdir) + { + if (! is_dir($configdir)) { + safe_exec('mkdir -p ' . escapeshellarg($configdir)); + } + $config = makeCorrectFile($configdir . '/dummy.conf'); + $dummy = "[dummy] +user = ".Settings::Get('system.httpuser')." +listen = /run/" . base64_encode($configdir) . "-fpm.sock +pm = static +pm.max_children = 1 +"; + file_put_contents($config, $dummy); + } + /** * return the admin-data of a specific admin * diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index c594e6d3..5887e9a7 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -59,11 +59,18 @@ class apache extends HttpConfigBase { if ((int) Settings::Get('phpfpm.enabled') == 1) { // get all start/stop commands - $startstop_sel = Database::prepare("SELECT reload_cmd FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); + $startstop_sel = Database::prepare("SELECT reload_cmd, config_dir FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); Database::pexecute($startstop_sel); $restart_cmds = $startstop_sel->fetchAll(PDO::FETCH_ASSOC); // restart all php-fpm instances foreach ($restart_cmds as $restart_cmd) { + // check whether the config dir is empty (no domains uses this daemon) + // so we need to create a dummy + $isDirEmpty = !(new \FilesystemIterator($restart_cmd['config_dir']))->valid(); + if ($isDirEmpty) { + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::reload: fpm config directory "' . $restart_cmd['config_dir'] . '" is empty. Creating dummy.'); + phpinterface_fpm::createDummyPool($restart_cmd['config_dir']); + } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::reload: running ' . $restart_cmd['reload_cmd']); safe_exec(escapeshellcmd($restart_cmd['reload_cmd'])); } diff --git a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php index 3525a471..99232c8c 100644 --- a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php +++ b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php @@ -59,11 +59,18 @@ class lighttpd extends HttpConfigBase { if ((int) Settings::Get('phpfpm.enabled') == 1) { // get all start/stop commands - $startstop_sel = Database::prepare("SELECT reload_cmd FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); + $startstop_sel = Database::prepare("SELECT reload_cmd, config_dir FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); Database::pexecute($startstop_sel); $restart_cmds = $startstop_sel->fetchAll(PDO::FETCH_ASSOC); // restart all php-fpm instances foreach ($restart_cmds as $restart_cmd) { + // check whether the config dir is empty (no domains uses this daemon) + // so we need to create a dummy + $isDirEmpty = !(new \FilesystemIterator($restart_cmd['config_dir']))->valid(); + if ($isDirEmpty) { + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'lighttpd::reload: fpm config directory "' . $restart_cmd['config_dir'] . '" is empty. Creating dummy.'); + phpinterface_fpm::createDummyPool($restart_cmd['config_dir']); + } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'lighttpd::reload: running ' . $restart_cmd['reload_cmd']); safe_exec(escapeshellcmd($restart_cmd['reload_cmd'])); } diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index 2bf53daa..0685ed7c 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -74,11 +74,18 @@ class nginx extends HttpConfigBase safe_exec(Settings::Get('system.phpreload_command')); } elseif ((int) Settings::Get('phpfpm.enabled') == 1) { // get all start/stop commands - $startstop_sel = Database::prepare("SELECT reload_cmd FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); + $startstop_sel = Database::prepare("SELECT reload_cmd, config_dir FROM `" . TABLE_PANEL_FPMDAEMONS . "`"); Database::pexecute($startstop_sel); $restart_cmds = $startstop_sel->fetchAll(PDO::FETCH_ASSOC); // restart all php-fpm instances foreach ($restart_cmds as $restart_cmd) { + // check whether the config dir is empty (no domains uses this daemon) + // so we need to create a dummy + $isDirEmpty = !(new \FilesystemIterator($restart_cmd['config_dir']))->valid(); + if ($isDirEmpty) { + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'nginx::reload: fpm config directory "' . $restart_cmd['config_dir'] . '" is empty. Creating dummy.'); + phpinterface_fpm::createDummyPool($restart_cmd['config_dir']); + } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'nginx::reload: running ' . $restart_cmd['reload_cmd']); safe_exec(escapeshellcmd($restart_cmd['reload_cmd'])); } From 3969ef63c5b96180a9239166e3b232b7e4ed657b Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 11:18:03 +0100 Subject: [PATCH 113/179] do not check hide-options 'domains' in customer_tickets, fixes #502 Signed-off-by: Michael Kaufmann (d00p) --- customer_tickets.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/customer_tickets.php b/customer_tickets.php index d8562826..1a7508b9 100644 --- a/customer_tickets.php +++ b/customer_tickets.php @@ -20,10 +20,6 @@ define('AREA', 'customer'); require './lib/init.php'; -// redirect if this customer page is hidden via settings -if (Settings::IsInList('panel.customer_hide_options','domains')) { - redirectTo('customer_index.php'); -} if (isset($_POST['id'])) { From 9aaadb1f8b4997fe9c6b82131f7581f1199e15e4 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 14:40:36 +0100 Subject: [PATCH 114/179] implement lets-encrypt api-v02 (testing only currently; not activated in froxlor, test with 'php froxlor_master_cronjob.php --letsencrypt_v2 --debug' but set api endpoint to staging); no chain is returned currently, seems to be a known bug Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/ssl/class.lescript.php | 75 +--- lib/classes/ssl/class.lescript_v2.php | 599 ++++++++++++++++++++++++++ scripts/jobs/cron_letsencrypt_v2.php | 292 +++++++++++++ 3 files changed, 898 insertions(+), 68 deletions(-) create mode 100644 lib/classes/ssl/class.lescript_v2.php create mode 100644 scripts/jobs/cron_letsencrypt_v2.php diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index 9923d5b0..c1745be7 100644 --- a/lib/classes/ssl/class.lescript.php +++ b/lib/classes/ssl/class.lescript.php @@ -30,7 +30,6 @@ class lescript { // https://letsencrypt.org/repository/ - public $license; private $logger; @@ -111,19 +110,7 @@ class lescript } $accountUrl=$this->client->getLastLocation(); - $this->log('Accepting lets encrypt Terms of Service'); - - $this->license = $this->client->getAgreementURL(); - - // Terms of Service are optional according to ACME specs; if no ToS are presented, no need to update registration - if (!empty($this->license)) { - $response = $this->postRegAgreement(parse_url($accountUrl, PHP_URL_PATH)); - if ($this->client->getLastCode() != 202) { - throw new \RuntimeException("Terms of Service not accepted. Whole response: " . json_encode($response)); - } - } - - $leregistered=1; + $leregistered = 1; $this->setLeRegisteredState($leregistered); // Account registered $this->log('Lets encrypt Terms of Service accepted'); } @@ -373,21 +360,16 @@ class lescript private function postNewReg() { + $this->log('Getting last terms of service URL'); + $directory = $this->client->get('/directory'); + if (!isset($directory['meta']) || !isset($directory['meta']['terms-of-service'])) { + throw new \RuntimeException("No terms of service link available!"); + } $this->log('Sending registration to letsencrypt server'); return $this->signedRequest('/acme/new-reg', array( 'resource' => 'new-reg', - 'agreement' => $this->license - )); - } - - private function postRegAgreement($uri) - { - $this->log('Accepting agreement at URL: ' . $this->license); - - return $this->signedRequest($uri, array( - 'resource' => 'reg', - 'agreement' => $this->license + 'agreement' => $directory['meta']['terms-of-service'] )); } @@ -592,49 +574,6 @@ class Client preg_match_all('~Link: <(.+)>;rel="up"~', $this->lastHeader, $matches); return $matches[1]; } - - public function getAgreementURLFromLastResponse() - { - if (preg_match_all('~Link: <(.+)>;rel="terms-of-service"~', $this->lastHeader, $matches)) { - return $matches[1][0]; - } - return ""; - } - public function getAgreementURLFromDirectory() - { - // FIXME: Current license should be found in /directory but LE does not implement this yet - // $this->curl('GET', '/directory'); - return ""; - } - public function getAgreementURLFromTermsUrl() - { - $this->curl('GET', '/terms'); - if (preg_match_all('~Location: (.+)~', $this->lastHeader, $matches)) { - return trim($matches[1][0]); - } - return ""; - } - - public function getAgreementURL() - { - // 1. check the header of the last response - $license=$this->getAgreementURLFromLastResponse(); - if (!empty($license)) return $license; - - // 2. query directory for license - $license=$this->getAgreementURLFromDirectory(); - if (!empty($license)) return $license; - - // 3. query /terms endpoint (not ACME standard but implemented by let's enrypt) - $license=$this->getAgreementURLFromTermsUrl(); - if (!empty($license)) return $license; - - // Fallback: use latest known license. This is only valid for let's encrypt and should be removed as soon as there is an official - // ACME-endpoint to get the current ToS - return "https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"; - // return ""; - } - } class Base64UrlSafeEncoder diff --git a/lib/classes/ssl/class.lescript_v2.php b/lib/classes/ssl/class.lescript_v2.php new file mode 100644 index 00000000..074def62 --- /dev/null +++ b/lib/classes/ssl/class.lescript_v2.php @@ -0,0 +1,599 @@ + +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of the nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// This file is copied from https://github.com/analogic/lescript +// and modified to work without files and integrate in Froxlor +class lescript_v2 +{ + + // https://letsencrypt.org/repository/ + private $logger; + + private $client; + + private $accountKey; + + private $customerid; + + private $isFroxlorVhost; + + private $isLeProduction; + + private $version; + + private $_req_uris = array(); + + private $_acc_location = null; + + public function __construct($logger, $version = '2') + { + $this->logger = $logger; + $this->version = $version; + if (Settings::Get('system.letsencryptca') == 'production') { + $ca = 'https://acme-v02.api.letsencrypt.org'; + } else { + $ca = 'https://acme-staging-v02.api.letsencrypt.org'; + } + $this->client = new Client($ca); + $this->log("Using '$ca' to generate certificate"); + + // get request-uris from /directory + $response = $this->client->get('/directory'); + $this->_req_uris['newAccount'] = $response['newAccount']; + $this->_req_uris['newOrder'] = $response['newOrder']; + $this->_req_uris['newNonce'] = $response['newNonce']; + $this->_req_uris['revokeCert'] = $response['revokeCert']; + } + + public function initAccount($certrow, $isFroxlorVhost = false) + { + // Let's see if we have the private accountkey + $this->accountKey = $certrow['leprivatekey']; + $this->customerId = (! $isFroxlorVhost ? $certrow['customerid'] : null); + $this->isFroxlorVhost = $isFroxlorVhost; + $this->isLeProduction = (Settings::Get('system.letsencryptca') == 'production'); + + $leregistered = $certrow['leregistered']; + + if (! $this->accountKey || $this->accountKey == 'unset' || ! $this->isLeProduction) { + + // generate and save new private key for account + // --------------------------------------------- + + $this->log('Creating new account key'); + $keys = $this->generateKey(); + // Only store the accountkey in production, in staging always generate a new key + if ($this->isLeProduction) { + if ($isFroxlorVhost) { + Settings::Set('system.lepublickey', $keys['public']); + Settings::Set('system.leprivatekey', $keys['private']); + Settings::Set('system.leregistered', 0); // key is not registered + } else { + $upd_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `lepublickey` = :public, `leprivatekey` = :private, `leregistered` = :registered " . "WHERE `customerid` = :customerid;"); + Database::pexecute($upd_stmt, array( + 'public' => $keys['public'], + 'private' => $keys['private'], + 'registered' => 0, + 'customerid' => $this->customerId + )); + } + } + $leregistered = 0; + $this->accountKey = $keys['private']; + } else { + $this->log('Using existing account key'); + } + + if ($leregistered == 0) { // Account not registered + + $this->log('Starting new account registration'); + $response = $this->postNewReg(); + if ($this->client->getLastCode() == 409) { + $this->log('The key was already registered. Using existing account.'); + } else if ($this->client->getLastCode() == 201) { + $this->log('New account registered.'); + } else { + throw new \RuntimeException("Account not initialized, probably due to rate limiting. Whole response: " . json_encode($response)); + } + $this->_acc_location = $this->client->getLastLocation(); + + $leregistered = 1; + $this->setLeRegisteredState($leregistered); + } + } + + /** + * + * @param array $domains + * @param string $domainkey + * @param string $csr + * optional, same behavior as $reuseCsr from the original class, but we're passing the content of the csr already + * + * @throws \RuntimeException + * @return string[] + */ + public function signDomains(array $domains, $domainkey = null, $csr = null) + { + if (! $this->accountKey) { + throw new \RuntimeException("Account not initialized"); + } + + $this->log('Starting certificate generation process for domains'); + + $privateAccountKey = openssl_pkey_get_private($this->accountKey); + $accountKeyDetails = openssl_pkey_get_details($privateAccountKey); + + // start domains authentication + // ---------------------------- + + foreach ($domains as $domain) { + + // 1. getting available authentication options + // ------------------------------------------- + + $this->log("Requesting challenge for $domain"); + + $response = $this->signedRequest($this->_req_uris['newOrder'], array( + "identifiers" => array( + array( + "type" => "dns", + "value" => $domain + ) + ) + ), false); + + if ($this->client->getLastCode() == 403) { + $this->log("Got status 403 - setting LE status to unregistered."); + $this->setLeRegisteredState(0); + throw new RuntimeException("Got 'unauthorized' response - we need to re-register at next run. Whole response: " . json_encode($response)); + } + + // if response is not an array but a string, it's most likely a server-error, e.g. + // ErrorAn error occurred while processing your request. + //

Reference #179.d8be1402.1458059103.3613c4db + if (! is_array($response)) { + throw new RuntimeException("Invalid response from LE for domain $domain. Whole response: " . json_encode($response)); + } + + if (! array_key_exists('authorizations', $response)) { + throw new RuntimeException("No authorizations received for $domain. Whole response: " . json_encode($response)); + } + + // get authorization + $auth_response = $this->client->get($response['authorizations'][0]); + + if (! array_key_exists('challenges', $auth_response)) { + throw new RuntimeException("No challenges received for $domain. Whole response: " . json_encode($auth_response)); + } + + // choose http-01 challenge only + $challenge = array_reduce($auth_response['challenges'], function ($v, $w) { + return $v ? $v : ($w['type'] == 'http-01' ? $w : false); + }); + + if (! $challenge) { + throw new RuntimeException("HTTP Challenge for $domain is not available. Whole response: " . json_encode($response)); + } + + $this->log("Got challenge token for $domain"); + $location = $challenge['url']; + $finalizeLink = $response['finalize']; + + // 2. saving authentication token for web verification + // --------------------------------------------------- + + $directory = Settings::Get('system.letsencryptchallengepath') . '/.well-known/acme-challenge'; + $tokenPath = $directory . '/' . $challenge['token']; + + if (! file_exists($directory) && ! @mkdir($directory, 0755, true)) { + throw new \RuntimeException("Couldn't create directory to expose challenge: ${tokenPath}"); + } + + $header = array( + // need to be in precise order! + "e" => Base64UrlSafeEncoder::encode($accountKeyDetails["rsa"]["e"]), + "kty" => "RSA", + "n" => Base64UrlSafeEncoder::encode($accountKeyDetails["rsa"]["n"]) + ); + $payload = $challenge['token'] . '.' . Base64UrlSafeEncoder::encode(hash('sha256', json_encode($header), true)); + + file_put_contents($tokenPath, $payload); + chmod($tokenPath, 0644); + + // 3. verification process itself + // ------------------------------- + + $uri = "http://${domain}/.well-known/acme-challenge/${challenge['token']}"; + + $this->log("Token for $domain saved at $tokenPath and should be available at $uri"); + + // simple self check + if (Settings::Get('system.disable_le_selfcheck') == '0') { + $selfcheckContextOptions = array( + 'http' => array( + 'header' => "User-Agent: Froxlor/" . $this->version + ) + ); + $selfcheckContext = stream_context_create($selfcheckContextOptions); + if ($payload !== trim(@file_get_contents($uri, false, $selfcheckContext))) { + $errmsg = json_encode(error_get_last()); + if ($errmsg != "null") { + $errmsg = "; PHP error: " . $errmsg; + } else { + $errmsg = ""; + } + $this->logger->logAction(CRON_ACTION, LOG_WARNING, "[Lets Encrypt self-check] Please check $uri - token seems to be not available. This is just a simple self-check, it might be wrong but consider using this information when Let's Encrypt fails to issue a certificate" . $errmsg); + } + } + + $this->log("Sending request to challenge"); + + // send request to challenge + $result = $this->signedRequest($challenge['url'], array( + "type" => "http-01", + "keyAuthorization" => $payload, + "token" => $challenge['token'] + ), false); + + // waiting loop + // we wait for a maximum of 30 seconds to avoid endless loops + $count = 0; + do { + if (empty($result['status']) || $result['status'] == "invalid") { + @unlink($tokenPath); + throw new \RuntimeException("Verification ended with error: " . json_encode($result)); + } + $ended = ! ($result['status'] === "pending" || $result['status'] === "processing"); + + if (! $ended) { + $this->log("Verification " . $result['status'] . ", sleeping 1s"); + sleep(1); + $count ++; + } + + $result = $this->client->get($location); + } while (! $ended && $count < 30); + + $this->log("Verification ended with status: ${result['status']}"); + @unlink($tokenPath); + } + + // requesting certificate + // ---------------------- + + // generate private key for domain if not exist + if (empty($domainkey) || Settings::Get('system.letsencryptreuseold') == 0) { + $keys = $this->generateKey(); + $domainkey = $keys['private']; + } + + // load domain key + $privateDomainKey = openssl_pkey_get_private($domainkey); + + if (empty($csr)) { + $csr = $this->generateCSR($privateDomainKey, $domains); + } + + // request certificates creation + $result = $this->signedRequest($finalizeLink, array( + 'csr' => $csr + ), false); + if ($this->client->getLastCode() !== 200) { + throw new \RuntimeException("Invalid response code: " . $this->client->getLastCode() . ", " . json_encode($result)); + } + if (! isset($result['certificate'])) { + throw new \RuntimeException("No certificate URL specified in result"); + } + + $certificates = array(); + $certdata = $this->client->get($result['certificate']); + $this->log("Got certificate! YAY!"); + $certificates[] = $certdata; + foreach ($this->client->getLastLinks() as $link) { + $this->log("Requesting chained cert at $link"); + $result = $this->client->get($link); + $certificates[] = $result; + } + + if (empty($certificates)) + throw new \RuntimeException('No certificates generated'); + + $fullchain = implode("\n", $certificates); + $crt = array_shift($certificates); + $chain = implode("\n", $certificates); + + $this->log("Done, returning new certificates and key"); + return array( + 'fullchain' => $fullchain, + 'crt' => $crt, + 'chain' => $chain, + 'key' => $domainkey, + 'csr' => $csr + ); + } + + private function setLeRegisteredState($state) + { + if ($this->isLeProduction) { + if ($this->isFroxlorVhost) { + Settings::Set('system.leregistered', $state); + } else { + $upd_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `leregistered` = :registered " . "WHERE `customerid` = :customerid;"); + Database::pexecute($upd_stmt, array( + 'registered' => $state, + 'customerid' => $this->customerId + )); + } + } + } + + private function parsePemFromBody($body) + { + $pem = chunk_split(base64_encode($body), 64, "\n"); + return "-----BEGIN CERTIFICATE-----\n" . $pem . "-----END CERTIFICATE-----\n"; + } + + private function postNewReg() + { + $this->log('Getting last terms of service URL'); + $directory = $this->client->get('/directory'); + if (! isset($directory['meta']) || ! isset($directory['meta']['termsOfService'])) { + throw new \RuntimeException("No terms of service link available!"); + } + $this->log('Sending registration to letsencrypt server'); + + return $this->signedRequest($this->_req_uris['newAccount'], array( + 'termsOfServiceAgreed' => true + )); + } + + private function generateCSR($privateKey, array $domains) + { + $domain = reset($domains); + $san = implode(",", array_map(function ($dns) { + return "DNS:" . $dns; + }, $domains)); + $tmpConf = tmpfile(); + $tmpConfMeta = stream_get_meta_data($tmpConf); + $tmpConfPath = $tmpConfMeta["uri"]; + + // workaround to get SAN working + fwrite($tmpConf, 'HOME = . +RANDFILE = $ENV::HOME/.rnd +[ req ] +default_bits = ' . Settings::Get('system.letsencryptkeysize') . ' +default_keyfile = privkey.pem +distinguished_name = req_distinguished_name +req_extensions = v3_req +[ req_distinguished_name ] +countryName = Country Name (2 letter code) +[ v3_req ] +basicConstraints = CA:FALSE +subjectAltName = ' . $san . ' +keyUsage = nonRepudiation, digitalSignature, keyEncipherment'); + + $csr = openssl_csr_new(array( + "CN" => $domain, + "ST" => Settings::Get('system.letsencryptstate'), + "C" => Settings::Get('system.letsencryptcountrycode'), + "O" => "Unknown" + ), $privateKey, array( + "config" => $tmpConfPath, + "digest_alg" => "sha256" + )); + + if (! $csr) + throw new \RuntimeException("CSR couldn't be generated! " . openssl_error_string()); + + openssl_csr_export($csr, $csr); + fclose($tmpConf); + + preg_match('~REQUEST-----(.*)-----END~s', $csr, $matches); + + return trim(Base64UrlSafeEncoder::encode(base64_decode($matches[1]))); + } + + private function generateKey() + { + $res = openssl_pkey_new(array( + "private_key_type" => OPENSSL_KEYTYPE_RSA, + "private_key_bits" => (int) Settings::Get('system.letsencryptkeysize') + )); + + if (! openssl_pkey_export($res, $privateKey)) { + throw new \RuntimeException("Key export failed!"); + } + + $details = openssl_pkey_get_details($res); + + return array( + 'private' => $privateKey, + 'public' => $details['key'] + ); + } + + private function signedRequest($uri, array $payload, $needs_jwk = true) + { + $privateKey = openssl_pkey_get_private($this->accountKey); + $details = openssl_pkey_get_details($privateKey); + + $header = array( + "alg" => "RS256" + ); + + if ($needs_jwk) { + $header["jwk"] = array( + "kty" => "RSA", + "n" => Base64UrlSafeEncoder::encode($details["rsa"]["n"]), + "e" => Base64UrlSafeEncoder::encode($details["rsa"]["e"]) + ); + } else { + // need account-url + $header["kid"] = $this->_acc_location; + } + + $protected = $header; + $protected["nonce"] = $this->client->getLastNonce(); + $protected["url"] = $uri; + + $payload64 = Base64UrlSafeEncoder::encode(json_encode($payload, JSON_UNESCAPED_SLASHES)); + $protected64 = Base64UrlSafeEncoder::encode(json_encode($protected)); + + openssl_sign($protected64 . '.' . $payload64, $signed, $privateKey, "SHA256"); + + $signed64 = Base64UrlSafeEncoder::encode($signed); + + $data = array( + 'protected' => $protected64, + 'payload' => $payload64, + 'signature' => $signed64 + ); + + $this->log("Sending signed request to $uri"); + return $this->client->post($uri, json_encode($data)); + } + + protected function log($message) + { + $this->logger->logAction(CRON_ACTION, LOG_INFO, "letsencrypt-v2 " . $message); + } +} + +class Client +{ + + private $lastCode; + + public $lastHeader; + + private $base; + + public function __construct($base) + { + $this->base = $base; + } + + private function curl($method, $url, $data = null) + { + $headers = array( + 'Accept: application/json', + 'Content-Type: application/json' + ); + $handle = curl_init(); + curl_setopt($handle, CURLOPT_URL, preg_match('~^http~', $url) ? $url : $this->base . $url); + curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); + curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); + curl_setopt($handle, CURLOPT_HEADER, true); + + // DO NOT DO THAT! + // curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false); + // curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); + + switch ($method) { + case 'GET': + break; + case 'POST': + curl_setopt($handle, CURLOPT_POST, true); + curl_setopt($handle, CURLOPT_POSTFIELDS, $data); + break; + } + $response = curl_exec($handle); + + if (curl_errno($handle)) { + throw new \RuntimeException('Curl: ' . curl_error($handle)); + } + + $header_size = curl_getinfo($handle, CURLINFO_HEADER_SIZE); + + $header = substr($response, 0, $header_size); + $body = substr($response, $header_size); + + $this->lastHeader = $header; + $this->lastCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); + + $data = json_decode($body, true); + return $data === null ? $body : $data; + } + + public function post($url, $data) + { + return $this->curl('POST', $url, $data); + } + + public function get($url) + { + return $this->curl('GET', $url); + } + + public function getLastNonce() + { + if (preg_match('~Replay\-Nonce: (.+)~i', $this->lastHeader, $matches)) { + return trim($matches[1]); + } + + $this->curl('GET', '/directory'); + return $this->getLastNonce(); + } + + public function getLastLocation() + { + if (preg_match('~Location: (.+)~i', $this->lastHeader, $matches)) { + return trim($matches[1]); + } + return null; + } + + public function getLastCode() + { + return $this->lastCode; + } + + public function getLastLinks() + { + preg_match_all('~Link: <(.+)>;rel="up"~', $this->lastHeader, $matches); + return $matches[1]; + } +} + +class Base64UrlSafeEncoder +{ + + public static function encode($input) + { + return str_replace('=', '', strtr(base64_encode($input), '+/', '-_')); + } + + public static function decode($input) + { + $remainder = strlen($input) % 4; + if ($remainder) { + $padlen = 4 - $remainder; + $input .= str_repeat('=', $padlen); + } + return base64_decode(strtr($input, '-_', '+/')); + } +} diff --git a/scripts/jobs/cron_letsencrypt_v2.php b/scripts/jobs/cron_letsencrypt_v2.php new file mode 100644 index 00000000..b08d3679 --- /dev/null +++ b/scripts/jobs/cron_letsencrypt_v2.php @@ -0,0 +1,292 @@ + + * @author Froxlor team (2016-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Cron + * + * @since 0.9.35 + * + */ + +$cronlog->logAction(CRON_ACTION, LOG_INFO, "Updating Let's Encrypt certificates"); + +if (! extension_loaded('curl')) { + $cronlog->logAction(CRON_ACTION, LOG_ERR, "Let's Encrypt requires the php cURL extension to be installed."); + exit(); +} + +$certificates_stmt = Database::query(" + SELECT + domssl.`id`, + domssl.`domainid`, + domssl.expirationdate, + domssl.`ssl_cert_file`, + domssl.`ssl_key_file`, + domssl.`ssl_ca_file`, + domssl.`ssl_csr_file`, + dom.`domain`, + dom.`wwwserveralias`, + dom.`iswildcarddomain`, + dom.`documentroot`, + dom.`id` AS 'domainid', + dom.`ssl_redirect`, + cust.`leprivatekey`, + cust.`lepublickey`, + cust.`leregistered`, + cust.`customerid`, + cust.`loginname` + FROM + `" . TABLE_PANEL_CUSTOMERS . "` AS cust, + `" . TABLE_PANEL_DOMAINS . "` AS dom + LEFT JOIN + `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` AS domssl ON + dom.`id` = domssl.`domainid` + WHERE + dom.`customerid` = cust.`customerid` + AND dom.`letsencrypt` = 1 + AND dom.`aliasdomain` IS NULL + AND ( + domssl.`expirationdate` < DATE_ADD(NOW(), INTERVAL 30 DAY) + OR domssl.`expirationdate` IS NULL + ) + "); + +$aliasdomains_stmt = Database::prepare(" + SELECT + dom.`id` as domainid, + dom.`domain`, + dom.`wwwserveralias`, + dom.`iswildcarddomain` + FROM `" . TABLE_PANEL_DOMAINS . "` AS dom + WHERE + dom.`aliasdomain` = :id + AND dom.`letsencrypt` = 1 + "); + +$updcert_stmt = Database::prepare(" + REPLACE INTO + `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` + SET + `id` = :id, + `domainid` = :domainid, + `ssl_cert_file` = :crt, + `ssl_key_file` = :key, + `ssl_ca_file` = :ca, + `ssl_cert_chainfile` = :chain, + `ssl_csr_file` = :csr, + `expirationdate` = :expirationdate + "); + +$upddom_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_DOMAINS . "` SET `ssl_redirect` = '1' WHERE `id` = :domainid"); + +// flag for re-generation of vhost files +$changedetected = 0; + +// first - generate LE for system-vhost if enabled +if (Settings::Get('system.le_froxlor_enabled') == '1') { + + $certrow = array( + 'loginname' => 'froxlor.panel', + 'domain' => Settings::Get('system.hostname'), + 'domainid' => 0, + 'documentroot' => FROXLOR_INSTALL_DIR, + 'leprivatekey' => Settings::Get('system.leprivatekey'), + 'lepublickey' => Settings::Get('system.lepublickey'), + 'leregistered' => Settings::Get('system.leregistered'), + 'ssl_redirect' => Settings::Get('system.le_froxlor_redirect'), + 'expirationdate' => null, + 'ssl_cert_file' => null, + 'ssl_key_file' => null, + 'ssl_ca_file' => null, + 'ssl_csr_file' => null, + 'id' => null + ); + + $froxlor_ssl_settings_stmt = Database::prepare(" + SELECT * FROM `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` + WHERE `domainid` = '0' AND + (`expirationdate` < DATE_ADD(NOW(), INTERVAL 30 DAY) OR `expirationdate` IS NULL) + "); + $froxlor_ssl = Database::pexecute_first($froxlor_ssl_settings_stmt); + + $insert_or_update_required = true; + if ($froxlor_ssl) { + $certrow['id'] = $froxlor_ssl['id']; + $certrow['expirationdate'] = $froxlor_ssl['expirationdate']; + $certrow['ssl_cert_file'] = $froxlor_ssl['ssl_cert_file']; + $certrow['ssl_key_file'] = $froxlor_ssl['ssl_key_file']; + $certrow['ssl_ca_file'] = $froxlor_ssl['ssl_ca_file']; + $certrow['ssl_csr_file'] = $froxlor_ssl['ssl_csr_file']; + } else { + // check whether we have an entry with valid certificates which just does not need + // updating yet, so we need to skip this here + $froxlor_ssl_settings_stmt = Database::prepare(" + SELECT * FROM `" . TABLE_PANEL_DOMAIN_SSL_SETTINGS . "` WHERE `domainid` = '0' + "); + $froxlor_ssl = Database::pexecute_first($froxlor_ssl_settings_stmt); + if ($froxlor_ssl && ! empty($froxlor_ssl['ssl_cert_file'])) { + $insert_or_update_required = false; + } + } + + if ($insert_or_update_required) { + $domains = array( + $certrow['domain'] + ); + + // Only renew let's encrypt certificate if no broken ssl_redirect is enabled + // - this temp. deactivation of the ssl-redirect is handled by the webserver-cronjob + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Updating " . $certrow['domain']); + + $cronlog = FroxlorLogger::getInstanceOf(array( + 'loginname' => $certrow['loginname'] + )); + + try { + // Initialize Lescript with documentroot + $le = new lescript_v2($cronlog, $version); + + // Initialize Lescript + $le->initAccount($certrow, true); + + // Request the new certificate (old key may be used) + $return = $le->signDomains($domains, $certrow['ssl_key_file']); + + // We are interessted in the expirationdate + $newcert = openssl_x509_parse($return['crt']); + + // Store the new data + Database::pexecute($updcert_stmt, array( + 'id' => $certrow['id'], + 'domainid' => $certrow['domainid'], + 'crt' => $return['crt'], + 'key' => $return['key'], + 'ca' => $return['chain'], + 'chain' => $return['chain'], + 'csr' => $return['csr'], + 'expirationdate' => date('Y-m-d H:i:s', $newcert['validTo_time_t']) + )); + + if ($certrow['ssl_redirect'] == 3) { + Settings::Set('system.le_froxlor_redirect', '1'); + } + + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Updated Let's Encrypt certificate for " . $certrow['domain']); + + $changedetected = 1; + } catch (Exception $e) { + $cronlog->logAction(CRON_ACTION, LOG_ERR, "Could not get Let's Encrypt certificate for " . $certrow['domain'] . ": " . $e->getMessage()); + } + } +} + +// customer domains +$certrows = $certificates_stmt->fetchAll(PDO::FETCH_ASSOC); +foreach ($certrows as $certrow) { + + // set logger to corresponding loginname for the log to appear in the users system-log + $cronlog = FroxlorLogger::getInstanceOf(array( + 'loginname' => $certrow['loginname'] + )); + + // Only renew let's encrypt certificate if no broken ssl_redirect is enabled + if ($certrow['ssl_redirect'] != 2) { + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Updating " . $certrow['domain']); + + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Adding SAN entry: " . $certrow['domain']); + $domains = array( + $certrow['domain'] + ); + if ($certrow['iswildcarddomain'] == 1) { + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Adding SAN entry: *." . $certrow['domain']); + $domains[] = '*.' . $certrow['domain']; + } + elseif ($certrow['wwwserveralias'] == 1) { + // add www. to SAN list + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Adding SAN entry: www." . $certrow['domain']); + $domains[] = 'www.' . $certrow['domain']; + } + + // add alias domains (and possibly www.) to SAN list + Database::pexecute($aliasdomains_stmt, array( + 'id' => $certrow['domainid'] + )); + $aliasdomains = $aliasdomains_stmt->fetchAll(PDO::FETCH_ASSOC); + foreach ($aliasdomains as $aliasdomain) { + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Adding SAN entry: " . $aliasdomain['domain']); + $domains[] = $aliasdomain['domain']; + if ($aliasdomain['iswildcarddomain'] == 1) { + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Adding SAN entry: *." . $aliasdomain['domain']); + $domains[] = '*.' . $aliasdomain['domain']; + } + elseif ($aliasdomain['wwwserveralias'] == 1) { + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Adding SAN entry: www." . $aliasdomain['domain']); + $domains[] = 'www.' . $aliasdomain['domain']; + } + } + + try { + // Initialize Lescript with documentroot + $le = new lescript_v2($cronlog, $version); + + // Initialize Lescript + $le->initAccount($certrow); + + // Request the new certificate (old key may be used) + $return = $le->signDomains($domains, $certrow['ssl_key_file']); + + // We are interessted in the expirationdate + $newcert = openssl_x509_parse($return['crt']); + + // Store the new data + Database::pexecute($updcert_stmt, array( + 'id' => $certrow['id'], + 'domainid' => $certrow['domainid'], + 'crt' => $return['crt'], + 'key' => $return['key'], + 'ca' => $return['chain'], + 'chain' => $return['chain'], + 'csr' => $return['csr'], + 'expirationdate' => date('Y-m-d H:i:s', $newcert['validTo_time_t']) + )); + + if ($certrow['ssl_redirect'] == 3) { + Database::pexecute($upddom_stmt, array( + 'domainid' => $certrow['domainid'] + )); + } + + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Updated Let's Encrypt certificate for " . $certrow['domain']); + + $changedetected = 1; + } catch (Exception $e) { + $cronlog->logAction(CRON_ACTION, LOG_ERR, "Could not get Let's Encrypt certificate for " . $certrow['domain'] . ": " . $e->getMessage()); + } + } else { + $cronlog->logAction(CRON_ACTION, LOG_WARNING, "Skipping Let's Encrypt generation for " . $certrow['domain'] . " due to an enabled ssl_redirect"); + } +} + +// If we have a change in a certificate, we need to update the webserver - configs +// This is easiest done by just creating a new task ;) +if ($changedetected) { + inserttask(1); +} + +// reset logger +$cronlog = FroxlorLogger::getInstanceOf(array( + 'loginname' => 'cronjob' +)); +$cronlog->logAction(CRON_ACTION, LOG_INFO, "Let's Encrypt certificates have been updated"); From d40d1f30b63fa21d73d6be2239d6235885d0e725 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 14:50:52 +0100 Subject: [PATCH 115/179] make it a setting to switch between ACME v1 and v2 Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/131.ssl.php | 17 +++++++++++++++-- install/froxlor.sql | 3 ++- install/updates/froxlor/0.9/update_0.9.inc.php | 9 +++++++++ lib/version.inc.php | 2 +- scripts/jobs/cron_letsencrypt.php | 6 ++++++ 5 files changed, 33 insertions(+), 4 deletions(-) diff --git a/actions/admin/settings/131.ssl.php b/actions/admin/settings/131.ssl.php index 68f2a9e8..b9b2d459 100644 --- a/actions/admin/settings/131.ssl.php +++ b/actions/admin/settings/131.ssl.php @@ -100,6 +100,19 @@ return array( 'cronmodule' => 'froxlor/letsencrypt', 'save_method' => 'storeSettingField' ), + 'system_leapiversion' => array( + 'label' => $lng['serversettings']['leapiversion'], + 'settinggroup' => 'system', + 'varname' => 'leapiversion', + 'type' => 'option', + 'default' => '1', + 'option_mode' => 'one', + 'option_options' => array( + '1' => 'ACME v1', + '2' => 'ACME v2' + ), + 'save_method' => 'storeSettingField' + ), 'system_letsencryptacmeconf' => array( 'label' => $lng['serversettings']['letsencryptacmeconf'], 'settinggroup' => 'system', @@ -117,8 +130,8 @@ return array( 'default' => 'testing', 'option_mode' => 'one', 'option_options' => array( - 'testing' => 'https://acme-staging.api.letsencrypt.org (Test)', - 'production' => 'https://acme-v01.api.letsencrypt.org (Live)' + 'testing' => 'https://acme-staging'.(Settings::Get('system.leapiversion') == '2' ? '-v02' : '').'.api.letsencrypt.org (Test)', + 'production' => 'https://acme-v0'.Settings::Get('system.leapiversion').'.api.letsencrypt.org (Live)' ), 'save_method' => 'storeSettingField' ), diff --git a/install/froxlor.sql b/install/froxlor.sql index 3fdc57dd..e96c62b6 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -534,6 +534,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('system', 'letsencryptkeysize', '4096'), ('system', 'letsencryptreuseold', 0), ('system', 'leenabled', '0'), + ('system', 'leapiversion', '1'), ('system', 'backupenabled', '0'), ('system', 'dnsenabled', '0'), ('system', 'dns_server', 'bind'), @@ -588,7 +589,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.8'), - ('panel', 'db_version', '201801080'); + ('panel', 'db_version', '201801090'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 0483ba44..de39f9e3 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3725,3 +3725,12 @@ if (isDatabaseVersion('201801070')) { updateToDbVersion('201801080'); } + +if (isDatabaseVersion('201801080')) { + + showUpdateStep("Adding new setting for Let's Encrypt ACME version"); + Settings::AddNew('system.leapiversion', '1'); + lastStepStatus(0); + + updateToDbVersion('201801090'); +} diff --git a/lib/version.inc.php b/lib/version.inc.php index 5f433e8b..2632a02f 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201801080'; +$dbversion = '201801090'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/scripts/jobs/cron_letsencrypt.php b/scripts/jobs/cron_letsencrypt.php index 126d7dcd..b25b9a8d 100644 --- a/scripts/jobs/cron_letsencrypt.php +++ b/scripts/jobs/cron_letsencrypt.php @@ -20,6 +20,12 @@ if (! defined('MASTER_CRONJOB')) * */ +if (Settings::Get('system.leapiversion') == '2') { + // use ACME v2 is specified + require_once __DIR__ . '/cron_letsencrypt_v2.php'; + exit; +} + $cronlog->logAction(CRON_ACTION, LOG_INFO, "Updating Let's Encrypt certificates"); if (! extension_loaded('curl')) { From b2b9d4e31a5128233cc9a82d4c20d6fe41f71c34 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 14:56:41 +0100 Subject: [PATCH 116/179] add missing setting-strings for new acme-version setting; allow using let's encrypt with wildcard-alias when using ACME-v2 Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 8 ++++---- customer_domains.php | 4 ++-- lng/english.lng.php | 2 ++ lng/german.lng.php | 2 ++ 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index 0faa8854..7812ad2d 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -633,8 +633,8 @@ if ($page == 'domains' || $page == 'overview') { $ocsp_stapling = 0; } - // We can't enable let's encrypt for wildcard - domains - if ($serveraliasoption == '0' && $letsencrypt == '1') { + // We can't enable let's encrypt for wildcard - domains if using acme-v1 + if ($serveraliasoption == '0' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '1') { standard_error('nowildcardwithletsencrypt'); } @@ -1511,8 +1511,8 @@ if ($page == 'domains' || $page == 'overview') { $ocsp_stapling = 0; } - // We can't enable let's encrypt for wildcard domains - if ($serveraliasoption == '0' && $letsencrypt == '1') { + // We can't enable let's encrypt for wildcard domains when using acme-v1 + if ($serveraliasoption == '0' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '1') { standard_error('nowildcardwithletsencrypt'); } diff --git a/customer_domains.php b/customer_domains.php index f14b69a7..350c715f 100644 --- a/customer_domains.php +++ b/customer_domains.php @@ -681,8 +681,8 @@ if ($page == 'overview') { $letsencrypt = '0'; } - // We can't enable let's encrypt for wildcard - domains - if ($iswildcarddomain == '1' && $letsencrypt == '1') { + // We can't enable let's encrypt for wildcard - domains when using acme-v1 + if ($iswildcarddomain == '1' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '1') { standard_error('nowildcardwithletsencrypt'); } diff --git a/lng/english.lng.php b/lng/english.lng.php index 039073ff..bb49e106 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2088,3 +2088,5 @@ $lng['menue']['phpsettings']['fpmdaemons'] = 'PHP-FPM versions'; $lng['admin']['phpsettings']['activephpconfigs'] = 'In use for php-config(s)'; $lng['admin']['phpsettingsforsubdomains'] = 'Apply php-config to all subdomains:'; $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'If yes the chosen php-config will be updated to all subdomains'; +$lng['serversettings']['leapiversion']['title'] = "Chose Let's Encrypt ACME implementation"; +$lng['serversettings']['leapiversion']['description'] = "Chose between ACME v1 and ACME v2 implementation for Let's Encrypt. ACME v2 let's you use wildcard-certificates."; diff --git a/lng/german.lng.php b/lng/german.lng.php index 941ebf82..271687db 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1739,3 +1739,5 @@ $lng['menue']['phpsettings']['fpmdaemons'] = 'PHP-FPM Versionen'; $lng['admin']['phpsettings']['activephpconfigs'] = 'In Verwendung für PHP-Konfiguration(en)'; $lng['admin']['phpsettingsforsubdomains'] = 'PHP-Config für alle Subdomains übernehmen:'; $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'Wenn ja, wird die gewählte PHP-Config für alle Subdomains übernommen'; +$lng['serversettings']['leapiversion']['title'] = "Wähle Let's Encrypt ACME Implementierung"; +$lng['serversettings']['leapiversion']['description'] = "Wähle zwischen ACME v1 und ACME v2 Implementierung von Let's Encrypt. ACME v2 erlaubt Wildcard-Zertifikate."; From f49cb81e4923e8668575a983a65245de8faa2599 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 15:33:23 +0100 Subject: [PATCH 117/179] disable wildcard-usage with Let's Encrypt as ACME-v2 only supports the dns-01 challenge for now (pity) Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 10 ++++++++++ customer_domains.php | 5 +++++ lng/english.lng.php | 3 ++- lng/german.lng.php | 3 ++- 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index 7812ad2d..6ce493ac 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -637,6 +637,11 @@ if ($page == 'domains' || $page == 'overview') { if ($serveraliasoption == '0' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '1') { standard_error('nowildcardwithletsencrypt'); } + // if using acme-v2 we cannot issue wildcard-certificates + // because they currently only support the dns-01 challenge + if ($serveraliasoption == '0' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '2') { + standard_error('nowildcardwithletsencryptv2'); + } // Temporarily deactivate ssl_redirect until Let's Encrypt certificate was generated if ($ssl_redirect > 0 && $letsencrypt == 1) { @@ -1515,6 +1520,11 @@ if ($page == 'domains' || $page == 'overview') { if ($serveraliasoption == '0' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '1') { standard_error('nowildcardwithletsencrypt'); } + // if using acme-v2 we cannot issue wildcard-certificates + // because they currently only support the dns-01 challenge + if ($serveraliasoption == '0' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '2') { + standard_error('nowildcardwithletsencryptv2'); + } // Temporarily deactivate ssl_redirect until Let's Encrypt certificate was generated if ($ssl_redirect > 0 && $letsencrypt == 1 && $result['letsencrypt'] != $letsencrypt) { diff --git a/customer_domains.php b/customer_domains.php index 350c715f..23bbb07f 100644 --- a/customer_domains.php +++ b/customer_domains.php @@ -685,6 +685,11 @@ if ($page == 'overview') { if ($iswildcarddomain == '1' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '1') { standard_error('nowildcardwithletsencrypt'); } + // if using acme-v2 we cannot issue wildcard-certificates + // because they currently only support the dns-01 challenge + if ($iswildcarddomain == '0' && $letsencrypt == '1' && Settings::Get('system.leapiversion') == '2') { + standard_error('nowildcardwithletsencryptv2'); + } // Temporarily deactivate ssl_redirect until Let's Encrypt certificate was generated if ($ssl_redirect > 0 && $letsencrypt == 1 && $result['letsencrypt'] != $letsencrypt) { diff --git a/lng/english.lng.php b/lng/english.lng.php index bb49e106..45190d40 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -1940,7 +1940,7 @@ $lng['admin']['letsencrypt']['description'] = 'Get a free certificate from . The certificate will be created and renewed automatically.
ATTENTION: This feature is still in beta.'; $lng['error']['sslredirectonlypossiblewithsslipport'] = 'Using Let\'s Encrypt is only possible when the domain has at least one ssl-enabled IP/port combination assigned.'; -$lng['error']['nowildcardwithletsencrypt'] = 'Let\'s Encrypt cannot (yet) handle wildcard-domains. Please set the ServerAlias to WWW or disable it completely'; +$lng['error']['nowildcardwithletsencrypt'] = 'Let\'s Encrypt cannot handle wildcard-domains using ACME v1. Please set the ServerAlias to WWW or disable it completely'; $lng['panel']['letsencrypt'] = 'Using Let\'s encrypt'; $lng['crondesc']['cron_letsencrypt'] = 'updating Let\'s Encrypt certificates'; $lng['serversettings']['letsencryptca']['title'] = "Let's Encrypt environment"; @@ -2090,3 +2090,4 @@ $lng['admin']['phpsettingsforsubdomains'] = 'Apply php-config to all subdomains: $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'If yes the chosen php-config will be updated to all subdomains'; $lng['serversettings']['leapiversion']['title'] = "Chose Let's Encrypt ACME implementation"; $lng['serversettings']['leapiversion']['description'] = "Chose between ACME v1 and ACME v2 implementation for Let's Encrypt. ACME v2 let's you use wildcard-certificates."; +$lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt can only validate wildcard-domains by DNS with ACME v2, sorry. Please set the ServerAlias to WWW or disable it completely'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 271687db..7ae3b8d4 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1593,7 +1593,7 @@ $lng['admin']['letsencrypt']['description'] = 'Holt ein kostenloses Zertifikat v $lng['customer']['letsencrypt']['title'] = 'Benutze Let\'s Encrypt'; $lng['customer']['letsencrypt']['description'] = 'Holt ein kostenloses Zertifikat von
Let\'s Encrypt. Das Zertifikat wird automatisch erstellt und verlängert.
ACHTUNG: Dieses Feature befindet sich noch im Test.'; $lng['error']['sslredirectonlypossiblewithsslipport'] = 'Die Nutzung von Let\'s Encrypt ist nur möglich, wenn die Domain mindestens eine IP/Port - Kombination mit aktiviertem SSL zugewiesen hat.'; -$lng['error']['nowildcardwithletsencrypt'] = 'Let\'s Encrypt kann (noch) nicht mit Wildcard-Domains umgehen. Bitte den ServerAlias auf WWW setzen oder deaktivieren'; +$lng['error']['nowildcardwithletsencrypt'] = 'Let\'s Encrypt kann in ACME v1 nicht mit Wildcard-Domains umgehen. Bitte den ServerAlias auf WWW setzen oder deaktivieren'; $lng['panel']['letsencrypt'] = 'Benutzt Let\'s encrypt'; $lng['crondesc']['cron_letsencrypt'] = 'aktualisiert Let\'s Encrypt Zertifikate'; $lng['serversettings']['letsencryptca']['title'] = "Let's Encrypt Umgebung"; @@ -1741,3 +1741,4 @@ $lng['admin']['phpsettingsforsubdomains'] = 'PHP-Config für alle Subdomains üb $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'Wenn ja, wird die gewählte PHP-Config für alle Subdomains übernommen'; $lng['serversettings']['leapiversion']['title'] = "Wähle Let's Encrypt ACME Implementierung"; $lng['serversettings']['leapiversion']['description'] = "Wähle zwischen ACME v1 und ACME v2 Implementierung von Let's Encrypt. ACME v2 erlaubt Wildcard-Zertifikate."; +$lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt kann in ACME v2 Wildcard-Domains nur via DNS validieren, sorry. Bitte den ServerAlias auf WWW setzen oder deaktivieren'; From 07a4f045f182c68a49d76f25400ff69d4ac12342 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 16:08:13 +0100 Subject: [PATCH 118/179] do not advertise wildcard-certificates as it might never be possible in froxlor (no http-01 challenge) Signed-off-by: Michael Kaufmann (d00p) --- lng/english.lng.php | 2 +- lng/german.lng.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lng/english.lng.php b/lng/english.lng.php index 45190d40..c864e66d 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2089,5 +2089,5 @@ $lng['admin']['phpsettings']['activephpconfigs'] = 'In use for php-config(s)'; $lng['admin']['phpsettingsforsubdomains'] = 'Apply php-config to all subdomains:'; $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'If yes the chosen php-config will be updated to all subdomains'; $lng['serversettings']['leapiversion']['title'] = "Chose Let's Encrypt ACME implementation"; -$lng['serversettings']['leapiversion']['description'] = "Chose between ACME v1 and ACME v2 implementation for Let's Encrypt. ACME v2 let's you use wildcard-certificates."; +$lng['serversettings']['leapiversion']['description'] = "Chose between ACME v1 and ACME v2 implementation for Let's Encrypt."; $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt can only validate wildcard-domains by DNS with ACME v2, sorry. Please set the ServerAlias to WWW or disable it completely'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 7ae3b8d4..7943e0d4 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1740,5 +1740,5 @@ $lng['admin']['phpsettings']['activephpconfigs'] = 'In Verwendung für PHP-Konfi $lng['admin']['phpsettingsforsubdomains'] = 'PHP-Config für alle Subdomains übernehmen:'; $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'Wenn ja, wird die gewählte PHP-Config für alle Subdomains übernommen'; $lng['serversettings']['leapiversion']['title'] = "Wähle Let's Encrypt ACME Implementierung"; -$lng['serversettings']['leapiversion']['description'] = "Wähle zwischen ACME v1 und ACME v2 Implementierung von Let's Encrypt. ACME v2 erlaubt Wildcard-Zertifikate."; +$lng['serversettings']['leapiversion']['description'] = "Wähle zwischen ACME v1 und ACME v2 Implementierung von Let's Encrypt."; $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt kann in ACME v2 Wildcard-Domains nur via DNS validieren, sorry. Bitte den ServerAlias auf WWW setzen oder deaktivieren'; From 84abb33e5490bb8ae860c97cd9ece66b28d0a4f4 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 17:12:55 +0100 Subject: [PATCH 119/179] exclude wildcard-domains agains also vor ACMEv2 of LE2 Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_letsencrypt_v2.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/jobs/cron_letsencrypt_v2.php b/scripts/jobs/cron_letsencrypt_v2.php index b08d3679..6b1148d3 100644 --- a/scripts/jobs/cron_letsencrypt_v2.php +++ b/scripts/jobs/cron_letsencrypt_v2.php @@ -57,6 +57,7 @@ $certificates_stmt = Database::query(" dom.`customerid` = cust.`customerid` AND dom.`letsencrypt` = 1 AND dom.`aliasdomain` IS NULL + AND dom.`iswildcarddomain` = 0 AND ( domssl.`expirationdate` < DATE_ADD(NOW(), INTERVAL 30 DAY) OR domssl.`expirationdate` IS NULL @@ -73,6 +74,7 @@ $aliasdomains_stmt = Database::prepare(" WHERE dom.`aliasdomain` = :id AND dom.`letsencrypt` = 1 + AND dom.`iswildcarddomain` = 0 "); $updcert_stmt = Database::prepare(" From ba58991d11f80ac28694f485b695c96d4659a586 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 17:14:57 +0100 Subject: [PATCH 120/179] allow per php-config setting of adding '-pass-header Authorization' / 'CGIPassAuth On' to the domains vhosts Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 3 ++- install/updates/froxlor/0.9/update_0.9.inc.php | 9 +++++++++ .../admin/phpconfig/formfield.phpconfig_add.php | 9 +++++++++ .../admin/phpconfig/formfield.phpconfig_edit.php | 9 +++++++++ lib/version.inc.php | 2 +- lng/english.lng.php | 1 + lng/german.lng.php | 1 + scripts/jobs/cron_tasks.inc.http.10.apache.php | 11 ++++++++++- .../jobs/cron_tasks.inc.http.15.apache_fcgid.php | 14 +++++++++++++- 9 files changed, 55 insertions(+), 4 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index e96c62b6..26ec3281 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -589,7 +589,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.8'), - ('panel', 'db_version', '201801090'); + ('panel', 'db_version', '201801091'); DROP TABLE IF EXISTS `panel_tasks`; @@ -795,6 +795,7 @@ CREATE TABLE `panel_phpconfigs` ( `fpm_reqslow` varchar(15) NOT NULL default '5s', `phpsettings` text NOT NULL, `fpmsettingid` int(11) NOT NULL DEFAULT '1', + `pass_authorizationheader` tinyint(1) NOT NULL default '0', PRIMARY KEY (`id`), KEY `fpmsettingid` (`fpmsettingid`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index de39f9e3..52f26e39 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3734,3 +3734,12 @@ if (isDatabaseVersion('201801080')) { updateToDbVersion('201801090'); } + +if (isDatabaseVersion('201801090')) { + + showUpdateStep("Adding field pass_authorizationheader for php-configs"); + Database::query("ALTER TABLE `" . TABLE_PANEL_PHPCONFIGS . "` ADD `pass_authorizationheader` tinyint(1) NOT NULL default '0';"); + lastStepStatus(0); + + updateToDbVersion('201801091'); +} diff --git a/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php b/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php index 07889120..6d30adfd 100644 --- a/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php +++ b/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php @@ -90,6 +90,15 @@ return array( 'maxlength' => 10, 'value' => '5s' ), + 'phpfpm_pass_authorizationheader' => array( + 'visible' => (Settings::Get('phpfpm.enabled') == 1 ? true : false), + 'label' => $lng['admin']['phpsettings']['pass_authorizationheader'], + 'type' => 'checkbox', + 'values' => array( + array ('label' => $lng['panel']['yes'], 'value' => '1') + ), + 'value' => array() + ), 'phpsettings' => array( 'style' => 'align-top', 'label' => $lng['admin']['phpsettings']['phpinisettings'], diff --git a/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php b/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php index 9ae736ed..e2e8fd11 100644 --- a/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php +++ b/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php @@ -93,6 +93,15 @@ return array( 'maxlength' => 10, 'value' => $result['fpm_reqslow'] ), + 'phpfpm_pass_authorizationheader' => array( + 'visible' => (Settings::Get('phpfpm.enabled') == 1 ? true : false), + 'label' => $lng['admin']['phpsettings']['pass_authorizationheader'], + 'type' => 'checkbox', + 'values' => array( + array ('label' => $lng['panel']['yes'], 'value' => '1') + ), + 'value' => array($result['pass_authorizationheader']) + ), 'phpsettings' => array( 'style' => 'align-top', 'label' => $lng['admin']['phpsettings']['phpinisettings'], diff --git a/lib/version.inc.php b/lib/version.inc.php index 2632a02f..40aa7b18 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201801090'; +$dbversion = '201801091'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index c864e66d..b33762e3 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2091,3 +2091,4 @@ $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'If yes the $lng['serversettings']['leapiversion']['title'] = "Chose Let's Encrypt ACME implementation"; $lng['serversettings']['leapiversion']['description'] = "Chose between ACME v1 and ACME v2 implementation for Let's Encrypt."; $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt can only validate wildcard-domains by DNS with ACME v2, sorry. Please set the ServerAlias to WWW or disable it completely'; +$lng['admin']['phpsettings']['pass_authorizationheader'] = 'Add "-pass-header Authorization" to vhosts'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 7943e0d4..1302358b 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1742,3 +1742,4 @@ $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'Wenn ja, wi $lng['serversettings']['leapiversion']['title'] = "Wähle Let's Encrypt ACME Implementierung"; $lng['serversettings']['leapiversion']['description'] = "Wähle zwischen ACME v1 und ACME v2 Implementierung von Let's Encrypt."; $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt kann in ACME v2 Wildcard-Domains nur via DNS validieren, sorry. Bitte den ServerAlias auf WWW setzen oder deaktivieren'; +$lng['admin']['phpsettings']['pass_authorizationheader'] = 'Füge "-pass-header Authorization" in Vhosts ein'; diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 5887e9a7..b3147f03 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -330,8 +330,17 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SetHandler proxy:unix:' . $php->getInterface()->getSocketFile() . '|fcgi://localhost' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; + if ($phpconfig['pass_authorizationheader'] == '1') { + $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; + $this->virtualhosts_data[$vhosts_filename] .= ' CGIPassAuth On' . "\n"; + $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; + } } else { - $this->virtualhosts_data[$vhosts_filename] .= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . Settings::Get('phpfpm.idle_timeout') . "\n"; + $addheader = ""; + if ($phpconfig['pass_authorizationheader'] == '1') { + $addheader = " -pass-header Authorization"; + } + $this->virtualhosts_data[$vhosts_filename] .= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . Settings::Get('phpfpm.idle_timeout') . $addheader . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; $file_extensions = explode(' ', $phpconfig['file_extensions']); $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index ab53539c..b2385abb 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -54,13 +54,25 @@ class apache_fcgid extends apache // for this path, as this would be the first require and therefore grant all access if ($mypath_dir->isUserProtected() == false) { $php_options_text.= ' ' . "\n"; + if ($phpconfig['pass_authorizationheader'] == '1') { + $php_options_text.= ' CGIPassAuth On' . "\n"; + } $php_options_text.= ' Require all granted' . "\n"; $php_options_text.= ' AllowOverride All' . "\n"; $php_options_text.= ' ' . "\n"; + } elseif ($phpconfig['pass_authorizationheader'] == '1') { + // allow Pass of Authorization header + $php_options_text.= ' ' . "\n"; + $php_options_text.= ' CGIPassAuth On' . "\n"; + $php_options_text.= ' ' . "\n"; } } else { - $php_options_text.= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . Settings::Get('phpfpm.idle_timeout') . "\n"; + $addheader = ""; + if ($phpconfig['pass_authorizationheader'] == '1') { + $addheader = " -pass-header Authorization"; + } + $php_options_text.= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . Settings::Get('phpfpm.idle_timeout') . $addheader . "\n"; $php_options_text.= ' ' . "\n"; $php_options_text.= ' ' . "\n"; $php_options_text.= ' SetHandler php5-fastcgi'. "\n"; From 6b44dfe9b238e52572dc952e778d906a6060675c Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 9 Jan 2018 17:22:20 +0100 Subject: [PATCH 121/179] well, we should also save the new settings :) Signed-off-by: Michael Kaufmann (d00p) --- admin_phpsettings.php | 14 +++++++++++--- lng/english.lng.php | 2 +- lng/german.lng.php | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/admin_phpsettings.php b/admin_phpsettings.php index 2b2e33b7..0fa1b831 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -124,11 +124,13 @@ if ($page == 'overview') { $fpm_enableslowlog = 0; $fpm_reqtermtimeout = 0; $fpm_reqslowtimeout = 0; + $fpm_pass_authorizationheader = 0; } elseif (Settings::Get('phpfpm.enabled') == 1) { $fpm_config_id = intval($_POST['fpmconfig']); $fpm_enableslowlog = isset($_POST['phpfpm_enable_slowlog']) ? (int) $_POST['phpfpm_enable_slowlog'] : 0; $fpm_reqtermtimeout = validate($_POST['phpfpm_reqtermtimeout'], 'phpfpm_reqtermtimeout', '/^([0-9]+)(|s|m|h|d)$/'); $fpm_reqslowtimeout = validate($_POST['phpfpm_reqslowtimeout'], 'phpfpm_reqslowtimeout', '/^([0-9]+)(|s|m|h|d)$/'); + $fpm_pass_authorizationheader = isset($_POST['phpfpm_pass_authorizationheader']) ? (int) $_POST['phpfpm_pass_authorizationheader'] : 0; // disable fcgid stuff $binary = '/usr/bin/php-cgi'; $file_extensions = 'php'; @@ -153,7 +155,8 @@ if ($page == 'overview') { `fpm_reqterm` = :fpmreqterm, `fpm_reqslow` = :fpmreqslow, `phpsettings` = :phpsettings, - `fpmsettingid` = :fpmsettingid"); + `fpmsettingid` = :fpmsettingid, + `pass_authorizationheader` = :fpmpassauth"); $ins_data = array( 'desc' => $description, 'binary' => $binary, @@ -165,7 +168,8 @@ if ($page == 'overview') { 'fpmreqterm' => $fpm_reqtermtimeout, 'fpmreqslow' => $fpm_reqslowtimeout, 'phpsettings' => $phpsettings, - 'fpmsettingid' => $fpm_config_id + 'fpmsettingid' => $fpm_config_id, + 'fpmpassauth' => $fpm_pass_authorizationheader ); Database::pexecute($ins_stmt, $ins_data); @@ -283,11 +287,13 @@ if ($page == 'overview') { $fpm_enableslowlog = 0; $fpm_reqtermtimeout = 0; $fpm_reqslowtimeout = 0; + $fpm_pass_authorizationheader = 0; } elseif (Settings::Get('phpfpm.enabled') == 1) { $fpm_config_id = intval($_POST['fpmconfig']); $fpm_enableslowlog = isset($_POST['phpfpm_enable_slowlog']) ? (int) $_POST['phpfpm_enable_slowlog'] : 0; $fpm_reqtermtimeout = validate($_POST['phpfpm_reqtermtimeout'], 'phpfpm_reqtermtimeout', '/^([0-9]+)(|s|m|h|d)$/'); $fpm_reqslowtimeout = validate($_POST['phpfpm_reqslowtimeout'], 'phpfpm_reqslowtimeout', '/^([0-9]+)(|s|m|h|d)$/'); + $fpm_pass_authorizationheader = isset($_POST['phpfpm_pass_authorizationheader']) ? (int) $_POST['phpfpm_pass_authorizationheader'] : 0; // disable fcgid stuff $binary = '/usr/bin/php-cgi'; $file_extensions = 'php'; @@ -312,7 +318,8 @@ if ($page == 'overview') { `fpm_reqterm` = :fpmreqterm, `fpm_reqslow` = :fpmreqslow, `phpsettings` = :phpsettings, - `fpmsettingid` = :fpmsettingid + `fpmsettingid` = :fpmsettingid, + `pass_authorizationheader` = :fpmpassauth WHERE `id` = :id"); $upd_data = array( 'desc' => $description, @@ -326,6 +333,7 @@ if ($page == 'overview') { 'fpmreqslow' => $fpm_reqslowtimeout, 'phpsettings' => $phpsettings, 'fpmsettingid' => $fpm_config_id, + 'fpmpassauth' => $fpm_pass_authorizationheader, 'id' => $id ); Database::pexecute($upd_stmt, $upd_data); diff --git a/lng/english.lng.php b/lng/english.lng.php index b33762e3..fe598231 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2091,4 +2091,4 @@ $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'If yes the $lng['serversettings']['leapiversion']['title'] = "Chose Let's Encrypt ACME implementation"; $lng['serversettings']['leapiversion']['description'] = "Chose between ACME v1 and ACME v2 implementation for Let's Encrypt."; $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt can only validate wildcard-domains by DNS with ACME v2, sorry. Please set the ServerAlias to WWW or disable it completely'; -$lng['admin']['phpsettings']['pass_authorizationheader'] = 'Add "-pass-header Authorization" to vhosts'; +$lng['admin']['phpsettings']['pass_authorizationheader'] = 'Add "-pass-header Authorization" / "CGIPassAuth On" to vhosts'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 1302358b..197eab84 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1742,4 +1742,4 @@ $lng['serversettings']['phpsettingsforsubdomains']['description'] = 'Wenn ja, wi $lng['serversettings']['leapiversion']['title'] = "Wähle Let's Encrypt ACME Implementierung"; $lng['serversettings']['leapiversion']['description'] = "Wähle zwischen ACME v1 und ACME v2 Implementierung von Let's Encrypt."; $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt kann in ACME v2 Wildcard-Domains nur via DNS validieren, sorry. Bitte den ServerAlias auf WWW setzen oder deaktivieren'; -$lng['admin']['phpsettings']['pass_authorizationheader'] = 'Füge "-pass-header Authorization" in Vhosts ein'; +$lng['admin']['phpsettings']['pass_authorizationheader'] = 'Füge "-pass-header Authorization" / "CGIPassAuth On" in Vhosts ein'; From 9312e4967e5559cf48370431180aca4c81bc68ee Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 08:45:20 +0100 Subject: [PATCH 122/179] fix access to idle-timeout setting which moved from global settings to per-fpm-daemon setting, thx to gunnyst for pointing this out Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/phpinterface/class.phpinterface.php | 6 ++++++ scripts/jobs/cron_tasks.inc.http.10.apache.php | 2 +- scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/classes/phpinterface/class.phpinterface.php b/lib/classes/phpinterface/class.phpinterface.php index 9bf6bf41..88fe7bbc 100644 --- a/lib/classes/phpinterface/class.phpinterface.php +++ b/lib/classes/phpinterface/class.phpinterface.php @@ -91,6 +91,12 @@ class phpinterface { SELECT * FROM `" . TABLE_PANEL_PHPCONFIGS . "` WHERE `id` = :id" ); $this->_php_configs_cache[$php_config_id] = Database::pexecute_first($stmt, array('id' => $php_config_id)); + if ((int)Settings::Get('phpfpm.enabled') == 1) { + $stmt = Database::prepare(" + SELECT * FROM `" . TABLE_PANEL_FPMDAEMONS . "` WHERE `id` = :id" + ); + $this->_php_configs_cache[$php_config_id]['fpm_settings'] = Database::pexecute_first($stmt, array('id' => $this->_php_configs_cache[$php_config_id]['fpmsettingid'])); + } } return $this->_php_configs_cache[$php_config_id]; diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index b3147f03..1eb0528d 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -340,7 +340,7 @@ class apache extends HttpConfigBase if ($phpconfig['pass_authorizationheader'] == '1') { $addheader = " -pass-header Authorization"; } - $this->virtualhosts_data[$vhosts_filename] .= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . Settings::Get('phpfpm.idle_timeout') . $addheader . "\n"; + $this->virtualhosts_data[$vhosts_filename] .= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . $phpconfig['fpm_settings']['idle_timeout'] . $addheader . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; $file_extensions = explode(' ', $phpconfig['file_extensions']); $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index b2385abb..fcd16533 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -72,7 +72,7 @@ class apache_fcgid extends apache if ($phpconfig['pass_authorizationheader'] == '1') { $addheader = " -pass-header Authorization"; } - $php_options_text.= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . Settings::Get('phpfpm.idle_timeout') . $addheader . "\n"; + $php_options_text.= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . $phpconfig['fpm_settings']['idle_timeout'] . $addheader . "\n"; $php_options_text.= ' ' . "\n"; $php_options_text.= ' ' . "\n"; $php_options_text.= ' SetHandler php5-fastcgi'. "\n"; From 4bcdfc0786067b69f9eef1c3da60d51ed2c625be Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 10:12:26 +0100 Subject: [PATCH 123/179] Added option to set the TLS protocol versions to be used in webservers Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/131.ssl.php | 23 +++++++++++++++---- install/froxlor.sql | 3 ++- .../updates/froxlor/0.9/update_0.9.inc.php | 9 ++++++++ lng/english.lng.php | 2 ++ lng/german.lng.php | 2 ++ .../jobs/cron_tasks.inc.http.10.apache.php | 4 ++-- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 2 +- 7 files changed, 36 insertions(+), 9 deletions(-) diff --git a/actions/admin/settings/131.ssl.php b/actions/admin/settings/131.ssl.php index b9b2d459..1ad1768a 100644 --- a/actions/admin/settings/131.ssl.php +++ b/actions/admin/settings/131.ssl.php @@ -30,6 +30,20 @@ return array( 'save_method' => 'storeSettingField', 'overview_option' => true ), + 'system_ssl_protocols' => array( + 'label' => $lng['serversettings']['ssl']['ssl_protocols'], + 'settinggroup' => 'system', + 'varname' => 'ssl_protocols', + 'type' => 'option', + 'default' => 'TLSv1,TLSv1.2', + 'option_mode' => 'multiple', + 'option_options' => array( + 'TLSv1' => 'TLSv1', + 'TLSv1.1' => 'TLSv1.1', + 'TLSv1.2' => 'TLSv1.2' + ), + 'save_method' => 'storeSettingField' + ), 'system_ssl_cipher_list' => array( 'label' => $lng['serversettings']['ssl']['ssl_cipher_list'], 'settinggroup' => 'system', @@ -87,8 +101,7 @@ return array( 'string_type' => 'string', 'string_emptyallowed' => false, 'default' => 'shmcb:/var/run/apache2/ocsp-stapling.cache(131072)', - 'visible' => Settings::Get('system.webserver') == "apache2" && - Settings::Get('system.apache24') == 1, + 'visible' => Settings::Get('system.webserver') == "apache2" && Settings::Get('system.apache24') == 1, 'save_method' => 'storeSettingField' ), 'system_leenabled' => array( @@ -120,7 +133,7 @@ return array( 'type' => 'string', 'string_type' => 'file', 'default' => '/etc/apache2/conf-enabled/acme.conf', - 'save_method' => 'storeSettingField', + 'save_method' => 'storeSettingField' ), 'system_letsencryptca' => array( 'label' => $lng['serversettings']['letsencryptca'], @@ -130,8 +143,8 @@ return array( 'default' => 'testing', 'option_mode' => 'one', 'option_options' => array( - 'testing' => 'https://acme-staging'.(Settings::Get('system.leapiversion') == '2' ? '-v02' : '').'.api.letsencrypt.org (Test)', - 'production' => 'https://acme-v0'.Settings::Get('system.leapiversion').'.api.letsencrypt.org (Live)' + 'testing' => 'https://acme-staging' . (Settings::Get('system.leapiversion') == '2' ? '-v02' : '') . '.api.letsencrypt.org (Test)', + 'production' => 'https://acme-v0' . Settings::Get('system.leapiversion') . '.api.letsencrypt.org (Live)' ), 'save_method' => 'storeSettingField' ), diff --git a/install/froxlor.sql b/install/froxlor.sql index 26ec3281..f56d0a39 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -557,6 +557,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('system', 'leregistered', '0'), ('system', 'nssextrausers', '0'), ('system', 'disable_le_selfcheck', '0'), + ('system', 'ssl_protocols', 'TLSv1,TLSv1.2'), ('panel', 'decimal_places', '4'), ('panel', 'adminmail', 'admin@SERVERNAME'), ('panel', 'phpmyadmin_url', ''), @@ -589,7 +590,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.8'), - ('panel', 'db_version', '201801091'); + ('panel', 'db_version', '201801100'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 52f26e39..48212f1d 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3743,3 +3743,12 @@ if (isDatabaseVersion('201801090')) { updateToDbVersion('201801091'); } + +if (isDatabaseVersion('201801091')) { + + showUpdateStep("Adding new setting for SSL protocols"); + Settings::AddNew('system.ssl_protocols', 'TLSv1,TLSv1.2'); + lastStepStatus(0); + + updateToDbVersion('201801100'); +} diff --git a/lng/english.lng.php b/lng/english.lng.php index fe598231..0893cdb6 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2092,3 +2092,5 @@ $lng['serversettings']['leapiversion']['title'] = "Chose Let's Encrypt ACME impl $lng['serversettings']['leapiversion']['description'] = "Chose between ACME v1 and ACME v2 implementation for Let's Encrypt."; $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt can only validate wildcard-domains by DNS with ACME v2, sorry. Please set the ServerAlias to WWW or disable it completely'; $lng['admin']['phpsettings']['pass_authorizationheader'] = 'Add "-pass-header Authorization" / "CGIPassAuth On" to vhosts'; +$lng['serversettings']['ssl']['ssl_protocols']['title'] = 'Configure the TLS protocol version'; +$lng['serversettings']['ssl']['ssl_protocols']['description'] = 'This is a list of ssl protocols that you want (or don\'t want) to use when using SSL. Notice: Some older browsers may not support the newest protcol versions.

Default value is:

TLSv1, TLSv1.2
'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 197eab84..830bb1c3 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1743,3 +1743,5 @@ $lng['serversettings']['leapiversion']['title'] = "Wähle Let's Encrypt ACME Imp $lng['serversettings']['leapiversion']['description'] = "Wähle zwischen ACME v1 und ACME v2 Implementierung von Let's Encrypt."; $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt kann in ACME v2 Wildcard-Domains nur via DNS validieren, sorry. Bitte den ServerAlias auf WWW setzen oder deaktivieren'; $lng['admin']['phpsettings']['pass_authorizationheader'] = 'Füge "-pass-header Authorization" / "CGIPassAuth On" in Vhosts ein'; +$lng['serversettings']['ssl']['ssl_protocols']['title'] = 'SSL Protokollversion festlegen'; +$lng['serversettings']['ssl']['ssl_protocols']['description'] = 'Dies ist eine Liste von SSL/TLS Protokollversionen die genutzt werden sollen (oder auch nicht genutzt werden sollen), wenn SSL verwendet wird. Hinweis: Ältere Browser sind möglicherweise nicht vollständig zum neusten Protokoll kompatibel.

Standard-Wert ist:
TLSv1, TLSv1.2
'; diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 1eb0528d..46fe68d3 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -454,7 +454,7 @@ class apache extends HttpConfigBase } else { $this->virtualhosts_data[$vhosts_filename] .= ' SSLEngine On' . "\n"; - $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; + $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { if (Settings::Get('system.http2_support') == '1') { $this->virtualhosts_data[$vhosts_filename] .= ' Protocols h2 http/1.1' . "\n"; @@ -892,7 +892,7 @@ class apache extends HttpConfigBase if ($domain['ssl_cert_file'] != '') { $vhost_content .= ' SSLEngine On' . "\n"; - $vhost_content .= ' SSLProtocol -ALL +TLSv1 +TLSv1.2' . "\n"; + $vhost_content .= ' SSLProtocol -ALL' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { if (isset($domain['http2']) && $domain['http2'] == '1') { $vhost_content .= ' Protocols h2 http/1.1' . "\n"; diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index 0685ed7c..5c932fd1 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -623,7 +623,7 @@ class nginx extends HttpConfigBase } else { // obsolete: ssl on now belongs to the listen block as 'ssl' at the end // $sslsettings .= "\t" . 'ssl on;' . "\n"; - $sslsettings .= "\t" . 'ssl_protocols TLSv1 TLSv1.2;' . "\n"; + $sslsettings .= "\t" . 'ssl_protocols ' . str_replace(",", " ", Settings::Get('system.ssl_protocols')) . ';' . "\n"; $sslsettings .= "\t" . 'ssl_ciphers ' . Settings::Get('system.ssl_cipher_list') . ';' . "\n"; $sslsettings .= "\t" . 'ssl_ecdh_curve secp384r1;' . "\n"; $sslsettings .= "\t" . 'ssl_prefer_server_ciphers on;' . "\n"; From 281b131c628b07464f28d28e6194f9b04780d521 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 10:21:02 +0100 Subject: [PATCH 124/179] ups, forgot to adjust version in lib/version.inc.php Signed-off-by: Michael Kaufmann (d00p) --- lib/version.inc.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/version.inc.php b/lib/version.inc.php index 40aa7b18..fb8d88d3 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201801091'; +$dbversion = '201801100'; // Distribution branding-tag (used for Debian etc.) $branding = ''; From f2a79d4d965346ac3fd74fef3e4f04fd6fef70b0 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 15:20:19 +0100 Subject: [PATCH 125/179] add new security.limit_extensions setting to fpm-daemon settings Signed-off-by: Michael Kaufmann (d00p) --- admin_phpsettings.php | 12 +++++++++--- install/froxlor.sql | 3 ++- install/updates/froxlor/0.9/update_0.9.inc.php | 9 +++++++++ lib/classes/phpinterface/class.phpinterface_fpm.php | 2 ++ .../admin/phpconfig/formfield.fpmconfig_add.php | 9 +++++++++ .../admin/phpconfig/formfield.fpmconfig_edit.php | 9 +++++++++ lib/version.inc.php | 2 +- lng/english.lng.php | 2 ++ lng/german.lng.php | 2 ++ scripts/jobs/cron_tasks.inc.http.10.apache.php | 10 +++++++++- scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php | 10 +++++++++- 11 files changed, 63 insertions(+), 7 deletions(-) diff --git a/admin_phpsettings.php b/admin_phpsettings.php index 0fa1b831..f8dcc5ef 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -417,6 +417,7 @@ if ($page == 'overview') { $max_spare_servers = isset($_POST['max_spare_servers']) ? (int) $_POST['max_spare_servers'] : 0; $max_requests = isset($_POST['max_requests']) ? (int) $_POST['max_requests'] : 0; $idle_timeout = isset($_POST['idle_timeout']) ? (int) $_POST['idle_timeout'] : 0; + $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions'); if (strlen($description) == 0 || strlen($description) > 50) { standard_error('descriptioninvalid'); @@ -433,7 +434,8 @@ if ($page == 'overview') { `min_spare_servers` = :min_spare_servers, `max_spare_servers` = :max_spare_servers, `max_requests` = :max_requests, - `idle_timeout` = :idle_timeout + `idle_timeout` = :idle_timeout, + `limit_extensions` = :limit_extensions "); $ins_data = array( 'desc' => $description, @@ -445,7 +447,8 @@ if ($page == 'overview') { 'min_spare_servers' => $min_spare_servers, 'max_spare_servers' => $max_spare_servers, 'max_requests' => $max_requests, - 'idle_timeout' => $idle_timeout + 'idle_timeout' => $idle_timeout, + 'limit_extensions' => $limit_extensions ); Database::pexecute($ins_stmt, $ins_data); @@ -543,6 +546,7 @@ if ($page == 'overview') { $max_spare_servers = isset($_POST['max_spare_servers']) ? (int) $_POST['max_spare_servers'] : $result['max_spare_servers']; $max_requests = isset($_POST['max_requests']) ? (int) $_POST['max_requests'] : $result['max_requests']; $idle_timeout = isset($_POST['idle_timeout']) ? (int) $_POST['idle_timeout'] : $result['idle_timeout']; + $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions'); if (strlen($description) == 0 || strlen($description) > 50) { standard_error('descriptioninvalid'); @@ -559,7 +563,8 @@ if ($page == 'overview') { `min_spare_servers` = :min_spare_servers, `max_spare_servers` = :max_spare_servers, `max_requests` = :max_requests, - `idle_timeout` = :idle_timeout + `idle_timeout` = :idle_timeout, + `limit_extensions` = :limit_extensions WHERE `id` = :id "); $upd_data = array( @@ -573,6 +578,7 @@ if ($page == 'overview') { 'max_spare_servers' => $max_spare_servers, 'max_requests' => $max_requests, 'idle_timeout' => $idle_timeout, + 'limit_extensions' => $limit_extensions, 'id' => $id ); Database::pexecute($upd_stmt, $upd_data); diff --git a/install/froxlor.sql b/install/froxlor.sql index f56d0a39..cbcae082 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -590,7 +590,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.8'), - ('panel', 'db_version', '201801100'); + ('panel', 'db_version', '201801101'); DROP TABLE IF EXISTS `panel_tasks`; @@ -770,6 +770,7 @@ CREATE TABLE `panel_fpmdaemons` ( `max_spare_servers` int(4) NOT NULL DEFAULT '35', `max_requests` int(4) NOT NULL DEFAULT '0', `idle_timeout` int(4) NOT NULL DEFAULT '30', + `limit_extensions` varchar(255) NOT NULL default '.php', PRIMARY KEY (`id`), UNIQUE KEY `reload` (`reload_cmd`), UNIQUE KEY `config` (`config_dir`) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 48212f1d..9891df2b 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3752,3 +3752,12 @@ if (isDatabaseVersion('201801091')) { updateToDbVersion('201801100'); } + +if (isDatabaseVersion('201801100')) { + + showUpdateStep("Adding field for security.limit_extensions fpm-setting"); + Database::query("ALTER TABLE `" . TABLE_PANEL_FPMDAEMONS . "` ADD `limit_extensions` varchar(255) NOT NULL default '.php';"); + lastStepStatus(0); + + updateToDbVersion('201801101'); +} diff --git a/lib/classes/phpinterface/class.phpinterface_fpm.php b/lib/classes/phpinterface/class.phpinterface_fpm.php index 2622b090..0509666a 100644 --- a/lib/classes/phpinterface/class.phpinterface_fpm.php +++ b/lib/classes/phpinterface/class.phpinterface_fpm.php @@ -192,6 +192,7 @@ class phpinterface_fpm $fpm_max_spare_servers = (int) $this->_fpm_cfg['max_spare_servers']; $fpm_requests = (int) $this->_fpm_cfg['max_requests']; $fpm_process_idle_timeout = (int) $this->_fpm_cfg['idle_timeout']; + $fpm_limit_extensions = $this->_fpm_cfg['limit_extensions']; if ($fpm_children == 0) { $fpm_children = 1; @@ -255,6 +256,7 @@ class phpinterface_fpm } $fpm_config .= ';chroot = ' . makeCorrectDir($this->_domain['documentroot']) . "\n"; + $fpm_config .= 'security.limit_extensions = '.$fpm_limit_extensions . "\n"; $tmpdir = makeCorrectDir(Settings::Get('phpfpm.tmpdir') . '/' . $this->_domain['loginname'] . '/'); if (! is_dir($tmpdir)) { diff --git a/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php b/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php index 88a1bb8b..a8d91d86 100644 --- a/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php @@ -81,6 +81,15 @@ return array( 'desc' => $lng['serversettings']['phpfpm_settings']['idle_timeout']['description'], 'type' => 'int', 'value' => 30 + ), + 'limit_extensions' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['description'], + 'type' => 'string', + 'string_delimiter' => ' ', + 'string_regexp' => '^\.[a-z]([a-z0-9]+)', + 'string_emptyallowed' => false, + 'value' => '.php' ) ) ) diff --git a/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php index d5e8c17f..6b8199e3 100644 --- a/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php @@ -82,6 +82,15 @@ return array( 'desc' => $lng['serversettings']['phpfpm_settings']['idle_timeout']['description'], 'type' => 'int', 'value' => $result['idle_timeout'] + ), + 'limit_extensions' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['description'], + 'type' => 'string', + 'string_delimiter' => ' ', + 'string_regexp' => '^\.[a-z]([a-z0-9]+)', + 'string_emptyallowed' => false, + 'value' => $result['limit_extensions'] ) ) ) diff --git a/lib/version.inc.php b/lib/version.inc.php index fb8d88d3..ac4adb0f 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201801100'; +$dbversion = '201801101'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index 0893cdb6..0830a2ef 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2094,3 +2094,5 @@ $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt can only validate $lng['admin']['phpsettings']['pass_authorizationheader'] = 'Add "-pass-header Authorization" / "CGIPassAuth On" to vhosts'; $lng['serversettings']['ssl']['ssl_protocols']['title'] = 'Configure the TLS protocol version'; $lng['serversettings']['ssl']['ssl_protocols']['description'] = 'This is a list of ssl protocols that you want (or don\'t want) to use when using SSL. Notice: Some older browsers may not support the newest protcol versions.

Default value is:
TLSv1, TLSv1.2
'; +$lng['serversettings']['phpfpm_settings']['limit_extensions']['title'] = 'Allowed extensions'; +$lng['serversettings']['phpfpm_settings']['limit_extensions']['description'] = 'Limits the extensions of the main script FPM will allow to parse. This can prevent configuration mistakes on the web server side. You should only limit FPM to .php extensions to prevent malicious users to use other extensions to execute php code. Default value: .php'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 830bb1c3..160ebb9a 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1745,3 +1745,5 @@ $lng['error']['nowildcardwithletsencryptv2'] = 'Let\'s Encrypt kann in ACME v2 W $lng['admin']['phpsettings']['pass_authorizationheader'] = 'Füge "-pass-header Authorization" / "CGIPassAuth On" in Vhosts ein'; $lng['serversettings']['ssl']['ssl_protocols']['title'] = 'SSL Protokollversion festlegen'; $lng['serversettings']['ssl']['ssl_protocols']['description'] = 'Dies ist eine Liste von SSL/TLS Protokollversionen die genutzt werden sollen (oder auch nicht genutzt werden sollen), wenn SSL verwendet wird. Hinweis: Ältere Browser sind möglicherweise nicht vollständig zum neusten Protokoll kompatibel.

Standard-Wert ist:
TLSv1, TLSv1.2
'; +$lng['serversettings']['phpfpm_settings']['limit_extensions']['title'] = 'Erlaubte Dateiendungen'; +$lng['serversettings']['phpfpm_settings']['limit_extensions']['description'] = 'Beschränkt die Dateierweiterungen des Haupt-Skripts, das FPM zu parsen erlaubt. Dies kann Konfigurationsfehler auf der Webserverseite verhindern. Sie sollten FPM nur auf .php Erweiterungen beschränken, um zu verhindern, dass bösartige Nutzter andere Erweiterungen verwenden, um PHP Code auszuführen. Standardwert: .php'; diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 46fe68d3..ce6bc072 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -327,7 +327,15 @@ class apache extends HttpConfigBase // mod_proxy stuff for apache-2.4 if (Settings::Get('system.apache24') == '1' && Settings::Get('phpfpm.use_mod_proxy') == '1') { - $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; + $filesmatch = $phpconfig['limit_extensions']; + $extensions = explode(" ", $filesmatch); + $filesmatch = ""; + foreach ($extensions as $ext) { + $filesmatch .= $ext.'|'; + } + // start block, cut off last pipe and close block + $filesmatch = '('.substr($filesmatch, -1).')'; + $this->virtualhosts_data[$vhosts_filename] .= ' '. "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SetHandler proxy:unix:' . $php->getInterface()->getSocketFile() . '|fcgi://localhost' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; if ($phpconfig['pass_authorizationheader'] == '1') { diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index fcd16533..85e5ae64 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -44,7 +44,15 @@ class apache_fcgid extends apache if (Settings::Get('system.apache24') == '1' && Settings::Get('phpfpm.use_mod_proxy') == '1' ) { - $php_options_text.= ' '. "\n"; + $filesmatch = $phpconfig['limit_extensions']; + $extensions = explode(" ", $filesmatch); + $filesmatch = ""; + foreach ($extensions as $ext) { + $filesmatch .= $ext.'|'; + } + // start block, cut off last pipe and close block + $filesmatch = '('.substr($filesmatch, -1).')'; + $php_options_text.= ' '. "\n"; $php_options_text.= ' SetHandler proxy:unix:' . $php->getInterface()->getSocketFile() . '|fcgi://localhost'. "\n"; $php_options_text.= ' ' . "\n"; From 941dd14c725ce745fecee64e2ec176dacdb9762d Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 15:22:22 +0100 Subject: [PATCH 126/179] read limit_extensions value from wrong array Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 2 +- scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index ce6bc072..76e1e5ce 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -327,7 +327,7 @@ class apache extends HttpConfigBase // mod_proxy stuff for apache-2.4 if (Settings::Get('system.apache24') == '1' && Settings::Get('phpfpm.use_mod_proxy') == '1') { - $filesmatch = $phpconfig['limit_extensions']; + $filesmatch = $phpconfig['fpm_settings']['limit_extensions']; $extensions = explode(" ", $filesmatch); $filesmatch = ""; foreach ($extensions as $ext) { diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index 85e5ae64..6c4bfcb3 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -44,7 +44,7 @@ class apache_fcgid extends apache if (Settings::Get('system.apache24') == '1' && Settings::Get('phpfpm.use_mod_proxy') == '1' ) { - $filesmatch = $phpconfig['limit_extensions']; + $filesmatch = $phpconfig['fpm_settings']['limit_extensions']; $extensions = explode(" ", $filesmatch); $filesmatch = ""; foreach ($extensions as $ext) { From bba872618aaeae063320ded4092361984152e591 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 15:28:48 +0100 Subject: [PATCH 127/179] fix ssl-procotols in apache-cron; fix files-match regex in apache-cron Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 8 ++++---- scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 76e1e5ce..92ac03e8 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -331,10 +331,10 @@ class apache extends HttpConfigBase $extensions = explode(" ", $filesmatch); $filesmatch = ""; foreach ($extensions as $ext) { - $filesmatch .= $ext.'|'; + $filesmatch .= substr($ext, 1).'|'; } // start block, cut off last pipe and close block - $filesmatch = '('.substr($filesmatch, -1).')'; + $filesmatch = '('.substr($filesmatch, 0, -1).')'; $this->virtualhosts_data[$vhosts_filename] .= ' '. "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SetHandler proxy:unix:' . $php->getInterface()->getSocketFile() . '|fcgi://localhost' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; @@ -462,7 +462,7 @@ class apache extends HttpConfigBase } else { $this->virtualhosts_data[$vhosts_filename] .= ' SSLEngine On' . "\n"; - $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; + $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL +' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { if (Settings::Get('system.http2_support') == '1') { $this->virtualhosts_data[$vhosts_filename] .= ' Protocols h2 http/1.1' . "\n"; @@ -900,7 +900,7 @@ class apache extends HttpConfigBase if ($domain['ssl_cert_file'] != '') { $vhost_content .= ' SSLEngine On' . "\n"; - $vhost_content .= ' SSLProtocol -ALL' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; + $vhost_content .= ' SSLProtocol -ALL +' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { if (isset($domain['http2']) && $domain['http2'] == '1') { $vhost_content .= ' Protocols h2 http/1.1' . "\n"; diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index 6c4bfcb3..6d507ec4 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -48,10 +48,10 @@ class apache_fcgid extends apache $extensions = explode(" ", $filesmatch); $filesmatch = ""; foreach ($extensions as $ext) { - $filesmatch .= $ext.'|'; + $filesmatch .= substr($ext, 1).'|'; } // start block, cut off last pipe and close block - $filesmatch = '('.substr($filesmatch, -1).')'; + $filesmatch = '('.substr($filesmatch, 0, -1).')'; $php_options_text.= ' '. "\n"; $php_options_text.= ' SetHandler proxy:unix:' . $php->getInterface()->getSocketFile() . '|fcgi://localhost'. "\n"; $php_options_text.= ' ' . "\n"; From 62006d584e910681e1287909b97b8c4b4754c8c9 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 15:42:11 +0100 Subject: [PATCH 128/179] fix limit_extensions setting Signed-off-by: Michael Kaufmann (d00p) --- admin_phpsettings.php | 4 ++-- lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php | 5 +---- lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php | 5 +---- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/admin_phpsettings.php b/admin_phpsettings.php index f8dcc5ef..b86c9de3 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -417,7 +417,7 @@ if ($page == 'overview') { $max_spare_servers = isset($_POST['max_spare_servers']) ? (int) $_POST['max_spare_servers'] : 0; $max_requests = isset($_POST['max_requests']) ? (int) $_POST['max_requests'] : 0; $idle_timeout = isset($_POST['idle_timeout']) ? (int) $_POST['idle_timeout'] : 0; - $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions'); + $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions', '^(\.[a-z]([a-z0-9]+)\ ?)+$'); if (strlen($description) == 0 || strlen($description) > 50) { standard_error('descriptioninvalid'); @@ -546,7 +546,7 @@ if ($page == 'overview') { $max_spare_servers = isset($_POST['max_spare_servers']) ? (int) $_POST['max_spare_servers'] : $result['max_spare_servers']; $max_requests = isset($_POST['max_requests']) ? (int) $_POST['max_requests'] : $result['max_requests']; $idle_timeout = isset($_POST['idle_timeout']) ? (int) $_POST['idle_timeout'] : $result['idle_timeout']; - $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions'); + $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions', '^(\.[a-z]([a-z0-9]+)\ ?)+$'); if (strlen($description) == 0 || strlen($description) > 50) { standard_error('descriptioninvalid'); diff --git a/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php b/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php index a8d91d86..d5e86de2 100644 --- a/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php @@ -85,10 +85,7 @@ return array( 'limit_extensions' => array( 'label' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['title'], 'desc' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['description'], - 'type' => 'string', - 'string_delimiter' => ' ', - 'string_regexp' => '^\.[a-z]([a-z0-9]+)', - 'string_emptyallowed' => false, + 'type' => 'text', 'value' => '.php' ) ) diff --git a/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php index 6b8199e3..74593812 100644 --- a/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php @@ -86,10 +86,7 @@ return array( 'limit_extensions' => array( 'label' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['title'], 'desc' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['description'], - 'type' => 'string', - 'string_delimiter' => ' ', - 'string_regexp' => '^\.[a-z]([a-z0-9]+)', - 'string_emptyallowed' => false, + 'type' => 'text', 'value' => $result['limit_extensions'] ) ) From eed3a91385ae5459094553282db08ca66db92aad Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 15:45:21 +0100 Subject: [PATCH 129/179] fix (not yet perfect) regex for limit_extension setting Signed-off-by: Michael Kaufmann (d00p) --- admin_phpsettings.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/admin_phpsettings.php b/admin_phpsettings.php index b86c9de3..f43ce116 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -417,7 +417,7 @@ if ($page == 'overview') { $max_spare_servers = isset($_POST['max_spare_servers']) ? (int) $_POST['max_spare_servers'] : 0; $max_requests = isset($_POST['max_requests']) ? (int) $_POST['max_requests'] : 0; $idle_timeout = isset($_POST['idle_timeout']) ? (int) $_POST['idle_timeout'] : 0; - $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions', '^(\.[a-z]([a-z0-9]+)\ ?)+$'); + $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions', '/^(\.[a-z]([a-z0-9]+)\ ?)+$/'); if (strlen($description) == 0 || strlen($description) > 50) { standard_error('descriptioninvalid'); @@ -546,7 +546,7 @@ if ($page == 'overview') { $max_spare_servers = isset($_POST['max_spare_servers']) ? (int) $_POST['max_spare_servers'] : $result['max_spare_servers']; $max_requests = isset($_POST['max_requests']) ? (int) $_POST['max_requests'] : $result['max_requests']; $idle_timeout = isset($_POST['idle_timeout']) ? (int) $_POST['idle_timeout'] : $result['idle_timeout']; - $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions', '^(\.[a-z]([a-z0-9]+)\ ?)+$'); + $limit_extensions = validate($_POST['limit_extensions'], 'limit_extensions', '/^(\.[a-z]([a-z0-9]+)\ ?)+$/'); if (strlen($description) == 0 || strlen($description) > 50) { standard_error('descriptioninvalid'); From 29433ce96313b04f2e6c5921e5d9c8d1f19c6a52 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 15:49:07 +0100 Subject: [PATCH 130/179] escape possible dots in extension (e.g. to allow .php.xml or similar) Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 2 +- scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 92ac03e8..420e9c22 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -334,7 +334,7 @@ class apache extends HttpConfigBase $filesmatch .= substr($ext, 1).'|'; } // start block, cut off last pipe and close block - $filesmatch = '('.substr($filesmatch, 0, -1).')'; + $filesmatch = '('.str_replace(".", "\.", substr($filesmatch, 0, -1)).')'; $this->virtualhosts_data[$vhosts_filename] .= ' '. "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SetHandler proxy:unix:' . $php->getInterface()->getSocketFile() . '|fcgi://localhost' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index 6d507ec4..0b3119e7 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -51,7 +51,7 @@ class apache_fcgid extends apache $filesmatch .= substr($ext, 1).'|'; } // start block, cut off last pipe and close block - $filesmatch = '('.substr($filesmatch, 0, -1).')'; + $filesmatch = '('.str_replace(".", "\.", substr($filesmatch, 0, -1)).')'; $php_options_text.= ' '. "\n"; $php_options_text.= ' SetHandler proxy:unix:' . $php->getInterface()->getSocketFile() . '|fcgi://localhost'. "\n"; $php_options_text.= ' ' . "\n"; From 8c617732800a2281c69cc2d5e33ecbe3952bf981 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 10 Jan 2018 17:01:17 +0100 Subject: [PATCH 131/179] fix usage of extensions from limit_extensions list in apache-cron Signed-off-by: Michael Kaufmann (d00p) --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 11 +++++++++-- scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php | 10 +++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 420e9c22..55f230d0 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -350,8 +350,15 @@ class apache extends HttpConfigBase } $this->virtualhosts_data[$vhosts_filename] .= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . $phpconfig['fpm_settings']['idle_timeout'] . $addheader . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; - $file_extensions = explode(' ', $phpconfig['file_extensions']); - $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; + $filesmatch = $phpconfig['fpm_settings']['limit_extensions']; + $extensions = explode(" ", $filesmatch); + $filesmatch = ""; + foreach ($extensions as $ext) { + $filesmatch .= substr($ext, 1).'|'; + } + // start block, cut off last pipe and close block + $filesmatch = '('.str_replace(".", "\.", substr($filesmatch, 0, -1)).')'; + $this->virtualhosts_data[$vhosts_filename] .= ' '. "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' AddHandler php5-fastcgi .php' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' Action php5-fastcgi /fastcgiphp' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' Options +ExecCGI' . "\n"; diff --git a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index 0b3119e7..acf49948 100644 --- a/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php +++ b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php @@ -82,7 +82,15 @@ class apache_fcgid extends apache } $php_options_text.= ' FastCgiExternalServer ' . $php->getInterface()->getAliasConfigDir() . $srvName . ' -socket ' . $php->getInterface()->getSocketFile() . ' -idle-timeout ' . $phpconfig['fpm_settings']['idle_timeout'] . $addheader . "\n"; $php_options_text.= ' ' . "\n"; - $php_options_text.= ' ' . "\n"; + $filesmatch = $phpconfig['fpm_settings']['limit_extensions']; + $extensions = explode(" ", $filesmatch); + $filesmatch = ""; + foreach ($extensions as $ext) { + $filesmatch .= substr($ext, 1).'|'; + } + // start block, cut off last pipe and close block + $filesmatch = '('.str_replace(".", "\.", substr($filesmatch, 0, -1)).')'; + $php_options_text.= ' '. "\n"; $php_options_text.= ' SetHandler php5-fastcgi'. "\n"; $php_options_text.= ' Action php5-fastcgi /fastcgiphp' . "\n"; $php_options_text.= ' Options +ExecCGI' . "\n"; From 29968e6026ebcc81978ba34c45a299444ebf3f78 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 11 Jan 2018 10:44:42 +0100 Subject: [PATCH 132/179] add stretch config-templates, testers/feedback welcome Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/stretch.xml | 4582 +++++++++++++++++ lng/english.lng.php | 6 +- lng/german.lng.php | 6 +- .../Sparkle/admin/configfiles/configfiles.tpl | 18 +- 4 files changed, 4592 insertions(+), 20 deletions(-) create mode 100644 lib/configfiles/stretch.xml diff --git a/lib/configfiles/stretch.xml b/lib/configfiles/stretch.xml new file mode 100644 index 00000000..a425306a --- /dev/null +++ b/lib/configfiles/stretch.xml @@ -0,0 +1,4582 @@ + + + + + + + + + + + {{settings.system.apacheconf_vhost}} + + + + + {{settings.system.apacheconf_vhost}} + + + + + + + {{settings.system.apacheconf_diroptions}} + + + + + {{settings.system.apacheconf_diroptions}} + + + + + + + + + + + {{settings.system.deactivateddocroot}} + + + + + + + + + //service[@type='http']/general/commands + + + + {{settings.phpfpm.enabled}} + + + + + + {{settings.system.leenabled}} + + + Require all granted + +]]> +
+
+ +
+ + + + + "{{settings.system.letsencryptchallengepath}}/.well-known/acme-challenge/") + +# default listening port for IPv6 falls back to the IPv4 port +include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port +include_shell "/usr/share/lighttpd/create-mime.assign.pl" +include_shell "/usr/share/lighttpd/include-conf-enabled.pl" +]]> + + + //service[@type='http']/general/commands + + {{settings.system.apacheconf_vhost}} + + > /etc/lighttpd/lighttpd.conf]]> + + + {{settings.system.apacheconf_vhost}} + + > /etc/lighttpd/lighttpd.conf]]> + + + {{settings.system.apacheconf_diroptions}} + + > /etc/lighttpd/lighttpd.conf]]> + + + {{settings.system.apacheconf_diroptions}} + + > /etc/lighttpd/lighttpd.conf]]> + + + + + + + + + + {{settings.phpfpm.enabled}} + + {{settings.system.mod_fcgid}} + + + + + + + + + + + + + {{settings.system.leenabled}} + + + + + + {{settings.phpfpm.enabled}} + + {{settings.system.mod_fcgid}} + + + + + //service[@type='http']/general/commands + + {{settings.phpfpm.enabled}} + + {{settings.system.mod_fcgid}} + + + + + + + + + + + + > /etc/bind/named.conf.local]]> + + + + + + + + + +# add these entries to the list if any speficied: + +################################# +# allow-dnsupdate-from A global setting to allow DNS updates from these IP ranges. +# +# allow-dnsupdate-from=127.0.0.0/8,::1 + +################################# +# allow-recursion List of subnets that are allowed to recurse +# +allow-recursion=127.0.0.1 + +################################# +# also-notify When notifying a domain, also notify these nameservers +# +# also-notify= + +################################# +# any-to-tcp Answer ANY queries with tc=1, shunting to TCP +# +# any-to-tcp=no + +################################# +# cache-ttl Seconds to store packets in the PacketCache +# +# cache-ttl=20 + +################################# +# carbon-interval Number of seconds between carbon (graphite) updates +# +# carbon-interval=30 + +################################# +# carbon-ourname If set, overrides our reported hostname for carbon stats +# +# carbon-ourname= + +################################# +# carbon-server If set, send metrics in carbon (graphite) format to this server +# +# carbon-server= + +################################# +# chroot If set, chroot to this directory for more security +# +# chroot= + +################################# +# config-dir Location of configuration directory (pdns.conf) +# +config-dir=/etc/powerdns + +################################# +# config-name Name of this virtual configuration - will rename the binary image +# +# config-name= + +################################# +# control-console Debugging switch - don't use +# +# control-console=no + +################################# +# daemon Operate as a daemon +# +daemon=yes + +################################# +# default-ksk-algorithms Default KSK algorithms +# +# default-ksk-algorithms=rsasha256 + +################################# +# default-ksk-size Default KSK size (0 means default) +# +# default-ksk-size=0 + +################################# +# default-soa-mail mail address to insert in the SOA record if none set in the backend +# +# default-soa-mail= + +################################# +# default-soa-name name to insert in the SOA record if none set in the backend +# +# default-soa-name=a.misconfigured.powerdns.server + +################################# +# default-ttl Seconds a result is valid if not set otherwise +# +# default-ttl=3600 + +################################# +# default-zsk-algorithms Default ZSK algorithms +# +# default-zsk-algorithms=rsasha256 + +################################# +# default-zsk-size Default ZSK size (0 means default) +# +# default-zsk-size=0 + +################################# +# direct-dnskey Fetch DNSKEY RRs from backend during DNSKEY synthesis +# +# direct-dnskey=no + +################################# +# disable-axfr Disable zonetransfers but do allow TCP queries +# +# disable-axfr=no + +################################# +# disable-axfr-rectify Disable the rectify step during an outgoing AXFR. Only required for regression testing. +# +# disable-axfr-rectify=no + +################################# +# disable-tcp Do not listen to TCP queries +# +# disable-tcp=no + +################################# +# distributor-threads Default number of Distributor (backend) threads to start +# +# distributor-threads=3 + +################################# +# do-ipv6-additional-processing Do AAAA additional processing +# +# do-ipv6-additional-processing=yes + +################################# +# edns-subnet-processing If we should act on EDNS Subnet options +# +# edns-subnet-processing=no + +################################# +# entropy-source If set, read entropy from this file +# +# entropy-source=/dev/urandom + +################################# +# experimental-api-key REST API Static authentication key (required for API use) +# +# experimental-api-key= + +################################# +# experimental-api-readonly If the JSON API should disallow data modification +# +# experimental-api-readonly=no + +################################# +# experimental-dname-processing If we should support DNAME records +# +# experimental-dname-processing=no + +################################# +# experimental-dnsupdate Enable/Disable DNS update (RFC2136) support. Default is no. +# +# experimental-dnsupdate=no + +################################# +# experimental-json-interface If the webserver should serve JSON data +# +# experimental-json-interface=no + +################################# +# experimental-logfile Filename of the log file for JSON parser +# +# experimental-logfile=/var/log/pdns.log + +################################# +# forward-dnsupdate A global setting to allow DNS update packages that are for a Slave domain, to be forwarded to the master. +# +# forward-dnsupdate=yes + +################################# +# guardian Run within a guardian process +# +guardian=yes + +################################# +# include-dir Include *.conf files from this directory +# +# include-dir= + +################################# +# launch Which backends to launch and order to query them in +# +# launch= + +################################# +# load-modules Load this module - supply absolute or relative path +# +# load-modules= + +################################# +# local-address Local IP addresses to which we bind +# +local-address=,127.0.0.1 + +################################# +# local-address-nonexist-fail Fail to start if one or more of the local-address's do not exist on this server +# +# local-address-nonexist-fail=yes + +################################# +# local-ipv6 Local IP address to which we bind +# +# local-ipv6= + +################################# +# local-ipv6-nonexist-fail Fail to start if one or more of the local-ipv6 addresses do not exist on this server +# +# local-ipv6-nonexist-fail=yes + +################################# +# local-port The port on which we listen +# +# local-port=53 + +################################# +# log-dns-details If PDNS should log DNS non-erroneous details +# +# log-dns-details=no + +################################# +# log-dns-queries If PDNS should log all incoming DNS queries +# +# log-dns-queries=no + +################################# +# logging-facility Log under a specific facility +# +# logging-facility= + +################################# +# loglevel Amount of logging. Higher is more. Do not set below 3 +# +# loglevel=4 + +################################# +# lua-prequery-script Lua script with prequery handler +# +# lua-prequery-script= + +################################# +# master Act as a master +# +master=yes + +################################# +# max-cache-entries Maximum number of cache entries +# +# max-cache-entries=1000000 + +################################# +# max-ent-entries Maximum number of empty non-terminals in a zone +# +# max-ent-entries=100000 + +################################# +# max-nsec3-iterations Limit the number of NSEC3 hash iterations +# +# max-nsec3-iterations=500 + +################################# +# max-queue-length Maximum queuelength before considering situation lost +# +# max-queue-length=5000 + +################################# +# max-signature-cache-entries Maximum number of signatures cache entries +# +# max-signature-cache-entries= + +################################# +# max-tcp-connections Maximum number of TCP connections +# +# max-tcp-connections=10 + +################################# +# module-dir Default directory for modules +# +# module-dir=/usr/lib/TRIPLET/pdns + +################################# +# negquery-cache-ttl Seconds to store negative query results in the QueryCache +# +# negquery-cache-ttl=60 + +################################# +# no-shuffle Set this to prevent random shuffling of answers - for regression testing +# +# no-shuffle=off + +################################# +# only-notify Only send AXFR NOTIFY to these IP addresses or netmasks +# +# only-notify=0.0.0.0/0,::/0 + +################################# +# out-of-zone-additional-processing Do out of zone additional processing +# +# out-of-zone-additional-processing=yes + +################################# +# overload-queue-length Maximum queuelength moving to packetcache only +# +# overload-queue-length=0 + +################################# +# pipebackend-abi-version Version of the pipe backend ABI +# +# pipebackend-abi-version=1 + +################################# +# prevent-self-notification Don't send notifications to what we think is ourself +# +# prevent-self-notification=yes + +################################# +# query-cache-ttl Seconds to store query results in the QueryCache +# +# query-cache-ttl=20 + +################################# +# query-local-address Source IP address for sending queries +# +# query-local-address=0.0.0.0 + +################################# +# query-local-address6 Source IPv6 address for sending queries +# +# query-local-address6=:: + +################################# +# query-logging Hint backends that queries should be logged +# +# query-logging=no + +################################# +# queue-limit Maximum number of milliseconds to queue a query +# +# queue-limit=1500 + +################################# +# receiver-threads Default number of receiver threads to start +# +# receiver-threads=1 + +################################# +# recursive-cache-ttl Seconds to store packets for recursive queries in the PacketCache +# +# recursive-cache-ttl=10 + +################################# +# recursor If recursion is desired, IP address of a recursing nameserver +# +# recursor=no + +################################# +# retrieval-threads Number of AXFR-retrieval threads for slave operation +# +# retrieval-threads=2 + +################################# +# reuseport Enable higher performance on compliant kernels by using SO_REUSEPORT allowing each receiver thread to open its own socket +# +# reuseport=no + +################################# +# security-poll-suffix Domain name from which to query security update notifications +# +# security-poll-suffix=secpoll.powerdns.com. + +################################# +# send-root-referral Send out old-fashioned root-referral instead of ServFail in case of no authority +# +# send-root-referral=no + +################################# +# server-id Returned when queried for 'server.id' TXT or NSID, defaults to hostname - disabled or custom +# +# server-id= + +################################# +# setgid If set, change group id to this gid for more security +# +setgid=pdns + +################################# +# setuid If set, change user id to this uid for more security +# +setuid=pdns + +################################# +# signing-threads Default number of signer threads to start +# +# signing-threads=3 + +################################# +# slave Act as a slave +# +# slave=no + +################################# +# slave-cycle-interval Reschedule failed SOA serial checks once every .. seconds +# +# slave-cycle-interval=60 + +################################# +# slave-renotify If we should send out notifications for slaved updates +# +# slave-renotify=no + +################################# +# soa-expire-default Default SOA expire +# +# soa-expire-default=604800 + +################################# +# soa-minimum-ttl Default SOA minimum ttl +# +# soa-minimum-ttl=3600 + +################################# +# soa-refresh-default Default SOA refresh +# +# soa-refresh-default=10800 + +################################# +# soa-retry-default Default SOA retry +# +# soa-retry-default=3600 + +################################# +# socket-dir Where the controlsocket will live +# +# socket-dir=/var/run + +################################# +# tcp-control-address If set, PowerDNS can be controlled over TCP on this address +# +# tcp-control-address= + +################################# +# tcp-control-port If set, PowerDNS can be controlled over TCP on this address +# +# tcp-control-port=53000 + +################################# +# tcp-control-range If set, remote control of PowerDNS is possible over these networks only +# +# tcp-control-range=127.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, ::1/128, fe80::/10 + +################################# +# tcp-control-secret If set, PowerDNS can be controlled over TCP after passing this secret +# +# tcp-control-secret= + +################################# +# traceback-handler Enable the traceback handler (Linux only) +# +# traceback-handler=yes + +################################# +# trusted-notification-proxy IP address of incoming notification proxy +# +# trusted-notification-proxy= + +################################# +# udp-truncation-threshold Maximum UDP response size before we truncate +# +# udp-truncation-threshold=1680 + +################################# +# version-string PowerDNS version in packets - full, anonymous, powerdns or custom +# + +version-string=powerdns +################################# +# webserver Start a webserver for monitoring +# +# webserver=no + +################################# +# webserver-address IP Address of webserver to listen on +# +# webserver-address=127.0.0.1 + +################################# +# webserver-allow-from Webserver access is only allowed from these subnets +# +# webserver-allow-from=0.0.0.0/0,::/0 + +################################# +# webserver-password Password required for accessing the webserver +# +# webserver-password= + +################################# +# webserver-port Port of webserver to listen on +# +# webserver-port=8081 + +################################# +# webserver-print-arguments If the webserver should print arguments +# +# webserver-print-arguments=no + +# include froxlor-bind-specific config +include-dir=/etc/powerdns/froxlor/ +]]> + + + + + + + + + + + + + +# add these entries to the list if any speficied: + +################################# +# allow-dnsupdate-from A global setting to allow DNS updates from these IP ranges. +# +# allow-dnsupdate-from=127.0.0.0/8,::1 + +################################# +# allow-recursion List of subnets that are allowed to recurse +# +allow-recursion=127.0.0.1 + +################################# +# also-notify When notifying a domain, also notify these nameservers +# +# also-notify= + +################################# +# any-to-tcp Answer ANY queries with tc=1, shunting to TCP +# +# any-to-tcp=no + +################################# +# cache-ttl Seconds to store packets in the PacketCache +# +# cache-ttl=20 + +################################# +# carbon-interval Number of seconds between carbon (graphite) updates +# +# carbon-interval=30 + +################################# +# carbon-ourname If set, overrides our reported hostname for carbon stats +# +# carbon-ourname= + +################################# +# carbon-server If set, send metrics in carbon (graphite) format to this server +# +# carbon-server= + +################################# +# chroot If set, chroot to this directory for more security +# +# chroot= + +################################# +# config-dir Location of configuration directory (pdns.conf) +# +config-dir=/etc/powerdns + +################################# +# config-name Name of this virtual configuration - will rename the binary image +# +# config-name= + +################################# +# control-console Debugging switch - don't use +# +# control-console=no + +################################# +# daemon Operate as a daemon +# +daemon=yes + +################################# +# default-ksk-algorithms Default KSK algorithms +# +# default-ksk-algorithms=rsasha256 + +################################# +# default-ksk-size Default KSK size (0 means default) +# +# default-ksk-size=0 + +################################# +# default-soa-mail mail address to insert in the SOA record if none set in the backend +# +# default-soa-mail= + +################################# +# default-soa-name name to insert in the SOA record if none set in the backend +# +# default-soa-name=a.misconfigured.powerdns.server + +################################# +# default-ttl Seconds a result is valid if not set otherwise +# +# default-ttl=3600 + +################################# +# default-zsk-algorithms Default ZSK algorithms +# +# default-zsk-algorithms=rsasha256 + +################################# +# default-zsk-size Default ZSK size (0 means default) +# +# default-zsk-size=0 + +################################# +# direct-dnskey Fetch DNSKEY RRs from backend during DNSKEY synthesis +# +# direct-dnskey=no + +################################# +# disable-axfr Disable zonetransfers but do allow TCP queries +# +# disable-axfr=no + +################################# +# disable-axfr-rectify Disable the rectify step during an outgoing AXFR. Only required for regression testing. +# +# disable-axfr-rectify=no + +################################# +# disable-tcp Do not listen to TCP queries +# +# disable-tcp=no + +################################# +# distributor-threads Default number of Distributor (backend) threads to start +# +# distributor-threads=3 + +################################# +# do-ipv6-additional-processing Do AAAA additional processing +# +# do-ipv6-additional-processing=yes + +################################# +# edns-subnet-processing If we should act on EDNS Subnet options +# +# edns-subnet-processing=no + +################################# +# entropy-source If set, read entropy from this file +# +# entropy-source=/dev/urandom + +################################# +# experimental-api-key REST API Static authentication key (required for API use) +# +# experimental-api-key= + +################################# +# experimental-api-readonly If the JSON API should disallow data modification +# +# experimental-api-readonly=no + +################################# +# experimental-dname-processing If we should support DNAME records +# +# experimental-dname-processing=no + +################################# +# experimental-dnsupdate Enable/Disable DNS update (RFC2136) support. Default is no. +# +# experimental-dnsupdate=no + +################################# +# experimental-json-interface If the webserver should serve JSON data +# +# experimental-json-interface=no + +################################# +# experimental-logfile Filename of the log file for JSON parser +# +# experimental-logfile=/var/log/pdns.log + +################################# +# forward-dnsupdate A global setting to allow DNS update packages that are for a Slave domain, to be forwarded to the master. +# +# forward-dnsupdate=yes + +################################# +# guardian Run within a guardian process +# +guardian=yes + +################################# +# include-dir Include *.conf files from this directory +# +# include-dir= + +################################# +# launch Which backends to launch and order to query them in +# +# launch= +launch=bind + +################################# +# load-modules Load this module - supply absolute or relative path +# +# load-modules= + +################################# +# local-address Local IP addresses to which we bind +# +local-address=,127.0.0.1 + +################################# +# local-address-nonexist-fail Fail to start if one or more of the local-address's do not exist on this server +# +# local-address-nonexist-fail=yes + +################################# +# local-ipv6 Local IP address to which we bind +# +# local-ipv6= + +################################# +# local-ipv6-nonexist-fail Fail to start if one or more of the local-ipv6 addresses do not exist on this server +# +# local-ipv6-nonexist-fail=yes + +################################# +# local-port The port on which we listen +# +# local-port=53 + +################################# +# log-dns-details If PDNS should log DNS non-erroneous details +# +# log-dns-details=no + +################################# +# log-dns-queries If PDNS should log all incoming DNS queries +# +# log-dns-queries=no + +################################# +# logging-facility Log under a specific facility +# +# logging-facility= + +################################# +# loglevel Amount of logging. Higher is more. Do not set below 3 +# +# loglevel=4 + +################################# +# lua-prequery-script Lua script with prequery handler +# +# lua-prequery-script= + +################################# +# master Act as a master +# +master=yes + +################################# +# max-cache-entries Maximum number of cache entries +# +# max-cache-entries=1000000 + +################################# +# max-ent-entries Maximum number of empty non-terminals in a zone +# +# max-ent-entries=100000 + +################################# +# max-nsec3-iterations Limit the number of NSEC3 hash iterations +# +# max-nsec3-iterations=500 + +################################# +# max-queue-length Maximum queuelength before considering situation lost +# +# max-queue-length=5000 + +################################# +# max-signature-cache-entries Maximum number of signatures cache entries +# +# max-signature-cache-entries= + +################################# +# max-tcp-connections Maximum number of TCP connections +# +# max-tcp-connections=10 + +################################# +# module-dir Default directory for modules +# +# module-dir=/usr/lib/TRIPLET/pdns + +################################# +# negquery-cache-ttl Seconds to store negative query results in the QueryCache +# +# negquery-cache-ttl=60 + +################################# +# no-shuffle Set this to prevent random shuffling of answers - for regression testing +# +# no-shuffle=off + +################################# +# only-notify Only send AXFR NOTIFY to these IP addresses or netmasks +# +# only-notify=0.0.0.0/0,::/0 + +################################# +# out-of-zone-additional-processing Do out of zone additional processing +# +# out-of-zone-additional-processing=yes + +################################# +# overload-queue-length Maximum queuelength moving to packetcache only +# +# overload-queue-length=0 + +################################# +# pipebackend-abi-version Version of the pipe backend ABI +# +# pipebackend-abi-version=1 + +################################# +# prevent-self-notification Don't send notifications to what we think is ourself +# +# prevent-self-notification=yes + +################################# +# query-cache-ttl Seconds to store query results in the QueryCache +# +# query-cache-ttl=20 + +################################# +# query-local-address Source IP address for sending queries +# +# query-local-address=0.0.0.0 + +################################# +# query-local-address6 Source IPv6 address for sending queries +# +# query-local-address6=:: + +################################# +# query-logging Hint backends that queries should be logged +# +# query-logging=no + +################################# +# queue-limit Maximum number of milliseconds to queue a query +# +# queue-limit=1500 + +################################# +# receiver-threads Default number of receiver threads to start +# +# receiver-threads=1 + +################################# +# recursive-cache-ttl Seconds to store packets for recursive queries in the PacketCache +# +# recursive-cache-ttl=10 + +################################# +# recursor If recursion is desired, IP address of a recursing nameserver +# +# recursor=no + +################################# +# retrieval-threads Number of AXFR-retrieval threads for slave operation +# +# retrieval-threads=2 + +################################# +# reuseport Enable higher performance on compliant kernels by using SO_REUSEPORT allowing each receiver thread to open its own socket +# +# reuseport=no + +################################# +# security-poll-suffix Domain name from which to query security update notifications +# +# security-poll-suffix=secpoll.powerdns.com. + +################################# +# send-root-referral Send out old-fashioned root-referral instead of ServFail in case of no authority +# +# send-root-referral=no + +################################# +# server-id Returned when queried for 'server.id' TXT or NSID, defaults to hostname - disabled or custom +# +# server-id= + +################################# +# setgid If set, change group id to this gid for more security +# +setgid=pdns + +################################# +# setuid If set, change user id to this uid for more security +# +setuid=pdns + +################################# +# signing-threads Default number of signer threads to start +# +# signing-threads=3 + +################################# +# slave Act as a slave +# +# slave=no + +################################# +# slave-cycle-interval Reschedule failed SOA serial checks once every .. seconds +# +# slave-cycle-interval=60 + +################################# +# slave-renotify If we should send out notifications for slaved updates +# +# slave-renotify=no + +################################# +# soa-expire-default Default SOA expire +# +# soa-expire-default=604800 + +################################# +# soa-minimum-ttl Default SOA minimum ttl +# +# soa-minimum-ttl=3600 + +################################# +# soa-refresh-default Default SOA refresh +# +# soa-refresh-default=10800 + +################################# +# soa-retry-default Default SOA retry +# +# soa-retry-default=3600 + +################################# +# socket-dir Where the controlsocket will live +# +# socket-dir=/var/run + +################################# +# tcp-control-address If set, PowerDNS can be controlled over TCP on this address +# +# tcp-control-address= + +################################# +# tcp-control-port If set, PowerDNS can be controlled over TCP on this address +# +# tcp-control-port=53000 + +################################# +# tcp-control-range If set, remote control of PowerDNS is possible over these networks only +# +# tcp-control-range=127.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, ::1/128, fe80::/10 + +################################# +# tcp-control-secret If set, PowerDNS can be controlled over TCP after passing this secret +# +# tcp-control-secret= + +################################# +# traceback-handler Enable the traceback handler (Linux only) +# +# traceback-handler=yes + +################################# +# trusted-notification-proxy IP address of incoming notification proxy +# +# trusted-notification-proxy= + +################################# +# udp-truncation-threshold Maximum UDP response size before we truncate +# +# udp-truncation-threshold=1680 + +################################# +# version-string PowerDNS version in packets - full, anonymous, powerdns or custom +# + +version-string=powerdns +################################# +# webserver Start a webserver for monitoring +# +# webserver=no + +################################# +# webserver-address IP Address of webserver to listen on +# +# webserver-address=127.0.0.1 + +################################# +# webserver-allow-from Webserver access is only allowed from these subnets +# +# webserver-allow-from=0.0.0.0/0,::/0 + +################################# +# webserver-password Password required for accessing the webserver +# +# webserver-password= + +################################# +# webserver-port Port of webserver to listen on +# +# webserver-port=8081 + +################################# +# webserver-print-arguments If the webserver should print arguments +# +# webserver-print-arguments=no + +# include froxlor-bind-specific config +include-dir=/etc/powerdns/froxlor/ +]]> + + + + + named.conf + +# How often to check for zone changes. See 'Operation' section. +bind-check-interval=180 + +# Uncomment to enable Huffman compression on zone data. +# Currently saves around 20% of memory actually used, but slows down operation. +# bind-enable-huffman +]]> + + + + + + + + + + + + {{settings.system.vmail_gid}} + + + + + {{settings.system.vmail_uid}} + + + + + + + + + + + + + + + + + +password = +dbname = +hosts = +query = SELECT destination FROM mail_virtual WHERE email = '%s' AND trim(destination) <> '' +]]> + + + + +password = +dbname = +hosts = +query = SELECT domain FROM panel_domains WHERE domain = '%s' AND isemaildomain = '1' +]]> + + + + +password = +dbname = +expansion_limit = 1 +hosts = +query = SELECT CONCAT(homedir,maildir) FROM mail_users WHERE email = '%s' +]]> + + + + +password = +dbname = +hosts = +query = SELECT DISTINCT username FROM mail_users WHERE email in ((SELECT mail_virtual.email_full FROM mail_virtual WHERE mail_virtual.email = '%s' UNION SELECT mail_virtual.destination FROM mail_virtual WHERE mail_virtual.email = '%s')); +]]> + + + + +password = +dbname = +expansion_limit = 1 +hosts = +query = SELECT uid FROM mail_users WHERE email = '%s' +]]> + + + + +password = +dbname = +expansion_limit = 1 +hosts = +query = SELECT gid FROM mail_users WHERE email = '%s' +]]> + + + + +]]> + + + + + + + + + + + //service[@type='smtp']/general/commands[@index=1] + + //service[@type='smtp']/general/installs[@index=1] + + //service[@type='smtp']/general/commands[@index=2] + + + + +# SENDING MAIL +# +# The myorigin parameter specifies the domain that locally-posted +# mail appears to come from. The default is to append $myhostname, +# which is fine for small sites. If you run a domain with multiple +# machines, you should (1) change this to $mydomain and (2) set up +# a domain-wide alias database that aliases each user to +# user@that.users.mailhost. +# +# For the sake of consistency between sender and recipient addresses, +# myorigin also specifies the default domain name that is appended +# to recipient addresses that have no @domain part. +# +# Debian GNU/Linux specific: Specifying a file name will cause the +# first line of that file to be used as the name. The Debian default +# is /etc/mailname. +# +#myorigin = /etc/mailname +#myorigin = $myhostname +#myorigin = $mydomain + +# RECEIVING MAIL + +# The inet_interfaces parameter specifies the network interface +# addresses that this mail system receives mail on. By default, +# the software claims all active interfaces on the machine. The +# parameter also controls delivery of mail to user@[ip.address]. +# +# See also the proxy_interfaces parameter, for network addresses that +# are forwarded to us via a proxy or network address translator. +# +# Note: you need to stop/start Postfix when this parameter changes. +# +inet_interfaces = all +#inet_interfaces = $myhostname +#inet_interfaces = $myhostname, localhost + +# The proxy_interfaces parameter specifies the network interface +# addresses that this mail system receives mail on by way of a +# proxy or network address translation unit. This setting extends +# the address list specified with the inet_interfaces parameter. +# +# You must specify your proxy/NAT addresses when your system is a +# backup MX host for other domains, otherwise mail delivery loops +# will happen when the primary MX host is down. +# +#proxy_interfaces = +#proxy_interfaces = 1.2.3.4 + +# The mydestination parameter specifies the list of domains that this +# machine considers itself the final destination for. +# +# These domains are routed to the delivery agent specified with the +# local_transport parameter setting. By default, that is the UNIX +# compatible delivery agent that lookups all recipients in /etc/passwd +# and /etc/aliases or their equivalent. +# +# The default is $myhostname + localhost.$mydomain. On a mail domain +# gateway, you should also include $mydomain. +# +# Do not specify the names of virtual domains - those domains are +# specified elsewhere (see VIRTUAL_README). +# +# Do not specify the names of domains that this machine is backup MX +# host for. Specify those names via the relay_domains settings for +# the SMTP server, or use permit_mx_backup if you are lazy (see +# STANDARD_CONFIGURATION_README). +# +# The local machine is always the final destination for mail addressed +# to user@[the.net.work.address] of an interface that the mail system +# receives mail on (see the inet_interfaces parameter). +# +# Specify a list of host or domain names, /file/name or type:table +# patterns, separated by commas and/or whitespace. A /file/name +# pattern is replaced by its contents; a type:table is matched when +# a name matches a lookup key (the right-hand side is ignored). +# Continue long lines by starting the next line with whitespace. +# +# See also below, section "REJECTING MAIL FOR UNKNOWN LOCAL USERS". +# +#mydestination = $myhostname, localhost.$mydomain, localhost +mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain +#mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain, +# mail.$mydomain, www.$mydomain, ftp.$mydomain + +# REJECTING MAIL FOR UNKNOWN LOCAL USERS +# +# The local_recipient_maps parameter specifies optional lookup tables +# with all names or addresses of users that are local with respect +# to $mydestination, $inet_interfaces or $proxy_interfaces. +# +# If this parameter is defined, then the SMTP server will reject +# mail for unknown local users. This parameter is defined by default. +# +# To turn off local recipient checking in the SMTP server, specify +# local_recipient_maps = (i.e. empty). +# +# The default setting assumes that you use the default Postfix local +# delivery agent for local delivery. You need to update the +# local_recipient_maps setting if: +# +# - You define $mydestination domain recipients in files other than +# /etc/passwd, /etc/aliases, or the $virtual_alias_maps files. +# For example, you define $mydestination domain recipients in +# the $virtual_mailbox_maps files. +# +# - You redefine the local delivery agent in master.cf. +# +# - You redefine the "local_transport" setting in main.cf. +# +# - You use the "luser_relay", "mailbox_transport", or "fallback_transport" +# feature of the Postfix local delivery agent (see local(8)). +# +# Details are described in the LOCAL_RECIPIENT_README file. +# +# Beware: if the Postfix SMTP server runs chrooted, you probably have +# to access the passwd file via the proxymap service, in order to +# overcome chroot restrictions. The alternative, having a copy of +# the system passwd file in the chroot jail is just not practical. +# +# The right-hand side of the lookup tables is conveniently ignored. +# In the left-hand side, specify a bare username, an @domain.tld +# wild-card, or specify a user@domain.tld address. +# +#local_recipient_maps = unix:passwd.byname $alias_maps +#local_recipient_maps = proxy:unix:passwd.byname $alias_maps +#local_recipient_maps = + +# The unknown_local_recipient_reject_code specifies the SMTP server +# response code when a recipient domain matches $mydestination or +# ${proxy,inet}_interfaces, while $local_recipient_maps is non-empty +# and the recipient address or address local-part is not found. +# +# The default setting is 550 (reject mail) but it is safer to start +# with 450 (try again later) until you are certain that your +# local_recipient_maps settings are OK. +# +unknown_local_recipient_reject_code = 550 + +# TRUST AND RELAY CONTROL + +# The mynetworks parameter specifies the list of "trusted" SMTP +# clients that have more privileges than "strangers". +# +# In particular, "trusted" SMTP clients are allowed to relay mail +# through Postfix. See the smtpd_recipient_restrictions parameter +# in postconf(5). +# +# You can specify the list of "trusted" network addresses by hand +# or you can let Postfix do it for you (which is the default). +# +# By default (mynetworks_style = subnet), Postfix "trusts" SMTP +# clients in the same IP subnetworks as the local machine. +# On Linux, this does works correctly only with interfaces specified +# with the "ifconfig" command. +# +# Specify "mynetworks_style = class" when Postfix should "trust" SMTP +# clients in the same IP class A/B/C networks as the local machine. +# Don't do this with a dialup site - it would cause Postfix to "trust" +# your entire provider's network. Instead, specify an explicit +# mynetworks list by hand, as described below. +# +# Specify "mynetworks_style = host" when Postfix should "trust" +# only the local machine. +# +#mynetworks_style = class +#mynetworks_style = subnet +#mynetworks_style = host + +# Alternatively, you can specify the mynetworks list by hand, in +# which case Postfix ignores the mynetworks_style setting. +# +# Specify an explicit list of network/netmask patterns, where the +# mask specifies the number of bits in the network part of a host +# address. +# +# You can also specify the absolute pathname of a pattern file instead +# of listing the patterns here. Specify type:table for table-based lookups +# (the value on the table right-hand side is not used). +# +#mynetworks = 168.100.189.0/28, 127.0.0.0/8 +#mynetworks = $config_directory/mynetworks +#mynetworks = hash:/etc/postfix/network_table +mynetworks = 127.0.0.0/8 + +# The relay_domains parameter restricts what destinations this system will +# relay mail to. See the smtpd_recipient_restrictions description in +# postconf(5) for detailed information. +# +# By default, Postfix relays mail +# - from "trusted" clients (IP address matches $mynetworks) to any destination, +# - from "untrusted" clients to destinations that match $relay_domains or +# subdomains thereof, except addresses with sender-specified routing. +# The default relay_domains value is $mydestination. +# +# In addition to the above, the Postfix SMTP server by default accepts mail +# that Postfix is final destination for: +# - destinations that match $inet_interfaces or $proxy_interfaces, +# - destinations that match $mydestination +# - destinations that match $virtual_alias_domains, +# - destinations that match $virtual_mailbox_domains. +# These destinations do not need to be listed in $relay_domains. +# +# Specify a list of hosts or domains, /file/name patterns or type:name +# lookup tables, separated by commas and/or whitespace. Continue +# long lines by starting the next line with whitespace. A file name +# is replaced by its contents; a type:name table is matched when a +# (parent) domain appears as lookup key. +# +# NOTE: Postfix will not automatically forward mail for domains that +# list this system as their primary or backup MX host. See the +# permit_mx_backup restriction description in postconf(5). +# +#relay_domains = $mydestination + +# INTERNET OR INTRANET + +# The relayhost parameter specifies the default host to send mail to +# when no entry is matched in the optional transport(5) table. When +# no relayhost is given, mail is routed directly to the destination. +# +# On an intranet, specify the organizational domain name. If your +# internal DNS uses no MX records, specify the name of the intranet +# gateway host instead. +# +# In the case of SMTP, specify a domain, host, host:port, [host]:port, +# [address] or [address]:port; the form [host] turns off MX lookups. +# +# If you're connected via UUCP, see also the default_transport parameter. +# +#relayhost = $mydomain +#relayhost = [gateway.my.domain] +#relayhost = [mailserver.isp.tld] +#relayhost = uucphost +#relayhost = [an.ip.add.ress] + +# REJECTING UNKNOWN RELAY USERS +# +# The relay_recipient_maps parameter specifies optional lookup tables +# with all addresses in the domains that match $relay_domains. +# +# If this parameter is defined, then the SMTP server will reject +# mail for unknown relay users. This feature is off by default. +# +# The right-hand side of the lookup tables is conveniently ignored. +# In the left-hand side, specify an @domain.tld wild-card, or specify +# a user@domain.tld address. +# +#relay_recipient_maps = hash:/etc/postfix/relay_recipients + +# INPUT RATE CONTROL +# +# The in_flow_delay configuration parameter implements mail input +# flow control. This feature is turned on by default, although it +# still needs further development (it's disabled on SCO UNIX due +# to an SCO bug). +# +# A Postfix process will pause for $in_flow_delay seconds before +# accepting a new message, when the message arrival rate exceeds the +# message delivery rate. With the default 100 SMTP server process +# limit, this limits the mail inflow to 100 messages a second more +# than the number of messages delivered per second. +# +# Specify 0 to disable the feature. Valid delays are 0..10. +# +#in_flow_delay = 1s + +# ADDRESS REWRITING +# +# The ADDRESS_REWRITING_README document gives information about +# address masquerading or other forms of address rewriting including +# username->Firstname.Lastname mapping. + +# ADDRESS REDIRECTION (VIRTUAL DOMAIN) +# +# The VIRTUAL_README document gives information about the many forms +# of domain hosting that Postfix supports. + +# "USER HAS MOVED" BOUNCE MESSAGES +# +# See the discussion in the ADDRESS_REWRITING_README document. + +# TRANSPORT MAP +# +# See the discussion in the ADDRESS_REWRITING_README document. + +# ALIAS DATABASE +# +# The alias_maps parameter specifies the list of alias databases used +# by the local delivery agent. The default list is system dependent. +# +# On systems with NIS, the default is to search the local alias +# database, then the NIS alias database. See aliases(5) for syntax +# details. +# +# If you change the alias database, run "postalias /etc/aliases" (or +# wherever your system stores the mail alias file), or simply run +# "newaliases" to build the necessary DBM or DB file. +# +# It will take a minute or so before changes become visible. Use +# "postfix reload" to eliminate the delay. +# +#alias_maps = dbm:/etc/aliases +#alias_maps = hash:/etc/aliases +#alias_maps = hash:/etc/aliases, nis:mail.aliases +#alias_maps = netinfo:/aliases + +# The alias_database parameter specifies the alias database(s) that +# are built with "newaliases" or "sendmail -bi". This is a separate +# configuration parameter, because alias_maps (see above) may specify +# tables that are not necessarily all under control by Postfix. +# +#alias_database = dbm:/etc/aliases +#alias_database = dbm:/etc/mail/aliases +#alias_database = hash:/etc/aliases +#alias_database = hash:/etc/aliases, hash:/opt/majordomo/aliases + +# ADDRESS EXTENSIONS (e.g., user+foo) +# +# The recipient_delimiter parameter specifies the separator between +# user names and address extensions (user+foo). See canonical(5), +# local(8), relocated(5) and virtual(5) for the effects this has on +# aliases, canonical, virtual, relocated and .forward file lookups. +# Basically, the software tries user+foo and .forward+foo before +# trying user and .forward. +# +#recipient_delimiter = + + +# DELIVERY TO MAILBOX +# +# The home_mailbox parameter specifies the optional pathname of a +# mailbox file relative to a user's home directory. The default +# mailbox file is /var/spool/mail/user or /var/mail/user. Specify +# "Maildir/" for qmail-style delivery (the / is required). +# +#home_mailbox = Mailbox +#home_mailbox = Maildir/ + +# The mail_spool_directory parameter specifies the directory where +# UNIX-style mailboxes are kept. The default setting depends on the +# system type. +# +#mail_spool_directory = /var/mail +#mail_spool_directory = /var/spool/mail + +# The mailbox_command parameter specifies the optional external +# command to use instead of mailbox delivery. The command is run as +# the recipient with proper HOME, SHELL and LOGNAME environment settings. +# Exception: delivery for root is done as $default_user. +# +# Other environment variables of interest: USER (recipient username), +# EXTENSION (address extension), DOMAIN (domain part of address), +# and LOCAL (the address localpart). +# +# Unlike other Postfix configuration parameters, the mailbox_command +# parameter is not subjected to $parameter substitutions. This is to +# make it easier to specify shell syntax (see example below). +# +# Avoid shell meta characters because they will force Postfix to run +# an expensive shell process. Procmail alone is expensive enough. +# +# IF YOU USE THIS TO DELIVER MAIL SYSTEM-WIDE, YOU MUST SET UP AN +# ALIAS THAT FORWARDS MAIL FOR ROOT TO A REAL USER. +# +mailbox_command = /usr/lib/dovecot/deliver +#mailbox_command = /usr/bin/procmail -a "$EXTENSION" + +# The mailbox_transport specifies the optional transport in master.cf +# to use after processing aliases and .forward files. This parameter +# has precedence over the mailbox_command, fallback_transport and +# luser_relay parameters. +# +# Specify a string of the form transport:nexthop, where transport is +# the name of a mail delivery transport defined in master.cf. The +# :nexthop part is optional. For more details see the sample transport +# configuration file. +# +# NOTE: if you use this feature for accounts not in the UNIX password +# file, then you must update the "local_recipient_maps" setting in +# the main.cf file, otherwise the SMTP server will reject mail for +# non-UNIX accounts with "User unknown in local recipient table". +# +# Cyrus IMAP over LMTP. Specify ``lmtpunix cmd="lmtpd" +# listen="/var/imap/socket/lmtp" prefork=0'' in cyrus.conf. +#mailbox_transport = lmtp:unix:/var/imap/socket/lmtp +# +# Cyrus IMAP via command line. Uncomment the "cyrus...pipe" and +# subsequent line in master.cf. +#mailbox_transport = cyrus + +# The fallback_transport specifies the optional transport in master.cf +# to use for recipients that are not found in the UNIX passwd database. +# This parameter has precedence over the luser_relay parameter. +# +# Specify a string of the form transport:nexthop, where transport is +# the name of a mail delivery transport defined in master.cf. The +# :nexthop part is optional. For more details see the sample transport +# configuration file. +# +# NOTE: if you use this feature for accounts not in the UNIX password +# file, then you must update the "local_recipient_maps" setting in +# the main.cf file, otherwise the SMTP server will reject mail for +# non-UNIX accounts with "User unknown in local recipient table". +# +#fallback_transport = lmtp:unix:/file/name +#fallback_transport = cyrus +#fallback_transport = + +# The luser_relay parameter specifies an optional destination address +# for unknown recipients. By default, mail for unknown@$mydestination, +# unknown@[$inet_interfaces] or unknown@[$proxy_interfaces] is returned +# as undeliverable. +# +# The following expansions are done on luser_relay: $user (recipient +# username), $shell (recipient shell), $home (recipient home directory), +# $recipient (full recipient address), $extension (recipient address +# extension), $domain (recipient domain), $local (entire recipient +# localpart), $recipient_delimiter. Specify ${name?value} or +# ${name:value} to expand value only when $name does (does not) exist. +# +# luser_relay works only for the default Postfix local delivery agent. +# +# NOTE: if you use this feature for accounts not in the UNIX password +# file, then you must specify "local_recipient_maps =" (i.e. empty) in +# the main.cf file, otherwise the SMTP server will reject mail for +# non-UNIX accounts with "User unknown in local recipient table". +# +#luser_relay = $user@other.host +#luser_relay = $local@other.host +#luser_relay = admin+$local + +# JUNK MAIL CONTROLS +# +# The controls listed here are only a very small subset. The file +# SMTPD_ACCESS_README provides an overview. + +# The header_checks parameter specifies an optional table with patterns +# that each logical message header is matched against, including +# headers that span multiple physical lines. +# +# By default, these patterns also apply to MIME headers and to the +# headers of attached messages. With older Postfix versions, MIME and +# attached message headers were treated as body text. +# +# For details, see "man header_checks". +# +#header_checks = regexp:/etc/postfix/header_checks + +# FAST ETRN SERVICE +# +# Postfix maintains per-destination logfiles with information about +# deferred mail, so that mail can be flushed quickly with the SMTP +# "ETRN domain.tld" command, or by executing "sendmail -qRdomain.tld". +# See the ETRN_README document for a detailed description. +# +# The fast_flush_domains parameter controls what destinations are +# eligible for this service. By default, they are all domains that +# this server is willing to relay mail to. +# +#fast_flush_domains = $relay_domains + +# SHOW SOFTWARE VERSION OR NOT +# +# The smtpd_banner parameter specifies the text that follows the 220 +# code in the SMTP server's greeting banner. Some people like to see +# the mail version advertised. By default, Postfix shows no version. +# +# You MUST specify $myhostname at the start of the text. That is an +# RFC requirement. Postfix itself does not care. +# +#smtpd_banner = $myhostname ESMTP $mail_name +#smtpd_banner = $myhostname ESMTP $mail_name ($mail_version) +smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU) + + +# PARALLEL DELIVERY TO THE SAME DESTINATION +# +# How many parallel deliveries to the same user or domain? With local +# delivery, it does not make sense to do massively parallel delivery +# to the same user, because mailbox updates must happen sequentially, +# and expensive pipelines in .forward files can cause disasters when +# too many are run at the same time. With SMTP deliveries, 10 +# simultaneous connections to the same domain could be sufficient to +# raise eyebrows. +# +# Each message delivery transport has its XXX_destination_concurrency_limit +# parameter. The default is $default_destination_concurrency_limit for +# most delivery transports. For the local delivery agent the default is 2. + +#local_destination_concurrency_limit = 2 +#default_destination_concurrency_limit = 20 + +# DEBUGGING CONTROL +# +# The debug_peer_level parameter specifies the increment in verbose +# logging level when an SMTP client or server host name or address +# matches a pattern in the debug_peer_list parameter. +# +#debug_peer_level = 2 + +# The debug_peer_list parameter specifies an optional list of domain +# or network patterns, /file/name patterns or type:name tables. When +# an SMTP client or server host name or address matches a pattern, +# increase the verbose logging level by the amount specified in the +# debug_peer_level parameter. +# +#debug_peer_list = 127.0.0.1 +#debug_peer_list = some.domain + +# The debugger_command specifies the external command that is executed +# when a Postfix daemon program is run with the -D option. +# +# Use "command .. & sleep 5" so that the debugger can attach before +# the process marches on. If you use an X-based debugger, be sure to +# set up your XAUTHORITY environment variable before starting Postfix. +# +debugger_command = + PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin + ddd $daemon_directory/$process_name $process_id & sleep 5 + +# If you can't use X, use this to capture the call stack when a +# daemon crashes. The result is in a file in the configuration +# directory, and is named after the process name and the process ID. +# +# debugger_command = +# PATH=/bin:/usr/bin:/usr/local/bin; export PATH; (echo cont; +# echo where) | gdb $daemon_directory/$process_name $process_id 2>&1 +# >$config_directory/$process_name.$process_id.log & sleep 5 +# +# Another possibility is to run gdb under a detached screen session. +# To attach to the screen sesssion, su root and run "screen -r +# " where uniquely matches one of the detached +# sessions (from "screen -list"). +# +# debugger_command = +# PATH=/bin:/usr/bin:/sbin:/usr/sbin; export PATH; screen +# -dmS $process_name gdb $daemon_directory/$process_name +# $process_id & sleep 1 + +# INSTALL-TIME CONFIGURATION INFORMATION +# +# The following parameters are used when installing a new Postfix version. +# +# sendmail_path: The full pathname of the Postfix sendmail command. +# This is the Sendmail-compatible mail posting interface. +# +sendmail_path = /usr/sbin/sendmail + +# newaliases_path: The full pathname of the Postfix newaliases command. +# This is the Sendmail-compatible command to build alias databases. +# +newaliases_path = /usr/bin/newaliases + +# mailq_path: The full pathname of the Postfix mailq command. This +# is the Sendmail-compatible mail queue listing command. +# +mailq_path = /usr/bin/mailq + +# setgid_group: The group for mail submission and queue management +# commands. This must be a group name with a numerical group ID that +# is not shared with other accounts, not even with the Postfix account. +# +setgid_group = postdrop + +# html_directory: The location of the Postfix HTML documentation. +# +html_directory = no + +# manpage_directory: The location of the Postfix on-line manual pages. +# +manpage_directory = /usr/share/man + +# sample_directory: The location of the Postfix sample configuration files. +# This parameter is obsolete as of Postfix 2.1. +# +sample_directory = /usr/share/doc/postfix + +# readme_directory: The location of the Postfix README files. +# +readme_directory = /usr/share/doc/postfix +inet_protocols = ipv4 + +append_dot_mydomain = no +biff = no +smtpd_helo_required = yes +smtpd_recipient_restrictions = permit_mynetworks, + permit_sasl_authenticated, + reject_unauth_destination, + reject_unauth_pipelining, + reject_non_fqdn_recipient +smtpd_sender_restrictions = permit_mynetworks, + reject_sender_login_mismatch, + permit_sasl_authenticated, + reject_unknown_helo_hostname, + reject_unknown_recipient_domain, + reject_unknown_sender_domain +smtpd_client_restrictions = permit_mynetworks, + permit_sasl_authenticated, + reject_unknown_client_hostname + +# Postfix 2.10 requires this option. Postfix < 2.10 ignores this. +# The option is intentionally left empty. +smtpd_relay_restrictions = + +# Maximum size of Message in bytes (50MB) +message_size_limit = 52428800 + +## SASL Auth Settings +smtpd_sasl_auth_enable = yes +smtpd_sasl_local_domain = $myhostname +broken_sasl_auth_clients = yes +## Dovecot Settings for deliver, SASL Auth and virtual transport +smtpd_sasl_type = dovecot +virtual_transport = dovecot +dovecot_destination_recipient_limit = 1 +smtpd_sasl_path = private/auth + +# Virtual delivery settings +virtual_mailbox_base = / +virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual_mailbox_maps.cf +virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual_mailbox_domains.cf +virtual_alias_maps = mysql:/etc/postfix/mysql-virtual_alias_maps.cf +smtpd_sender_login_maps = mysql:/etc/postfix/mysql-virtual_sender_permissions.cf +virtual_uid_maps = static: +virtual_gid_maps = static: + +# Local delivery settings +local_transport = local +alias_maps = $alias_database + +# Default Mailbox size, is set to 0 which means unlimited! +mailbox_size_limit = 0 +virtual_mailbox_limit = 0 + +### TLS settings +### +## TLS for outgoing mails from the server to another server +#smtp_tls_security_level = may +#smtp_tls_note_starttls_offer = yes +## TLS for incoming connections (clients or other mail servers) +#smtpd_tls_security_level = may +#smtpd_tls_cert_file = /etc/ssl/server/.pem +#smtpd_tls_key_file = $smtpd_tls_cert_file +#smtpd_tls_CAfile = /etc/ssl/certs/ca-certificates.crt +#smtpd_tls_loglevel = 1 +#smtpd_tls_received_header = yes +]]> + + + //service[@type='smtp']/general/files[@index=0] + + + + + //service[@type='smtp']/general/commands[@index=3] + + + + + + + + + + + + + to select which instance is used (an alternative +# to -c ). The instance name is also added to Dovecot processes +# in ps output. +#instance_name = dovecot + +# Greeting message for clients. +#login_greeting = Dovecot ready. + +# Space separated list of trusted network ranges. Connections from these +# IPs are allowed to override their IP addresses and ports (for logging and +# for authentication checks). disable_plaintext_auth is also ignored for +# these networks. Typically you'd specify your IMAP proxy servers here. +#login_trusted_networks = + +# Space separated list of login access check sockets (e.g. tcpwrap) +#login_access_sockets = + +# With proxy_maybe=yes if proxy destination matches any of these IPs, don't do +# proxying. This isn't necessary normally, but may be useful if the destination +# IP is e.g. a load balancer's IP. +#auth_proxy_self = + +# Show more verbose process titles (in ps). Currently shows user name and +# IP address. Useful for seeing who are actually using the IMAP processes +# (eg. shared mailboxes or if same uid is used for multiple accounts). +#verbose_proctitle = no + +# Should all processes be killed when Dovecot master process shuts down. +# Setting this to "no" means that Dovecot can be upgraded without +# forcing existing client connections to close (although that could also be +# a problem if the upgrade is e.g. because of a security fix). +#shutdown_clients = yes + +# If non-zero, run mail commands via this many connections to doveadm server, +# instead of running them directly in the same process. +#doveadm_worker_count = 0 +# UNIX socket or host:port used for connecting to doveadm server +#doveadm_socket_path = doveadm-server + +# Space separated list of environment variables that are preserved on Dovecot +# startup and passed down to all of its child processes. You can also give +# key=value pairs to always set specific settings. +#import_environment = TZ + +## +## Dictionary server settings +## + +# Dictionary can be used to store key=value lists. This is used by several +# plugins. The dictionary can be accessed either directly or though a +# dictionary server. The following dict block maps dictionary names to URIs +# when the server is used. These can then be referenced using URIs in format +# "proxy::". + +dict { + #quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext + #expire = sqlite:/etc/dovecot/dovecot-dict-sql.conf.ext +} + +# Most of the actual configuration gets included below. The filenames are +# first sorted by their ASCII value and parsed in that order. The 00-prefixes +# in filenames are intended to make it easier to understand the ordering. +!include conf.d/*.conf + +# A config file can also tried to be included without giving an error if +# it's not found: +!include_try local.conf +]]> + + + + dbname= user= password= + +# Default password scheme. +# +# List of supported schemes is in +# http://wiki2.dovecot.org/Authentication/PasswordSchemes +# +default_pass_scheme = CRYPT + +# passdb query to retrieve the password. It can return fields: +# password - The user's password. This field must be returned. +# user - user@domain from the database. Needed with case-insensitive lookups. +# username and domain - An alternative way to represent the "user" field. +# +# The "user" field is often necessary with case-insensitive lookups to avoid +# e.g. "name" and "nAme" logins creating two different mail directories. If +# your user and domain names are in separate fields, you can return "username" +# and "domain" fields instead of "user". +# +# The query can also return other fields which have a special meaning, see +# http://wiki2.dovecot.org/PasswordDatabase/ExtraFields +# +# Commonly used available substitutions (see http://wiki2.dovecot.org/Variables +# for full list): +# %u = entire user@domain +# %n = user part of user@domain +# %d = domain part of user@domain +# +# Note that these can be used only as input to SQL query. If the query outputs +# any of these substitutions, they're not touched. Otherwise it would be +# difficult to have eg. usernames containing '%' characters. +# +# Example: +# password_query = SELECT userid AS user, pw AS password \ +# FROM users WHERE userid = '%u' AND active = 'Y' +# +#password_query = \ +# SELECT username, domain, password \ +# FROM users WHERE username = '%n' AND domain = '%d' + +# userdb query to retrieve the user information. It can return fields: +# uid - System UID (overrides mail_uid setting) +# gid - System GID (overrides mail_gid setting) +# home - Home directory +# mail - Mail location (overrides mail_location setting) +# +# None of these are strictly required. If you use a single UID and GID, and +# home or mail directory fits to a template string, you could use userdb static +# instead. For a list of all fields that can be returned, see +# http://wiki2.dovecot.org/UserDatabase/ExtraFields +# +# Examples: +# user_query = SELECT home, uid, gid FROM users WHERE userid = '%u' +# user_query = SELECT dir AS home, user AS uid, group AS gid FROM users where userid = '%u' +# user_query = SELECT home, 501 AS uid, 501 AS gid FROM users WHERE userid = '%u' +# +#user_query = \ +# SELECT home, uid, gid \ +# FROM users WHERE username = '%n' AND domain = '%d' +user_query = SELECT CONCAT(homedir, maildir) AS home, CONCAT('maildir:', homedir, maildir) AS mail, uid, gid, CONCAT('*:storage=', quota, 'M') as quota_rule FROM mail_users WHERE (username = '%u' OR email = '%u') + +# If you wish to avoid two SQL lookups (passdb + userdb), you can use +# userdb prefetch instead of userdb sql in dovecot.conf. In that case you'll +# also have to return userdb fields in password_query prefixed with "userdb_" +# string. For example: +#password_query = \ +# SELECT userid AS user, password, \ +# home AS userdb_home, uid AS userdb_uid, gid AS userdb_gid \ +# FROM users WHERE userid = '%u' +password_query = SELECT username AS user, password_enc AS password, CONCAT(homedir, maildir) AS userdb_home, uid AS userdb_uid, gid AS userdb_gid, CONCAT('maildir:', homedir, maildir) AS userdb_mail, CONCAT('*:storage=', quota, 'M') as userdb_quota_rule FROM mail_users WHERE (username = '%u' OR email = '%u') AND ((imap = 1 AND '%Ls' = 'imap') OR (pop3 = 1 AND '%Ls' = 'pop3') OR '%Ls' = 'smtp' OR '%Ls' = 'sieve') + +# Query to get a list of all usernames. +#iterate_query = SELECT username AS user FROM users +]]> + + + + to characters. For example "#@/@" means +# that '#' and '/' characters are translated to '@'. +#auth_username_translation = + +# Username formatting before it's looked up from databases. You can use +# the standard variables here, eg. %Lu would lowercase the username, %n would +# drop away the domain if it was given, or "%n-AT-%d" would change the '@' into +# "-AT-". This translation is done after auth_username_translation changes. +#auth_username_format = %Lu + +# If you want to allow master users to log in by specifying the master +# username within the normal username string (ie. not using SASL mechanism's +# support for it), you can specify the separator character here. The format +# is then . UW-IMAP uses "*" as the +# separator, so that could be a good choice. +#auth_master_user_separator = + +# Username to use for users logging in with ANONYMOUS SASL mechanism +#auth_anonymous_username = anonymous + +# Maximum number of dovecot-auth worker processes. They're used to execute +# blocking passdb and userdb queries (eg. MySQL and PAM). They're +# automatically created and destroyed as needed. +#auth_worker_max_count = 30 + +# Host name to use in GSSAPI principal names. The default is to use the +# name returned by gethostname(). Use "$ALL" (with quotes) to allow all keytab +# entries. +#auth_gssapi_hostname = + +# Kerberos keytab to use for the GSSAPI mechanism. Will use the system +# default (usually /etc/krb5.keytab) if not specified. You may need to change +# the auth service to run as root to be able to read this file. +#auth_krb5_keytab = + +# Do NTLM and GSS-SPNEGO authentication using Samba's winbind daemon and +# ntlm_auth helper. +#auth_use_winbind = no + +# Path for Samba's ntlm_auth helper binary. +#auth_winbind_helper_path = /usr/bin/ntlm_auth + +# Time to delay before replying to failed authentications. +#auth_failure_delay = 2 secs + +# Require a valid SSL client certificate or the authentication fails. +#auth_ssl_require_client_cert = no + +# Take the username from client's SSL certificate, using +# X509_NAME_get_text_by_NID() which returns the subject's DN's +# CommonName. +#auth_ssl_username_from_cert = no + +# Space separated list of wanted authentication mechanisms: +# plain login digest-md5 cram-md5 ntlm rpa apop anonymous gssapi otp skey +# gss-spnego +# NOTE: See also disable_plaintext_auth setting. +auth_mechanisms = plain login + +## +## Password and user databases +## + +# +# Password database is used to verify user's password (and nothing more). +# You can have multiple passdbs and userdbs. This is useful if you want to +# allow both system users (/etc/passwd) and virtual users to login without +# duplicating the system users into virtual database. +# +# +# +# User database specifies where mails are located and what user/group IDs +# own them. For single-UID configuration use "static" userdb. +# +# + +#!include auth-deny.conf.ext +#!include auth-master.conf.ext + +#!include auth-system.conf.ext +!include auth-sql.conf.ext +#!include auth-ldap.conf.ext +#!include auth-passwdfile.conf.ext +#!include auth-checkpassword.conf.ext +#!include auth-vpopmail.conf.ext +#!include auth-static.conf.ext +]]> + + + + +# +mail_location = mbox:~/mail:INBOX=/var/mail/%u + +# If you need to set multiple mailbox locations or want to change default +# namespace settings, you can do it by defining namespace sections. +# +# You can have private, shared and public namespaces. Private namespaces +# are for user's personal mails. Shared namespaces are for accessing other +# users' mailboxes that have been shared. Public namespaces are for shared +# mailboxes that are managed by sysadmin. If you create any shared or public +# namespaces you'll typically want to enable ACL plugin also, otherwise all +# users can access all the shared mailboxes, assuming they have permissions +# on filesystem level to do so. +namespace inbox { + # Namespace type: private, shared or public + #type = private + + # Hierarchy separator to use. You should use the same separator for all + # namespaces or some clients get confused. '/' is usually a good one. + # The default however depends on the underlying mail storage format. + #separator = + + # Prefix required to access this namespace. This needs to be different for + # all namespaces. For example "Public/". + #prefix = + + # Physical location of the mailbox. This is in same format as + # mail_location, which is also the default for it. + #location = + + # There can be only one INBOX, and this setting defines which namespace + # has it. + inbox = yes + + # If namespace is hidden, it's not advertised to clients via NAMESPACE + # extension. You'll most likely also want to set list=no. This is mostly + # useful when converting from another server with different namespaces which + # you want to deprecate but still keep working. For example you can create + # hidden namespaces with prefixes "~/mail/", "~%u/mail/" and "mail/". + #hidden = no + + # Show the mailboxes under this namespace with LIST command. This makes the + # namespace visible for clients that don't support NAMESPACE extension. + # "children" value lists child mailboxes, but hides the namespace prefix. + #list = yes + + # Namespace handles its own subscriptions. If set to "no", the parent + # namespace handles them (empty prefix should always have this as "yes") + #subscriptions = yes +} + +# Example shared namespace configuration +#namespace { + #type = shared + #separator = / + + # Mailboxes are visible under "shared/user@domain/" + # %%n, %%d and %%u are expanded to the destination user. + #prefix = shared/%%u/ + + # Mail location for other users' mailboxes. Note that %variables and ~/ + # expands to the logged in user's data. %%n, %%d, %%u and %%h expand to the + # destination user's data. + #location = maildir:%%h/Maildir:INDEX=~/Maildir/shared/%%u + + # Use the default namespace for saving subscriptions. + #subscriptions = no + + # List the shared/ namespace only if there are visible shared mailboxes. + #list = children +#} +# Should shared INBOX be visible as "shared/user" or "shared/user/INBOX"? +#mail_shared_explicit_inbox = no + +# System user and group used to access mails. If you use multiple, userdb +# can override these by returning uid or gid fields. You can use either numbers +# or names. +#mail_uid = +#mail_gid = + +# Group to enable temporarily for privileged operations. Currently this is +# used only with INBOX when either its initial creation or dotlocking fails. +# Typically this is set to "mail" to give access to /var/mail. +#mail_privileged_group = + +# Grant access to these supplementary groups for mail processes. Typically +# these are used to set up access to shared mailboxes. Note that it may be +# dangerous to set these if users can create symlinks (e.g. if "mail" group is +# set here, ln -s /var/mail ~/mail/var could allow a user to delete others' +# mailboxes, or ln -s /secret/shared/box ~/mail/mybox would allow reading it). +mail_access_groups = vmail + +# Allow full filesystem access to clients. There's no access checks other than +# what the operating system does for the active UID/GID. It works with both +# maildir and mboxes, allowing you to prefix mailboxes names with eg. /path/ +# or ~user/. +#mail_full_filesystem_access = no + +# Dictionary for key=value mailbox attributes. Currently used by URLAUTH, but +# soon intended to be used by METADATA as well. +#mail_attribute_dict = + +## +## Mail processes +## + +# Don't use mmap() at all. This is required if you store indexes to shared +# filesystems (NFS or clustered filesystem). +#mmap_disable = no + +# Rely on O_EXCL to work when creating dotlock files. NFS supports O_EXCL +# since version 3, so this should be safe to use nowadays by default. +#dotlock_use_excl = yes + +# When to use fsync() or fdatasync() calls: +# optimized (default): Whenever necessary to avoid losing important data +# always: Useful with e.g. NFS when write()s are delayed +# never: Never use it (best performance, but crashes can lose data) +#mail_fsync = optimized + +# Locking method for index files. Alternatives are fcntl, flock and dotlock. +# Dotlocking uses some tricks which may create more disk I/O than other locking +# methods. NFS users: flock doesn't work, remember to change mmap_disable. +#lock_method = fcntl + +# Directory in which LDA/LMTP temporarily stores incoming mails >128 kB. +#mail_temp_dir = /tmp + +# Valid UID range for users, defaults to 500 and above. This is mostly +# to make sure that users can't log in as daemons or other system users. +# Note that denying root logins is hardcoded to dovecot binary and can't +# be done even if first_valid_uid is set to 0. +#first_valid_uid = 500 +#last_valid_uid = 0 + +# Valid GID range for users, defaults to non-root/wheel. Users having +# non-valid GID as primary group ID aren't allowed to log in. If user +# belongs to supplementary groups with non-valid GIDs, those groups are +# not set. +#first_valid_gid = 1 +#last_valid_gid = 0 + +# Maximum allowed length for mail keyword name. It's only forced when trying +# to create new keywords. +#mail_max_keyword_length = 50 + +# ':' separated list of directories under which chrooting is allowed for mail +# processes (ie. /var/mail will allow chrooting to /var/mail/foo/bar too). +# This setting doesn't affect login_chroot, mail_chroot or auth chroot +# settings. If this setting is empty, "/./" in home dirs are ignored. +# WARNING: Never add directories here which local users can modify, that +# may lead to root exploit. Usually this should be done only if you don't +# allow shell access for users. +#valid_chroot_dirs = + +# Default chroot directory for mail processes. This can be overridden for +# specific users in user database by giving /./ in user's home directory +# (eg. /home/./user chroots into /home). Note that usually there is no real +# need to do chrooting, Dovecot doesn't allow users to access files outside +# their mail directory anyway. If your home directories are prefixed with +# the chroot directory, append "/." to mail_chroot. +#mail_chroot = + +# UNIX socket path to master authentication server to find users. +# This is used by imap (for shared users) and lda. +#auth_socket_path = /var/run/dovecot/auth-userdb + +# Directory where to look up mail plugins. +#mail_plugin_dir = /usr/lib/dovecot/modules + +# Space separated list of plugins to load for all services. Plugins specific to +# IMAP, LDA, etc. are added to this list in their own .conf files. +#mail_plugins = + +## +## Mailbox handling optimizations +## + +# Mailbox list indexes can be used to optimize IMAP STATUS commands. They are +# also required for IMAP NOTIFY extension to be enabled. +#mailbox_list_index = no + +# The minimum number of mails in a mailbox before updates are done to cache +# file. This allows optimizing Dovecot's behavior to do less disk writes at +# the cost of more disk reads. +#mail_cache_min_mail_count = 0 + +# When IDLE command is running, mailbox is checked once in a while to see if +# there are any new mails or other changes. This setting defines the minimum +# time to wait between those checks. Dovecot can also use dnotify, inotify and +# kqueue to find out immediately when changes occur. +#mailbox_idle_check_interval = 30 secs + +# Save mails with CR+LF instead of plain LF. This makes sending those mails +# take less CPU, especially with sendfile() syscall with Linux and FreeBSD. +# But it also creates a bit more disk I/O which may just make it slower. +# Also note that if other software reads the mboxes/maildirs, they may handle +# the extra CRs wrong and cause problems. +#mail_save_crlf = no + +# Max number of mails to keep open and prefetch to memory. This only works with +# some mailbox formats and/or operating systems. +#mail_prefetch_count = 0 + +# How often to scan for stale temporary files and delete them (0 = never). +# These should exist only after Dovecot dies in the middle of saving mails. +#mail_temp_scan_interval = 1w + +## +## Maildir-specific settings +## + +# By default LIST command returns all entries in maildir beginning with a dot. +# Enabling this option makes Dovecot return only entries which are directories. +# This is done by stat()ing each entry, so it causes more disk I/O. +# (For systems setting struct dirent->d_type, this check is free and it's +# done always regardless of this setting) +#maildir_stat_dirs = no + +# When copying a message, do it with hard links whenever possible. This makes +# the performance much better, and it's unlikely to have any side effects. +#maildir_copy_with_hardlinks = yes + +# Assume Dovecot is the only MUA accessing Maildir: Scan cur/ directory only +# when its mtime changes unexpectedly or when we can't find the mail otherwise. +#maildir_very_dirty_syncs = no + +# If enabled, Dovecot doesn't use the S= in the Maildir filenames for +# getting the mail's physical size, except when recalculating Maildir++ quota. +# This can be useful in systems where a lot of the Maildir filenames have a +# broken size. The performance hit for enabling this is very small. +#maildir_broken_filename_sizes = no + +# Always move mails from new/ directory to cur/, even when the \Recent flags +# aren't being reset. +#maildir_empty_new = no + +## +## mbox-specific settings +## + +# Which locking methods to use for locking mbox. There are four available: +# dotlock: Create .lock file. This is the oldest and most NFS-safe +# solution. If you want to use /var/mail/ like directory, the users +# will need write access to that directory. +# dotlock_try: Same as dotlock, but if it fails because of permissions or +# because there isn't enough disk space, just skip it. +# fcntl : Use this if possible. Works with NFS too if lockd is used. +# flock : May not exist in all systems. Doesn't work with NFS. +# lockf : May not exist in all systems. Doesn't work with NFS. +# +# You can use multiple locking methods; if you do the order they're declared +# in is important to avoid deadlocks if other MTAs/MUAs are using multiple +# locking methods as well. Some operating systems don't allow using some of +# them simultaneously. +# +# The Debian value for mbox_write_locks differs from upstream Dovecot. It is +# changed to be compliant with Debian Policy (section 11.6) for NFS safety. +# Dovecot: mbox_write_locks = dotlock fcntl +# Debian: mbox_write_locks = fcntl dotlock +# +#mbox_read_locks = fcntl +#mbox_write_locks = fcntl dotlock + +# Maximum time to wait for lock (all of them) before aborting. +#mbox_lock_timeout = 5 mins + +# If dotlock exists but the mailbox isn't modified in any way, override the +# lock file after this much time. +#mbox_dotlock_change_timeout = 2 mins + +# When mbox changes unexpectedly we have to fully read it to find out what +# changed. If the mbox is large this can take a long time. Since the change +# is usually just a newly appended mail, it'd be faster to simply read the +# new mails. If this setting is enabled, Dovecot does this but still safely +# fallbacks to re-reading the whole mbox file whenever something in mbox isn't +# how it's expected to be. The only real downside to this setting is that if +# some other MUA changes message flags, Dovecot doesn't notice it immediately. +# Note that a full sync is done with SELECT, EXAMINE, EXPUNGE and CHECK +# commands. +#mbox_dirty_syncs = yes + +# Like mbox_dirty_syncs, but don't do full syncs even with SELECT, EXAMINE, +# EXPUNGE or CHECK commands. If this is set, mbox_dirty_syncs is ignored. +#mbox_very_dirty_syncs = no + +# Delay writing mbox headers until doing a full write sync (EXPUNGE and CHECK +# commands and when closing the mailbox). This is especially useful for POP3 +# where clients often delete all mails. The downside is that our changes +# aren't immediately visible to other MUAs. +#mbox_lazy_writes = yes + +# If mbox size is smaller than this (e.g. 100k), don't write index files. +# If an index file already exists it's still read, just not updated. +#mbox_min_index_size = 0 + +# Mail header selection algorithm to use for MD5 POP3 UIDLs when +# pop3_uidl_format=%m. For backwards compatibility we use apop3d inspired +# algorithm, but it fails if the first Received: header isn't unique in all +# mails. An alternative algorithm is "all" that selects all headers. +#mbox_md5 = apop3d + +## +## mdbox-specific settings +## + +# Maximum dbox file size until it's rotated. +#mdbox_rotate_size = 2M + +# Maximum dbox file age until it's rotated. Typically in days. Day begins +# from midnight, so 1d = today, 2d = yesterday, etc. 0 = check disabled. +#mdbox_rotate_interval = 0 + +# When creating new mdbox files, immediately preallocate their size to +# mdbox_rotate_size. This setting currently works only in Linux with some +# filesystems (ext4, xfs). +#mdbox_preallocate_space = no + +## +## Mail attachments +## + +# sdbox and mdbox support saving mail attachments to external files, which +# also allows single instance storage for them. Other backends don't support +# this for now. + +# Directory root where to store mail attachments. Disabled, if empty. +#mail_attachment_dir = + +# Attachments smaller than this aren't saved externally. It's also possible to +# write a plugin to disable saving specific attachments externally. +#mail_attachment_min_size = 128k + +# Filesystem backend to use for saving attachments: +# posix : No SiS done by Dovecot (but this might help FS's own deduplication) +# sis posix : SiS with immediate byte-by-byte comparison during saving +# sis-queue posix : SiS with delayed comparison and deduplication +#mail_attachment_fs = sis posix + +# Hash format to use in attachment filenames. You can add any text and +# variables: %{md4}, %{md5}, %{sha1}, %{sha256}, %{sha512}, %{size}. +# Variables can be truncated, e.g. %{sha256:80} returns only first 80 bits +#mail_attachment_hash = %{sha1} +]]> + + + + + #service_count = 1 + + # Number of processes to always keep waiting for more connections. + #process_min_avail = 0 + + # If you set service_count=0, you probably need to grow this. + #vsz_limit = $default_vsz_limit +} + +service pop3-login { + inet_listener pop3 { + #port = 110 + } + inet_listener pop3s { + #port = 995 + #ssl = yes + } +} + +service lmtp { + unix_listener lmtp { + #mode = 0666 + } + + # Create inet listener only if you can't use the above UNIX socket + #inet_listener lmtp { + # Avoid making LMTP visible for the entire internet + #address = + #port = + #} +} + +service imap { + # Most of the memory goes to mmap()ing files. You may need to increase this + # limit if you have huge mailboxes. + #vsz_limit = $default_vsz_limit + + # Max. number of IMAP processes (connections) + #process_limit = 1024 +} + +service pop3 { + # Max. number of POP3 processes (connections) + #process_limit = 1024 +} + +service auth { + # auth_socket_path points to this userdb socket by default. It's typically + # used by dovecot-lda, doveadm, possibly imap process, etc. Users that have + # full permissions to this socket are able to get a list of all usernames and + # get the results of everyone's userdb lookups. + # + # The default 0666 mode allows anyone to connect to the socket, but the + # userdb lookups will succeed only if the userdb returns an "uid" field that + # matches the caller process's UID. Also if caller's uid or gid matches the + # socket's uid or gid the lookup succeeds. Anything else causes a failure. + # + # To give the caller full permissions to lookup all users, set the mode to + # something else than 0666 and Dovecot lets the kernel enforce the + # permissions (e.g. 0777 allows everyone full permissions). + unix_listener auth-userdb { + #mode = 0666 + #user = + #group = + } + + # Postfix smtp-auth + unix_listener /var/spool/postfix/private/auth { + mode = 0660 + user = postfix + group = postfix + } + + # Exim4 smtp-auth + unix_listener auth-client { + mode = 0660 + user = mail + # group = Debian-exim + } + + # Auth process is run as this user. + #user = $default_internal_user +} + +service auth-worker { + # Auth worker process is run as root by default, so that it can access + # /etc/shadow. If this isn't necessary, the user should be changed to + # $default_internal_user. + #user = root +} + +service dict { + # If dict proxy is used, mail processes should have access to its socket. + # For example: mode=0660, group=vmail and global mail_access_groups=vmail + unix_listener dict { + #mode = 0600 + #user = + #group = + } +} +]]> + + + + . %d expands to recipient domain. +postmaster_address = postmaster@ + +# Hostname to use in various parts of sent mails (e.g. in Message-Id) and +# in LMTP replies. Default is the system's real hostname@domain. +#hostname = + +# If user is over quota, return with temporary failure instead of +# bouncing the mail. +#quota_full_tempfail = no + +# Binary to use for sending mails. +#sendmail_path = /usr/sbin/sendmail + +# If non-empty, send mails via this SMTP host[:port] instead of sendmail. +#submission_host = + +# Subject: header to use for rejection mails. You can use the same variables +# as for rejection_reason below. +#rejection_subject = Rejected: %s + +# Human readable error message for rejection mails. You can use variables: +# %n = CRLF, %r = reason, %s = original subject, %t = recipient +#rejection_reason = Your message to <%t> was automatically rejected:%n%r + +# Delimiter character between local-part and detail in email address. +#recipient_delimiter = + + +# Header where the original recipient address (SMTP's RCPT TO: address) is taken +# from if not available elsewhere. With dovecot-lda -a parameter overrides this. +# A commonly used header for this is X-Original-To. +#lda_original_recipient_header = + +# Should saving a mail to a nonexistent mailbox automatically create it? +#lda_mailbox_autocreate = no + +# Should automatically created mailboxes be also automatically subscribed? +#lda_mailbox_autosubscribe = no + +protocol lda { + # Space separated list of plugins to load (default is global mail_plugins). + mail_plugins = $mail_plugins quota sieve +} +]]> + + + + + + + + + #service_count = 1 + + # Number of processes to always keep waiting for more connections. + #process_min_avail = 0 + + # If you set service_count=0, you probably need to grow this. + #vsz_limit = 64M +#} + +#service managesieve { + # Max. number of ManageSieve processes (connections) + #process_limit = 1024 +#} + +# Service configuration + +protocol sieve { + # Maximum ManageSieve command line length in bytes. ManageSieve usually does + # not involve overly long command lines, so this setting will not normally + # need adjustment + #managesieve_max_line_length = 65536 + + # Maximum number of ManageSieve connections allowed for a user from each IP + # address. + # NOTE: The username is compared case-sensitively. + #mail_max_userip_connections = 10 + + # Space separated list of plugins to load (none known to be useful so far). + # Do NOT try to load IMAP plugins here. + #mail_plugins = + + # MANAGESIEVE logout format string: + # %i - total number of bytes read from client + # %o - total number of bytes sent to client + #managesieve_logout_format = bytes=%i/%o + + # To fool ManageSieve clients that are focused on CMU's timesieved you can + # specify the IMPLEMENTATION capability that Dovecot reports to clients. + # For example: 'Cyrus timsieved v2.2.13' + #managesieve_implementation_string = Dovecot Pigeonhole + + # Explicitly specify the SIEVE and NOTIFY capability reported by the server + # before login. If left unassigned these will be reported dynamically + # according to what the Sieve interpreter supports by default (after login + # this may differ depending on the user). + #managesieve_sieve_capability = + #managesieve_notify_capability = + + # The maximum number of compile errors that are returned to the client upon + # script upload or script verification. + #managesieve_max_compile_errors = 5 + + # Refer to 90-sieve.conf for script quota configuration and configuration of + # Sieve execution limits. +} +]]> + + + + = 2.1.4) : %v.%u +# Dovecot v0.99.x : %v.%u +# tpop3d : %Mf +# +# Note that Outlook 2003 seems to have problems with %v.%u format which was +# Dovecot's default, so if you're building a new server it would be a good +# idea to change this. %08Xu%08Xv should be pretty fail-safe. +# +#pop3_uidl_format = %08Xu%08Xv + +# Permanently save UIDLs sent to POP3 clients, so pop3_uidl_format changes +# won't change those UIDLs. Currently this works only with Maildir. +#pop3_save_uidl = no + +# What to do about duplicate UIDLs if they exist? +# allow: Show duplicates to clients. +# rename: Append a temporary -2, -3, etc. counter after the UIDL. +#pop3_uidl_duplicates = allow + +# This option changes POP3 behavior so that it's not possible to actually +# delete mails via POP3, only hide them from future POP3 sessions. The mails +# will still be counted towards user's quota until actually deleted via IMAP. +# Use e.g. "$POP3Deleted" as the value (it will be visible as IMAP keyword). +# Make sure you can legally archive mails before enabling this setting. +#pop3_deleted_flag = + +# POP3 logout format string: +# %i - total number of bytes read from client +# %o - total number of bytes sent to client +# %t - number of TOP commands +# %p - number of bytes sent to client as a result of TOP command +# %r - number of RETR commands +# %b - number of bytes sent to client as a result of RETR command +# %d - number of deleted messages +# %m - number of messages (before deletion) +# %s - mailbox size in bytes (before deletion) +# %u - old/new UIDL hash. may help finding out if UIDLs changed unexpectedly +#pop3_logout_format = top=%t/%p, retr=%r/%b, del=%d/%m, size=%s + +# Workarounds for various client bugs: +# outlook-no-nuls: +# Outlook and Outlook Express hang if mails contain NUL characters. +# This setting replaces them with 0x80 character. +# oe-ns-eoh: +# Outlook Express and Netscape Mail breaks if end of headers-line is +# missing. This option simply sends it if it's missing. +# The list is space-separated. +#pop3_client_workarounds = + +protocol pop3 { + # Space separated list of plugins to load (default is global mail_plugins). + #mail_plugins = $mail_plugins + + # Maximum number of POP3 connections allowed for a user from each IP address. + # NOTE: The username is compared case-sensitively. + #mail_max_userip_connections = 10 +} +]]> + + + + See sieve_before fore executing scripts before the user's personal + # script. + #sieve_default = /var/lib/dovecot/sieve/default.sieve + + # Directory for :personal include scripts for the include extension. This + # is also where the ManageSieve service stores the user's scripts. + sieve_dir = ~/sieve + + # Directory for :global include scripts for the include extension. + #sieve_global_dir = + + # Path to a script file or a directory containing script files that need to be + # executed before the user's script. If the path points to a directory, all + # the Sieve scripts contained therein (with the proper .sieve extension) are + # executed. The order of execution within a directory is determined by the + # file names, using a normal 8bit per-character comparison. Multiple script + # file or directory paths can be specified by appending an increasing number. + #sieve_before = + #sieve_before2 = + #sieve_before3 = (etc...) + + # Identical to sieve_before, only the specified scripts are executed after the + # user's script (only when keep is still in effect!). Multiple script file or + # directory paths can be specified by appending an increasing number. + #sieve_after = + #sieve_after2 = + #sieve_after2 = (etc...) + + # Which Sieve language extensions are available to users. By default, all + # supported extensions are available, except for deprecated extensions or + # those that are still under development. Some system administrators may want + # to disable certain Sieve extensions or enable those that are not available + # by default. This setting can use '+' and '-' to specify differences relative + # to the default. For example `sieve_extensions = +imapflags' will enable the + # deprecated imapflags extension in addition to all extensions were already + # enabled by default. + #sieve_extensions = +notify +imapflags + + # Which Sieve language extensions are ONLY available in global scripts. This + # can be used to restrict the use of certain Sieve extensions to administrator + # control, for instance when these extensions can cause security concerns. + # This setting has higher precedence than the `sieve_extensions' setting + # (above), meaning that the extensions enabled with this setting are never + # available to the user's personal script no matter what is specified for the + # `sieve_extensions' setting. The syntax of this setting is similar to the + # `sieve_extensions' setting, with the difference that extensions are + # enabled or disabled for exclusive use in global scripts. Currently, no + # extensions are marked as such by default. + #sieve_global_extensions = + + # The Pigeonhole Sieve interpreter can have plugins of its own. Using this + # setting, the used plugins can be specified. Check the Dovecot wiki + # (wiki2.dovecot.org) or the pigeonhole website + # (http://pigeonhole.dovecot.org) for available plugins. + # The sieve_extprograms plugin is included in this release. + #sieve_plugins = + + # The separator that is expected between the :user and :detail + # address parts introduced by the subaddress extension. This may + # also be a sequence of characters (e.g. '--'). The current + # implementation looks for the separator from the left of the + # localpart and uses the first one encountered. The :user part is + # left of the separator and the :detail part is right. This setting + # is also used by Dovecot's LMTP service. + #recipient_delimiter = + + + # The maximum size of a Sieve script. The compiler will refuse to compile any + # script larger than this limit. If set to 0, no limit on the script size is + # enforced. + #sieve_max_script_size = 1M + + # The maximum number of actions that can be performed during a single script + # execution. If set to 0, no limit on the total number of actions is enforced. + #sieve_max_actions = 32 + + # The maximum number of redirect actions that can be performed during a single + # script execution. If set to 0, no redirect actions are allowed. + #sieve_max_redirects = 4 + + # The maximum number of personal Sieve scripts a single user can have. If set + # to 0, no limit on the number of scripts is enforced. + # (Currently only relevant for ManageSieve) + #sieve_quota_max_scripts = 0 + + # The maximum amount of disk storage a single user's scripts may occupy. If + # set to 0, no limit on the used amount of disk storage is enforced. + # (Currently only relevant for ManageSieve) + #sieve_quota_max_storage = 0 +} +]]> + + + + + + + + + + //service[@type='mail']/general/installs[@index=1] + + //service[@type='mail']/general/files[@index=1] + + //service[@type='mail']/general/commands[@index=1] + + + + + + + + + + "]]> + "]]> + + + + FTP Server" +ServerType standalone +DeferWelcome off + +MultilineRFC2228 on +DefaultServer on +ShowSymlinks on + +TimeoutNoTransfer 600 +TimeoutStalled 600 +TimeoutIdle 1200 + +DisplayLogin welcome.msg +DisplayChdir .message true +ListOptions "-l" + +DenyFilter \*.*/ + +# Use this to jail all users in their homes +# DefaultRoot ~ + +# Users require a valid shell listed in /etc/shells to login. +# Use this directive to release that constrain. +# RequireValidShell off + +# Port 21 is the standard FTP port. +Port 21 + +# In some cases you have to specify passive ports range to by-pass +# firewall limitations. Ephemeral ports can be used for that, but +# feel free to use a more narrow range. +# PassivePorts 49152 65534 + +# If your host was NATted, this option is useful in order to +# allow passive tranfers to work. You have to use your public +# address and opening the passive ports used on your firewall as well. +# MasqueradeAddress 1.2.3.4 + +# This is useful for masquerading address with dynamic IPs: +# refresh any configured MasqueradeAddress directives every 8 hours + +# DynMasqRefresh 28800 + + +# To prevent DoS attacks, set the maximum number of child processes +# to 30. If you need to allow more than 30 concurrent connections +# at once, simply increase this value. Note that this ONLY works +# in standalone mode, in inetd mode you should use an inetd server +# that allows you to limit maximum number of processes per service +# (such as xinetd) +MaxInstances 30 + +# Set the user and group that the server normally runs at. +User proftpd +Group nogroup + +# Umask 022 is a good standard umask to prevent new files and dirs +# (second parm) from being group and world writable. +Umask 022 022 +# Normally, we want files to be overwriteable. +AllowOverwrite on + +# Uncomment this if you are using NIS or LDAP via NSS to retrieve passwords: +# PersistentPasswd off + +# This is required to use both PAM-based authentication and local passwords +# AuthOrder mod_auth_pam.c* mod_auth_unix.c + +# Be warned: use of this directive impacts CPU average load! +# Uncomment this if you like to see progress and transfer rate with ftpwho +# in downloads. That is not needed for uploads rates. +# +# UseSendFile off + +TransferLog /var/log/proftpd/xferlog +SystemLog /var/log/proftpd/proftpd.log + +# Logging onto /var/log/lastlog is enabled but set to off by default +#UseLastlog on + +# In order to keep log file dates consistent after chroot, use timezone info +# from /etc/localtime. If this is not set, and proftpd is configured to +# chroot (e.g. DefaultRoot or ), it will use the non-daylight +# savings timezone regardless of whether DST is in effect. +#SetEnv TZ :/etc/localtime + + +QuotaEngine on + + + +Ratios off + + + +# Delay engine reduces impact of the so-called Timing Attack described in +# http://www.securityfocus.com/bid/11430/discuss +# It is on by default. + +DelayEngine on + + + +ControlsEngine off +ControlsMaxClients 2 +ControlsLog /var/log/proftpd/controls.log +ControlsInterval 5 +ControlsSocket /var/run/proftpd/proftpd.sock + + + +AdminControlsEngine off + + +# +# Alternative authentication frameworks +# +#Include /etc/proftpd/ldap.conf +Include /etc/proftpd/sql.conf + +# +# This is used for FTPS connections +# +Include /etc/proftpd/tls.conf + +# +# Useful to keep VirtualHost/VirtualRoot directives separated +# +#Include /etc/proftpd/virtuals.conf + +# A basic anonymous configuration, no upload directories. + +# +# User ftp +# Group nogroup +# # We want clients to be able to login with "anonymous" as well as "ftp" +# UserAlias anonymous ftp +# # Cosmetic changes, all files belongs to ftp user +# DirFakeUser on ftp +# DirFakeGroup on ftp +# +# RequireValidShell off +# +# # Limit the maximum number of anonymous logins +# MaxClients 10 +# +# # We want 'welcome.msg' displayed at login, and '.message' displayed +# # in each newly chdired directory. +# DisplayLogin welcome.msg +# DisplayChdir .message +# +# # Limit WRITE everywhere in the anonymous chroot +# +# +# DenyAll +# +# +# +# # Uncomment this if you're brave. +# # +# # # Umask 022 is a good standard umask to prevent new files and dirs +# # # (second parm) from being group and world writable. +# # Umask 022 022 +# # +# # DenyAll +# # +# # +# # AllowAll +# # +# # +# +# + +# Include other custom configuration files +Include /etc/proftpd/conf.d/ +]]> + + + + + + + + + +DefaultRoot ~ +RequireValidShell off +AuthOrder mod_sql.c + +# +# Choose a SQL backend among MySQL or PostgreSQL. +# Both modules are loaded in default configuration, so you have to specify the backend +# or comment out the unused module in /etc/proftpd/modules.conf. +# Use 'mysql' or 'postgres' as possible values. +# +SQLBackend mysql +# +SQLEngine on +SQLAuthenticate on +# +# Use both a crypted or plaintext password +SQLAuthTypes Crypt + +SQLAuthenticate users* groups* + +# +# Connection +SQLConnectInfo @ +# +# Describes both users/groups tables +# +SQLUserInfo ftp_users username password uid gid homedir shell +SQLGroupInfo ftp_groups groupname gid members +# +SQLUserWhereClause "login_enabled = 'y'" + +SQLLog PASS login +SQLNamedQuery login UPDATE "last_login=now(), login_count=login_count+1 WHERE username='%u'" ftp_users + +SQLLog RETR download +SQLNamedQuery download UPDATE "down_count=down_count+1, down_bytes=down_bytes+%b WHERE username='%u'" ftp_users + +SQLLog STOR upload +SQLNamedQuery upload UPDATE "up_count=up_count+1, up_bytes=up_bytes+%b WHERE username='%u'" ftp_users + +QuotaEngine on +QuotaShowQuotas on +QuotaDisplayUnits Mb +QuotaLock /var/lock/ftpd.quotatab.lock +QuotaLimitTable sql:/get-quota-limit +QuotaTallyTable sql:/get-quota-tally/update-quota-tally/insert-quota-tally +SQLNamedQuery get-quota-limit SELECT "ftp_users.username AS name, ftp_quotalimits.quota_type, ftp_quotalimits.per_session, ftp_quotalimits.limit_type, panel_customers.diskspace*1024 AS bytes_in_avail, ftp_quotalimits.bytes_out_avail, ftp_quotalimits.bytes_xfer_avail, ftp_quotalimits.files_in_avail, ftp_quotalimits.files_out_avail, ftp_quotalimits.files_xfer_avail FROM ftp_users, ftp_quotalimits, panel_customers WHERE ftp_users.username = '%{0}' AND panel_customers.loginname = SUBSTRING_INDEX('%{0}', 'ftp', 1) AND quota_type ='%{1}'" +SQLNamedQuery get-quota-tally SELECT "name, quota_type, bytes_in_used,bytes_out_used, bytes_xfer_used, files_in_used, files_out_used,files_xfer_used FROM ftp_quotatallies WHERE name = '%{0}' AND quota_type = '%{1}'" +SQLNamedQuery update-quota-tally UPDATE "bytes_in_used = bytes_in_used + %{0}, bytes_out_used = bytes_out_used + %{1}, bytes_xfer_used = bytes_xfer_used + %{2}, files_in_used = files_in_used + %{3}, files_out_used= files_out_used + %{4}, files_xfer_used = files_xfer_used + %{5} WHERE name= '%{6}' AND quota_type = '%{7}'" ftp_quotatallies +SQLNamedQuery insert-quota-tally INSERT "%{0}, %{1}, %{2}, %{3}, %{4},%{5}, %{6}, %{7}" ftp_quotatallies + + +]]> + + + + +TLSEngine on +TLSLog /var/log/proftpd/tls.log +TLSProtocol TLSv1 TLSv1.1 TLSv1.2 +TLSRSACertificateFile /etc/ssl/certs/proftpd.crt +TLSRSACertificateKeyFile /etc/ssl/private/proftpd.key +TLSECCertificateFile /etc/ssl/certs/proftpd_ec.crt +TLSECCertificateKeyFile /etc/ssl/private/proftpd_ec.key +TLSOptions NoCertRequest NoSessionReuseRequired +TLSVerifyClient off + +# Are clients required to use FTP over TLS when talking to this server? +#TLSRequired on + +# Allow SSL/TLS renegotiations when the client requests them, but +# do not force the renegotations. Some clients do not support +# SSL/TLS renegotiations; when mod_tls forces a renegotiation, these +# clients will close the data connection, or there will be a timeout +# on an idle data connection. +# +#TLSRenegotiate required off + +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# Mandatory : user password. You must have a password. + +MYSQLPassword + + +# Mandatory : database to open. + +MYSQLDatabase + + +# Mandatory : how passwords are stored +# Valid values are : "cleartext", "crypt", "sha1", "md5" and "password" +# ("password" = MySQL password() function) +# You can also use "any" to try "crypt", "sha1", "md5" *and* "password" + +MYSQLCrypt any + + +# In the following directives, parts of the strings are replaced at +# run-time before performing queries : +# +# \L is replaced by the login of the user trying to authenticate. +# \I is replaced by the IP address the user connected to. +# \P is replaced by the port number the user connected to. +# \R is replaced by the IP address the user connected from. +# \D is replaced by the remote IP address, as a long decimal number. +# +# Very complex queries can be performed using these substitution strings, +# especially for virtual hosting. + + +# Query to execute in order to fetch the password + +MYSQLGetPW SELECT password FROM ftp_users WHERE username="\L" AND login_enabled="y" + + +# Query to execute in order to fetch the system user name or uid + +MYSQLGetUID SELECT uid FROM ftp_users WHERE username="\L" AND login_enabled="y" + + +# Optional : default UID - if set this overrides MYSQLGetUID + +#MYSQLDefaultUID 1000 + + +# Query to execute in order to fetch the system user group or gid + +MYSQLGetGID SELECT gid FROM ftp_users WHERE username="\L" AND login_enabled="y" + + +# Optional : default GID - if set this overrides MYSQLGetGID + +#MYSQLDefaultGID 1000 + + +# Query to execute in order to fetch the home directory + +MYSQLGetDir SELECT homedir FROM ftp_users WHERE username="\L" AND login_enabled="y" + + +# Optional : query to get the maximal number of files +# Pure-FTPd must have been compiled with virtual quotas support. + +# MySQLGetQTAFS SELECT QuotaFiles FROM users WHERE User='\L' + + +# Optional : query to get the maximal disk usage (virtual quotas) +# The number should be in Megabytes. +# Pure-FTPd must have been compiled with virtual quotas support. + +MySQLGetQTASZ SELECT panel_customers.diskspace/1024 AS QuotaSize FROM panel_customers, ftp_users WHERE username = "\L" AND panel_customers.loginname = SUBSTRING_INDEX('\L', 'ftp', 1) + + +# Optional : ratios. The server has to be compiled with ratio support. + +# MySQLGetRatioUL SELECT ULRatio FROM users WHERE User='\L' +# MySQLGetRatioDL SELECT DLRatio FROM users WHERE User='\L' + + +# Optional : bandwidth throttling. +# The server has to be compiled with throttling support. +# Values are in KB/s . + +# MySQLGetBandwidthUL SELECT ULBandwidth FROM users WHERE User='\L' +# MySQLGetBandwidthDL SELECT DLBandwidth FROM users WHERE User='\L' + +# Enable ~ expansion. NEVER ENABLE THIS BLINDLY UNLESS : +# 1) You know what you are doing. +# 2) Real and virtual users match. + +# MySQLForceTildeExpansion 1 + + +# If you're using a transactionnal storage engine, you can enable SQL +# transactions to avoid races. Leave this commented if you are using the +# traditional MyIsam engine. + +# MySQLTransactions On +]]> + + + + + + + + + + + + + + + + + + + + + + + scripts/froxlor_master_cronjob.php +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + *.log { + missingok + weekly + rotate 4 + compress + delaycompress + notifempty + create + sharedscripts + postrotate + > /dev/null 2>&1 || true + endscript +} +]]> + + + + + + + + + {{settings.system.mod_fcgid_ownvhost}} + + + + + + + + + + + + + + {{settings.system.webserver}} + + + + + + {{settings.system.webserver}} + + + + + {{settings.phpfpm.enabled_ownvhost}} + + {{settings.phpfpm.vhost_httpuser}} + + + + + + {{settings.system.webserver}} + + {{settings.phpfpm.enabled_ownvhost}} + + + + + + + + + + diff --git a/lng/english.lng.php b/lng/english.lng.php index 0830a2ef..6f81978a 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -1828,7 +1828,7 @@ $lng['serversettings']['panel_password_special_char_required']['description'] = $lng['serversettings']['panel_password_special_char']['title'] = 'Special characters list'; $lng['serversettings']['panel_password_special_char']['description'] = 'One of these characters is required if the above option is set.'; $lng['phpfpm']['use_mod_proxy']['title'] = 'Use mod_proxy / mod_proxy_fcgi'; -$lng['phpfpm']['use_mod_proxy']['description'] = 'Activate to use php-fpm via mod_proxy_fcgi. Requires at least apache-2.4.9'; +$lng['phpfpm']['use_mod_proxy']['description'] = 'Must be enabled when using Debian 9.x (Stretch). Activate to use php-fpm via mod_proxy_fcgi. Requires at least apache-2.4.9'; $lng['error']['no_phpinfo'] = 'Sorry, unable to read phpinfo()'; $lng['admin']['movetoadmin'] = 'Move customer'; @@ -1849,9 +1849,9 @@ $lng['usersettings']['custom_notes']['show'] = 'Show your notes on the dashboard $lng['error']['fcgidandphpfpmnogoodtogether'] = 'FCGID and PHP-FPM cannot be activated at the same time'; // Added in Froxlor 0.9.34 -$lng['admin']['configfiles']['legend'] = 'You are about to configure a service/daemon. The following legend explains the nomenclature.'; +$lng['admin']['configfiles']['legend'] = '

You are about to configure a service/daemon

'; $lng['admin']['configfiles']['commands'] = 'Commands: These commands are to be executed line by line as root-user in a shell. It is safe to copy the whole block and paste it into the shell.'; -$lng['admin']['configfiles']['files'] = 'Configfiles: This is an example of the contents of a configuration file. The commands before these textfields should open an editor with the target file. Just copy and paste the contents into the editor and save the file.

Please note: The MySQL-password has not been replaced for security reasons. Please replace "FROXLOR_MYSQL_PASSWORD" on your own. If you forgot your MySQL-password you\'ll find it in "lib/userdata.inc.php"'; +$lng['admin']['configfiles']['files'] = 'Configfiles: The commands before the textfields should open an editor with the target file. Just copy and paste the contents into the editor and save the file.
Please note: The MySQL-password has not been replaced for security reasons. Please replace "FROXLOR_MYSQL_PASSWORD" on your own or use the javascript form below to replace it on-site. If you forgot your MySQL-password you\'ll find it in "lib/userdata.inc.php"'; $lng['serversettings']['apache_itksupport']['title'] = 'Use modifications for Apache ITK-MPM'; $lng['serversettings']['apache_itksupport']['description'] = 'ATTENTION: use only if you acutally have apache itk-mpm enabled
otherwise your webserver will not be able to start'; $lng['integrity_check']['DatabaseCharset'] = 'Characterset of database (should be UTF-8)'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 160ebb9a..f67f55f5 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1553,7 +1553,7 @@ $lng['serversettings']['panel_password_special_char_required']['description'] = $lng['serversettings']['panel_password_special_char']['title'] = 'Sonderzeichen-Liste'; $lng['serversettings']['panel_password_special_char']['description'] = 'Mindestens eines dieser Sonderzeichen muss in dem Passwort vorkommen, sofern die Sonderzeichen-Option aktiviert ist.'; $lng['phpfpm']['use_mod_proxy']['title'] = 'Verwende mod_proxy / mod_proxy_fcgi'; -$lng['phpfpm']['use_mod_proxy']['description'] = 'Diese Option kann aktiviert werden, um php-fpm via mod_proxy_fcgi einzubinden. Dies setzt mindestens apache-2.4.9 voraus'; +$lng['phpfpm']['use_mod_proxy']['description'] = 'Muss gesetzt sein bei Debian 9.x (Stretch). Diese Option kann aktiviert werden, um php-fpm via mod_proxy_fcgi einzubinden. Dies setzt mindestens apache-2.4.9 voraus'; $lng['error']['no_phpinfo'] = 'Entschuldigung, es ist nicht möglich die phpinfo() auszulesen.'; $lng['admin']['movetoadmin'] = 'Kunde verschieben'; @@ -1574,9 +1574,9 @@ $lng['usersettings']['custom_notes']['show'] = 'Zeige die Notizen auf dem Dashbo $lng['error']['fcgidandphpfpmnogoodtogether'] = 'FCGID und PHP-FPM können nicht gleichzeitig aktiviert werden.'; // Added in Froxlor 0.9.34 -$lng['admin']['configfiles']['legend'] = 'Du konfigurierst nun einen Service/Daemon. Die folgende Legende zeigt unsere Nomenklatur.'; +$lng['admin']['configfiles']['legend'] = '

Du konfigurierst nun einen Service/Daemon.

'; $lng['admin']['configfiles']['commands'] = 'Kommandos: Die angezeigten Befehle müssen als Benutzer root in einer Shell ausgeführt werden. Es kann auch problemlos der ganze Block kopiert und in die Shell eingefügt werden.'; -$lng['admin']['configfiles']['files'] = 'Konfigurationsdateien: Dies ist der Inhalt einer Konfigurationsdatei. Der Befehl direkt vor dem Textfeld sollte einen Editor mit der Zieldatei öffnen. Der Inhalt kann nun einfach kopiert und in den Editor eingefügt und die Datei gespeichert werden.

Beachten Sie: Das MySQL-Passwort wurde aus Sicherheitsgründen nicht ersetzt. Bitte ersetzen Sie "FROXLOR_MYSQL_PASSWORD" manuell durch das entsprechende Passwort. Falls Sie es vergessen haben sollten, finden Sie es in der Datei "lib/userdata.inc.php".'; +$lng['admin']['configfiles']['files'] = 'Konfigurationsdateien: Der Befehl direkt vor dem Textfeld sollte einen Editor mit der Zieldatei öffnen. Der Inhalt kann nun einfach kopiert und in den Editor eingefügt und die Datei gespeichert werden.
Bitte beachten: Das MySQL-Passwort wurde aus Sicherheitsgründen nicht ersetzt. Bitte ersetze "FROXLOR_MYSQL_PASSWORD" manuell oder nutze das folgende Formular, um es temporär auf dieser Seite zu setzen. Falls das Passwort vergessen wurde, findet es sich in der Datei "lib/userdata.inc.php".'; $lng['serversettings']['apache_itksupport']['title'] = 'Anpassungen für Apache ITK-MPM verwenden'; $lng['serversettings']['apache_itksupport']['description'] = '
Achtung: Bitte nur verwenden, wenn wirklich Apache itk-mpm verwendet wird, ansonsten wird der Webserver nicht starten.
'; $lng['integrity_check']['DatabaseCharset'] = 'Characterset der Datenbank (sollte UTF-8 sein)'; diff --git a/templates/Sparkle/admin/configfiles/configfiles.tpl b/templates/Sparkle/admin/configfiles/configfiles.tpl index cab16fb1..d469aed3 100644 --- a/templates/Sparkle/admin/configfiles/configfiles.tpl +++ b/templates/Sparkle/admin/configfiles/configfiles.tpl @@ -11,25 +11,15 @@ $header
-

{$lng['admin']['configfiles']['legend']}


+

{$lng['admin']['configfiles']['legend']}

+

{$lng['admin']['configfiles']['commands']}

+

{$lng['admin']['configfiles']['files']}

- {$lng['admin']['configfiles']['commands']}
- -


-

- {$lng['admin']['configfiles']['files']}
- -

FROXLOR_MYSQL_PASSWORD:
+

From 6e651200ca5c6168aee1f6027e4256a60f64e588 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 11 Jan 2018 13:04:38 +0100 Subject: [PATCH 133/179] Make php.ini flag/value possibilities dynamic (settings) Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/136.phpfpm.php | 34 ++++- install/froxlor.sql | 98 ++++++++++++++- .../updates/froxlor/0.9/update_0.9.inc.php | 104 +++++++++++++++ .../phpinterface/class.phpinterface_fpm.php | 118 ++---------------- lib/version.inc.php | 2 +- lng/english.lng.php | 4 + lng/german.lng.php | 4 + 7 files changed, 255 insertions(+), 109 deletions(-) diff --git a/actions/admin/settings/136.phpfpm.php b/actions/admin/settings/136.phpfpm.php index 13e733ae..a62f0c2f 100644 --- a/actions/admin/settings/136.phpfpm.php +++ b/actions/admin/settings/136.phpfpm.php @@ -86,7 +86,39 @@ return array( 'default' => false, 'visible' => Settings::Get('system.apache24'), 'save_method' => 'storeSettingField' - ) + ), + 'system_phpfpm_ini_flags' => array( + 'label' => $lng['phpfpm']['ini_flags'], + 'settinggroup' => 'phpfpm', + 'varname' => 'ini_flags', + 'type' => 'text', + 'default' => '', + 'save_method' => 'storeSettingField' + ), + 'system_phpfpm_ini_values' => array( + 'label' => $lng['phpfpm']['ini_values'], + 'settinggroup' => 'phpfpm', + 'varname' => 'ini_values', + 'type' => 'text', + 'default' => '', + 'save_method' => 'storeSettingField' + ), + 'system_phpfpm_ini_admin_flags' => array( + 'label' => $lng['phpfpm']['ini_admin_flags'], + 'settinggroup' => 'phpfpm', + 'varname' => 'ini_admin_flags', + 'type' => 'text', + 'default' => '', + 'save_method' => 'storeSettingField' + ), + 'system_phpfpm_ini_admin_values' => array( + 'label' => $lng['phpfpm']['ini_admin_values'], + 'settinggroup' => 'phpfpm', + 'varname' => 'ini_admin_values', + 'type' => 'text', + 'default' => '', + 'save_method' => 'storeSettingField' + ) ), ), ), diff --git a/install/froxlor.sql b/install/froxlor.sql index cbcae082..fd762195 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -423,6 +423,102 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('phpfpm', 'vhost_defaultini', '2'), ('phpfpm', 'fastcgi_ipcdir', '/var/lib/apache2/fastcgi/'), ('phpfpm', 'use_mod_proxy', '0'), + ('phpfpm', 'ini_flags', 'asp_tags +display_errors +display_startup_errors +html_errors +log_errors +magic_quotes_gpc +magic_quotes_runtime +magic_quotes_sybase +mail.add_x_header +session.cookie_secure +session.use_cookies +short_open_tag +track_errors +xmlrpc_errors +suhosin.simulation +suhosin.session.encrypt +suhosin.session.cryptua +suhosin.session.cryptdocroot +suhosin.cookie.encrypt +suhosin.cookie.cryptua +suhosin.cookie.cryptdocroot +suhosin.executor.disable_eval +mbstring.func_overload'), + ('phpfpm', 'ini_values', 'auto_append_file +auto_prepend_file +date.timezone +default_charset +error_reporting +include_path +log_errors_max_len +mail.log +max_execution_time +session.cookie_domain +session.cookie_lifetime +session.cookie_path +session.name +session.serialize_handler +upload_max_filesize +xmlrpc_error_number +session.auto_start +always_populate_raw_post_data +suhosin.session.cryptkey +suhosin.session.cryptraddr +suhosin.session.checkraddr +suhosin.cookie.cryptkey +suhosin.cookie.plainlist +suhosin.cookie.cryptraddr +suhosin.cookie.checkraddr +suhosin.executor.func.blacklist +suhosin.executor.eval.whitelist'), + ('phpfpm', 'ini_admin_flags', 'allow_call_time_pass_reference +allow_url_fopen +allow_url_include +auto_detect_line_endings +cgi.fix_pathinfo +cgi.force_redirect +enable_dl +expose_php +file_uploads +ignore_repeated_errors +ignore_repeated_source +log_errors +register_argc_argv +report_memleaks +opcache.enable +opcache.consistency_checks +opcache.dups_fix +opcache.load_comments +opcache.revalidate_path +opcache.save_comments +opcache.use_cwd +opcache.validate_timestamps +opcache.fast_shutdown'), + ('phpfpm', 'ini_admin_values', 'cgi.redirect_status_env +date.timezone +disable_classes +disable_functions +error_log +gpc_order +max_input_time +max_input_vars +memory_limit +open_basedir +output_buffering +post_max_size +precision +sendmail_path +session.gc_divisor +session.gc_probability +variables_order +opcache.log_verbosity_level +opcache.restrict_api +opcache.revalidate_freq +opcache.max_accelerated_files +opcache.memory_consumption +opcache.interned_strings_buffer'), ('nginx', 'fastcgiparams', '/etc/nginx/fastcgi_params'), ('system', 'lastaccountnumber', '0'), ('system', 'lastguid', '9999'), @@ -590,7 +686,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.8'), - ('panel', 'db_version', '201801101'); + ('panel', 'db_version', '201801110'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 9891df2b..e9e1e39e 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3761,3 +3761,107 @@ if (isDatabaseVersion('201801100')) { updateToDbVersion('201801101'); } + +if (isDatabaseVersion('201801101')) { + + showUpdateStep("Adding dynamic php-fpm php.ini settings"); + Settings::AddNew('phpfpm.ini_flags', 'asp_tags +display_errors +display_startup_errors +html_errors +log_errors +magic_quotes_gpc +magic_quotes_runtime +magic_quotes_sybase +mail.add_x_header +session.cookie_secure +session.use_cookies +short_open_tag +track_errors +xmlrpc_errors +suhosin.simulation +suhosin.session.encrypt +suhosin.session.cryptua +suhosin.session.cryptdocroot +suhosin.cookie.encrypt +suhosin.cookie.cryptua +suhosin.cookie.cryptdocroot +suhosin.executor.disable_eval +mbstring.func_overload'); + Settings::AddNew('phpfpm.ini_values', 'auto_append_file +auto_prepend_file +date.timezone +default_charset +error_reporting +include_path +log_errors_max_len +mail.log +max_execution_time +session.cookie_domain +session.cookie_lifetime +session.cookie_path +session.name +session.serialize_handler +upload_max_filesize +xmlrpc_error_number +session.auto_start +always_populate_raw_post_data +suhosin.session.cryptkey +suhosin.session.cryptraddr +suhosin.session.checkraddr +suhosin.cookie.cryptkey +suhosin.cookie.plainlist +suhosin.cookie.cryptraddr +suhosin.cookie.checkraddr +suhosin.executor.func.blacklist +suhosin.executor.eval.whitelist'); + Settings::AddNew('phpfpm.ini_admin_flags', 'allow_call_time_pass_reference +allow_url_fopen +allow_url_include +auto_detect_line_endings +cgi.fix_pathinfo +cgi.force_redirect +enable_dl +expose_php +file_uploads +ignore_repeated_errors +ignore_repeated_source +log_errors +register_argc_argv +report_memleaks +opcache.enable +opcache.consistency_checks +opcache.dups_fix +opcache.load_comments +opcache.revalidate_path +opcache.save_comments +opcache.use_cwd +opcache.validate_timestamps +opcache.fast_shutdown'); + Settings::AddNew('phpfpm.ini_admin_values', 'cgi.redirect_status_env +date.timezone +disable_classes +disable_functions +error_log +gpc_order +max_input_time +max_input_vars +memory_limit +open_basedir +output_buffering +post_max_size +precision +sendmail_path +session.gc_divisor +session.gc_probability +variables_order +opcache.log_verbosity_level +opcache.restrict_api +opcache.revalidate_freq +opcache.max_accelerated_files +opcache.memory_consumption +opcache.interned_strings_buffer'); + lastStepStatus(0); + + updateToDbVersion('201801110'); +} diff --git a/lib/classes/phpinterface/class.phpinterface_fpm.php b/lib/classes/phpinterface/class.phpinterface_fpm.php index 0509666a..f72a2410 100644 --- a/lib/classes/phpinterface/class.phpinterface_fpm.php +++ b/lib/classes/phpinterface/class.phpinterface_fpm.php @@ -48,112 +48,7 @@ class phpinterface_fpm * * @var array */ - private $_ini = array( - 'php_value' => array( - 'auto_append_file', - 'auto_prepend_file', - 'date.timezone', - 'default_charset', - 'error_reporting', - 'include_path', - 'log_errors_max_len', - 'mail.log', - 'max_execution_time', - 'session.cookie_domain', - 'session.cookie_lifetime', - 'session.cookie_path', - 'session.name', - 'session.serialize_handler', - 'upload_max_filesize', - 'xmlrpc_error_number', - 'session.auto_start', - 'always_populate_raw_post_data', - 'suhosin.session.cryptkey', - 'suhosin.session.cryptraddr', - 'suhosin.session.checkraddr', - 'suhosin.cookie.cryptkey', - 'suhosin.cookie.plainlist', - 'suhosin.cookie.cryptraddr', - 'suhosin.cookie.checkraddr', - 'suhosin.executor.func.blacklist', - 'suhosin.executor.eval.whitelist' - ), - 'php_flag' => array( - 'asp_tags', - 'display_errors', - 'display_startup_errors', - 'html_errors', - 'log_errors', - 'magic_quotes_gpc', - 'magic_quotes_runtime', - 'magic_quotes_sybase', - 'mail.add_x_header', - 'session.cookie_secure', - 'session.use_cookies', - 'short_open_tag', - 'track_errors', - 'xmlrpc_errors', - 'suhosin.simulation', - 'suhosin.session.encrypt', - 'suhosin.session.cryptua', - 'suhosin.session.cryptdocroot', - 'suhosin.cookie.encrypt', - 'suhosin.cookie.cryptua', - 'suhosin.cookie.cryptdocroot', - 'suhosin.executor.disable_eval', - 'mbstring.func_overload' - ), - 'php_admin_value' => array( - 'cgi.redirect_status_env', - 'date.timezone', - 'disable_classes', - 'disable_functions', - 'error_log', - 'gpc_order', - 'max_input_time', - 'max_input_vars', - 'memory_limit', - 'open_basedir', - 'output_buffering', - 'post_max_size', - 'precision', - 'sendmail_path', - 'session.gc_divisor', - 'session.gc_probability', - 'variables_order', - 'opcache.log_verbosity_level', - 'opcache.restrict_api', - 'opcache.revalidate_freq', - 'opcache.max_accelerated_files', - 'opcache.memory_consumption', - 'opcache.interned_strings_buffer' - ), - 'php_admin_flag' => array( - 'allow_call_time_pass_reference', - 'allow_url_fopen', - 'allow_url_include', - 'auto_detect_line_endings', - 'cgi.fix_pathinfo', - 'cgi.force_redirect', - 'enable_dl', - 'expose_php', - 'file_uploads', - 'ignore_repeated_errors', - 'ignore_repeated_source', - 'log_errors', - 'register_argc_argv', - 'report_memleaks', - 'opcache.enable', - 'opcache.consistency_checks', - 'opcache.dups_fix', - 'opcache.load_comments', - 'opcache.revalidate_path', - 'opcache.save_comments', - 'opcache.use_cwd', - 'opcache.validate_timestamps', - 'opcache.fast_shutdown' - ) - ); + private $_ini = array(); /** * main constructor @@ -165,6 +60,17 @@ class phpinterface_fpm } $this->_domain = $domain; $this->_readFpmConfig($domain['fpm_config_id']); + $this->_buildIniMapping(); + } + + private function _buildIniMapping() + { + $this->_ini = array( + 'php_flag' => explode("\n", Settings::Get('phpfpm.ini_flags')), + 'php_value' => explode("\n", Settings::Get('phpfpm.ini_values')), + 'php_admin_flag' => explode("\n", Settings::Get('phpfpm.ini_admin_flags')), + 'php_admin_value' => explode("\n", Settings::Get('phpfpm.ini_admin_values')) + ); } private function _readFpmConfig($fpm_config_id) diff --git a/lib/version.inc.php b/lib/version.inc.php index ac4adb0f..4f1da38b 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201801101'; +$dbversion = '201801110'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index 6f81978a..831893f2 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2096,3 +2096,7 @@ $lng['serversettings']['ssl']['ssl_protocols']['title'] = 'Configure the TLS pro $lng['serversettings']['ssl']['ssl_protocols']['description'] = 'This is a list of ssl protocols that you want (or don\'t want) to use when using SSL. Notice: Some older browsers may not support the newest protcol versions.

Default value is:
TLSv1, TLSv1.2
'; $lng['serversettings']['phpfpm_settings']['limit_extensions']['title'] = 'Allowed extensions'; $lng['serversettings']['phpfpm_settings']['limit_extensions']['description'] = 'Limits the extensions of the main script FPM will allow to parse. This can prevent configuration mistakes on the web server side. You should only limit FPM to .php extensions to prevent malicious users to use other extensions to execute php code. Default value: .php'; +$lng['phpfpm']['ini_flags'] = 'Enter possible php_flags for php.ini. One entry per line'; +$lng['phpfpm']['ini_values'] = 'Enter possible php_values for php.ini. One entry per line'; +$lng['phpfpm']['ini_admin_flags'] = 'Enter possible php_admin_flags for php.ini. One entry per line'; +$lng['phpfpm']['ini_admin_values'] = 'Enter possible php_admin_values for php.ini. One entry per line'; diff --git a/lng/german.lng.php b/lng/german.lng.php index f67f55f5..9ccfa6da 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1747,3 +1747,7 @@ $lng['serversettings']['ssl']['ssl_protocols']['title'] = 'SSL Protokollversion $lng['serversettings']['ssl']['ssl_protocols']['description'] = 'Dies ist eine Liste von SSL/TLS Protokollversionen die genutzt werden sollen (oder auch nicht genutzt werden sollen), wenn SSL verwendet wird. Hinweis: Ältere Browser sind möglicherweise nicht vollständig zum neusten Protokoll kompatibel.

Standard-Wert ist:
TLSv1, TLSv1.2
'; $lng['serversettings']['phpfpm_settings']['limit_extensions']['title'] = 'Erlaubte Dateiendungen'; $lng['serversettings']['phpfpm_settings']['limit_extensions']['description'] = 'Beschränkt die Dateierweiterungen des Haupt-Skripts, das FPM zu parsen erlaubt. Dies kann Konfigurationsfehler auf der Webserverseite verhindern. Sie sollten FPM nur auf .php Erweiterungen beschränken, um zu verhindern, dass bösartige Nutzter andere Erweiterungen verwenden, um PHP Code auszuführen. Standardwert: .php'; +$lng['phpfpm']['ini_flags'] = 'Mögliche php_flags für die php.ini. Pro Zeile eine Direktive'; +$lng['phpfpm']['ini_values'] = 'Mögliche php_values für die php.ini. Pro Zeile eine Direktive'; +$lng['phpfpm']['ini_admin_flags'] = 'Mögliche php_admin_flags für die php.ini. Pro Zeile eine Direktive'; +$lng['phpfpm']['ini_admin_values'] = 'Mögliche php_admin_values für die php.ini. Pro Zeile eine Direktive'; From 9a00a67f7147b194b6a9413cd540990b9414b0d8 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 13 Jan 2018 11:33:20 +0100 Subject: [PATCH 134/179] apache2-suexec => apache2-suexec-pristine for debian stretch Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/stretch.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/configfiles/stretch.xml b/lib/configfiles/stretch.xml index a425306a..52f5e48d 100644 --- a/lib/configfiles/stretch.xml +++ b/lib/configfiles/stretch.xml @@ -4529,7 +4529,7 @@ aliases: files - + {{settings.system.mod_fcgid_ownvhost}} @@ -4549,7 +4549,7 @@ aliases: files {{settings.system.webserver}} - + From d16a7b2089dbaef36cfe6d7704a0a0c92d0245fd Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 15 Jan 2018 07:45:50 +0100 Subject: [PATCH 135/179] on installation, set apache-2.4 as default if apache is detected; clearify that apache2 is 2.2; output complete folder where the userdata.inc.php file is to be put when necessary to avoid misunderstanding Signed-off-by: Michael Kaufmann (d00p) --- install/lib/class.FroxlorInstall.php | 2 +- install/lng/english.lng.php | 6 +++--- install/lng/french.lng.php | 4 ++-- install/lng/german.lng.php | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/install/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index dc8cf74b..d253d59b 100644 --- a/install/lib/class.FroxlorInstall.php +++ b/install/lib/class.FroxlorInstall.php @@ -1208,7 +1208,7 @@ class FroxlorInstall $this->_data['webserver'] = $_POST['webserver']; } else { if (strtoupper(@php_sapi_name()) == "APACHE2HANDLER" || stristr($_SERVER['SERVER_SOFTWARE'], "apache/2")) { - $this->_data['webserver'] = 'apache2'; + $this->_data['webserver'] = 'apache24'; } elseif (substr(strtoupper(@php_sapi_name()), 0, 8) == "LIGHTTPD" || stristr($_SERVER['SERVER_SOFTWARE'], "lighttpd")) { $this->_data['webserver'] = 'lighttpd'; } elseif (substr(strtoupper(@php_sapi_name()), 0, 8) == "NGINX" || stristr($_SERVER['SERVER_SOFTWARE'], "nginx")) { diff --git a/install/lng/english.lng.php b/install/lng/english.lng.php index 7faf8b1f..409421a5 100644 --- a/install/lng/english.lng.php +++ b/install/lng/english.lng.php @@ -63,7 +63,7 @@ $lng['install']['serversettings'] = 'Server settings'; $lng['install']['servername'] = 'Server name (FQDN, no ip-address)'; $lng['install']['serverip'] = 'Server IP'; $lng['install']['webserver'] = 'Webserver'; -$lng['install']['apache2'] = 'Apache 2'; +$lng['install']['apache2'] = 'Apache 2.2'; $lng['install']['apache24'] = 'Apache 2.4'; $lng['install']['lighttpd'] = 'LigHTTPd'; $lng['install']['nginx'] = 'NGINX'; @@ -83,8 +83,8 @@ $lng['install']['changing_data'] = 'Adjusting settings...'; $lng['install']['creating_entries'] = 'Inserting new values...'; $lng['install']['adding_admin_user'] = 'Creating admin-account...'; $lng['install']['creating_configfile'] = 'Creating configfile...'; -$lng['install']['creating_configfile_temp'] = 'File was saved in /tmp/userdata.inc.php, please move to lib/.'; -$lng['install']['creating_configfile_failed'] = 'Could not create lib/userdata.inc.php, please create it manually with the following content:'; +$lng['install']['creating_configfile_temp'] = 'File was saved in /tmp/userdata.inc.php, please move to '.dirname(dirname(__DIR__)).'/lib/.'; +$lng['install']['creating_configfile_failed'] = 'Could not create '.dirname(dirname(__DIR__)).'/lib/userdata.inc.php, please create it manually with the following content:'; $lng['install']['froxlor_succ_installed'] = 'Froxlor was installed successfully.'; $lng['click_here_to_refresh'] = 'Click here to check again'; diff --git a/install/lng/french.lng.php b/install/lng/french.lng.php index 925b6220..43d86530 100644 --- a/install/lng/french.lng.php +++ b/install/lng/french.lng.php @@ -79,8 +79,8 @@ $lng['install']['changing_data'] = 'Ajustement des paramètres...'; $lng['install']['creating_entries'] = 'Insertion des nouvelles valeurs...'; $lng['install']['adding_admin_user'] = 'Création du compte administrateur...'; $lng['install']['creating_configfile'] = 'Création du fichier de configuration...'; -$lng['install']['creating_configfile_temp'] = 'Le fichier a été enregistré dans /tmp/userdata.inc.php, merci de le déplacer dans lib/.'; -$lng['install']['creating_configfile_failed'] = 'Impossible de créer lib/userdata.inc.php, merci de le créer manuellement avec le contenu suivant:'; +$lng['install']['creating_configfile_temp'] = 'Le fichier a été enregistré dans /tmp/userdata.inc.php, merci de le déplacer dans '.dirname(dirname(__DIR__)).'/lib/.'; +$lng['install']['creating_configfile_failed'] = 'Impossible de créer '.dirname(dirname(__DIR__)).'/lib/userdata.inc.php, merci de le créer manuellement avec le contenu suivant:'; $lng['install']['froxlor_succ_installed'] = 'Froxlor a été installé avec succès.'; $lng['click_here_to_refresh'] = 'Cliquez ici pour vérifier à nouveau'; diff --git a/install/lng/german.lng.php b/install/lng/german.lng.php index c8e8b095..02dd9b8d 100644 --- a/install/lng/german.lng.php +++ b/install/lng/german.lng.php @@ -83,8 +83,8 @@ $lng['install']['changing_data'] = 'Einstellungen anpassen...'; $lng['install']['creating_entries'] = 'Trage neue Werte ein...'; $lng['install']['adding_admin_user'] = 'Erstelle Admin-Benutzer...'; $lng['install']['creating_configfile'] = 'Erstelle Konfigurationsdatei...'; -$lng['install']['creating_configfile_temp'] = 'Datei wurde in /tmp/userdata.inc.php gespeichert, bitte nach lib/ verschieben.'; -$lng['install']['creating_configfile_failed'] = 'Konnte lib/userdata.inc.php nicht erstellen, bitte manuell mit folgendem Inhalt anlegen:'; +$lng['install']['creating_configfile_temp'] = 'Datei wurde in /tmp/userdata.inc.php gespeichert, bitte nach '.dirname(dirname(__DIR__)).'/lib/ verschieben.'; +$lng['install']['creating_configfile_failed'] = 'Konnte '.dirname(dirname(__DIR__)).'/lib/userdata.inc.php nicht erstellen, bitte manuell mit folgendem Inhalt anlegen:'; $lng['install']['froxlor_succ_installed'] = 'Froxlor wurde erfolgreich installiert.'; $lng['click_here_to_refresh'] = 'Hier klicken, um erneut zu prüfen'; From 52c7839b9ba48137cd22395af0b0b8db8a922d51 Mon Sep 17 00:00:00 2001 From: lonesomewalker Date: Tue, 16 Jan 2018 14:57:42 +0100 Subject: [PATCH 136/179] Update class.DnsEntry.php Klammerfehler bei Bind, PowerDNS braucht ja keinen Linesplit. --- lib/classes/dns/class.DnsEntry.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/classes/dns/class.DnsEntry.php b/lib/classes/dns/class.DnsEntry.php index 27f0dd8f..f4726e4d 100644 --- a/lib/classes/dns/class.DnsEntry.php +++ b/lib/classes/dns/class.DnsEntry.php @@ -52,7 +52,7 @@ class DnsEntry if (substr($_l, 0, 1) == '"') { $_l = substr($_l, 1); } - $_content = '( "' . $_l . '"' . PHP_EOL; + $_content = $_l . '"' . PHP_EOL; $_l = array_pop($_contentlines); // check for ending quote if (substr($_l, -1) == '"') { @@ -63,7 +63,7 @@ class DnsEntry $_content .= "\t\t\t\t" . '"' . $_cl . '"' . PHP_EOL; } // last line - $_content .= "\t\t\t\t" . '"'.$_l.'" )'; + $_content .= "\t\t\t\t" . '"'.$_l; } $result = $this->record . "\t" . $this->ttl . "\t" . $this->class . "\t" . $this->type . "\t" . (($this->priority >= 0 && ($this->type == 'MX' || $this->type == 'SRV')) ? $this->priority . "\t" : "") . $_content . PHP_EOL; return $result; From c3fb6f6a1c053c3f5f0b97899fba9137b69ad7ea Mon Sep 17 00:00:00 2001 From: Andreas Grundler Date: Thu, 18 Jan 2018 18:16:53 +0100 Subject: [PATCH 137/179] =?UTF-8?q?http2=20Konfiguration=20nur=20einf?= =?UTF-8?q?=C3=BCgen=20wenn=20http2=20in=20den=20Einstellungen=20aktiviert?= =?UTF-8?q?=20ist?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jobs/cron_tasks.inc.http.10.apache.php | 306 +++++++++--------- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 2 +- 2 files changed, 154 insertions(+), 154 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 55f230d0..9fcf71d8 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -16,7 +16,7 @@ if (! defined('MASTER_CRONJOB')) * @author Froxlor team (2010-) * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt * @package Cron - * + * */ require_once (dirname(__FILE__) . '/../classes/class.HttpConfigBase.php'); @@ -91,13 +91,13 @@ class apache extends HttpConfigBase $vhosts_folder = makeCorrectDir(dirname(Settings::Get('system.apacheconf_vhost'))); } $vhosts_filename = makeCorrectFile($vhosts_folder . '/05_froxlor_dirfix_nofcgid.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; - + // check for custom values, see #1638 $custom_opts = Settings::Get('system.apacheglobaldiropt'); if (! empty($custom_opts)) { @@ -113,7 +113,7 @@ class apache extends HttpConfigBase } } $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; - + $ocsp_cache_filename = makeCorrectFile($vhosts_folder . '/03_froxlor_ocsp_cache.conf'); if (Settings::Get('system.use_ssl') == '1' && Settings::Get('system.apache24') == 1) { $this->virtualhosts_data[$ocsp_cache_filename] = 'SSLStaplingCache ' . Settings::Get('system.apache24_ocsp_cache_path') . "\n"; @@ -137,13 +137,13 @@ class apache extends HttpConfigBase } else { $vhosts_folder = makeCorrectDir(dirname(Settings::Get('system.apacheconf_vhost'))); } - + $vhosts_filename = makeCorrectFile($vhosts_folder . '/05_froxlor_default_errorhandler.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + $statusCodes = array( '401', '403', @@ -167,26 +167,26 @@ class apache extends HttpConfigBase public function createIpPort() { $result_ipsandports_stmt = Database::query("SELECT * FROM `" . TABLE_PANEL_IPSANDPORTS . "` ORDER BY `ip` ASC, `port` ASC"); - + while ($row_ipsandports = $result_ipsandports_stmt->fetch(PDO::FETCH_ASSOC)) { if (filter_var($row_ipsandports['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $ipport = '[' . $row_ipsandports['ip'] . ']:' . $row_ipsandports['port']; } else { $ipport = $row_ipsandports['ip'] . ':' . $row_ipsandports['port']; } - + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::createIpPort: creating ip/port settings for ' . $ipport); $vhosts_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/10_froxlor_ipandport_' . trim(str_replace(':', '.', $row_ipsandports['ip']), '.') . '.' . $row_ipsandports['port'] . '.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + if ($row_ipsandports['listen_statement'] == '1') { $this->virtualhosts_data[$vhosts_filename] .= 'Listen ' . $ipport . "\n"; $this->logger->logAction(CRON_ACTION, LOG_DEBUG, $ipport . ' :: inserted listen-statement'); } - + if ($row_ipsandports['namevirtualhost_statement'] == '1') { // >=apache-2.4 enabled? if (Settings::Get('system.apache24') == '1') { @@ -196,22 +196,22 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_DEBUG, $ipport . ' :: inserted namevirtualhost-statement'); } } - + if ($row_ipsandports['vhostcontainer'] == '1') { - + $without_vhost = $this->virtualhosts_data[$vhosts_filename]; $close_vhost = true; - + $this->virtualhosts_data[$vhosts_filename] .= '' . "\n"; - + $mypath = $this->getMyPath($row_ipsandports); - + $this->virtualhosts_data[$vhosts_filename] .= 'DocumentRoot "' . $mypath . '"' . "\n"; - + if ($row_ipsandports['vhostcontainer_servername_statement'] == '1') { $this->virtualhosts_data[$vhosts_filename] .= ' ServerName ' . Settings::Get('system.hostname') . "\n"; } - + $is_redirect = false; // check for SSL redirect if ($row_ipsandports['ssl'] == '0' && Settings::Get('system.le_froxlor_redirect') == '1') { @@ -223,11 +223,11 @@ class apache extends HttpConfigBase $is_redirect = false; } else { $_sslport = $this->checkAlternativeSslPort(); - + $mypath = 'https://' . Settings::Get('system.hostname') . $_sslport . '/'; $code = '301'; $modrew_red = ' [R=' . $code . ';L,NE]'; - + // redirect everything, not only root-directory, #541 $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' RewriteEngine On' . "\n"; @@ -242,7 +242,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; } } - + if (! $is_redirect) { // create fcgid -Part (starter is created in apache_fcgid) if (Settings::Get('system.mod_fcgid_ownvhost') == '1' && Settings::Get('system.mod_fcgid') == '1') { @@ -266,7 +266,7 @@ class apache extends HttpConfigBase ); $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig(Settings::Get('system.mod_fcgid_defaultini_ownvhost')); - + $starter_filename = makeCorrectFile($configdir . '/php-fcgi-starter'); $this->virtualhosts_data[$vhosts_filename] .= ' SuexecUserGroup "' . Settings::Get('system.mod_fcgid_httpuser') . '" "' . Settings::Get('system.mod_fcgid_httpgroup') . '"' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; @@ -317,14 +317,14 @@ class apache extends HttpConfigBase 'documentroot' => $mypath, 'fpm_config_id' => isset($fpm_config['id']) ? $fpm_config['id'] : 1 ); - + $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig(Settings::Get('phpfpm.vhost_defaultini')); $srvName = substr(md5($ipport), 0, 4) . '.fpm.external'; if ($row_ipsandports['ssl']) { $srvName = substr(md5($ipport), 0, 4) . '.ssl-fpm.external'; } - + // mod_proxy stuff for apache-2.4 if (Settings::Get('system.apache24') == '1' && Settings::Get('phpfpm.use_mod_proxy') == '1') { $filesmatch = $phpconfig['fpm_settings']['limit_extensions']; @@ -401,7 +401,7 @@ class apache extends HttpConfigBase 'documentroot' => $mypath ); } - + /** * dirprotection, see #72 * @@ -410,36 +410,36 @@ class apache extends HttpConfigBase * $this->virtualhosts_data[$vhosts_filename] .= "\t\tAllow from all\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tOptions -Indexes\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; - * + * * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tOrder Deny,Allow\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tDeny from All\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; * end of dirprotection */ - + if ($row_ipsandports['specialsettings'] != '') { $this->virtualhosts_data[$vhosts_filename] .= $this->processSpecialConfigTemplate($row_ipsandports['specialsettings'], $domain, $row_ipsandports['ip'], $row_ipsandports['port'], $row_ipsandports['ssl'] == '1') . "\n"; } - + if ($row_ipsandports['ssl'] == '1' && Settings::Get('system.use_ssl') == '1') { if ($row_ipsandports['ssl_cert_file'] == '') { $row_ipsandports['ssl_cert_file'] = Settings::Get('system.ssl_cert_file'); } - + if ($row_ipsandports['ssl_key_file'] == '') { $row_ipsandports['ssl_key_file'] = Settings::Get('system.ssl_key_file'); } - + if ($row_ipsandports['ssl_ca_file'] == '') { $row_ipsandports['ssl_ca_file'] = Settings::Get('system.ssl_ca_file'); } - + // #418 if ($row_ipsandports['ssl_cert_chainfile'] == '') { $row_ipsandports['ssl_cert_chainfile'] = Settings::Get('system.ssl_cert_chainfile'); } - + $domain = array( 'id' => 0, 'domain' => Settings::Get('system.hostname'), @@ -448,26 +448,26 @@ class apache extends HttpConfigBase 'documentroot' => $mypath, 'parentdomainid' => 0 ); - + // override corresponding array values $domain['ssl_cert_file'] = $row_ipsandports['ssl_cert_file']; $domain['ssl_key_file'] = $row_ipsandports['ssl_key_file']; $domain['ssl_ca_file'] = $row_ipsandports['ssl_ca_file']; $domain['ssl_cert_chainfile'] = $row_ipsandports['ssl_cert_chainfile']; - + // SSL STUFF $dssl = new DomainSSL(); // this sets the ssl-related array-indices in the $domain array // if the domain has customer-defined ssl-certificates $dssl->setDomainSSLFilesArray($domain); - + if ($domain['ssl_cert_file'] != '') { - + // check for existence, #1485 if (! file_exists($domain['ssl_cert_file'])) { $this->logger->logAction(CRON_ACTION, LOG_ERR, $ipport . ' :: certificate file "' . $domain['ssl_cert_file'] . '" does not exist! Cannot create ssl-directives'); } else { - + $this->virtualhosts_data[$vhosts_filename] .= ' SSLEngine On' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL +' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { @@ -481,7 +481,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLVerifyDepth 10' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLCertificateFile ' . makeCorrectFile($domain['ssl_cert_file']) . "\n"; - + if ($domain['ssl_key_file'] != '') { // check for existence, #1485 if (! file_exists($domain['ssl_key_file'])) { @@ -490,7 +490,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCertificateKeyFile ' . makeCorrectFile($domain['ssl_key_file']) . "\n"; } } - + if ($domain['ssl_ca_file'] != '') { // check for existence, #1485 if (! file_exists($domain['ssl_ca_file'])) { @@ -499,7 +499,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCACertificateFile ' . makeCorrectFile($domain['ssl_ca_file']) . "\n"; } } - + // #418 if ($domain['ssl_cert_chainfile'] != '') { // check for existence, #1485 @@ -519,7 +519,7 @@ class apache extends HttpConfigBase $close_vhost = false; } } - + if ($close_vhost) { $this->virtualhosts_data[$vhosts_filename] .= '' . "\n"; } @@ -527,12 +527,12 @@ class apache extends HttpConfigBase } unset($vhosts_filename); } - + /** * bug #32 */ $this->_createStandardDirectoryEntry(); - + /** * bug #unknown-yet */ @@ -550,31 +550,31 @@ class apache extends HttpConfigBase protected function composePhpOptions($domain, $ssl_vhost = false) { $php_options_text = ''; - + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { // This vHost has PHP enabled and we are using the regular mod_php $cmail = getCustomerDetail($domain['customerid'], 'email'); $php_options_text .= ' php_admin_value sendmail_path "/usr/sbin/sendmail -t -f ' . $cmail . '"' . PHP_EOL; - + if ($domain['openbasedir'] == '1') { if ($domain['openbasedir_path'] == '1' || strstr($domain['documentroot'], ":") !== false) { $_phpappendopenbasedir = appendOpenBasedirPath($domain['customerroot'], true); } else { $_phpappendopenbasedir = appendOpenBasedirPath($domain['documentroot'], true); } - + $_custom_openbasedir = explode(':', Settings::Get('system.phpappendopenbasedir')); foreach ($_custom_openbasedir as $cobd) { $_phpappendopenbasedir .= appendOpenBasedirPath($cobd); } - + $php_options_text .= ' php_admin_value open_basedir "' . $_phpappendopenbasedir . '"' . "\n"; } } else { $php_options_text .= ' # PHP is disabled for this vHost' . "\n"; $php_options_text .= ' php_flag engine off' . "\n"; } - + /** * check for apache-itk-support, #1400 * why is this here? Because it only works with mod_php @@ -584,7 +584,7 @@ class apache extends HttpConfigBase $php_options_text .= ' AssignUserID ' . $domain['loginname'] . ' ' . $domain['loginname'] . "\n"; $php_options_text .= ' ' . "\n"; } - + return $php_options_text; } @@ -597,18 +597,18 @@ class apache extends HttpConfigBase protected function getServerNames($domain) { $servernames_text = ' ServerName ' . $domain['domain'] . "\n"; - + $server_alias = ''; if ($domain['iswildcarddomain'] == '1') { $server_alias = '*.' . $domain['domain']; } elseif ($domain['wwwserveralias'] == '1') { $server_alias = 'www.' . $domain['domain']; } - + if (trim($server_alias) != '') { $servernames_text .= ' ServerAlias ' . $server_alias . "\n"; } - + $alias_domains_stmt = Database::prepare(" SELECT `domain`, `iswildcarddomain`, `wwwserveralias` FROM `" . TABLE_PANEL_DOMAINS . "` @@ -617,10 +617,10 @@ class apache extends HttpConfigBase Database::pexecute($alias_domains_stmt, array( 'domainid' => $domain['id'] )); - + while (($alias_domain = $alias_domains_stmt->fetch(PDO::FETCH_ASSOC)) !== false) { $server_alias = ' ServerAlias ' . $alias_domain['domain']; - + if ($alias_domain['iswildcarddomain'] == '1') { $server_alias .= ' *.' . $alias_domain['domain']; } else { @@ -628,10 +628,10 @@ class apache extends HttpConfigBase $server_alias .= ' www.' . $alias_domain['domain']; } } - + $servernames_text .= $server_alias . "\n"; } - + $servernames_text .= ' ServerAdmin ' . $domain['email'] . "\n"; return $servernames_text; } @@ -644,7 +644,7 @@ class apache extends HttpConfigBase $webroot_text = ''; $domain['customerroot'] = makeCorrectDir($domain['customerroot']); $domain['documentroot'] = makeCorrectDir($domain['documentroot']); - + if ($domain['deactivated'] == '1' && Settings::Get('system.deactivateddocroot') != '') { $webroot_text .= ' # Using docroot for deactivated users...' . "\n"; $webroot_text .= ' DocumentRoot "' . makeCorrectDir(Settings::Get('system.deactivateddocroot')) . "\"\n"; @@ -663,7 +663,7 @@ class apache extends HttpConfigBase $webroot_text .= ' DocumentRoot "' . $domain['documentroot'] . "\"\n"; $this->_deactivated = false; } - + return $webroot_text; } @@ -673,7 +673,7 @@ class apache extends HttpConfigBase protected function getStats($domain) { $stats_text = ''; - + if ($domain['speciallogfile'] == '1') { $statDomain = ($domain['parentdomainid'] == '0') ? $domain['domain'] : $domain['parentdomain']; if (Settings::Get('system.awstats_enabled') == '1') { @@ -699,7 +699,7 @@ class apache extends HttpConfigBase $stats_text .= ' Alias /awstats-icon "' . makeCorrectDir(Settings::Get('system.awstats_icons')) . '"' . "\n"; } } - + return $stats_text; } @@ -709,7 +709,7 @@ class apache extends HttpConfigBase protected function getLogfiles($domain) { $logfiles_text = ''; - + if ($domain['speciallogfile'] == '1') { if ($domain['parentdomainid'] == '0') { $speciallogfile = '-' . $domain['domain']; @@ -719,23 +719,23 @@ class apache extends HttpConfigBase } else { $speciallogfile = ''; } - + // The normal access/error - logging is enabled $error_log = makeCorrectFile(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-error.log'); // Create the logfile if it does not exist (fixes #46) touch($error_log); chown($error_log, Settings::Get('system.httpuser')); chgrp($error_log, Settings::Get('system.httpgroup')); - + $access_log = makeCorrectFile(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-access.log'); // Create the logfile if it does not exist (fixes #46) touch($access_log); chown($access_log, Settings::Get('system.httpuser')); chgrp($access_log, Settings::Get('system.httpgroup')); - + $logfiles_text .= ' ErrorLog "' . $error_log . "\"\n"; $logfiles_text .= ' CustomLog "' . $access_log . '" combined' . "\n"; - + if (Settings::Get('system.awstats_enabled') == '1') { if ((int) $domain['parentdomainid'] == 0) { // prepare the aliases and subdomains for stats config files @@ -748,25 +748,25 @@ class apache extends HttpConfigBase Database::pexecute($alias_domains_stmt, array( 'domainid' => $domain['id'] )); - + while (($alias_domain = $alias_domains_stmt->fetch(PDO::FETCH_ASSOC)) !== false) { - + $server_alias .= ' ' . $alias_domain['domain'] . ' '; - + if ($alias_domain['iswildcarddomain'] == '1') { $server_alias .= '*.' . $alias_domain['domain']; } elseif ($alias_domain['wwwserveralias'] == '1') { $server_alias .= 'www.' . $alias_domain['domain']; } } - + $alias = ''; if ($domain['iswildcarddomain'] == '1') { $alias = '*.' . $domain['domain']; } elseif ($domain['wwwserveralias'] == '1') { $alias = 'www.' . $domain['domain']; } - + // After inserting the AWStats information, // be sure to build the awstats conf file as well // and chown it using $awstats_params, #258 @@ -774,7 +774,7 @@ class apache extends HttpConfigBase createAWStatsConf(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-access.log', $domain['domain'], $alias . $server_alias, $domain['customerroot'], $domain); } } - + return $logfiles_text; } @@ -791,13 +791,13 @@ class apache extends HttpConfigBase // number of dots in a domain specifies it's position (and depth of subdomain) starting at 29 going downwards on higher depth $vhost_no = (string) (30 - substr_count($domain['domain'], ".") + 1); } - + if ($ssl_vhost === true) { $vhost_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/' . $vhost_no . '_froxlor_ssl_vhost_' . $domain['domain'] . '.conf'); } else { $vhost_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/' . $vhost_no . '_froxlor_normal_vhost_' . $domain['domain'] . '.conf'); } - + return $vhost_filename; } @@ -809,27 +809,27 @@ class apache extends HttpConfigBase if ($ssl_vhost === true && ($domain['ssl_redirect'] != '1' && $domain['ssl'] != '1')) { return ''; } - + $query = "SELECT * FROM `" . TABLE_PANEL_IPSANDPORTS . "` `i`, `" . TABLE_DOMAINTOIP . "` `dip` WHERE dip.id_domain = :domainid AND i.id = dip.id_ipandports "; - + if ($ssl_vhost === true && ($domain['ssl'] == '1' || $domain['ssl_redirect'] == '1')) { // by ordering by cert-file the row with filled out SSL-Fields will be shown last, thus it is enough to fill out 1 set of SSL-Fields $query .= "AND i.ssl = '1' ORDER BY i.ssl_cert_file ASC;"; } else { $query .= "AND i.ssl = '0';"; } - + $vhost_content = ''; $result_stmt = Database::prepare($query); Database::pexecute($result_stmt, array( 'domainid' => $domain['id'] )); - + $ipportlist = ''; $_vhost_content = ''; while ($ipandport = $result_stmt->fetch(PDO::FETCH_ASSOC)) { - + $ipport = ''; $domain['ip'] = $ipandport['ip']; $domain['port'] = $ipandport['port']; @@ -838,29 +838,29 @@ class apache extends HttpConfigBase $domain['ssl_key_file'] = $ipandport['ssl_key_file']; $domain['ssl_ca_file'] = $ipandport['ssl_ca_file']; $domain['ssl_cert_chainfile'] = $ipandport['ssl_cert_chainfile']; - + // SSL STUFF $dssl = new DomainSSL(); // this sets the ssl-related array-indices in the $domain array // if the domain has customer-defined ssl-certificates $dssl->setDomainSSLFilesArray($domain); } - + if (filter_var($domain['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $ipport = '[' . $domain['ip'] . ']:' . $domain['port'] . ' '; } else { $ipport = $domain['ip'] . ':' . $domain['port'] . ' '; } - + if ($ipandport['default_vhostconf_domain'] != '') { $_vhost_content .= $this->processSpecialConfigTemplate($ipandport['default_vhostconf_domain'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } $ipportlist .= $ipport; } - + $vhost_content .= '' . "\n"; $vhost_content .= $this->getServerNames($domain); - + $domain['documentroot_norewrite'] = $domain['documentroot']; if (($ssl_vhost == false && $domain['ssl'] == '1' && $domain['ssl_redirect'] == '1')) { // We must not check if our port differs from port 443, @@ -879,37 +879,37 @@ class apache extends HttpConfigBase $ssldestport = Database::pexecute_first($ssldestport_stmt, array( 'domainid' => $domain['id'] )); - + if ($ssldestport['port'] != '') { $_sslport = ":" . $ssldestport['port']; } - + $domain['documentroot'] = 'https://%{HTTP_HOST}' . $_sslport . '/'; $domain['documentroot_norewrite'] = 'https://' . $domain['domain'] . $_sslport . '/'; } - + if ($ssl_vhost === true && $domain['ssl'] == '1' && Settings::Get('system.use_ssl') == '1') { if ($domain['ssl_cert_file'] == '') { $domain['ssl_cert_file'] = Settings::Get('system.ssl_cert_file'); } - + if ($domain['ssl_key_file'] == '') { $domain['ssl_key_file'] = Settings::Get('system.ssl_key_file'); } - + if ($domain['ssl_ca_file'] == '') { $domain['ssl_ca_file'] = Settings::Get('system.ssl_ca_file'); } - + if ($domain['ssl_cert_chainfile'] == '') { $domain['ssl_cert_chainfile'] = Settings::Get('system.ssl_cert_chainfile'); } - + if ($domain['ssl_cert_file'] != '') { $vhost_content .= ' SSLEngine On' . "\n"; $vhost_content .= ' SSLProtocol -ALL +' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { - if (isset($domain['http2']) && $domain['http2'] == '1') { + if (isset($domain['http2']) && $domain['http2'] == '1' && Settings::Get('system.http2_support') == '1') { $vhost_content .= ' Protocols h2 http/1.1' . "\n"; } $vhost_content .= ' SSLCompression Off' . "\n"; @@ -919,23 +919,23 @@ class apache extends HttpConfigBase $vhost_content .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; $vhost_content .= ' SSLVerifyDepth 10' . "\n"; $vhost_content .= ' SSLCertificateFile ' . makeCorrectFile($domain['ssl_cert_file']) . "\n"; - + if ($domain['ssl_key_file'] != '') { $vhost_content .= ' SSLCertificateKeyFile ' . makeCorrectFile($domain['ssl_key_file']) . "\n"; } - + if ($domain['ssl_ca_file'] != '') { $vhost_content .= ' SSLCACertificateFile ' . makeCorrectFile($domain['ssl_ca_file']) . "\n"; } - + if ($domain['ssl_cert_chainfile'] != '') { $vhost_content .= ' SSLCertificateChainFile ' . makeCorrectFile($domain['ssl_cert_chainfile']) . "\n"; } - + if (Settings::Get('system.apache24') == '1' && isset($domain['ocsp_stapling']) && $domain['ocsp_stapling'] == '1') { $vhost_content .= ' SSLUseStapling on' . PHP_EOL; } - + if ($domain['hsts'] >= 0) { $vhost_content .= ' ' . "\n"; $vhost_content .= ' Header always set Strict-Transport-Security "max-age=' . $domain['hsts']; @@ -955,20 +955,20 @@ class apache extends HttpConfigBase return '# no ssl-certificate was specified for this domain, therefore no explicit vhost is being generated'; } } - + // avoid using any whitespaces $domain['documentroot'] = trim($domain['documentroot']); - + if (preg_match('/^https?\:\/\//', $domain['documentroot'])) { $corrected_docroot = $domain['documentroot']; - + // Get domain's redirect code $code = getDomainRedirectCode($domain['id'], '301'); $modrew_red = ''; if ($code != '') { $modrew_red = ' [R=' . $code . ';L,NE]'; } - + // redirect everything, not only root-directory, #541 $vhost_content .= ' ' . "\n"; $vhost_content .= ' RewriteEngine On' . "\n"; @@ -984,7 +984,7 @@ class apache extends HttpConfigBase $vhost_content .= ' Redirect ' . $code . ' / ' . $domain['documentroot_norewrite'] . "\n"; $vhost_content .= ' ' . "\n"; } else { - + mkDirWithCorrectOwnership($domain['customerroot'], $domain['documentroot'], $domain['guid'], $domain['guid'], true, true); $vhost_content .= $this->getWebroot($domain); if ($this->_deactivated == false) { @@ -992,22 +992,22 @@ class apache extends HttpConfigBase $vhost_content .= $this->getStats($domain); } $vhost_content .= $this->getLogfiles($domain); - + if ($domain['specialsettings'] != '') { $vhost_content .= $this->processSpecialConfigTemplate($domain['specialsettings'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } - + if ($_vhost_content != '') { $vhost_content .= $_vhost_content; } - + if (Settings::Get('system.default_vhostconf') != '') { $vhost_content .= $this->processSpecialConfigTemplate(Settings::Get('system.default_vhostconf'), $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } } - + $vhost_content .= '' . "\n"; - + return $vhost_content; } @@ -1018,17 +1018,17 @@ class apache extends HttpConfigBase { $domains = WebserverBase::getVhostsToCreate(); foreach ($domains as $domain) { - + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::createVirtualHosts: creating vhost container for domain ' . $domain['id'] . ', customer ' . $domain['loginname']); $vhosts_filename = $this->getVhostFilename($domain); - + // Apply header $this->virtualhosts_data[$vhosts_filename] = '# Domain ID: ' . $domain['id'] . ' - CustomerID: ' . $domain['customerid'] . ' - CustomerLogin: ' . $domain['loginname'] . "\n"; - + if ($domain['deactivated'] != '1' || Settings::Get('system.deactivateddocroot') != '') { // Create vhost without ssl $this->virtualhosts_data[$vhosts_filename] .= $this->getVhostContent($domain, false); - + if ($domain['ssl'] == '1' || $domain['ssl_redirect'] == '1') { // Adding ssl stuff if enabled $vhosts_filename_ssl = $this->getVhostFilename($domain, true); @@ -1053,27 +1053,27 @@ class apache extends HttpConfigBase ORDER BY `htac`.`path` "); $diroptions = array(); - + while ($row_diroptions = $result_stmt->fetch(PDO::FETCH_ASSOC)) { if ($row_diroptions['customerid'] != 0 && isset($row_diroptions['customerroot']) && $row_diroptions['customerroot'] != '') { $diroptions[$row_diroptions['path']] = $row_diroptions; $diroptions[$row_diroptions['path']]['htpasswds'] = array(); } } - + $result_stmt = Database::query(" SELECT `htpw`.*, `c`.`guid`, `c`.`documentroot` AS `customerroot` FROM `" . TABLE_PANEL_HTPASSWDS . "` `htpw` LEFT JOIN `" . TABLE_PANEL_CUSTOMERS . "` `c` USING (`customerid`) ORDER BY `htpw`.`path`, `htpw`.`username` "); - + while ($row_htpasswds = $result_stmt->fetch(PDO::FETCH_ASSOC)) { if ($row_htpasswds['customerid'] != 0 && isset($row_htpasswds['customerroot']) && $row_htpasswds['customerroot'] != '') { if (! isset($diroptions[$row_htpasswds['path']]) || ! is_array($diroptions[$row_htpasswds['path']])) { $diroptions[$row_htpasswds['path']] = array(); } - + $diroptions[$row_htpasswds['path']]['path'] = $row_htpasswds['path']; $diroptions[$row_htpasswds['path']]['guid'] = $row_htpasswds['guid']; $diroptions[$row_htpasswds['path']]['customerroot'] = $row_htpasswds['customerroot']; @@ -1081,24 +1081,24 @@ class apache extends HttpConfigBase $diroptions[$row_htpasswds['path']]['htpasswds'][] = $row_htpasswds; } } - + foreach ($diroptions as $row_diroptions) { $row_diroptions['path'] = makeCorrectDir($row_diroptions['path']); mkDirWithCorrectOwnership($row_diroptions['customerroot'], $row_diroptions['path'], $row_diroptions['guid'], $row_diroptions['guid']); $diroptions_filename = makeCorrectFile(Settings::Get('system.apacheconf_diroptions') . '/40_froxlor_diroption_' . md5($row_diroptions['path']) . '.conf'); - + if (! isset($this->diroptions_data[$diroptions_filename])) { $this->diroptions_data[$diroptions_filename] = ''; } - + if (is_dir($row_diroptions['path'])) { $cperlenabled = customerHasPerlEnabled($row_diroptions['customerid']); - + $this->diroptions_data[$diroptions_filename] .= '' . "\n"; - + if (isset($row_diroptions['options_indexes']) && $row_diroptions['options_indexes'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' Options +Indexes'; - + // add perl options if enabled if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' +ExecCGI -MultiViews +SymLinksIfOwnerMatch +FollowSymLinks' . "\n"; @@ -1107,10 +1107,10 @@ class apache extends HttpConfigBase } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Setting Options +Indexes for ' . $row_diroptions['path']); } - + if (isset($row_diroptions['options_indexes']) && $row_diroptions['options_indexes'] == '0') { $this->diroptions_data[$diroptions_filename] .= ' Options -Indexes'; - + // add perl options if enabled if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' +ExecCGI -MultiViews +SymLinksIfOwnerMatch +FollowSymLinks' . "\n"; @@ -1119,7 +1119,7 @@ class apache extends HttpConfigBase } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Setting Options -Indexes for ' . $row_diroptions['path']); } - + $statusCodes = array( '404', '403', @@ -1136,7 +1136,7 @@ class apache extends HttpConfigBase $this->diroptions_data[$diroptions_filename] .= ' ErrorDocument ' . $statusCode . ' ' . $defhandler . "\n"; } } - + if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' AllowOverride None' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AddHandler cgi-script .cgi .pl' . "\n"; @@ -1154,18 +1154,18 @@ class apache extends HttpConfigBase $this->diroptions_data[$diroptions_filename] .= ' Allow from all' . "\n"; } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Enabling perl execution for ' . $row_diroptions['path']); - + // check for suexec-workaround, #319 if ((int) Settings::Get('perl.suexecworkaround') == 1) { // symlink this directory to suexec-safe-path $loginname = getCustomerDetail($row_diroptions['customerid'], 'loginname'); $suexecpath = makeCorrectDir(Settings::Get('perl.suexecpath') . '/' . $loginname . '/' . md5($row_diroptions['path']) . '/'); - + if (! file_exists($suexecpath)) { safe_exec('mkdir -p ' . escapeshellarg($suexecpath)); safe_exec('chown -R ' . escapeshellarg($row_diroptions['guid']) . ':' . escapeshellarg($row_diroptions['guid']) . ' ' . escapeshellarg($suexecpath)); } - + // symlink to {$givenpath}/cgi-bin // NOTE: symlinks are FILES, so do not append a / here $perlsymlink = makeCorrectFile($row_diroptions['path'] . '/cgi-bin'); @@ -1181,7 +1181,7 @@ class apache extends HttpConfigBase $loginname = getCustomerDetail($row_diroptions['customerid'], 'loginname'); $suexecpath = makeCorrectDir(Settings::Get('perl.suexecpath') . '/' . $loginname . '/' . md5($row_diroptions['path']) . '/'); $perlsymlink = makeCorrectFile($row_diroptions['path'] . '/cgi-bin'); - + // remove symlink if (file_exists($perlsymlink)) { safe_exec('rm -f ' . escapeshellarg($perlsymlink)); @@ -1192,24 +1192,24 @@ class apache extends HttpConfigBase } } } - + if (count($row_diroptions['htpasswds']) > 0) { $htpasswd_filename = makeCorrectFile(Settings::Get('system.apacheconf_htpasswddir') . '/' . $row_diroptions['customerid'] . '-' . md5($row_diroptions['path']) . '.htpasswd'); - + if (! isset($this->htpasswds_data[$htpasswd_filename])) { $this->htpasswds_data[$htpasswd_filename] = ''; } - + foreach ($row_diroptions['htpasswds'] as $row_htpasswd) { $this->htpasswds_data[$htpasswd_filename] .= $row_htpasswd['username'] . ':' . $row_htpasswd['password'] . "\n"; } - + $this->diroptions_data[$diroptions_filename] .= ' AuthType Basic' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AuthName "' . $row_htpasswd['authname'] . '"' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AuthUserFile ' . $htpasswd_filename . "\n"; $this->diroptions_data[$diroptions_filename] .= ' require valid-user' . "\n"; } - + $this->diroptions_data[$diroptions_filename] .= '' . "\n"; } } @@ -1222,19 +1222,19 @@ class apache extends HttpConfigBase { // Write diroptions $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_diroptions')); - + if (count($this->diroptions_data) > 0) { $optsDir = new frxDirectory(Settings::Get('system.apacheconf_diroptions')); if (! $optsDir->isConfigDir()) { // Save one big file $diroptions_file = ''; - + foreach ($this->diroptions_data as $diroptions_filename => $diroptions_content) { $diroptions_file .= $diroptions_content . "\n\n"; } - + $diroptions_filename = Settings::Get('system.apacheconf_diroptions'); - + // Apply header $diroptions_file = '# ' . basename($diroptions_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $diroptions_file; $diroptions_file_handler = fopen($diroptions_filename, 'w'); @@ -1245,11 +1245,11 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::writeConfigs: mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_diroptions')))); safe_exec('mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_diroptions')))); } - + // Write a single file for every diroption foreach ($this->diroptions_data as $diroptions_filename => $diroptions_file) { $this->known_diroptionsfilenames[] = basename($diroptions_filename); - + // Apply header $diroptions_file = '# ' . basename($diroptions_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $diroptions_file; $diroptions_file_handler = fopen($diroptions_filename, 'w'); @@ -1258,10 +1258,10 @@ class apache extends HttpConfigBase } } } - + // Write htpasswds $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_htpasswddir')); - + if (count($this->htpasswds_data) > 0) { if (! file_exists(Settings::Get('system.apacheconf_htpasswddir'))) { $umask = umask(); @@ -1269,7 +1269,7 @@ class apache extends HttpConfigBase mkdir(Settings::Get('system.apacheconf_htpasswddir'), 0751); umask($umask); } - + $htpasswdDir = new frxDirectory(Settings::Get('system.apacheconf_htpasswddir')); if ($htpasswdDir->isConfigDir(true)) { foreach ($this->htpasswds_data as $htpasswd_filename => $htpasswd_file) { @@ -1282,34 +1282,34 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_WARNING, 'WARNING!!! ' . Settings::Get('system.apacheconf_htpasswddir') . ' is not a directory. htpasswd directory protection is disabled!!!'); } } - + // Write virtualhosts $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_vhost')); - + if (count($this->virtualhosts_data) > 0) { $vhostDir = new frxDirectory(Settings::Get('system.apacheconf_vhost')); if (! $vhostDir->isConfigDir()) { // Save one big file $vhosts_file = ''; - + // sort by filename so the order is: // 1. subdomains x-29 // 2. subdomains as main-domains 30 // 3. main-domains 35 // #437 ksort($this->virtualhosts_data); - + foreach ($this->virtualhosts_data as $vhosts_filename => $vhost_content) { $vhosts_file .= $vhost_content . "\n\n"; } - + // Include diroptions file in case it exists if (file_exists(Settings::Get('system.apacheconf_diroptions'))) { $vhosts_file .= "\n" . 'Include ' . Settings::Get('system.apacheconf_diroptions') . "\n\n"; } - + $vhosts_filename = Settings::Get('system.apacheconf_vhost'); - + // Apply header $vhosts_file = '# ' . basename($vhosts_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $vhosts_file; $vhosts_file_handler = fopen($vhosts_filename, 'w'); @@ -1320,11 +1320,11 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::writeConfigs: mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_vhost')))); safe_exec('mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_vhost')))); } - + // Write a single file for every vhost foreach ($this->virtualhosts_data as $vhosts_filename => $vhosts_file) { $this->known_vhostfilenames[] = basename($vhosts_filename); - + // Apply header $vhosts_file = '# ' . basename($vhosts_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $vhosts_file; $vhosts_file_handler = fopen($vhosts_filename, 'w'); diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index 5c932fd1..d4d27c77 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -432,7 +432,7 @@ class nginx extends HttpConfigBase $_vhost_content .= $this->processSpecialConfigTemplate($ipandport['default_vhostconf_domain'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } - $http2 = $ssl_vhost == true && (isset($domain['http2']) && $domain['http2'] == '1'); + $http2 = $ssl_vhost == true && (isset($domain['http2']) && $domain['http2'] == '1' && Settings::Get('system.http2_support') == '1'); $vhost_content .= "\t" . 'listen ' . $ipport . ($ssl_vhost == true ? ' ssl' : '') . ($http2 == true ? ' http2' : '') . ';' . "\n"; } From ca76e572a2c0be6b92ac23684c6736da73e4b9e5 Mon Sep 17 00:00:00 2001 From: Andreas Grundler Date: Thu, 18 Jan 2018 18:18:30 +0100 Subject: [PATCH 138/179] http2 Option darf nur dann zu sehen sein wenn http2 in den Einstellungen aktiv ist --- lib/formfields/admin/domains/formfield.domains_add.php | 2 +- lib/formfields/admin/domains/formfield.domains_edit.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/formfields/admin/domains/formfield.domains_add.php b/lib/formfields/admin/domains/formfield.domains_add.php index 1976b034..71116996 100644 --- a/lib/formfields/admin/domains/formfield.domains_add.php +++ b/lib/formfields/admin/domains/formfield.domains_add.php @@ -174,7 +174,7 @@ return array( 'value' => array() ), 'http2' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false) && Settings::Get('system.webserver') != 'lighttpd', + 'visible' => ($ssl_ipsandports != '' ? true : false) && Settings::Get('system.webserver') != 'lighttpd' && Settings::Get('system.http2_support') == '1', 'label' => $lng['admin']['domain_http2']['title'], 'desc' => $lng['admin']['domain_http2']['description'], 'type' => 'checkbox', diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index 5588ab69..d37f4806 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -208,7 +208,7 @@ return array( ) ), 'http2' => array( - 'visible' => ($ssl_ipsandports != '' ? true : false) && Settings::Get('system.webserver') != 'lighttpd', + 'visible' => ($ssl_ipsandports != '' ? true : false) && Settings::Get('system.webserver') != 'lighttpd' && Settings::Get('system.http2_support') == '1', 'label' => $lng['admin']['domain_http2']['title'], 'desc' => $lng['admin']['domain_http2']['description'], 'type' => 'checkbox', From 6ac3cb2014813043388f96ced33531ecf90267d4 Mon Sep 17 00:00:00 2001 From: Andreas Grundler Date: Thu, 18 Jan 2018 18:23:08 +0100 Subject: [PATCH 139/179] =?UTF-8?q?Revert=20"http2=20Konfiguration=20nur?= =?UTF-8?q?=20einf=C3=BCgen=20wenn=20http2=20in=20den=20Einstellungen=20ak?= =?UTF-8?q?tiviert=20ist"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit c3fb6f6a1c053c3f5f0b97899fba9137b69ad7ea. --- .../jobs/cron_tasks.inc.http.10.apache.php | 306 +++++++++--------- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 2 +- 2 files changed, 154 insertions(+), 154 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 9fcf71d8..55f230d0 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -16,7 +16,7 @@ if (! defined('MASTER_CRONJOB')) * @author Froxlor team (2010-) * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt * @package Cron - * + * */ require_once (dirname(__FILE__) . '/../classes/class.HttpConfigBase.php'); @@ -91,13 +91,13 @@ class apache extends HttpConfigBase $vhosts_folder = makeCorrectDir(dirname(Settings::Get('system.apacheconf_vhost'))); } $vhosts_filename = makeCorrectFile($vhosts_folder . '/05_froxlor_dirfix_nofcgid.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; - + // check for custom values, see #1638 $custom_opts = Settings::Get('system.apacheglobaldiropt'); if (! empty($custom_opts)) { @@ -113,7 +113,7 @@ class apache extends HttpConfigBase } } $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; - + $ocsp_cache_filename = makeCorrectFile($vhosts_folder . '/03_froxlor_ocsp_cache.conf'); if (Settings::Get('system.use_ssl') == '1' && Settings::Get('system.apache24') == 1) { $this->virtualhosts_data[$ocsp_cache_filename] = 'SSLStaplingCache ' . Settings::Get('system.apache24_ocsp_cache_path') . "\n"; @@ -137,13 +137,13 @@ class apache extends HttpConfigBase } else { $vhosts_folder = makeCorrectDir(dirname(Settings::Get('system.apacheconf_vhost'))); } - + $vhosts_filename = makeCorrectFile($vhosts_folder . '/05_froxlor_default_errorhandler.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + $statusCodes = array( '401', '403', @@ -167,26 +167,26 @@ class apache extends HttpConfigBase public function createIpPort() { $result_ipsandports_stmt = Database::query("SELECT * FROM `" . TABLE_PANEL_IPSANDPORTS . "` ORDER BY `ip` ASC, `port` ASC"); - + while ($row_ipsandports = $result_ipsandports_stmt->fetch(PDO::FETCH_ASSOC)) { if (filter_var($row_ipsandports['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $ipport = '[' . $row_ipsandports['ip'] . ']:' . $row_ipsandports['port']; } else { $ipport = $row_ipsandports['ip'] . ':' . $row_ipsandports['port']; } - + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::createIpPort: creating ip/port settings for ' . $ipport); $vhosts_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/10_froxlor_ipandport_' . trim(str_replace(':', '.', $row_ipsandports['ip']), '.') . '.' . $row_ipsandports['port'] . '.conf'); - + if (! isset($this->virtualhosts_data[$vhosts_filename])) { $this->virtualhosts_data[$vhosts_filename] = ''; } - + if ($row_ipsandports['listen_statement'] == '1') { $this->virtualhosts_data[$vhosts_filename] .= 'Listen ' . $ipport . "\n"; $this->logger->logAction(CRON_ACTION, LOG_DEBUG, $ipport . ' :: inserted listen-statement'); } - + if ($row_ipsandports['namevirtualhost_statement'] == '1') { // >=apache-2.4 enabled? if (Settings::Get('system.apache24') == '1') { @@ -196,22 +196,22 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_DEBUG, $ipport . ' :: inserted namevirtualhost-statement'); } } - + if ($row_ipsandports['vhostcontainer'] == '1') { - + $without_vhost = $this->virtualhosts_data[$vhosts_filename]; $close_vhost = true; - + $this->virtualhosts_data[$vhosts_filename] .= '' . "\n"; - + $mypath = $this->getMyPath($row_ipsandports); - + $this->virtualhosts_data[$vhosts_filename] .= 'DocumentRoot "' . $mypath . '"' . "\n"; - + if ($row_ipsandports['vhostcontainer_servername_statement'] == '1') { $this->virtualhosts_data[$vhosts_filename] .= ' ServerName ' . Settings::Get('system.hostname') . "\n"; } - + $is_redirect = false; // check for SSL redirect if ($row_ipsandports['ssl'] == '0' && Settings::Get('system.le_froxlor_redirect') == '1') { @@ -223,11 +223,11 @@ class apache extends HttpConfigBase $is_redirect = false; } else { $_sslport = $this->checkAlternativeSslPort(); - + $mypath = 'https://' . Settings::Get('system.hostname') . $_sslport . '/'; $code = '301'; $modrew_red = ' [R=' . $code . ';L,NE]'; - + // redirect everything, not only root-directory, #541 $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' RewriteEngine On' . "\n"; @@ -242,7 +242,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; } } - + if (! $is_redirect) { // create fcgid -Part (starter is created in apache_fcgid) if (Settings::Get('system.mod_fcgid_ownvhost') == '1' && Settings::Get('system.mod_fcgid') == '1') { @@ -266,7 +266,7 @@ class apache extends HttpConfigBase ); $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig(Settings::Get('system.mod_fcgid_defaultini_ownvhost')); - + $starter_filename = makeCorrectFile($configdir . '/php-fcgi-starter'); $this->virtualhosts_data[$vhosts_filename] .= ' SuexecUserGroup "' . Settings::Get('system.mod_fcgid_httpuser') . '" "' . Settings::Get('system.mod_fcgid_httpgroup') . '"' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; @@ -317,14 +317,14 @@ class apache extends HttpConfigBase 'documentroot' => $mypath, 'fpm_config_id' => isset($fpm_config['id']) ? $fpm_config['id'] : 1 ); - + $php = new phpinterface($domain); $phpconfig = $php->getPhpConfig(Settings::Get('phpfpm.vhost_defaultini')); $srvName = substr(md5($ipport), 0, 4) . '.fpm.external'; if ($row_ipsandports['ssl']) { $srvName = substr(md5($ipport), 0, 4) . '.ssl-fpm.external'; } - + // mod_proxy stuff for apache-2.4 if (Settings::Get('system.apache24') == '1' && Settings::Get('phpfpm.use_mod_proxy') == '1') { $filesmatch = $phpconfig['fpm_settings']['limit_extensions']; @@ -401,7 +401,7 @@ class apache extends HttpConfigBase 'documentroot' => $mypath ); } - + /** * dirprotection, see #72 * @@ -410,36 +410,36 @@ class apache extends HttpConfigBase * $this->virtualhosts_data[$vhosts_filename] .= "\t\tAllow from all\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tOptions -Indexes\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; - * + * * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tOrder Deny,Allow\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\tDeny from All\n"; * $this->virtualhosts_data[$vhosts_filename] .= "\t\n"; * end of dirprotection */ - + if ($row_ipsandports['specialsettings'] != '') { $this->virtualhosts_data[$vhosts_filename] .= $this->processSpecialConfigTemplate($row_ipsandports['specialsettings'], $domain, $row_ipsandports['ip'], $row_ipsandports['port'], $row_ipsandports['ssl'] == '1') . "\n"; } - + if ($row_ipsandports['ssl'] == '1' && Settings::Get('system.use_ssl') == '1') { if ($row_ipsandports['ssl_cert_file'] == '') { $row_ipsandports['ssl_cert_file'] = Settings::Get('system.ssl_cert_file'); } - + if ($row_ipsandports['ssl_key_file'] == '') { $row_ipsandports['ssl_key_file'] = Settings::Get('system.ssl_key_file'); } - + if ($row_ipsandports['ssl_ca_file'] == '') { $row_ipsandports['ssl_ca_file'] = Settings::Get('system.ssl_ca_file'); } - + // #418 if ($row_ipsandports['ssl_cert_chainfile'] == '') { $row_ipsandports['ssl_cert_chainfile'] = Settings::Get('system.ssl_cert_chainfile'); } - + $domain = array( 'id' => 0, 'domain' => Settings::Get('system.hostname'), @@ -448,26 +448,26 @@ class apache extends HttpConfigBase 'documentroot' => $mypath, 'parentdomainid' => 0 ); - + // override corresponding array values $domain['ssl_cert_file'] = $row_ipsandports['ssl_cert_file']; $domain['ssl_key_file'] = $row_ipsandports['ssl_key_file']; $domain['ssl_ca_file'] = $row_ipsandports['ssl_ca_file']; $domain['ssl_cert_chainfile'] = $row_ipsandports['ssl_cert_chainfile']; - + // SSL STUFF $dssl = new DomainSSL(); // this sets the ssl-related array-indices in the $domain array // if the domain has customer-defined ssl-certificates $dssl->setDomainSSLFilesArray($domain); - + if ($domain['ssl_cert_file'] != '') { - + // check for existence, #1485 if (! file_exists($domain['ssl_cert_file'])) { $this->logger->logAction(CRON_ACTION, LOG_ERR, $ipport . ' :: certificate file "' . $domain['ssl_cert_file'] . '" does not exist! Cannot create ssl-directives'); } else { - + $this->virtualhosts_data[$vhosts_filename] .= ' SSLEngine On' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLProtocol -ALL +' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { @@ -481,7 +481,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLVerifyDepth 10' . "\n"; $this->virtualhosts_data[$vhosts_filename] .= ' SSLCertificateFile ' . makeCorrectFile($domain['ssl_cert_file']) . "\n"; - + if ($domain['ssl_key_file'] != '') { // check for existence, #1485 if (! file_exists($domain['ssl_key_file'])) { @@ -490,7 +490,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCertificateKeyFile ' . makeCorrectFile($domain['ssl_key_file']) . "\n"; } } - + if ($domain['ssl_ca_file'] != '') { // check for existence, #1485 if (! file_exists($domain['ssl_ca_file'])) { @@ -499,7 +499,7 @@ class apache extends HttpConfigBase $this->virtualhosts_data[$vhosts_filename] .= ' SSLCACertificateFile ' . makeCorrectFile($domain['ssl_ca_file']) . "\n"; } } - + // #418 if ($domain['ssl_cert_chainfile'] != '') { // check for existence, #1485 @@ -519,7 +519,7 @@ class apache extends HttpConfigBase $close_vhost = false; } } - + if ($close_vhost) { $this->virtualhosts_data[$vhosts_filename] .= '' . "\n"; } @@ -527,12 +527,12 @@ class apache extends HttpConfigBase } unset($vhosts_filename); } - + /** * bug #32 */ $this->_createStandardDirectoryEntry(); - + /** * bug #unknown-yet */ @@ -550,31 +550,31 @@ class apache extends HttpConfigBase protected function composePhpOptions($domain, $ssl_vhost = false) { $php_options_text = ''; - + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { // This vHost has PHP enabled and we are using the regular mod_php $cmail = getCustomerDetail($domain['customerid'], 'email'); $php_options_text .= ' php_admin_value sendmail_path "/usr/sbin/sendmail -t -f ' . $cmail . '"' . PHP_EOL; - + if ($domain['openbasedir'] == '1') { if ($domain['openbasedir_path'] == '1' || strstr($domain['documentroot'], ":") !== false) { $_phpappendopenbasedir = appendOpenBasedirPath($domain['customerroot'], true); } else { $_phpappendopenbasedir = appendOpenBasedirPath($domain['documentroot'], true); } - + $_custom_openbasedir = explode(':', Settings::Get('system.phpappendopenbasedir')); foreach ($_custom_openbasedir as $cobd) { $_phpappendopenbasedir .= appendOpenBasedirPath($cobd); } - + $php_options_text .= ' php_admin_value open_basedir "' . $_phpappendopenbasedir . '"' . "\n"; } } else { $php_options_text .= ' # PHP is disabled for this vHost' . "\n"; $php_options_text .= ' php_flag engine off' . "\n"; } - + /** * check for apache-itk-support, #1400 * why is this here? Because it only works with mod_php @@ -584,7 +584,7 @@ class apache extends HttpConfigBase $php_options_text .= ' AssignUserID ' . $domain['loginname'] . ' ' . $domain['loginname'] . "\n"; $php_options_text .= ' ' . "\n"; } - + return $php_options_text; } @@ -597,18 +597,18 @@ class apache extends HttpConfigBase protected function getServerNames($domain) { $servernames_text = ' ServerName ' . $domain['domain'] . "\n"; - + $server_alias = ''; if ($domain['iswildcarddomain'] == '1') { $server_alias = '*.' . $domain['domain']; } elseif ($domain['wwwserveralias'] == '1') { $server_alias = 'www.' . $domain['domain']; } - + if (trim($server_alias) != '') { $servernames_text .= ' ServerAlias ' . $server_alias . "\n"; } - + $alias_domains_stmt = Database::prepare(" SELECT `domain`, `iswildcarddomain`, `wwwserveralias` FROM `" . TABLE_PANEL_DOMAINS . "` @@ -617,10 +617,10 @@ class apache extends HttpConfigBase Database::pexecute($alias_domains_stmt, array( 'domainid' => $domain['id'] )); - + while (($alias_domain = $alias_domains_stmt->fetch(PDO::FETCH_ASSOC)) !== false) { $server_alias = ' ServerAlias ' . $alias_domain['domain']; - + if ($alias_domain['iswildcarddomain'] == '1') { $server_alias .= ' *.' . $alias_domain['domain']; } else { @@ -628,10 +628,10 @@ class apache extends HttpConfigBase $server_alias .= ' www.' . $alias_domain['domain']; } } - + $servernames_text .= $server_alias . "\n"; } - + $servernames_text .= ' ServerAdmin ' . $domain['email'] . "\n"; return $servernames_text; } @@ -644,7 +644,7 @@ class apache extends HttpConfigBase $webroot_text = ''; $domain['customerroot'] = makeCorrectDir($domain['customerroot']); $domain['documentroot'] = makeCorrectDir($domain['documentroot']); - + if ($domain['deactivated'] == '1' && Settings::Get('system.deactivateddocroot') != '') { $webroot_text .= ' # Using docroot for deactivated users...' . "\n"; $webroot_text .= ' DocumentRoot "' . makeCorrectDir(Settings::Get('system.deactivateddocroot')) . "\"\n"; @@ -663,7 +663,7 @@ class apache extends HttpConfigBase $webroot_text .= ' DocumentRoot "' . $domain['documentroot'] . "\"\n"; $this->_deactivated = false; } - + return $webroot_text; } @@ -673,7 +673,7 @@ class apache extends HttpConfigBase protected function getStats($domain) { $stats_text = ''; - + if ($domain['speciallogfile'] == '1') { $statDomain = ($domain['parentdomainid'] == '0') ? $domain['domain'] : $domain['parentdomain']; if (Settings::Get('system.awstats_enabled') == '1') { @@ -699,7 +699,7 @@ class apache extends HttpConfigBase $stats_text .= ' Alias /awstats-icon "' . makeCorrectDir(Settings::Get('system.awstats_icons')) . '"' . "\n"; } } - + return $stats_text; } @@ -709,7 +709,7 @@ class apache extends HttpConfigBase protected function getLogfiles($domain) { $logfiles_text = ''; - + if ($domain['speciallogfile'] == '1') { if ($domain['parentdomainid'] == '0') { $speciallogfile = '-' . $domain['domain']; @@ -719,23 +719,23 @@ class apache extends HttpConfigBase } else { $speciallogfile = ''; } - + // The normal access/error - logging is enabled $error_log = makeCorrectFile(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-error.log'); // Create the logfile if it does not exist (fixes #46) touch($error_log); chown($error_log, Settings::Get('system.httpuser')); chgrp($error_log, Settings::Get('system.httpgroup')); - + $access_log = makeCorrectFile(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-access.log'); // Create the logfile if it does not exist (fixes #46) touch($access_log); chown($access_log, Settings::Get('system.httpuser')); chgrp($access_log, Settings::Get('system.httpgroup')); - + $logfiles_text .= ' ErrorLog "' . $error_log . "\"\n"; $logfiles_text .= ' CustomLog "' . $access_log . '" combined' . "\n"; - + if (Settings::Get('system.awstats_enabled') == '1') { if ((int) $domain['parentdomainid'] == 0) { // prepare the aliases and subdomains for stats config files @@ -748,25 +748,25 @@ class apache extends HttpConfigBase Database::pexecute($alias_domains_stmt, array( 'domainid' => $domain['id'] )); - + while (($alias_domain = $alias_domains_stmt->fetch(PDO::FETCH_ASSOC)) !== false) { - + $server_alias .= ' ' . $alias_domain['domain'] . ' '; - + if ($alias_domain['iswildcarddomain'] == '1') { $server_alias .= '*.' . $alias_domain['domain']; } elseif ($alias_domain['wwwserveralias'] == '1') { $server_alias .= 'www.' . $alias_domain['domain']; } } - + $alias = ''; if ($domain['iswildcarddomain'] == '1') { $alias = '*.' . $domain['domain']; } elseif ($domain['wwwserveralias'] == '1') { $alias = 'www.' . $domain['domain']; } - + // After inserting the AWStats information, // be sure to build the awstats conf file as well // and chown it using $awstats_params, #258 @@ -774,7 +774,7 @@ class apache extends HttpConfigBase createAWStatsConf(Settings::Get('system.logfiles_directory') . $domain['loginname'] . $speciallogfile . '-access.log', $domain['domain'], $alias . $server_alias, $domain['customerroot'], $domain); } } - + return $logfiles_text; } @@ -791,13 +791,13 @@ class apache extends HttpConfigBase // number of dots in a domain specifies it's position (and depth of subdomain) starting at 29 going downwards on higher depth $vhost_no = (string) (30 - substr_count($domain['domain'], ".") + 1); } - + if ($ssl_vhost === true) { $vhost_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/' . $vhost_no . '_froxlor_ssl_vhost_' . $domain['domain'] . '.conf'); } else { $vhost_filename = makeCorrectFile(Settings::Get('system.apacheconf_vhost') . '/' . $vhost_no . '_froxlor_normal_vhost_' . $domain['domain'] . '.conf'); } - + return $vhost_filename; } @@ -809,27 +809,27 @@ class apache extends HttpConfigBase if ($ssl_vhost === true && ($domain['ssl_redirect'] != '1' && $domain['ssl'] != '1')) { return ''; } - + $query = "SELECT * FROM `" . TABLE_PANEL_IPSANDPORTS . "` `i`, `" . TABLE_DOMAINTOIP . "` `dip` WHERE dip.id_domain = :domainid AND i.id = dip.id_ipandports "; - + if ($ssl_vhost === true && ($domain['ssl'] == '1' || $domain['ssl_redirect'] == '1')) { // by ordering by cert-file the row with filled out SSL-Fields will be shown last, thus it is enough to fill out 1 set of SSL-Fields $query .= "AND i.ssl = '1' ORDER BY i.ssl_cert_file ASC;"; } else { $query .= "AND i.ssl = '0';"; } - + $vhost_content = ''; $result_stmt = Database::prepare($query); Database::pexecute($result_stmt, array( 'domainid' => $domain['id'] )); - + $ipportlist = ''; $_vhost_content = ''; while ($ipandport = $result_stmt->fetch(PDO::FETCH_ASSOC)) { - + $ipport = ''; $domain['ip'] = $ipandport['ip']; $domain['port'] = $ipandport['port']; @@ -838,29 +838,29 @@ class apache extends HttpConfigBase $domain['ssl_key_file'] = $ipandport['ssl_key_file']; $domain['ssl_ca_file'] = $ipandport['ssl_ca_file']; $domain['ssl_cert_chainfile'] = $ipandport['ssl_cert_chainfile']; - + // SSL STUFF $dssl = new DomainSSL(); // this sets the ssl-related array-indices in the $domain array // if the domain has customer-defined ssl-certificates $dssl->setDomainSSLFilesArray($domain); } - + if (filter_var($domain['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $ipport = '[' . $domain['ip'] . ']:' . $domain['port'] . ' '; } else { $ipport = $domain['ip'] . ':' . $domain['port'] . ' '; } - + if ($ipandport['default_vhostconf_domain'] != '') { $_vhost_content .= $this->processSpecialConfigTemplate($ipandport['default_vhostconf_domain'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } $ipportlist .= $ipport; } - + $vhost_content .= '' . "\n"; $vhost_content .= $this->getServerNames($domain); - + $domain['documentroot_norewrite'] = $domain['documentroot']; if (($ssl_vhost == false && $domain['ssl'] == '1' && $domain['ssl_redirect'] == '1')) { // We must not check if our port differs from port 443, @@ -879,37 +879,37 @@ class apache extends HttpConfigBase $ssldestport = Database::pexecute_first($ssldestport_stmt, array( 'domainid' => $domain['id'] )); - + if ($ssldestport['port'] != '') { $_sslport = ":" . $ssldestport['port']; } - + $domain['documentroot'] = 'https://%{HTTP_HOST}' . $_sslport . '/'; $domain['documentroot_norewrite'] = 'https://' . $domain['domain'] . $_sslport . '/'; } - + if ($ssl_vhost === true && $domain['ssl'] == '1' && Settings::Get('system.use_ssl') == '1') { if ($domain['ssl_cert_file'] == '') { $domain['ssl_cert_file'] = Settings::Get('system.ssl_cert_file'); } - + if ($domain['ssl_key_file'] == '') { $domain['ssl_key_file'] = Settings::Get('system.ssl_key_file'); } - + if ($domain['ssl_ca_file'] == '') { $domain['ssl_ca_file'] = Settings::Get('system.ssl_ca_file'); } - + if ($domain['ssl_cert_chainfile'] == '') { $domain['ssl_cert_chainfile'] = Settings::Get('system.ssl_cert_chainfile'); } - + if ($domain['ssl_cert_file'] != '') { $vhost_content .= ' SSLEngine On' . "\n"; $vhost_content .= ' SSLProtocol -ALL +' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { - if (isset($domain['http2']) && $domain['http2'] == '1' && Settings::Get('system.http2_support') == '1') { + if (isset($domain['http2']) && $domain['http2'] == '1') { $vhost_content .= ' Protocols h2 http/1.1' . "\n"; } $vhost_content .= ' SSLCompression Off' . "\n"; @@ -919,23 +919,23 @@ class apache extends HttpConfigBase $vhost_content .= ' SSLCipherSuite ' . Settings::Get('system.ssl_cipher_list') . "\n"; $vhost_content .= ' SSLVerifyDepth 10' . "\n"; $vhost_content .= ' SSLCertificateFile ' . makeCorrectFile($domain['ssl_cert_file']) . "\n"; - + if ($domain['ssl_key_file'] != '') { $vhost_content .= ' SSLCertificateKeyFile ' . makeCorrectFile($domain['ssl_key_file']) . "\n"; } - + if ($domain['ssl_ca_file'] != '') { $vhost_content .= ' SSLCACertificateFile ' . makeCorrectFile($domain['ssl_ca_file']) . "\n"; } - + if ($domain['ssl_cert_chainfile'] != '') { $vhost_content .= ' SSLCertificateChainFile ' . makeCorrectFile($domain['ssl_cert_chainfile']) . "\n"; } - + if (Settings::Get('system.apache24') == '1' && isset($domain['ocsp_stapling']) && $domain['ocsp_stapling'] == '1') { $vhost_content .= ' SSLUseStapling on' . PHP_EOL; } - + if ($domain['hsts'] >= 0) { $vhost_content .= ' ' . "\n"; $vhost_content .= ' Header always set Strict-Transport-Security "max-age=' . $domain['hsts']; @@ -955,20 +955,20 @@ class apache extends HttpConfigBase return '# no ssl-certificate was specified for this domain, therefore no explicit vhost is being generated'; } } - + // avoid using any whitespaces $domain['documentroot'] = trim($domain['documentroot']); - + if (preg_match('/^https?\:\/\//', $domain['documentroot'])) { $corrected_docroot = $domain['documentroot']; - + // Get domain's redirect code $code = getDomainRedirectCode($domain['id'], '301'); $modrew_red = ''; if ($code != '') { $modrew_red = ' [R=' . $code . ';L,NE]'; } - + // redirect everything, not only root-directory, #541 $vhost_content .= ' ' . "\n"; $vhost_content .= ' RewriteEngine On' . "\n"; @@ -984,7 +984,7 @@ class apache extends HttpConfigBase $vhost_content .= ' Redirect ' . $code . ' / ' . $domain['documentroot_norewrite'] . "\n"; $vhost_content .= ' ' . "\n"; } else { - + mkDirWithCorrectOwnership($domain['customerroot'], $domain['documentroot'], $domain['guid'], $domain['guid'], true, true); $vhost_content .= $this->getWebroot($domain); if ($this->_deactivated == false) { @@ -992,22 +992,22 @@ class apache extends HttpConfigBase $vhost_content .= $this->getStats($domain); } $vhost_content .= $this->getLogfiles($domain); - + if ($domain['specialsettings'] != '') { $vhost_content .= $this->processSpecialConfigTemplate($domain['specialsettings'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } - + if ($_vhost_content != '') { $vhost_content .= $_vhost_content; } - + if (Settings::Get('system.default_vhostconf') != '') { $vhost_content .= $this->processSpecialConfigTemplate(Settings::Get('system.default_vhostconf'), $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } } - + $vhost_content .= '' . "\n"; - + return $vhost_content; } @@ -1018,17 +1018,17 @@ class apache extends HttpConfigBase { $domains = WebserverBase::getVhostsToCreate(); foreach ($domains as $domain) { - + $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::createVirtualHosts: creating vhost container for domain ' . $domain['id'] . ', customer ' . $domain['loginname']); $vhosts_filename = $this->getVhostFilename($domain); - + // Apply header $this->virtualhosts_data[$vhosts_filename] = '# Domain ID: ' . $domain['id'] . ' - CustomerID: ' . $domain['customerid'] . ' - CustomerLogin: ' . $domain['loginname'] . "\n"; - + if ($domain['deactivated'] != '1' || Settings::Get('system.deactivateddocroot') != '') { // Create vhost without ssl $this->virtualhosts_data[$vhosts_filename] .= $this->getVhostContent($domain, false); - + if ($domain['ssl'] == '1' || $domain['ssl_redirect'] == '1') { // Adding ssl stuff if enabled $vhosts_filename_ssl = $this->getVhostFilename($domain, true); @@ -1053,27 +1053,27 @@ class apache extends HttpConfigBase ORDER BY `htac`.`path` "); $diroptions = array(); - + while ($row_diroptions = $result_stmt->fetch(PDO::FETCH_ASSOC)) { if ($row_diroptions['customerid'] != 0 && isset($row_diroptions['customerroot']) && $row_diroptions['customerroot'] != '') { $diroptions[$row_diroptions['path']] = $row_diroptions; $diroptions[$row_diroptions['path']]['htpasswds'] = array(); } } - + $result_stmt = Database::query(" SELECT `htpw`.*, `c`.`guid`, `c`.`documentroot` AS `customerroot` FROM `" . TABLE_PANEL_HTPASSWDS . "` `htpw` LEFT JOIN `" . TABLE_PANEL_CUSTOMERS . "` `c` USING (`customerid`) ORDER BY `htpw`.`path`, `htpw`.`username` "); - + while ($row_htpasswds = $result_stmt->fetch(PDO::FETCH_ASSOC)) { if ($row_htpasswds['customerid'] != 0 && isset($row_htpasswds['customerroot']) && $row_htpasswds['customerroot'] != '') { if (! isset($diroptions[$row_htpasswds['path']]) || ! is_array($diroptions[$row_htpasswds['path']])) { $diroptions[$row_htpasswds['path']] = array(); } - + $diroptions[$row_htpasswds['path']]['path'] = $row_htpasswds['path']; $diroptions[$row_htpasswds['path']]['guid'] = $row_htpasswds['guid']; $diroptions[$row_htpasswds['path']]['customerroot'] = $row_htpasswds['customerroot']; @@ -1081,24 +1081,24 @@ class apache extends HttpConfigBase $diroptions[$row_htpasswds['path']]['htpasswds'][] = $row_htpasswds; } } - + foreach ($diroptions as $row_diroptions) { $row_diroptions['path'] = makeCorrectDir($row_diroptions['path']); mkDirWithCorrectOwnership($row_diroptions['customerroot'], $row_diroptions['path'], $row_diroptions['guid'], $row_diroptions['guid']); $diroptions_filename = makeCorrectFile(Settings::Get('system.apacheconf_diroptions') . '/40_froxlor_diroption_' . md5($row_diroptions['path']) . '.conf'); - + if (! isset($this->diroptions_data[$diroptions_filename])) { $this->diroptions_data[$diroptions_filename] = ''; } - + if (is_dir($row_diroptions['path'])) { $cperlenabled = customerHasPerlEnabled($row_diroptions['customerid']); - + $this->diroptions_data[$diroptions_filename] .= '' . "\n"; - + if (isset($row_diroptions['options_indexes']) && $row_diroptions['options_indexes'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' Options +Indexes'; - + // add perl options if enabled if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' +ExecCGI -MultiViews +SymLinksIfOwnerMatch +FollowSymLinks' . "\n"; @@ -1107,10 +1107,10 @@ class apache extends HttpConfigBase } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Setting Options +Indexes for ' . $row_diroptions['path']); } - + if (isset($row_diroptions['options_indexes']) && $row_diroptions['options_indexes'] == '0') { $this->diroptions_data[$diroptions_filename] .= ' Options -Indexes'; - + // add perl options if enabled if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' +ExecCGI -MultiViews +SymLinksIfOwnerMatch +FollowSymLinks' . "\n"; @@ -1119,7 +1119,7 @@ class apache extends HttpConfigBase } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Setting Options -Indexes for ' . $row_diroptions['path']); } - + $statusCodes = array( '404', '403', @@ -1136,7 +1136,7 @@ class apache extends HttpConfigBase $this->diroptions_data[$diroptions_filename] .= ' ErrorDocument ' . $statusCode . ' ' . $defhandler . "\n"; } } - + if ($cperlenabled && isset($row_diroptions['options_cgi']) && $row_diroptions['options_cgi'] == '1') { $this->diroptions_data[$diroptions_filename] .= ' AllowOverride None' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AddHandler cgi-script .cgi .pl' . "\n"; @@ -1154,18 +1154,18 @@ class apache extends HttpConfigBase $this->diroptions_data[$diroptions_filename] .= ' Allow from all' . "\n"; } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'Enabling perl execution for ' . $row_diroptions['path']); - + // check for suexec-workaround, #319 if ((int) Settings::Get('perl.suexecworkaround') == 1) { // symlink this directory to suexec-safe-path $loginname = getCustomerDetail($row_diroptions['customerid'], 'loginname'); $suexecpath = makeCorrectDir(Settings::Get('perl.suexecpath') . '/' . $loginname . '/' . md5($row_diroptions['path']) . '/'); - + if (! file_exists($suexecpath)) { safe_exec('mkdir -p ' . escapeshellarg($suexecpath)); safe_exec('chown -R ' . escapeshellarg($row_diroptions['guid']) . ':' . escapeshellarg($row_diroptions['guid']) . ' ' . escapeshellarg($suexecpath)); } - + // symlink to {$givenpath}/cgi-bin // NOTE: symlinks are FILES, so do not append a / here $perlsymlink = makeCorrectFile($row_diroptions['path'] . '/cgi-bin'); @@ -1181,7 +1181,7 @@ class apache extends HttpConfigBase $loginname = getCustomerDetail($row_diroptions['customerid'], 'loginname'); $suexecpath = makeCorrectDir(Settings::Get('perl.suexecpath') . '/' . $loginname . '/' . md5($row_diroptions['path']) . '/'); $perlsymlink = makeCorrectFile($row_diroptions['path'] . '/cgi-bin'); - + // remove symlink if (file_exists($perlsymlink)) { safe_exec('rm -f ' . escapeshellarg($perlsymlink)); @@ -1192,24 +1192,24 @@ class apache extends HttpConfigBase } } } - + if (count($row_diroptions['htpasswds']) > 0) { $htpasswd_filename = makeCorrectFile(Settings::Get('system.apacheconf_htpasswddir') . '/' . $row_diroptions['customerid'] . '-' . md5($row_diroptions['path']) . '.htpasswd'); - + if (! isset($this->htpasswds_data[$htpasswd_filename])) { $this->htpasswds_data[$htpasswd_filename] = ''; } - + foreach ($row_diroptions['htpasswds'] as $row_htpasswd) { $this->htpasswds_data[$htpasswd_filename] .= $row_htpasswd['username'] . ':' . $row_htpasswd['password'] . "\n"; } - + $this->diroptions_data[$diroptions_filename] .= ' AuthType Basic' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AuthName "' . $row_htpasswd['authname'] . '"' . "\n"; $this->diroptions_data[$diroptions_filename] .= ' AuthUserFile ' . $htpasswd_filename . "\n"; $this->diroptions_data[$diroptions_filename] .= ' require valid-user' . "\n"; } - + $this->diroptions_data[$diroptions_filename] .= '' . "\n"; } } @@ -1222,19 +1222,19 @@ class apache extends HttpConfigBase { // Write diroptions $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_diroptions')); - + if (count($this->diroptions_data) > 0) { $optsDir = new frxDirectory(Settings::Get('system.apacheconf_diroptions')); if (! $optsDir->isConfigDir()) { // Save one big file $diroptions_file = ''; - + foreach ($this->diroptions_data as $diroptions_filename => $diroptions_content) { $diroptions_file .= $diroptions_content . "\n\n"; } - + $diroptions_filename = Settings::Get('system.apacheconf_diroptions'); - + // Apply header $diroptions_file = '# ' . basename($diroptions_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $diroptions_file; $diroptions_file_handler = fopen($diroptions_filename, 'w'); @@ -1245,11 +1245,11 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::writeConfigs: mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_diroptions')))); safe_exec('mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_diroptions')))); } - + // Write a single file for every diroption foreach ($this->diroptions_data as $diroptions_filename => $diroptions_file) { $this->known_diroptionsfilenames[] = basename($diroptions_filename); - + // Apply header $diroptions_file = '# ' . basename($diroptions_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $diroptions_file; $diroptions_file_handler = fopen($diroptions_filename, 'w'); @@ -1258,10 +1258,10 @@ class apache extends HttpConfigBase } } } - + // Write htpasswds $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_htpasswddir')); - + if (count($this->htpasswds_data) > 0) { if (! file_exists(Settings::Get('system.apacheconf_htpasswddir'))) { $umask = umask(); @@ -1269,7 +1269,7 @@ class apache extends HttpConfigBase mkdir(Settings::Get('system.apacheconf_htpasswddir'), 0751); umask($umask); } - + $htpasswdDir = new frxDirectory(Settings::Get('system.apacheconf_htpasswddir')); if ($htpasswdDir->isConfigDir(true)) { foreach ($this->htpasswds_data as $htpasswd_filename => $htpasswd_file) { @@ -1282,34 +1282,34 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_WARNING, 'WARNING!!! ' . Settings::Get('system.apacheconf_htpasswddir') . ' is not a directory. htpasswd directory protection is disabled!!!'); } } - + // Write virtualhosts $this->logger->logAction(CRON_ACTION, LOG_INFO, "apache::writeConfigs: rebuilding " . Settings::Get('system.apacheconf_vhost')); - + if (count($this->virtualhosts_data) > 0) { $vhostDir = new frxDirectory(Settings::Get('system.apacheconf_vhost')); if (! $vhostDir->isConfigDir()) { // Save one big file $vhosts_file = ''; - + // sort by filename so the order is: // 1. subdomains x-29 // 2. subdomains as main-domains 30 // 3. main-domains 35 // #437 ksort($this->virtualhosts_data); - + foreach ($this->virtualhosts_data as $vhosts_filename => $vhost_content) { $vhosts_file .= $vhost_content . "\n\n"; } - + // Include diroptions file in case it exists if (file_exists(Settings::Get('system.apacheconf_diroptions'))) { $vhosts_file .= "\n" . 'Include ' . Settings::Get('system.apacheconf_diroptions') . "\n\n"; } - + $vhosts_filename = Settings::Get('system.apacheconf_vhost'); - + // Apply header $vhosts_file = '# ' . basename($vhosts_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $vhosts_file; $vhosts_file_handler = fopen($vhosts_filename, 'w'); @@ -1320,11 +1320,11 @@ class apache extends HttpConfigBase $this->logger->logAction(CRON_ACTION, LOG_NOTICE, 'apache::writeConfigs: mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_vhost')))); safe_exec('mkdir ' . escapeshellarg(makeCorrectDir(Settings::Get('system.apacheconf_vhost')))); } - + // Write a single file for every vhost foreach ($this->virtualhosts_data as $vhosts_filename => $vhosts_file) { $this->known_vhostfilenames[] = basename($vhosts_filename); - + // Apply header $vhosts_file = '# ' . basename($vhosts_filename) . "\n" . '# Created ' . date('d.m.Y H:i') . "\n" . '# Do NOT manually edit this file, all changes will be deleted after the next domain change at the panel.' . "\n" . "\n" . $vhosts_file; $vhosts_file_handler = fopen($vhosts_filename, 'w'); diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index d4d27c77..5c932fd1 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -432,7 +432,7 @@ class nginx extends HttpConfigBase $_vhost_content .= $this->processSpecialConfigTemplate($ipandport['default_vhostconf_domain'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } - $http2 = $ssl_vhost == true && (isset($domain['http2']) && $domain['http2'] == '1' && Settings::Get('system.http2_support') == '1'); + $http2 = $ssl_vhost == true && (isset($domain['http2']) && $domain['http2'] == '1'); $vhost_content .= "\t" . 'listen ' . $ipport . ($ssl_vhost == true ? ' ssl' : '') . ($http2 == true ? ' http2' : '') . ';' . "\n"; } From 7442bf7347134d6e250bfa682b6e344dedf4ab22 Mon Sep 17 00:00:00 2001 From: Andreas Grundler Date: Thu, 18 Jan 2018 18:30:38 +0100 Subject: [PATCH 140/179] =?UTF-8?q?http2=20Konfiguration=20nur=20einf?= =?UTF-8?q?=C3=BCgen=20wenn=20http2=20in=20den=20Einstellungen=20aktiviert?= =?UTF-8?q?=20ist?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/jobs/cron_tasks.inc.http.10.apache.php | 2 +- scripts/jobs/cron_tasks.inc.http.30.nginx.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index 55f230d0..2a7ab516 100644 --- a/scripts/jobs/cron_tasks.inc.http.10.apache.php +++ b/scripts/jobs/cron_tasks.inc.http.10.apache.php @@ -909,7 +909,7 @@ class apache extends HttpConfigBase $vhost_content .= ' SSLEngine On' . "\n"; $vhost_content .= ' SSLProtocol -ALL +' . str_replace(","," +", Settings::Get('system.ssl_protocols')) . "\n"; if (Settings::Get('system.apache24') == '1') { - if (isset($domain['http2']) && $domain['http2'] == '1') { + if (isset($domain['http2']) && $domain['http2'] == '1' && Settings::Get('system.http2_support') == '1') { $vhost_content .= ' Protocols h2 http/1.1' . "\n"; } $vhost_content .= ' SSLCompression Off' . "\n"; diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index 5c932fd1..d4d27c77 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -432,7 +432,7 @@ class nginx extends HttpConfigBase $_vhost_content .= $this->processSpecialConfigTemplate($ipandport['default_vhostconf_domain'], $domain, $domain['ip'], $domain['port'], $ssl_vhost) . "\n"; } - $http2 = $ssl_vhost == true && (isset($domain['http2']) && $domain['http2'] == '1'); + $http2 = $ssl_vhost == true && (isset($domain['http2']) && $domain['http2'] == '1' && Settings::Get('system.http2_support') == '1'); $vhost_content .= "\t" . 'listen ' . $ipport . ($ssl_vhost == true ? ' ssl' : '') . ($http2 == true ? ' http2' : '') . ';' . "\n"; } From f3733ca24900ac3e5509930b439f5859201565c3 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 18 Jan 2018 19:50:28 +0100 Subject: [PATCH 141/179] set apache-2.4 as default ON also in froxlor.sql; fix wrong DbManagerMySQL::disableUser, fixes #505 Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- lib/classes/database/manager/class.DbManagerMySQL.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index fd762195..1bd72d32 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -601,7 +601,7 @@ opcache.interned_strings_buffer'), ('system', 'http2_support', '0'), ('system', 'perl_server', 'unix:/var/run/nginx/cgiwrap-dispatch.sock'), ('system', 'phpreload_command', ''), - ('system', 'apache24', '0'), + ('system', 'apache24', '1'), ('system', 'apache24_ocsp_cache_path', 'shmcb:/var/run/apache2/ocsp-stapling.cache(131072)'), ('system', 'documentroot_use_default_value', '0'), ('system', 'passwordcryptfunc', '3'), diff --git a/lib/classes/database/manager/class.DbManagerMySQL.php b/lib/classes/database/manager/class.DbManagerMySQL.php index bed0eadd..b9a8d3ec 100644 --- a/lib/classes/database/manager/class.DbManagerMySQL.php +++ b/lib/classes/database/manager/class.DbManagerMySQL.php @@ -134,7 +134,7 @@ class DbManagerMySQL { * @param string $host (unused in mysql) */ public function disableUser($username = null, $host = null) { - $stmt = Database::prepare("REVOKE ALL PRIVILEGES, GRANT OPTION FROM `".$row_database['databasename']."`"); + $stmt = Database::prepare('REVOKE ALL PRIVILEGES, GRANT OPTION FROM `' . $username . '`@`' . $host . '`'); Database::pexecute($stmt, array(), false); } From ca0ab1f97a684d0688de17a77cf4152ca3e7509c Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 21 Jan 2018 23:37:09 +0100 Subject: [PATCH 142/179] add fixed dovecot/conf.d/10-ssl.conf template for debian stretch; update phpMailer to 5.2.26 Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/stretch.xml | 68 +++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/lib/configfiles/stretch.xml b/lib/configfiles/stretch.xml index 52f5e48d..eb6c71d1 100644 --- a/lib/configfiles/stretch.xml +++ b/lib/configfiles/stretch.xml @@ -3372,6 +3372,74 @@ service dict { #group = } } +]]> + + + + +ssl = no + +# PEM encoded X.509 SSL/TLS certificate and private key. They're opened before +# dropping root privileges, so keep the key file unreadable by anyone but +# root. Included doc/mkcert.sh can be used to easily generate self-signed +# certificate, just make sure to update the domains in dovecot-openssl.cnf +#ssl_cert = From 3fb92259a86553695b7632eb73e9188bc582ba91 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 26 Jan 2018 17:17:22 +0100 Subject: [PATCH 143/179] readd starting and ending quotes which got removed with the braces in #503 Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/dns/class.DnsEntry.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/classes/dns/class.DnsEntry.php b/lib/classes/dns/class.DnsEntry.php index f4726e4d..11a7a614 100644 --- a/lib/classes/dns/class.DnsEntry.php +++ b/lib/classes/dns/class.DnsEntry.php @@ -52,18 +52,18 @@ class DnsEntry if (substr($_l, 0, 1) == '"') { $_l = substr($_l, 1); } - $_content = $_l . '"' . PHP_EOL; + $_content = '"' . $_l . '"' . PHP_EOL; $_l = array_pop($_contentlines); // check for ending quote - if (substr($_l, -1) == '"') { - $_l = substr($_l, 0, -1); + if (substr($_l, - 1) == '"') { + $_l = substr($_l, 0, - 1); } foreach ($_contentlines as $_cl) { // lines in between $_content .= "\t\t\t\t" . '"' . $_cl . '"' . PHP_EOL; } // last line - $_content .= "\t\t\t\t" . '"'.$_l; + $_content .= "\t\t\t\t" . '"' . $_l . '"'; } $result = $this->record . "\t" . $this->ttl . "\t" . $this->class . "\t" . $this->type . "\t" . (($this->priority >= 0 && ($this->type == 'MX' || $this->type == 'SRV')) ? $this->priority . "\t" : "") . $_content . PHP_EOL; return $result; From fcd0dddfd551b0ce7c4bdf0f757cf6a048858641 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 26 Jan 2018 17:18:12 +0100 Subject: [PATCH 144/179] Update phpMailer to 5.2.26 Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/phpmailer/class.PHPMailer.php | 805 +++++++++++----------- lib/classes/phpmailer/class.SMTP.php | 329 +++++---- 2 files changed, 590 insertions(+), 544 deletions(-) diff --git a/lib/classes/phpmailer/class.PHPMailer.php b/lib/classes/phpmailer/class.PHPMailer.php index cdb9413c..ff04b18b 100644 --- a/lib/classes/phpmailer/class.PHPMailer.php +++ b/lib/classes/phpmailer/class.PHPMailer.php @@ -1,38 +1,38 @@ -* @author Jim Jagielski (jimjag) -* @author Andy Prevost (codeworxtech) -* @author Brent R. Matzelle (original founder) -* @copyright 2012 - 2014 Marcus Bointon -* @copyright 2010 - 2012 Jim Jagielski -* @copyright 2004 - 2009 Andy Prevost -* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License -* @note This program is distributed in the hope that it will be useful - WITHOUT -* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -* FITNESS FOR A PARTICULAR PURPOSE. -*/ + * PHP Version 5 + * @package PHPMailer + * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project + * @author Marcus Bointon (Synchro/coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2014 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ /** * PHPMailer - PHP email creation and transport class. -* @package PHPMailer -* @author Marcus Bointon (Synchro/coolbru) -* @author Jim Jagielski (jimjag) -* @author Andy Prevost (codeworxtech) -* @author Brent R. Matzelle (original founder) -*/ + * @package PHPMailer + * @author Marcus Bointon (Synchro/coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + */ class PHPMailer { /** * The PHPMailer Version number. * @var string */ - public $Version = '5.2.21'; - + public $Version = '5.2.26'; + /** * Email priority. * Options: null (default), 1 = High, 3 = Normal, 5 = low. @@ -40,51 +40,51 @@ class PHPMailer * @var integer */ public $Priority = null; - + /** * The character set of the message. * @var string */ public $CharSet = 'iso-8859-1'; - + /** * The MIME Content-type of the message. * @var string */ public $ContentType = 'text/plain'; - + /** * The message encoding. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable". * @var string */ public $Encoding = '8bit'; - + /** * Holds the most recent mailer error message. * @var string */ public $ErrorInfo = ''; - + /** * The From email address for the message. * @var string */ public $From = 'root@localhost'; - + /** * The From name of the message. * @var string */ public $FromName = 'Root User'; - + /** * The Sender email (Return-Path) of the message. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. * @var string */ public $Sender = ''; - + /** * The Return-Path of the message. * If empty, it will be set to either From or Sender. @@ -94,20 +94,20 @@ class PHPMailer * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference */ public $ReturnPath = ''; - + /** * The Subject of the message. * @var string */ public $Subject = ''; - + /** * An HTML or plain text message body. * If HTML then call isHTML(true). * @var string */ public $Body = ''; - + /** * The plain-text message body. * This body can be read by mail clients that do not have HTML email @@ -116,7 +116,7 @@ class PHPMailer * @var string */ public $AltBody = ''; - + /** * An iCal message part body. * Only supported in simple alt or alt_inline message types @@ -126,55 +126,55 @@ class PHPMailer * @var string */ public $Ical = ''; - + /** * The complete compiled MIME message body. * @access protected * @var string */ protected $MIMEBody = ''; - + /** * The complete compiled MIME message headers. * @var string * @access protected */ protected $MIMEHeader = ''; - + /** * Extra headers that createHeader() doesn't fold in. * @var string * @access protected */ protected $mailHeader = ''; - + /** * Word-wrap the message body to this number of chars. * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance. * @var integer */ public $WordWrap = 0; - + /** * Which method to use to send mail. * Options: "mail", "sendmail", or "smtp". * @var string */ public $Mailer = 'mail'; - + /** * The path to the sendmail program. * @var string */ public $Sendmail = '/usr/sbin/sendmail'; - + /** * Whether mail() uses a fully sendmail-compatible MTA. * One which supports sendmail's "-oi -f" options. * @var boolean */ public $UseSendmailOptions = true; - + /** * Path to PHPMailer plugins. * Useful if the SMTP class is not in the PHP include path. @@ -182,13 +182,13 @@ class PHPMailer * @deprecated Should not be needed now there is an autoloader. */ public $PluginDir = ''; - + /** * The email address that a reading confirmation should be sent to, also known as read receipt. * @var string */ public $ConfirmReadingTo = ''; - + /** * The hostname to use in the Message-ID header and as default HELO string. * If empty, PHPMailer attempts to find one with, in order, @@ -197,7 +197,7 @@ class PHPMailer * @var string */ public $Hostname = ''; - + /** * An ID to be used in the Message-ID header. * If empty, a unique id will be generated. @@ -207,14 +207,14 @@ class PHPMailer * @var string */ public $MessageID = ''; - + /** * The message Date to be used in the Date header. * If empty, the current date will be added. * @var string */ public $MessageDate = ''; - + /** * SMTP hosts. * Either a single hostname or multiple semicolon-delimited hostnames. @@ -227,14 +227,14 @@ class PHPMailer * @var string */ public $Host = 'localhost'; - + /** * The default SMTP server port. * @var integer * @TODO Why is this needed when the SMTP class takes care of it? */ public $Port = 25; - + /** * The SMTP HELO of the message. * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find @@ -243,14 +243,14 @@ class PHPMailer * @see PHPMailer::$Hostname */ public $Helo = ''; - + /** * What kind of encryption to use on the SMTP connection. * Options: '', 'ssl' or 'tls' * @var string */ public $SMTPSecure = ''; - + /** * Whether to enable TLS encryption automatically if a server supports it, * even if `SMTPSecure` is not set to 'tls'. @@ -258,7 +258,7 @@ class PHPMailer * @var boolean */ public $SMTPAutoTLS = true; - + /** * Whether to use SMTP authentication. * Uses the Username and Password properties. @@ -267,53 +267,53 @@ class PHPMailer * @see PHPMailer::$Password */ public $SMTPAuth = false; - + /** * Options array passed to stream_context_create when connecting via SMTP. * @var array */ public $SMTPOptions = array(); - + /** * SMTP username. * @var string */ public $Username = ''; - + /** * SMTP password. * @var string */ public $Password = ''; - + /** * SMTP auth type. * Options are CRAM-MD5, LOGIN, PLAIN, NTLM, XOAUTH2, attempted in that order if not specified * @var string */ public $AuthType = ''; - + /** * SMTP realm. * Used for NTLM auth * @var string */ public $Realm = ''; - + /** * SMTP workstation. * Used for NTLM auth * @var string */ public $Workstation = ''; - + /** * The SMTP server timeout in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 * @var integer */ public $Timeout = 300; - + /** * SMTP class debug output mode. * Debug output level. @@ -327,7 +327,7 @@ class PHPMailer * @see SMTP::$do_debug */ public $SMTPDebug = 0; - + /** * How to handle debug output. * Options: @@ -343,7 +343,7 @@ class PHPMailer * @see SMTP::$Debugoutput */ public $Debugoutput = 'echo'; - + /** * Whether to keep SMTP connection open after each message. * If this is set to true then to close the connection @@ -351,7 +351,7 @@ class PHPMailer * @var boolean */ public $SMTPKeepAlive = false; - + /** * Whether to split multiple to addresses into multiple messages * or send them all in one message. @@ -359,14 +359,14 @@ class PHPMailer * @var boolean */ public $SingleTo = false; - + /** * Storage for addresses when SingleTo is enabled. * @var array * @TODO This should really not be public */ public $SingleToArray = array(); - + /** * Whether to generate VERP addresses on send. * Only applicable when sending via SMTP. @@ -375,13 +375,13 @@ class PHPMailer * @var boolean */ public $do_verp = false; - + /** * Whether to allow sending messages with an empty body. * @var boolean */ public $AllowEmpty = false; - + /** * The default line ending. * @note The default remains "\n". We force CRLF where we know @@ -389,47 +389,47 @@ class PHPMailer * @var string */ public $LE = "\n"; - + /** * DKIM selector. * @var string */ public $DKIM_selector = ''; - + /** * DKIM Identity. * Usually the email address used as the source of the email. * @var string */ public $DKIM_identity = ''; - + /** * DKIM passphrase. * Used if your key is encrypted. * @var string */ public $DKIM_passphrase = ''; - + /** * DKIM signing domain name. * @example 'example.com' * @var string */ public $DKIM_domain = ''; - + /** * DKIM private key file path. * @var string */ public $DKIM_private = ''; - + /** * DKIM private key string. * If set, takes precedence over `$DKIM_private`. * @var string */ public $DKIM_private_string = ''; - + /** * Callback Action function name. * @@ -440,23 +440,23 @@ class PHPMailer * * Parameters: * boolean $result result of the send action - * string $to email address of the recipient - * string $cc cc email addresses - * string $bcc bcc email addresses + * array $to email addresses of the recipients + * array $cc cc email addresses + * array $bcc bcc email addresses * string $subject the subject * string $body the email body * string $from email address of sender * @var string */ public $action_function = ''; - + /** * What to put in the X-Mailer header. * Options: An empty string for PHPMailer default, whitespace for none, or a string to use * @var string */ public $XMailer = ''; - + /** * Which validator to use by default when validating email addresses. * May be a callable to inject your own validator, but there are several built-in validators. @@ -465,42 +465,42 @@ class PHPMailer * @static */ public static $validator = 'auto'; - + /** * An instance of the SMTP sender class. * @var SMTP * @access protected */ protected $smtp = null; - + /** * The array of 'to' names and addresses. * @var array * @access protected */ protected $to = array(); - + /** * The array of 'cc' names and addresses. * @var array * @access protected */ protected $cc = array(); - + /** * The array of 'bcc' names and addresses. * @var array * @access protected */ protected $bcc = array(); - + /** * The array of reply-to names and addresses. * @var array * @access protected */ protected $ReplyTo = array(); - + /** * An array of all kinds of addresses. * Includes all of $to, $cc, $bcc @@ -509,7 +509,7 @@ class PHPMailer * @see PHPMailer::$to @see PHPMailer::$cc @see PHPMailer::$bcc */ protected $all_recipients = array(); - + /** * An array of names and addresses queued for validation. * In send(), valid and non duplicate entries are moved to $all_recipients @@ -521,7 +521,7 @@ class PHPMailer * @see PHPMailer::$all_recipients */ protected $RecipientsQueue = array(); - + /** * An array of reply-to names and addresses queued for validation. * In send(), valid and non duplicate entries are moved to $ReplyTo. @@ -531,77 +531,77 @@ class PHPMailer * @see PHPMailer::$ReplyTo */ protected $ReplyToQueue = array(); - + /** * The array of attachments. * @var array * @access protected */ protected $attachment = array(); - + /** * The array of custom headers. * @var array * @access protected */ protected $CustomHeader = array(); - + /** * The most recent Message-ID (including angular brackets). * @var string * @access protected */ protected $lastMessageID = ''; - + /** * The message's MIME type. * @var string * @access protected */ protected $message_type = ''; - + /** * The array of MIME boundary strings. * @var array * @access protected */ protected $boundary = array(); - + /** * The array of available languages. * @var array * @access protected */ protected $language = array(); - + /** * The number of errors encountered. * @var integer * @access protected */ protected $error_count = 0; - + /** * The S/MIME certificate file path. * @var string * @access protected */ protected $sign_cert_file = ''; - + /** * The S/MIME key file path. * @var string * @access protected */ protected $sign_key_file = ''; - + /** * The optional S/MIME extra certificates ("CA Chain") file path. * @var string * @access protected */ protected $sign_extracerts_file = ''; - + /** * The S/MIME password for the key. * Used only if the key is encrypted. @@ -609,47 +609,47 @@ class PHPMailer * @access protected */ protected $sign_key_pass = ''; - + /** * Whether to throw exceptions for errors. * @var boolean * @access protected */ protected $exceptions = false; - + /** * Unique ID used for message ID and boundaries. * @var string * @access protected */ protected $uniqueid = ''; - + /** * Error severity: message only, continue processing. */ const STOP_MESSAGE = 0; - + /** * Error severity: message, likely ok to continue processing. */ const STOP_CONTINUE = 1; - + /** * Error severity: message, plus full stop, critical error reached. */ const STOP_CRITICAL = 2; - + /** * SMTP RFC standard line ending. */ const CRLF = "\r\n"; - + /** * The maximum line length allowed by RFC 2822 section 2.1.1 * @var integer */ const MAX_LINE_LENGTH = 998; - + /** * Constructor. * @param boolean $exceptions Should we throw external exceptions? @@ -659,8 +659,10 @@ class PHPMailer if ($exceptions !== null) { $this->exceptions = (boolean)$exceptions; } + //Pick an appropriate debug output format automatically + $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); } - + /** * Destructor. */ @@ -669,7 +671,7 @@ class PHPMailer //Close any open SMTP connection nicely $this->smtpClose(); } - + /** * Call mail() in a safe_mode-aware fashion. * Also, unless sendmail_path points to sendmail (or something that @@ -691,7 +693,7 @@ class PHPMailer } else { $subject = $this->encodeHeader($this->secureHeader($subject)); } - + //Can't use additional_parameters in safe_mode, calling mail() with null params breaks //@link http://php.net/manual/en/function.mail.php if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) { @@ -743,7 +745,7 @@ class PHPMailer ) . "\n"; } } - + /** * Sets message type to HTML or plain. * @param boolean $isHtml True for HTML mode. @@ -757,7 +759,7 @@ class PHPMailer $this->ContentType = 'text/plain'; } } - + /** * Send messages using SMTP. * @return void @@ -766,7 +768,7 @@ class PHPMailer { $this->Mailer = 'smtp'; } - + /** * Send messages using PHP's mail() function. * @return void @@ -775,7 +777,7 @@ class PHPMailer { $this->Mailer = 'mail'; } - + /** * Send messages using $Sendmail. * @return void @@ -783,7 +785,7 @@ class PHPMailer public function isSendmail() { $ini_sendmail_path = ini_get('sendmail_path'); - + if (!stristr($ini_sendmail_path, 'sendmail')) { $this->Sendmail = '/usr/sbin/sendmail'; } else { @@ -791,7 +793,7 @@ class PHPMailer } $this->Mailer = 'sendmail'; } - + /** * Send messages using qmail. * @return void @@ -799,7 +801,7 @@ class PHPMailer public function isQmail() { $ini_sendmail_path = ini_get('sendmail_path'); - + if (!stristr($ini_sendmail_path, 'qmail')) { $this->Sendmail = '/var/qmail/bin/qmail-inject'; } else { @@ -807,7 +809,7 @@ class PHPMailer } $this->Mailer = 'qmail'; } - + /** * Add a "To" address. * @param string $address The email address to send to @@ -818,7 +820,7 @@ class PHPMailer { return $this->addOrEnqueueAnAddress('to', $address, $name); } - + /** * Add a "CC" address. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. @@ -830,7 +832,7 @@ class PHPMailer { return $this->addOrEnqueueAnAddress('cc', $address, $name); } - + /** * Add a "BCC" address. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer. @@ -842,7 +844,7 @@ class PHPMailer { return $this->addOrEnqueueAnAddress('bcc', $address, $name); } - + /** * Add a "Reply-To" address. * @param string $address The email address to reply to @@ -853,7 +855,7 @@ class PHPMailer { return $this->addOrEnqueueAnAddress('Reply-To', $address, $name); } - + /** * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still @@ -899,7 +901,7 @@ class PHPMailer // Immediately add standard addresses without IDN. return call_user_func_array(array($this, 'addAnAddress'), $params); } - + /** * Add an address to one of the recipient arrays or to the ReplyTo array. * Addresses that have been added already return false, but do not throw exceptions. @@ -944,7 +946,7 @@ class PHPMailer } return false; } - + /** * Parse and validate a string containing one or more RFC822-style comma-separated email addresses * of the form "display name
" into an array of name/address pairs. @@ -999,7 +1001,7 @@ class PHPMailer } return $addresses; } - + /** * Set the From and FromName properties. * @param string $address @@ -1033,7 +1035,7 @@ class PHPMailer } return true; } - + /** * Return the Message-ID header of the last email. * Technically this is the value from the last time the headers were created, @@ -1045,7 +1047,7 @@ class PHPMailer { return $this->lastMessageID; } - + /** * Check that a string looks like an email address. * @param string $address The email address to check @@ -1155,7 +1157,7 @@ class PHPMailer return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL); } } - + /** * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the * "intl" and "mbstring" PHP extensions. @@ -1166,7 +1168,7 @@ class PHPMailer // @TODO: Write our own "idn_to_ascii" function for PHP <= 5.2. return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding'); } - + /** * Converts IDN in given email address to its ASCII form, also known as punycode, if possible. * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet. @@ -1197,7 +1199,7 @@ class PHPMailer } return $address; } - + /** * Create a message and send it. * Uses the sending method specified by $Mailer. @@ -1220,7 +1222,7 @@ class PHPMailer return false; } } - + /** * Prepare a message for sending. * @throws phpmailerException @@ -1231,7 +1233,7 @@ class PHPMailer try { $this->error_count = 0; // Reset errors $this->mailHeader = ''; - + // Dequeue recipient and Reply-To addresses with IDN foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) { $params[1] = $this->punyencodeAddress($params[1]); @@ -1240,7 +1242,7 @@ class PHPMailer if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL); } - + // Validate From, Sender, and ConfirmReadingTo addresses foreach (array('From', 'Sender', 'ConfirmReadingTo') as $address_kind) { $this->$address_kind = trim($this->$address_kind); @@ -1258,18 +1260,18 @@ class PHPMailer return false; } } - + // Set whether the message is multipart/alternative if ($this->alternativeExists()) { $this->ContentType = 'multipart/alternative'; } - + $this->setMessageType(); // Refuse to send an empty message unless we are specifically allowing it if (!$this->AllowEmpty and empty($this->Body)) { throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL); } - + // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding) $this->MIMEHeader = ''; $this->MIMEBody = $this->createBody(); @@ -1277,7 +1279,7 @@ class PHPMailer $tempheaders = $this->MIMEHeader; $this->MIMEHeader = $this->createHeader(); $this->MIMEHeader .= $tempheaders; - + // To capture the complete message when using mail(), create // an extra header list which createHeader() doesn't fold in if ($this->Mailer == 'mail') { @@ -1291,7 +1293,7 @@ class PHPMailer $this->encodeHeader($this->secureHeader(trim($this->Subject))) ); } - + // Sign with DKIM if enabled if (!empty($this->DKIM_domain) && !empty($this->DKIM_selector) @@ -1316,7 +1318,7 @@ class PHPMailer return false; } } - + /** * Actually send a message. * Send the email via the selected mechanism @@ -1340,7 +1342,7 @@ class PHPMailer if (method_exists($this, $sendMethod)) { return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody); } - + return $this->mailSend($this->MIMEHeader, $this->MIMEBody); } } catch (phpmailerException $exc) { @@ -1352,7 +1354,7 @@ class PHPMailer } return false; } - + /** * Send mail using the $Sendmail program. * @param string $header The message headers @@ -1378,10 +1380,10 @@ class PHPMailer $sendmailFmt = '%s -oi -t'; } } - + // TODO: If possible, this should be changed to escapeshellarg. Needs thorough testing. $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender); - + if ($this->SingleTo) { foreach ($this->SingleToArray as $toAddr) { if (!@$mail = popen($sendmail, 'w')) { @@ -1426,7 +1428,7 @@ class PHPMailer } return true; } - + /** * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters. * @@ -1444,12 +1446,12 @@ class PHPMailer ) { return false; } - + $length = strlen($string); - + for ($i = 0; $i < $length; $i++) { $c = $string[$i]; - + // All other characters have a special meaning in at least one common shell, including = and +. // Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here. // Note that this does permit non-Latin alphanumeric characters based on the current locale. @@ -1457,10 +1459,10 @@ class PHPMailer return false; } } - + return true; } - + /** * Send mail using the PHP mail() function. * @param string $header The message headers @@ -1477,7 +1479,7 @@ class PHPMailer $toArr[] = $this->addrFormat($toaddr); } $to = implode(', ', $toArr); - + $params = null; //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver if (!empty($this->Sender) and $this->validateAddress($this->Sender)) { @@ -1508,7 +1510,7 @@ class PHPMailer } return true; } - + /** * Get an instance to use for SMTP operations. * Override this function to load your own SMTP implementation @@ -1521,7 +1523,7 @@ class PHPMailer } return $this->smtp; } - + /** * Send mail via SMTP. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. @@ -1549,7 +1551,7 @@ class PHPMailer $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError())); throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); } - + // Attempt to send to all recipients foreach (array($this->to, $this->cc, $this->bcc) as $togroup) { foreach ($togroup as $to) { @@ -1563,7 +1565,7 @@ class PHPMailer $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From); } } - + // Only send the DATA command if we have viable recipients if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) { throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL); @@ -1587,7 +1589,7 @@ class PHPMailer } return true; } - + /** * Initiate a connection to an SMTP server. * Returns false if the operation failed. @@ -1602,104 +1604,109 @@ class PHPMailer if (is_null($this->smtp)) { $this->smtp = $this->getSMTPInstance(); } - + //If no options are provided, use whatever is set in the instance if (is_null($options)) { $options = $this->SMTPOptions; } - + // Already connected? if ($this->smtp->connected()) { return true; } - + $this->smtp->setTimeout($this->Timeout); $this->smtp->setDebugLevel($this->SMTPDebug); $this->smtp->setDebugOutput($this->Debugoutput); $this->smtp->setVerp($this->do_verp); $hosts = explode(';', $this->Host); $lastexception = null; - + foreach ($hosts as $hostentry) { $hostinfo = array(); - if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) { - // Not a valid host entry - continue; - } - // $hostinfo[2]: optional ssl or tls prefix - // $hostinfo[3]: the hostname - // $hostinfo[4]: optional port number - // The host string prefix can temporarily override the current setting for SMTPSecure - // If it's not specified, the default value is used - $prefix = ''; - $secure = $this->SMTPSecure; - $tls = ($this->SMTPSecure == 'tls'); - if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) { - $prefix = 'ssl://'; - $tls = false; // Can't have SSL and TLS at the same time - $secure = 'ssl'; - } elseif ($hostinfo[2] == 'tls') { - $tls = true; - // tls doesn't use a prefix - $secure = 'tls'; - } - //Do we need the OpenSSL extension? - $sslext = defined('OPENSSL_ALGO_SHA1'); - if ('tls' === $secure or 'ssl' === $secure) { - //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled - if (!$sslext) { - throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL); + if (!preg_match( + '/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/', + trim($hostentry), + $hostinfo + )) { + // Not a valid host entry + $this->edebug('Ignoring invalid host: ' . $hostentry); + continue; } - } - $host = $hostinfo[3]; - $port = $this->Port; - $tport = (integer)$hostinfo[4]; - if ($tport > 0 and $tport < 65536) { - $port = $tport; - } - if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { - try { - if ($this->Helo) { - $hello = $this->Helo; - } else { - $hello = $this->serverHostname(); + // $hostinfo[2]: optional ssl or tls prefix + // $hostinfo[3]: the hostname + // $hostinfo[4]: optional port number + // The host string prefix can temporarily override the current setting for SMTPSecure + // If it's not specified, the default value is used + $prefix = ''; + $secure = $this->SMTPSecure; + $tls = ($this->SMTPSecure == 'tls'); + if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) { + $prefix = 'ssl://'; + $tls = false; // Can't have SSL and TLS at the same time + $secure = 'ssl'; + } elseif ($hostinfo[2] == 'tls') { + $tls = true; + // tls doesn't use a prefix + $secure = 'tls'; + } + //Do we need the OpenSSL extension? + $sslext = defined('OPENSSL_ALGO_SHA1'); + if ('tls' === $secure or 'ssl' === $secure) { + //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled + if (!$sslext) { + throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL); } - $this->smtp->hello($hello); - //Automatically enable TLS encryption if: - // * it's not disabled - // * we have openssl extension - // * we are not already using SSL - // * the server offers STARTTLS - if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) { - $tls = true; - } - if ($tls) { - if (!$this->smtp->startTLS()) { - throw new phpmailerException($this->lang('connect_host')); + } + $host = $hostinfo[3]; + $port = $this->Port; + $tport = (integer)$hostinfo[4]; + if ($tport > 0 and $tport < 65536) { + $port = $tport; + } + if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { + try { + if ($this->Helo) { + $hello = $this->Helo; + } else { + $hello = $this->serverHostname(); } - // We must resend EHLO after TLS negotiation $this->smtp->hello($hello); - } - if ($this->SMTPAuth) { - if (!$this->smtp->authenticate( - $this->Username, - $this->Password, - $this->AuthType, - $this->Realm, - $this->Workstation - ) - ) { - throw new phpmailerException($this->lang('authenticate')); + //Automatically enable TLS encryption if: + // * it's not disabled + // * we have openssl extension + // * we are not already using SSL + // * the server offers STARTTLS + if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) { + $tls = true; + } + if ($tls) { + if (!$this->smtp->startTLS()) { + throw new phpmailerException($this->lang('connect_host')); } + // We must resend EHLO after TLS negotiation + $this->smtp->hello($hello); + } + if ($this->SMTPAuth) { + if (!$this->smtp->authenticate( + $this->Username, + $this->Password, + $this->AuthType, + $this->Realm, + $this->Workstation + ) + ) { + throw new phpmailerException($this->lang('authenticate')); + } + } + return true; + } catch (phpmailerException $exc) { + $lastexception = $exc; + $this->edebug($exc->getMessage()); + // We must have connected, but then failed TLS or Auth, so close connection nicely + $this->smtp->quit(); } - return true; - } catch (phpmailerException $exc) { - $lastexception = $exc; - $this->edebug($exc->getMessage()); - // We must have connected, but then failed TLS or Auth, so close connection nicely - $this->smtp->quit(); } - } } // If we get here, all connection attempts have failed, so close connection hard $this->smtp->close(); @@ -1709,7 +1716,7 @@ class PHPMailer } return false; } - + /** * Close the active SMTP session if one exists. * @return void @@ -1723,7 +1730,7 @@ class PHPMailer } } } - + /** * Set the language for error messages. * Returns false if it cannot load the language file. @@ -1742,12 +1749,13 @@ class PHPMailer 'dk' => 'da', 'no' => 'nb', 'se' => 'sv', + 'sr' => 'rs' ); - + if (isset($renamed_langcodes[$langcode])) { $langcode = $renamed_langcodes[$langcode]; } - + // Define full set of translatable strings in English $PHPMAILER_LANG = array( 'authenticate' => 'SMTP Error: Could not authenticate.', @@ -1794,7 +1802,7 @@ class PHPMailer $this->language = $PHPMAILER_LANG; return (boolean)$foundlang; // Returns false if language not found } - + /** * Get the array of strings for the current language. * @return array @@ -1803,7 +1811,7 @@ class PHPMailer { return $this->language; } - + /** * Create recipient headers. * @access public @@ -1822,7 +1830,7 @@ class PHPMailer } return $type . ': ' . implode(', ', $addresses) . $this->LE; } - + /** * Format an address for use in a message header. * @access public @@ -1840,7 +1848,7 @@ class PHPMailer ) . '>'; } } - + /** * Word-wrap message. * For use with mailers that do not automatically perform wrapping @@ -1864,13 +1872,13 @@ class PHPMailer $is_utf8 = (strtolower($this->CharSet) == 'utf-8'); $lelen = strlen($this->LE); $crlflen = strlen(self::CRLF); - + $message = $this->fixEOL($message); //Remove a trailing line break if (substr($message, -$lelen) == $this->LE) { $message = substr($message, 0, -$lelen); } - + //Split message into lines $lines = explode($this->LE, $message); //Message will be rebuilt in here @@ -1915,7 +1923,7 @@ class PHPMailer } $part = substr($word, 0, $len); $word = substr($word, $len); - + if (strlen($word) > 0) { $message .= $part . sprintf('=%s', self::CRLF); } else { @@ -1928,7 +1936,7 @@ class PHPMailer $buf .= ' '; } $buf .= $word; - + if (strlen($buf) > $length and $buf_o != '') { $message .= $buf_o . $soft_break; $buf = $word; @@ -1938,10 +1946,10 @@ class PHPMailer } $message .= $buf . self::CRLF; } - + return $message; } - + /** * Find the last character boundary prior to $maxLength in a utf-8 * quoted-printable encoded string. @@ -1987,7 +1995,7 @@ class PHPMailer } return $maxLength; } - + /** * Apply word wrapping to the message body. * Wraps the message body to the number of chars set in the WordWrap property. @@ -2001,7 +2009,7 @@ class PHPMailer if ($this->WordWrap < 1) { return; } - + switch ($this->message_type) { case 'alt': case 'alt_inline': @@ -2014,7 +2022,7 @@ class PHPMailer break; } } - + /** * Assemble message headers. * @access public @@ -2023,12 +2031,9 @@ class PHPMailer public function createHeader() { $result = ''; - - if ($this->MessageDate == '') { - $this->MessageDate = self::rfcDate(); - } - $result .= $this->headerLine('Date', $this->MessageDate); - + + $result .= $this->headerLine('Date', $this->MessageDate == '' ? self::rfcDate() : $this->MessageDate); + // To be created automatically by mail() if ($this->SingleTo) { if ($this->Mailer != 'mail') { @@ -2045,14 +2050,14 @@ class PHPMailer $result .= $this->headerLine('To', 'undisclosed-recipients:;'); } } - + $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName))); - + // sendmail and mail() extract Cc from the header before sending if (count($this->cc) > 0) { $result .= $this->addrAppend('Cc', $this->cc); } - + // sendmail and mail() extract Bcc from the header before sending if (( $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail' @@ -2061,16 +2066,16 @@ class PHPMailer ) { $result .= $this->addrAppend('Bcc', $this->bcc); } - + if (count($this->ReplyTo) > 0) { $result .= $this->addrAppend('Reply-To', $this->ReplyTo); } - + // mail() sets the subject itself if ($this->Mailer != 'mail') { $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject))); } - + // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4 // https://tools.ietf.org/html/rfc5322#section-3.6.4 if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) { @@ -2093,11 +2098,11 @@ class PHPMailer $result .= $this->headerLine('X-Mailer', $myXmailer); } } - + if ($this->ConfirmReadingTo != '') { $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>'); } - + // Add custom headers foreach ($this->CustomHeader as $header) { $result .= $this->headerLine( @@ -2109,10 +2114,10 @@ class PHPMailer $result .= $this->headerLine('MIME-Version', '1.0'); $result .= $this->getMailMIME(); } - + return $result; } - + /** * Get the message MIME type headers. * @access public @@ -2157,14 +2162,14 @@ class PHPMailer $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding); } } - + if ($this->Mailer != 'mail') { $result .= $this->LE; } - + return $result; } - + /** * Returns the whole MIME message. * Includes complete headers and body. @@ -2177,7 +2182,7 @@ class PHPMailer { return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody; } - + /** * Create unique ID * @return string @@ -2185,7 +2190,7 @@ class PHPMailer protected function generateId() { return md5(uniqid(time())); } - + /** * Assemble the message body. * Returns an empty string on failure. @@ -2201,13 +2206,13 @@ class PHPMailer $this->boundary[1] = 'b1_' . $this->uniqueid; $this->boundary[2] = 'b2_' . $this->uniqueid; $this->boundary[3] = 'b3_' . $this->uniqueid; - + if ($this->sign_key_file) { $body .= $this->getMailMIME() . $this->LE; } - + $this->setWordWrap(); - + $bodyEncoding = $this->Encoding; $bodyCharSet = $this->CharSet; //Can we do a 7-bit downgrade? @@ -2221,7 +2226,7 @@ class PHPMailer if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) { $bodyEncoding = 'quoted-printable'; } - + $altBodyEncoding = $this->Encoding; $altBodyCharSet = $this->CharSet; //Can we do a 7-bit downgrade? @@ -2341,7 +2346,7 @@ class PHPMailer $body .= $this->encodeString($this->Body, $this->Encoding); break; } - + if ($this->isError()) { $body = ''; } elseif ($this->sign_key_file) { @@ -2397,7 +2402,7 @@ class PHPMailer } return $body; } - + /** * Return the start of a message boundary. * @access protected @@ -2427,10 +2432,10 @@ class PHPMailer $result .= $this->headerLine('Content-Transfer-Encoding', $encoding); } $result .= $this->LE; - + return $result; } - + /** * Return the end of a message boundary. * @access protected @@ -2441,7 +2446,7 @@ class PHPMailer { return $this->LE . '--' . $boundary . '--' . $this->LE; } - + /** * Set the message type. * PHPMailer only supports some preset message types, not arbitrary MIME structures. @@ -2466,7 +2471,7 @@ class PHPMailer $this->message_type = 'plain'; } } - + /** * Format a header line. * @access public @@ -2478,7 +2483,7 @@ class PHPMailer { return $name . ': ' . $value . $this->LE; } - + /** * Return a formatted mail line. * @access public @@ -2489,9 +2494,10 @@ class PHPMailer { return $value . $this->LE; } - + /** * Add an attachment from a path on the filesystem. + * Never use a user-supplied path to a file! * Returns false if the file could not be found or read. * @param string $path Path to the attachment. * @param string $name Overrides the attachment name. @@ -2507,17 +2513,17 @@ class PHPMailer if (!@is_file($path)) { throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE); } - + // If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($path); } - + $filename = basename($path); if ($name == '') { $name = $filename; } - + $this->attachment[] = array( 0 => $path, 1 => $filename, @@ -2528,7 +2534,7 @@ class PHPMailer 6 => $disposition, 7 => 0 ); - + } catch (phpmailerException $exc) { $this->setError($exc->getMessage()); $this->edebug($exc->getMessage()); @@ -2539,7 +2545,7 @@ class PHPMailer } return true; } - + /** * Return the array of attachments. * @return array @@ -2548,7 +2554,7 @@ class PHPMailer { return $this->attachment; } - + /** * Attach all file, string, and binary attachments to the message. * Returns an empty string on failure. @@ -2563,7 +2569,7 @@ class PHPMailer $mime = array(); $cidUniq = array(); $incl = array(); - + // Add all attachments foreach ($this->attachment as $attachment) { // Check if it is a valid disposition_filter @@ -2577,7 +2583,7 @@ class PHPMailer } else { $path = $attachment[0]; } - + $inclhash = md5(serialize($attachment)); if (in_array($inclhash, $incl)) { continue; @@ -2592,7 +2598,7 @@ class PHPMailer continue; } $cidUniq[$cid] = true; - + $mime[] = sprintf('--%s%s', $boundary, $this->LE); //Only include a filename property if we have one if (!empty($name)) { @@ -2613,11 +2619,11 @@ class PHPMailer if ($encoding != '7bit') { $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE); } - + if ($disposition == 'inline') { $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE); } - + // If a filename contains any of these chars, it should be quoted, // but not otherwise: RFC2183 & RFC2045 5.1 // Fixes a warning in IETF's msglint MIME checker @@ -2650,7 +2656,7 @@ class PHPMailer } else { $mime[] = $this->LE; } - + // Encode as string attachment if ($bString) { $mime[] = $this->encodeString($string, $encoding); @@ -2667,12 +2673,12 @@ class PHPMailer } } } - + $mime[] = sprintf('--%s--%s', $boundary, $this->LE); - + return implode('', $mime); } - + /** * Encode a file attachment in requested format. * Returns an empty string on failure. @@ -2714,7 +2720,7 @@ class PHPMailer return ''; } } - + /** * Encode a string in requested format. * Returns an empty string on failure. @@ -2750,7 +2756,7 @@ class PHPMailer } return $encoded; } - + /** * Encode a header string optimally. * Picks shortest of Q, B, quoted-printable or none. @@ -2784,12 +2790,12 @@ class PHPMailer $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); break; } - + //There are no chars that need encoding if ($matchcount == 0) { return ($str); } - + $maxlen = 75 - 7 - strlen($this->CharSet); // Try to select the encoding which should produce the shortest output if ($matchcount > strlen($str) / 3) { @@ -2810,13 +2816,13 @@ class PHPMailer $encoded = $this->wrapText($encoded, $maxlen, true); $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded)); } - + $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded); $encoded = trim(str_replace("\n", $this->LE, $encoded)); - + return $encoded; } - + /** * Check if a string contains multi-byte characters. * @access public @@ -2831,7 +2837,7 @@ class PHPMailer return false; } } - + /** * Does a string contain any 8-bit chars (in any charset)? * @param string $text @@ -2841,7 +2847,7 @@ class PHPMailer { return (boolean)preg_match('/[\x80-\xFF]/', $text); } - + /** * Encode and wrap long multibyte strings for mail headers * without breaking lines within a character. @@ -2860,7 +2866,7 @@ class PHPMailer if ($linebreak === null) { $linebreak = $this->LE; } - + $mb_length = mb_strlen($str, $this->CharSet); // Each line must have length <= 75, including $start and $end $length = 75 - strlen($start) - strlen($end); @@ -2868,7 +2874,7 @@ class PHPMailer $ratio = $mb_length / strlen($str); // Base64 has a 4:3 ratio $avgLength = floor($length * $ratio * .75); - + for ($i = 0; $i < $mb_length; $i += $offset) { $lookBack = 0; do { @@ -2879,12 +2885,12 @@ class PHPMailer } while (strlen($chunk) > $length); $encoded .= $chunk . $linebreak; } - + // Chomp the last linefeed $encoded = substr($encoded, 0, -strlen($linebreak)); return $encoded; } - + /** * Encode a string in quoted-printable format. * According to RFC2045 section 6.7. @@ -2908,7 +2914,7 @@ class PHPMailer ); return preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string); } - + /** * Backward compatibility wrapper for an old QP encoding function that was removed. * @see PHPMailer::encodeQP() @@ -2926,7 +2932,7 @@ class PHPMailer ) { return $this->encodeQP($string, $line_max); } - + /** * Encode a string using Q encoding. * @link http://tools.ietf.org/html/rfc2047 @@ -2974,7 +2980,7 @@ class PHPMailer // Replace every spaces to _ (more readable than =20) return str_replace(' ', '_', $encoded); } - + /** * Add a string or binary attachment (non-filesystem). * This method can be used to attach ascii or binary data, @@ -3009,7 +3015,7 @@ class PHPMailer 7 => 0 ); } - + /** * Add an embedded (inline) attachment from a file. * This can include images, sounds, and just about any other document type. @@ -3017,6 +3023,7 @@ class PHPMailer * displayed inline with the message, not just attached for download. * This is used in HTML messages that embed the images * the HTML refers to using the $cid value. + * Never use a user-supplied path to a file! * @param string $path Path to the attachment. * @param string $cid Content ID of the attachment; Use this to reference * the content when using an embedded image in HTML. @@ -3032,17 +3039,17 @@ class PHPMailer $this->setError($this->lang('file_access') . $path); return false; } - + // If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($path); } - + $filename = basename($path); if ($name == '') { $name = $filename; } - + // Append to $attachment array $this->attachment[] = array( 0 => $path, @@ -3056,7 +3063,7 @@ class PHPMailer ); return true; } - + /** * Add an embedded stringified attachment. * This can include images, sounds, and just about any other document type. @@ -3083,7 +3090,7 @@ class PHPMailer if ($type == '' and !empty($name)) { $type = self::filenameToType($name); } - + // Append to $attachment array $this->attachment[] = array( 0 => $string, @@ -3097,7 +3104,7 @@ class PHPMailer ); return true; } - + /** * Check if an inline attachment is present. * @access public @@ -3112,7 +3119,7 @@ class PHPMailer } return false; } - + /** * Check if an attachment (non-inline) is present. * @return boolean @@ -3126,7 +3133,7 @@ class PHPMailer } return false; } - + /** * Check if this message has an alternative body set. * @return boolean @@ -3135,7 +3142,7 @@ class PHPMailer { return !empty($this->AltBody); } - + /** * Clear queued addresses of given kind. * @access protected @@ -3151,7 +3158,7 @@ class PHPMailer } } } - + /** * Clear all To recipients. * @return void @@ -3164,7 +3171,7 @@ class PHPMailer $this->to = array(); $this->clearQueuedAddresses('to'); } - + /** * Clear all CC recipients. * @return void @@ -3177,7 +3184,7 @@ class PHPMailer $this->cc = array(); $this->clearQueuedAddresses('cc'); } - + /** * Clear all BCC recipients. * @return void @@ -3190,7 +3197,7 @@ class PHPMailer $this->bcc = array(); $this->clearQueuedAddresses('bcc'); } - + /** * Clear all ReplyTo recipients. * @return void @@ -3200,7 +3207,7 @@ class PHPMailer $this->ReplyTo = array(); $this->ReplyToQueue = array(); } - + /** * Clear all recipient types. * @return void @@ -3213,7 +3220,7 @@ class PHPMailer $this->all_recipients = array(); $this->RecipientsQueue = array(); } - + /** * Clear all filesystem, string, and binary attachments. * @return void @@ -3222,7 +3229,7 @@ class PHPMailer { $this->attachment = array(); } - + /** * Clear all custom headers. * @return void @@ -3231,7 +3238,7 @@ class PHPMailer { $this->CustomHeader = array(); } - + /** * Add an error message to the error container. * @access protected @@ -3258,7 +3265,7 @@ class PHPMailer } $this->ErrorInfo = $msg; } - + /** * Return an RFC 822 formatted date. * @access public @@ -3272,7 +3279,7 @@ class PHPMailer date_default_timezone_set(@date_default_timezone_get()); return date('D, j M Y H:i:s O'); } - + /** * Get the server hostname. * Returns 'localhost.localdomain' if unknown. @@ -3293,7 +3300,7 @@ class PHPMailer } return $result; } - + /** * Get an error message in the current language. * @access protected @@ -3305,7 +3312,7 @@ class PHPMailer if (count($this->language) < 1) { $this->setLanguage('en'); // set the default language } - + if (array_key_exists($key, $this->language)) { if ($key == 'smtp_connect_failed') { //Include a link to troubleshooting docs on SMTP connection failure @@ -3319,7 +3326,7 @@ class PHPMailer return $key; } } - + /** * Check if an error occurred. * @access public @@ -3329,7 +3336,7 @@ class PHPMailer { return ($this->error_count > 0); } - + /** * Ensure consistent line endings in a string. * Changes every end of line from CRLF, CR or LF to $this->LE. @@ -3347,7 +3354,7 @@ class PHPMailer } return $nstr; } - + /** * Add a custom header. * $name value can be overloaded to contain @@ -3366,7 +3373,7 @@ class PHPMailer $this->CustomHeader[] = array($name, $value); } } - + /** * Returns all custom headers. * @return array @@ -3375,17 +3382,19 @@ class PHPMailer { return $this->CustomHeader; } - + /** * Create a message body from an HTML string. * Automatically inlines images and creates a plain-text version by converting the HTML, * overwriting any existing values in Body and AltBody. - * $basedir is used when handling relative image paths, e.g. + * Do not source $message content from user input! + * $basedir is prepended when handling relative URLs, e.g. and must not be empty * will look for an image file in $basedir/images/a.png and convert it to inline. - * If you don't want to apply these transformations to your HTML, just set Body and AltBody yourself. + * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email) + * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly. * @access public * @param string $message HTML message string - * @param string $basedir base directory for relative paths to images + * @param string $basedir Absolute path to a base directory to prepend to relative paths to images * @param boolean|callable $advanced Whether to use the internal HTML to text converter * or your own custom converter @see PHPMailer::html2text() * @return string $message The transformed message Body @@ -3394,6 +3403,10 @@ class PHPMailer { preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images); if (array_key_exists(2, $images)) { + if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { + // Ensure $basedir has a trailing / + $basedir .= '/'; + } foreach ($images[2] as $imgindex => $url) { // Convert data URIs into embedded images if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) { @@ -3411,36 +3424,42 @@ class PHPMailer $message ); } - } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) { - // Do not change urls for absolute images (thanks to corvuscorax) - // Do not change urls that are already inline images - $filename = basename($url); - $directory = dirname($url); - if ($directory == '.') { - $directory = ''; - } - $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 - if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { - $basedir .= '/'; - } - if (strlen($directory) > 1 && substr($directory, -1) != '/') { - $directory .= '/'; - } - if ($this->addEmbeddedImage( - $basedir . $directory . $filename, - $cid, - $filename, - 'base64', - self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION)) - ) - ) { - $message = preg_replace( - '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', - $images[1][$imgindex] . '="cid:' . $cid . '"', - $message - ); - } + continue; } + if ( + // Only process relative URLs if a basedir is provided (i.e. no absolute local paths) + !empty($basedir) + // Ignore URLs containing parent dir traversal (..) + && (strpos($url, '..') === false) + // Do not change urls that are already inline images + && substr($url, 0, 4) !== 'cid:' + // Do not change absolute URLs, including anonymous protocol + && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url) + ) { + $filename = basename($url); + $directory = dirname($url); + if ($directory == '.') { + $directory = ''; + } + $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2 + if (strlen($directory) > 1 && substr($directory, -1) != '/') { + $directory .= '/'; + } + if ($this->addEmbeddedImage( + $basedir . $directory . $filename, + $cid, + $filename, + 'base64', + self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION)) + ) + ) { + $message = preg_replace( + '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', + $images[1][$imgindex] . '="cid:' . $cid . '"', + $message + ); + } + } } } $this->isHTML(true); @@ -3453,7 +3472,7 @@ class PHPMailer } return $this->Body; } - + /** * Convert an HTML string into plain text. * This is used by msgHTML(). @@ -3485,7 +3504,7 @@ class PHPMailer $this->CharSet ); } - + /** * Get the MIME type for a file extension. * @param string $ext File extension @@ -3600,7 +3619,7 @@ class PHPMailer } return 'application/octet-stream'; } - + /** * Map a file name to a MIME type. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data. @@ -3618,7 +3637,7 @@ class PHPMailer $pathinfo = self::mb_pathinfo($filename); return self::_mime_types($pathinfo['extension']); } - + /** * Multi-byte-safe pathinfo replacement. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. @@ -3665,7 +3684,7 @@ class PHPMailer return $ret; } } - + /** * Set or reset instance properties. * You should avoid this function - it's more verbose, less efficient, more error-prone and @@ -3690,7 +3709,7 @@ class PHPMailer return false; } } - + /** * Strip newlines to prevent header injection. * @access public @@ -3701,7 +3720,7 @@ class PHPMailer { return trim(str_replace(array("\r", "\n"), '', $str)); } - + /** * Normalize line breaks in a string. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format. @@ -3716,7 +3735,7 @@ class PHPMailer { return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); } - + /** * Set the public and private key files and password for S/MIME signing. * @access public @@ -3732,7 +3751,7 @@ class PHPMailer $this->sign_key_pass = $key_pass; $this->sign_extracerts_file = $extracerts_filename; } - + /** * Quoted-Printable-encode a DKIM header. * @access public @@ -3752,7 +3771,7 @@ class PHPMailer } return $line; } - + /** * Generate a DKIM signature. * @access public @@ -3790,7 +3809,7 @@ class PHPMailer $t = '3031300d060960864801650304020105000420' . $hash; $pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3); $eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t); - + if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) { openssl_pkey_free($privKey); return base64_encode($signature); @@ -3799,7 +3818,7 @@ class PHPMailer openssl_pkey_free($privKey); return ''; } - + /** * Generate a DKIM canonicalization header. * @access public @@ -3819,7 +3838,7 @@ class PHPMailer $signHeader = implode("\r\n", $lines); return $signHeader; } - + /** * Generate a DKIM canonicalization body. * @access public @@ -3840,7 +3859,7 @@ class PHPMailer } return $body; } - + /** * Create the DKIM header and body in a new message header. * @access public @@ -3920,7 +3939,7 @@ class PHPMailer $signed = $this->DKIM_Sign($toSign); return $dkimhdrs . $signed . "\r\n"; } - + /** * Detect if a string contains a line longer than the maximum line length allowed. * @param string $str @@ -3932,7 +3951,7 @@ class PHPMailer //+2 to include CRLF line break for a 1000 total return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str); } - + /** * Allows for public read access to 'to' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. @@ -3943,7 +3962,7 @@ class PHPMailer { return $this->to; } - + /** * Allows for public read access to 'cc' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. @@ -3954,7 +3973,7 @@ class PHPMailer { return $this->cc; } - + /** * Allows for public read access to 'bcc' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. @@ -3965,7 +3984,7 @@ class PHPMailer { return $this->bcc; } - + /** * Allows for public read access to 'ReplyTo' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. @@ -3976,7 +3995,7 @@ class PHPMailer { return $this->ReplyTo; } - + /** * Allows for public read access to 'all_recipients' property. * @note: Before the send() call, queued addresses (i.e. with IDN) are not yet included. @@ -3987,7 +4006,7 @@ class PHPMailer { return $this->all_recipients; } - + /** * Perform a callback. * @param boolean $isSent @@ -4019,7 +4038,7 @@ class phpmailerException extends Exception */ public function errorMessage() { - $errorMsg = '' . $this->getMessage() . "
\n"; + $errorMsg = '' . htmlspecialchars($this->getMessage()) . "
\n"; return $errorMsg; } -} +} \ No newline at end of file diff --git a/lib/classes/phpmailer/class.SMTP.php b/lib/classes/phpmailer/class.SMTP.php index 886782dc..a3a67baa 100644 --- a/lib/classes/phpmailer/class.SMTP.php +++ b/lib/classes/phpmailer/class.SMTP.php @@ -1,88 +1,88 @@ -* @author Jim Jagielski (jimjag) -* @author Andy Prevost (codeworxtech) -* @author Brent R. Matzelle (original founder) -* @copyright 2014 Marcus Bointon -* @copyright 2010 - 2012 Jim Jagielski -* @copyright 2004 - 2009 Andy Prevost -* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License -* @note This program is distributed in the hope that it will be useful - WITHOUT -* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -* FITNESS FOR A PARTICULAR PURPOSE. -*/ + * PHP Version 5 + * @package PHPMailer + * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project + * @author Marcus Bointon (Synchro/coolbru) + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2014 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ /** * PHPMailer RFC821 SMTP email transport class. -* Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. -* @package PHPMailer -* @author Chris Ryan -* @author Marcus Bointon -*/ + * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. + * @package PHPMailer + * @author Chris Ryan + * @author Marcus Bointon + */ class SMTP { /** * The PHPMailer SMTP version number. * @var string */ - const VERSION = '5.2.21'; - + const VERSION = '5.2.26'; + /** * SMTP line break constant. * @var string */ const CRLF = "\r\n"; - + /** * The SMTP port to use if one is not specified. * @var integer */ const DEFAULT_SMTP_PORT = 25; - + /** * The maximum line length allowed by RFC 2822 section 2.1.1 * @var integer */ const MAX_LINE_LENGTH = 998; - + /** * Debug level for no output */ const DEBUG_OFF = 0; - + /** * Debug level to show client -> server messages */ const DEBUG_CLIENT = 1; - + /** * Debug level to show client -> server and server -> client messages */ const DEBUG_SERVER = 2; - + /** * Debug level to show connection status, client -> server and server -> client messages */ const DEBUG_CONNECTION = 3; - + /** * Debug level to show all messages */ const DEBUG_LOWLEVEL = 4; - + /** * The PHPMailer SMTP Version number. * @var string * @deprecated Use the `VERSION` constant instead * @see SMTP::VERSION */ - public $Version = '5.2.21'; - + public $Version = '5.2.26'; + /** * SMTP server port number. * @var integer @@ -90,7 +90,7 @@ class SMTP * @see SMTP::DEFAULT_SMTP_PORT */ public $SMTP_PORT = 25; - + /** * SMTP reply line ending. * @var string @@ -98,7 +98,7 @@ class SMTP * @see SMTP::CRLF */ public $CRLF = "\r\n"; - + /** * Debug output level. * Options: @@ -110,7 +110,7 @@ class SMTP * @var integer */ public $do_debug = self::DEBUG_OFF; - + /** * How to handle debug output. * Options: @@ -125,7 +125,7 @@ class SMTP * @var string|callable */ public $Debugoutput = 'echo'; - + /** * Whether to use VERP. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path @@ -133,7 +133,7 @@ class SMTP * @var boolean */ public $do_verp = false; - + /** * The timeout value for connection, in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 @@ -142,31 +142,36 @@ class SMTP * @var integer */ public $Timeout = 300; - + /** * How long to wait for commands to complete, in seconds. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 * @var integer */ public $Timelimit = 300; - + /** - * @var array patterns to extract smtp transaction id from smtp reply - * Only first capture group will be use, use non-capturing group to deal with it - * Extend this class to override this property to fulfil your needs. + * @var array Patterns to extract an SMTP transaction id from reply to a DATA command. + * The first capture group in each regex will be used as the ID. */ protected $smtp_transaction_id_patterns = array( 'exim' => '/[0-9]{3} OK id=(.*)/', 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/', 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/' ); - + + /** + * @var string The last transaction ID issued in response to a DATA command, + * if one was detected + */ + protected $last_smtp_transaction_id; + /** * The socket for the server connection. * @var resource */ protected $smtp_conn; - + /** * Error information, if any, for the last SMTP command. * @var array @@ -177,14 +182,14 @@ class SMTP 'smtp_code' => '', 'smtp_code_ex' => '' ); - + /** * The reply the server sent to us for HELO. * If null, no HELO string has yet been received. * @var string|null */ protected $helo_rply = null; - + /** * The set of SMTP extensions sent in reply to EHLO command. * Indexes of the array are extension names. @@ -195,13 +200,13 @@ class SMTP * @var array|null */ protected $server_caps = null; - + /** * The most recent reply received from the server. * @var string */ protected $last_reply = ''; - + /** * Output debugging info via a user-selected method. * @see SMTP::$Debugoutput @@ -227,12 +232,11 @@ class SMTP break; case 'html': //Cleans up output a bit for a better looking, HTML-safe output - echo htmlentities( + echo gmdate('Y-m-d H:i:s') . ' ' . htmlentities( preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8' - ) - . "
\n"; + ) . "
\n"; break; case 'echo': default: @@ -242,10 +246,10 @@ class SMTP "\n", "\n \t ", trim($str) - )."\n"; + ) . "\n"; } } - + /** * Connect to an SMTP server. * @param string $host SMTP server IP or host name @@ -276,7 +280,8 @@ class SMTP } // Connect to the SMTP server $this->edebug( - "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true), + "Connection: opening to $host:$port, timeout=$timeout, options=" . + var_export($options, true), self::DEBUG_CONNECTION ); $errno = 0; @@ -339,7 +344,7 @@ class SMTP $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER); return true; } - + /** * Initiate a TLS (encrypted) session. * @access public @@ -350,28 +355,28 @@ class SMTP if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { return false; } - + //Allow the best TLS version(s) we can $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; - + //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT //so add them back in manually if we can if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; } - + // Begin encrypted connection - if (!stream_socket_enable_crypto( + set_error_handler(array($this, 'errorHandler')); + $crypto_ok = stream_socket_enable_crypto( $this->smtp_conn, true, $crypto_method - )) { - return false; - } - return true; + ); + restore_error_handler(); + return $crypto_ok; } - + /** * Perform SMTP authentication. * Must be run after hello(). @@ -396,23 +401,22 @@ class SMTP $this->setError('Authentication is not allowed before HELO/EHLO'); return false; } - + if (array_key_exists('EHLO', $this->server_caps)) { - // SMTP extensions are available. Let's try to find a proper authentication method - + // SMTP extensions are available; try to find a proper authentication method if (!array_key_exists('AUTH', $this->server_caps)) { $this->setError('Authentication is not allowed at this stage'); // 'at this stage' means that auth may be allowed after the stage changes // e.g. after STARTTLS return false; } - + self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL); self::edebug( 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), self::DEBUG_LOWLEVEL ); - + if (empty($authtype)) { foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN', 'NTLM', 'XOAUTH2') as $method) { if (in_array($method, $this->server_caps['AUTH'])) { @@ -424,9 +428,9 @@ class SMTP $this->setError('No supported authentication methods found'); return false; } - self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL); + self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL); } - + if (!in_array($authtype, $this->server_caps['AUTH'])) { $this->setError("The requested authentication method \"$authtype\" is not supported by the server"); return false; @@ -469,7 +473,7 @@ class SMTP return false; } $oauth = $OAuth->getOauth64(); - + // Start authentication if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { return false; @@ -499,7 +503,7 @@ class SMTP } //msg1 $msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1 - + if (!$this->sendCommand( 'AUTH NTLM', 'AUTH NTLM ' . base64_encode($msg1), @@ -532,10 +536,10 @@ class SMTP } // Get the challenge $challenge = base64_decode(substr($this->last_reply, 4)); - + // Build the response $response = $username . ' ' . $this->hmac($challenge, $password); - + // send encoded credentials return $this->sendCommand('Username', base64_encode($response), 235); default: @@ -544,13 +548,13 @@ class SMTP } return true; } - + /** * Calculate an MD5 HMAC hash. * Works like hash_hmac('md5', $data, $key) * in case that function is not available * @param string $data The data to hash - * @param string $key The key to hash with + * @param string $key The key to hash with * @access protected * @return string */ @@ -559,15 +563,15 @@ class SMTP if (function_exists('hash_hmac')) { return hash_hmac('md5', $data, $key); } - + // The following borrowed from // http://php.net/manual/en/function.mhash.php#27225 - + // RFC 2104 HMAC implementation for php. // Creates an md5 HMAC. // Eliminates the need to install mhash to compute a HMAC // by Lance Rushing - + $bytelen = 64; // byte length for md5 if (strlen($key) > $bytelen) { $key = pack('H*', md5($key)); @@ -577,10 +581,10 @@ class SMTP $opad = str_pad('', $bytelen, chr(0x5c)); $k_ipad = $key ^ $ipad; $k_opad = $key ^ $opad; - + return md5($k_opad . pack('H*', md5($k_ipad . $data))); } - + /** * Check connection state. * @access public @@ -603,7 +607,7 @@ class SMTP } return false; } - + /** * Close the socket and clean up the state of the class. * Don't use this function without first trying to use QUIT. @@ -623,7 +627,7 @@ class SMTP $this->edebug('Connection: closed', self::DEBUG_CONNECTION); } } - + /** * Send an SMTP DATA command. * Issues a data command and sends the msg_data to the server, @@ -642,7 +646,7 @@ class SMTP if (!$this->sendCommand('DATA', 'DATA', 354)) { return false; } - + /* The server is ready to accept data! * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF) * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into @@ -650,21 +654,21 @@ class SMTP * We will also look for lines that start with a '.' and prepend an additional '.'. * NOTE: this does not count towards line-length limit. */ - + // Normalize line breaks before exploding $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data)); - + /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field * of the first line (':' separated) does not contain a space then it _should_ be a header and we will * process all lines before a blank line as headers. */ - + $field = substr($lines[0], 0, strpos($lines[0], ':')); $in_headers = false; if (!empty($field) && strpos($field, ' ') === false) { $in_headers = true; } - + foreach ($lines as $line) { $lines_out = array(); if ($in_headers and $line == '') { @@ -694,7 +698,7 @@ class SMTP } } $lines_out[] = $line; - + //Send the lines to the server foreach ($lines_out as $line_out) { //RFC2821 section 4.5.2 @@ -704,17 +708,18 @@ class SMTP $this->client_send($line_out . self::CRLF); } } - + //Message data has been sent, complete the command //Increase timelimit for end of DATA command $savetimelimit = $this->Timelimit; $this->Timelimit = $this->Timelimit * 2; $result = $this->sendCommand('DATA END', '.', 250); + $this->recordLastTransactionID(); //Restore timelimit $this->Timelimit = $savetimelimit; return $result; } - + /** * Send an SMTP HELO or EHLO command. * Used to identify the sending server to the receiving server. @@ -730,7 +735,7 @@ class SMTP //Try extended hello first (RFC 2821) return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host)); } - + /** * Send an SMTP HELO or EHLO command. * Low-level implementation used by hello() @@ -751,7 +756,7 @@ class SMTP } return $noerror; } - + /** * Parse a reply to HELO/EHLO command to discover server extensions. * In case of HELO, the only parameter that can be discovered is a server name. @@ -762,7 +767,7 @@ class SMTP { $this->server_caps = array(); $lines = explode("\n", $this->helo_rply); - + foreach ($lines as $n => $s) { //First 4 chars contain response code followed by - or space $s = trim(substr($s, 4)); @@ -793,7 +798,7 @@ class SMTP } } } - + /** * Send an SMTP MAIL command. * Starts a mail transaction from the email address specified in @@ -814,7 +819,7 @@ class SMTP 250 ); } - + /** * Send an SMTP QUIT command. * Closes the socket if there is no error or the $close_on_error argument is true. @@ -833,7 +838,7 @@ class SMTP } return $noerror; } - + /** * Send an SMTP RCPT command. * Sets the TO argument to $toaddr. @@ -851,7 +856,7 @@ class SMTP array(250, 251) ); } - + /** * Send an SMTP RSET command. * Abort any transaction that is currently in progress. @@ -863,7 +868,7 @@ class SMTP { return $this->sendCommand('RSET', 'RSET', 250); } - + /** * Send a command to an SMTP server and check its return code. * @param string $command The command name - not sent to the server @@ -884,7 +889,7 @@ class SMTP return false; } $this->client_send($commandstring . self::CRLF); - + $this->last_reply = $this->get_lines(); // Fetch SMTP code and possible error code explanation $matches = array(); @@ -893,7 +898,8 @@ class SMTP $code_ex = (count($matches) > 2 ? $matches[2] : null); // Cut off error code from each response line $detail = preg_replace( - "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m", + "/{$code}[ -]" . + ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m", '', $this->last_reply ); @@ -903,9 +909,9 @@ class SMTP $code_ex = null; $detail = substr($this->last_reply, 4); } - + $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); - + if (!in_array($code, (array)$expect)) { $this->setError( "$command command failed", @@ -919,11 +925,11 @@ class SMTP ); return false; } - + $this->setError(''); return true; } - + /** * Send an SMTP SAML command. * Starts a mail transaction from the email address specified in $from. @@ -941,7 +947,7 @@ class SMTP { return $this->sendCommand('SAML', "SAML FROM:$from", 250); } - + /** * Send an SMTP VRFY command. * @param string $name The name to verify @@ -952,7 +958,7 @@ class SMTP { return $this->sendCommand('VRFY', "VRFY $name", array(250, 251)); } - + /** * Send an SMTP NOOP command. * Used to keep keep-alives alive, doesn't actually do anything @@ -963,7 +969,7 @@ class SMTP { return $this->sendCommand('NOOP', 'NOOP', 250); } - + /** * Send an SMTP TURN command. * This is an optional command for SMTP that this class does not support. @@ -979,7 +985,7 @@ class SMTP $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); return false; } - + /** * Send raw data to the server. * @param string $data The data to send @@ -989,9 +995,12 @@ class SMTP public function client_send($data) { $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT); - return fwrite($this->smtp_conn, $data); + set_error_handler(array($this, 'errorHandler')); + $result = fwrite($this->smtp_conn, $data); + restore_error_handler(); + return $result; } - + /** * Get the latest error. * @access public @@ -1001,7 +1010,7 @@ class SMTP { return $this->error; } - + /** * Get SMTP extensions available on the server * @access public @@ -1011,7 +1020,7 @@ class SMTP { return $this->server_caps; } - + /** * A multipurpose method * The method works in three ways, dependent on argument value and current state @@ -1037,7 +1046,7 @@ class SMTP $this->setError('No HELO/EHLO was sent'); return null; } - + // the tight logic knot ;) if (!array_key_exists($name, $this->server_caps)) { if ($name == 'HELO') { @@ -1049,10 +1058,10 @@ class SMTP $this->setError('HELO handshake was used. Client knows nothing about server extensions'); return null; } - + return $this->server_caps[$name]; } - + /** * Get the last reply from the server. * @access public @@ -1062,7 +1071,7 @@ class SMTP { return $this->last_reply; } - + /** * Read the SMTP server's response. * Either before eof or socket timeout occurs on the operation. @@ -1089,8 +1098,10 @@ class SMTP $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL); $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL); $data .= $str; - // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen - if ((isset($str[3]) and $str[3] == ' ')) { + // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled), + // or 4th character is a space, we are done reading, break the loop, + // string array access is a micro-optimisation over strlen + if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) { break; } // Timed-out? Log and break @@ -1105,7 +1116,7 @@ class SMTP // Now check if reads took too long if ($endtime and time() > $endtime) { $this->edebug( - 'SMTP -> get_lines(): timelimit reached ('. + 'SMTP -> get_lines(): timelimit reached (' . $this->Timelimit . ' sec)', self::DEBUG_LOWLEVEL ); @@ -1114,7 +1125,7 @@ class SMTP } return $data; } - + /** * Enable or disable VERP address generation. * @param boolean $enabled @@ -1123,7 +1134,7 @@ class SMTP { $this->do_verp = $enabled; } - + /** * Get VERP address generation mode. * @return boolean @@ -1132,7 +1143,7 @@ class SMTP { return $this->do_verp; } - + /** * Set error messages and codes. * @param string $message The error message @@ -1149,7 +1160,7 @@ class SMTP 'smtp_code_ex' => $smtp_code_ex ); } - + /** * Set debug output method. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it. @@ -1158,7 +1169,7 @@ class SMTP { $this->Debugoutput = $method; } - + /** * Get debug output method. * @return string @@ -1167,7 +1178,7 @@ class SMTP { return $this->Debugoutput; } - + /** * Set debug output level. * @param integer $level @@ -1176,7 +1187,7 @@ class SMTP { $this->do_debug = $level; } - + /** * Get debug output level. * @return integer @@ -1185,7 +1196,7 @@ class SMTP { return $this->do_debug; } - + /** * Set SMTP timeout. * @param integer $timeout @@ -1194,7 +1205,7 @@ class SMTP { $this->Timeout = $timeout; } - + /** * Get SMTP timeout. * @return integer @@ -1203,47 +1214,63 @@ class SMTP { return $this->Timeout; } - + /** * Reports an error number and string. * @param integer $errno The error number returned by PHP. * @param string $errmsg The error message returned by PHP. + * @param string $errfile The file the error occurred in + * @param integer $errline The line number the error occurred on */ - protected function errorHandler($errno, $errmsg) + protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0) { - $notice = 'Connection: Failed to connect to server.'; + $notice = 'Connection failed.'; $this->setError( $notice, $errno, $errmsg ); $this->edebug( - $notice . ' Error number ' . $errno . '. "Error notice: ' . $errmsg, + $notice . ' Error #' . $errno . ': ' . $errmsg . " [$errfile line $errline]", self::DEBUG_CONNECTION ); } - + /** - * Will return the ID of the last smtp transaction based on a list of patterns provided - * in SMTP::$smtp_transaction_id_patterns. + * Extract and return the ID of the last SMTP transaction based on + * a list of patterns provided in SMTP::$smtp_transaction_id_patterns. + * Relies on the host providing the ID in response to a DATA command. * If no reply has been received yet, it will return null. - * If no pattern has been matched, it will return false. + * If no pattern was matched, it will return false. * @return bool|null|string */ + protected function recordLastTransactionID() + { + $reply = $this->getLastReply(); + + if (empty($reply)) { + $this->last_smtp_transaction_id = null; + } else { + $this->last_smtp_transaction_id = false; + foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { + if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) { + $this->last_smtp_transaction_id = $matches[1]; + } + } + } + + return $this->last_smtp_transaction_id; + } + + /** + * Get the queue/transaction ID of the last SMTP transaction + * If no reply has been received yet, it will return null. + * If no pattern was matched, it will return false. + * @return bool|null|string + * @see recordLastTransactionID() + */ public function getLastTransactionID() { - $reply = $this->getLastReply(); - - if (empty($reply)) { - return null; - } - - foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) { - if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) { - return $matches[1]; - } - } - - return false; + return $this->last_smtp_transaction_id; } } From 2603a9c869e9262e1e6e7c3d18e5a521be940ea1 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 26 Jan 2018 17:30:20 +0100 Subject: [PATCH 145/179] add new setting to specify values for the PATH env-variable for php-fpm Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/136.phpfpm.php | 11 +++++++++++ install/froxlor.sql | 3 ++- install/updates/froxlor/0.9/update_0.9.inc.php | 9 +++++++++ lib/classes/phpinterface/class.phpinterface_fpm.php | 4 ++++ lib/version.inc.php | 2 +- lng/english.lng.php | 2 ++ lng/german.lng.php | 1 + 7 files changed, 30 insertions(+), 2 deletions(-) diff --git a/actions/admin/settings/136.phpfpm.php b/actions/admin/settings/136.phpfpm.php index a62f0c2f..c8b6e0ea 100644 --- a/actions/admin/settings/136.phpfpm.php +++ b/actions/admin/settings/136.phpfpm.php @@ -69,6 +69,17 @@ return array( 'default' => '/usr/share/php/:/usr/share/php5/', 'save_method' => 'storeSettingField' ), + 'system_phpfpm_envpath' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['envpath'], + 'settinggroup' => 'phpfpm', + 'varname' => 'envpath', + 'type' => 'string', + 'string_type' => 'dir', + 'string_delimiter' => ':', + 'string_emptyallowed' => true, + 'default' => '/usr/local/bin:/usr/bin:/bin', + 'save_method' => 'storeSettingField' + ), 'system_phpfpm_fastcgi_ipcdir' => array( 'label' => $lng['serversettings']['phpfpm_settings']['ipcdir'], 'settinggroup' => 'phpfpm', diff --git a/install/froxlor.sql b/install/froxlor.sql index 1bd72d32..a54798a4 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -414,6 +414,7 @@ INSERT INTO `panel_settings` (`settinggroup`, `varname`, `value`) VALUES ('phpfpm', 'max_requests', '0'), ('phpfpm', 'tmpdir', '/var/customers/tmp/'), ('phpfpm', 'peardir', '/usr/share/php/:/usr/share/php5/'), + ('phpfpm', 'envpath', '/usr/local/bin:/usr/bin:/bin'), ('phpfpm', 'enabled_ownvhost', '0'), ('phpfpm', 'vhost_httpuser', 'froxlorlocal'), ('phpfpm', 'vhost_httpgroup', 'froxlorlocal'), @@ -686,7 +687,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.38.8'), - ('panel', 'db_version', '201801110'); + ('panel', 'db_version', '201801260'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index e9e1e39e..6c9fa665 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3865,3 +3865,12 @@ opcache.interned_strings_buffer'); updateToDbVersion('201801110'); } + +if (isDatabaseVersion('201801110')) { + + showUpdateStep("Adding php-fpm php PATH setting for envrironment"); + Settings::AddNew("phpfpm.envpath", '/usr/local/bin:/usr/bin:/bin'); + lastStepStatus(0); + + updateToDbVersion('201801260'); +} diff --git a/lib/classes/phpinterface/class.phpinterface_fpm.php b/lib/classes/phpinterface/class.phpinterface_fpm.php index f72a2410..daf358ad 100644 --- a/lib/classes/phpinterface/class.phpinterface_fpm.php +++ b/lib/classes/phpinterface/class.phpinterface_fpm.php @@ -169,6 +169,10 @@ class phpinterface_fpm $this->getTempDir(); } + $env_path = Settings::Get('phpfpm.envpath'); + if (!empty($env_path)) { + $fpm_config .= 'env[PATH] = ' . $env_path . "\n"; + } $fpm_config .= 'env[TMP] = ' . $tmpdir . "\n"; $fpm_config .= 'env[TMPDIR] = ' . $tmpdir . "\n"; $fpm_config .= 'env[TEMP] = ' . $tmpdir . "\n"; diff --git a/lib/version.inc.php b/lib/version.inc.php index 4f1da38b..5ebe2f3b 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.38.8'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201801110'; +$dbversion = '201801260'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index 831893f2..bb58842e 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2100,3 +2100,5 @@ $lng['phpfpm']['ini_flags'] = 'Enter possible php_flags for php $lng['phpfpm']['ini_values'] = 'Enter possible php_values for php.ini. One entry per line'; $lng['phpfpm']['ini_admin_flags'] = 'Enter possible php_admin_flags for php.ini. One entry per line'; $lng['phpfpm']['ini_admin_values'] = 'Enter possible php_admin_values for php.ini. One entry per line'; +$lng['serversettings']['phpfpm_settings']['envpath'] = 'Paths to add to the PATH environment. Leave empty for no PATH environment variable'; + diff --git a/lng/german.lng.php b/lng/german.lng.php index 9ccfa6da..b822aa3b 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1751,3 +1751,4 @@ $lng['phpfpm']['ini_flags'] = 'Mögliche php_flags für die php $lng['phpfpm']['ini_values'] = 'Mögliche php_values für die php.ini. Pro Zeile eine Direktive'; $lng['phpfpm']['ini_admin_flags'] = 'Mögliche php_admin_flags für die php.ini. Pro Zeile eine Direktive'; $lng['phpfpm']['ini_admin_values'] = 'Mögliche php_admin_values für die php.ini. Pro Zeile eine Direktive'; +$lng['serversettings']['phpfpm_settings']['envpath'] = 'Pfade für die PATH Umgebungsvariable. Leerlassen, um keine PATH Umgebungsvariable zu setzen.'; From f896fe11a0519d2d26c1b1387fce7b00a32aaed9 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 27 Jan 2018 10:09:43 +0100 Subject: [PATCH 146/179] do not split dkim-entry content in generateDkimEntries(); re-add braces to enclose TXT record content Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/dns/class.DnsEntry.php | 4 ++-- lib/functions/dns/function.generateDkimEntries.php | 14 +------------- 2 files changed, 3 insertions(+), 15 deletions(-) diff --git a/lib/classes/dns/class.DnsEntry.php b/lib/classes/dns/class.DnsEntry.php index 11a7a614..a5685741 100644 --- a/lib/classes/dns/class.DnsEntry.php +++ b/lib/classes/dns/class.DnsEntry.php @@ -52,7 +52,7 @@ class DnsEntry if (substr($_l, 0, 1) == '"') { $_l = substr($_l, 1); } - $_content = '"' . $_l . '"' . PHP_EOL; + $_content = '("' . $_l . '"' . PHP_EOL; $_l = array_pop($_contentlines); // check for ending quote if (substr($_l, - 1) == '"') { @@ -63,7 +63,7 @@ class DnsEntry $_content .= "\t\t\t\t" . '"' . $_cl . '"' . PHP_EOL; } // last line - $_content .= "\t\t\t\t" . '"' . $_l . '"'; + $_content .= "\t\t\t\t" . '"' . $_l . '")'; } $result = $this->record . "\t" . $this->ttl . "\t" . $this->class . "\t" . $this->type . "\t" . (($this->priority >= 0 && ($this->type == 'MX' || $this->type == 'SRV')) ? $this->priority . "\t" : "") . $_content . PHP_EOL; return $result; diff --git a/lib/functions/dns/function.generateDkimEntries.php b/lib/functions/dns/function.generateDkimEntries.php index 622af765..993df741 100644 --- a/lib/functions/dns/function.generateDkimEntries.php +++ b/lib/functions/dns/function.generateDkimEntries.php @@ -54,20 +54,8 @@ function generateDkimEntries($domain) // end-part $dkim_txt .= 't=s'; - if (Settings::Get('system.dns_server') == 'pdns') { - // PowerDNS does not need/want splitted content - $txt_record_split = $dkim_txt; - } else { - // split if necessary - $txt_record_split = ''; - $lbr = 50; - for ($pos = 0; $pos <= strlen($dkim_txt) - 1; $pos += $lbr) { - $txt_record_split .= (($pos == 0) ? '("' : "\t\t\t\t\t \"") . substr($dkim_txt, $pos, $lbr) . (($pos >= strlen($dkim_txt) - $lbr) ? '")' : '"') . "\n"; - } - } - // dkim-entry - $zone_dkim[] = $txt_record_split; + $zone_dkim[] = $dkim_txt; // adsp-entry if (Settings::Get('dkim.dkim_add_adsp') == "1") { From f034695290575a215c58df76e8a9e49aa6cda8c0 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 27 Jan 2018 11:14:22 +0100 Subject: [PATCH 147/179] remove '/etc/postfix/master.cf: line x: using backwards-compatible default setting chroot=y' warning; set correct permission for dkim-public key as it should not be group or other writable Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/stretch.xml | 52 +++++++++++++++---------------- scripts/classes/class.DnsBase.php | 2 +- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/lib/configfiles/stretch.xml b/lib/configfiles/stretch.xml index eb6c71d1..80335daa 100644 --- a/lib/configfiles/stretch.xml +++ b/lib/configfiles/stretch.xml @@ -2343,12 +2343,12 @@ virtual_mailbox_limit = 0 # service type private unpriv chroot wakeup maxproc command + args # (yes) (yes) (yes) (never) (100) # ========================================================================== -smtp inet n - - - - smtpd -#smtp inet n - - - 1 postscreen -#smtpd pass - - - - - smtpd -#dnsblog unix - - - - 0 dnsblog -#tlsproxy unix - - - - 0 tlsproxy -#submission inet n - - - - smtpd +smtp inet n - y - - smtpd +#smtp inet n - y - 1 postscreen +#smtpd pass - - y - - smtpd +#dnsblog unix - - y - 0 dnsblog +#tlsproxy unix - - y - 0 tlsproxy +#submission inet n - y - - smtpd # -o syslog_name=postfix/submission # -o smtpd_tls_security_level=encrypt # -o smtpd_sasl_auth_enable=yes @@ -2359,7 +2359,7 @@ smtp inet n - - - - smtpd # -o smtpd_recipient_restrictions= # -o smtpd_relay_restrictions=permit_sasl_authenticated,reject # -o milter_macro_daemon_name=ORIGINATING -#smtps inet n - - - - smtpd +#smtps inet n - y - - smtpd # -o syslog_name=postfix/smtps # -o smtpd_tls_wrappermode=yes # -o smtpd_sasl_auth_enable=yes @@ -2370,32 +2370,32 @@ smtp inet n - - - - smtpd # -o smtpd_recipient_restrictions= # -o smtpd_relay_restrictions=permit_sasl_authenticated,reject # -o milter_macro_daemon_name=ORIGINATING -#628 inet n - - - - qmqpd -pickup unix n - - 60 1 pickup -cleanup unix n - - - 0 cleanup +#628 inet n - y - - qmqpd +pickup unix n - y 60 1 pickup +cleanup unix n - y - 0 cleanup qmgr unix n - n 300 1 qmgr #qmgr unix n - n 300 1 oqmgr -tlsmgr unix - - - 1000? 1 tlsmgr -rewrite unix - - - - - trivial-rewrite -bounce unix - - - - 0 bounce -defer unix - - - - 0 bounce -trace unix - - - - 0 bounce -verify unix - - - - 1 verify -flush unix n - - 1000? 0 flush +tlsmgr unix - - y 1000? 1 tlsmgr +rewrite unix - - y - - trivial-rewrite +bounce unix - - y - 0 bounce +defer unix - - y - 0 bounce +trace unix - - y - 0 bounce +verify unix - - y - 1 verify +flush unix n - y 1000? 0 flush proxymap unix - - n - - proxymap proxywrite unix - - n - 1 proxymap -smtp unix - - - - - smtp -relay unix - - - - - smtp +smtp unix - - y - - smtp +relay unix - - y - - smtp # -o smtp_helo_timeout=5 -o smtp_connect_timeout=5 -showq unix n - - - - showq -error unix - - - - - error -retry unix - - - - - error -discard unix - - - - - discard +showq unix n - y - - showq +error unix - - y - - error +retry unix - - y - - error +discard unix - - y - - discard local unix - n n - - local virtual unix - n n - - virtual -lmtp unix - - - - - lmtp -anvil unix - - - - 1 anvil -scache unix - - - - 1 scache +lmtp unix - - y - - lmtp +anvil unix - - y - 1 anvil +scache unix - - y - 1 scache # # ==================================================================== # Interfaces to non-Postfix software. Be sure to examine the manual diff --git a/scripts/classes/class.DnsBase.php b/scripts/classes/class.DnsBase.php index 46c83926..68a5ba3c 100644 --- a/scripts/classes/class.DnsBase.php +++ b/scripts/classes/class.DnsBase.php @@ -233,7 +233,7 @@ abstract class DnsBase $pubkey_file_handler = fopen($pubkey_filename, "w"); fwrite($pubkey_file_handler, $domain['dkim_pubkey']); fclose($pubkey_file_handler); - safe_exec("chmod 0664 " . escapeshellarg($pubkey_filename)); + safe_exec("chmod 0644 " . escapeshellarg($pubkey_filename)); } $dkimdomains .= $domain['domain'] . "\n"; From 194b7863b8486156c5517af298cccabc1bb485b8 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 27 Jan 2018 11:37:06 +0100 Subject: [PATCH 148/179] fix invalid ipv6 value in mysql-access-host setting Signed-off-by: Michael Kaufmann (d00p) --- .../function.storeSettingMysqlAccessHost.php | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/lib/functions/settings/function.storeSettingMysqlAccessHost.php b/lib/functions/settings/function.storeSettingMysqlAccessHost.php index b324f248..decb17b5 100644 --- a/lib/functions/settings/function.storeSettingMysqlAccessHost.php +++ b/lib/functions/settings/function.storeSettingMysqlAccessHost.php @@ -16,33 +16,36 @@ * @package Functions * */ - function storeSettingMysqlAccessHost($fieldname, $fielddata, $newfieldvalue) { $returnvalue = storeSettingField($fieldname, $fielddata, $newfieldvalue); - if($returnvalue !== false && is_array($fielddata) && isset($fielddata['settinggroup']) && $fielddata['settinggroup'] == 'system' && isset($fielddata['varname']) && $fielddata['varname'] == 'mysql_access_host') - { + if ($returnvalue !== false && is_array($fielddata) && isset($fielddata['settinggroup']) && $fielddata['settinggroup'] == 'system' && isset($fielddata['varname']) && $fielddata['varname'] == 'mysql_access_host') { $mysql_access_host_array = array_map('trim', explode(',', $newfieldvalue)); - if(in_array('127.0.0.1', $mysql_access_host_array) - && !in_array('localhost', $mysql_access_host_array)) - { + if (in_array('127.0.0.1', $mysql_access_host_array) && ! in_array('localhost', $mysql_access_host_array)) { $mysql_access_host_array[] = 'localhost'; } - if(!in_array('127.0.0.1', $mysql_access_host_array) - && in_array('localhost', $mysql_access_host_array)) - { + if (! in_array('127.0.0.1', $mysql_access_host_array) && in_array('localhost', $mysql_access_host_array)) { $mysql_access_host_array[] = '127.0.0.1'; } + // be aware that ipv6 addresses are enclosed in [ ] when passed here + $mysql_access_host_array = array_map('cleanMySQLAccessHost', $mysql_access_host_array); + $mysql_access_host_array = array_unique(array_trim($mysql_access_host_array)); $newfieldvalue = implode(',', $mysql_access_host_array); correctMysqlUsers($mysql_access_host_array); } - + return $returnvalue; } -?> +function cleanMySQLAccessHost($value) +{ + if (substr($value, 0, 1) == '[' && substr($value, - 1) == ']') { + return substr($value, 1, - 1); + } + return $value; +} From d8a301530326c559b965ac0ccdd287c20417a867 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 27 Jan 2018 11:50:34 +0100 Subject: [PATCH 149/179] put le acme version setting right above the CA setting, less confusing Signed-off-by: Michael Kaufmann (d00p) --- actions/admin/settings/131.ssl.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/actions/admin/settings/131.ssl.php b/actions/admin/settings/131.ssl.php index 1ad1768a..7bdeb3e4 100644 --- a/actions/admin/settings/131.ssl.php +++ b/actions/admin/settings/131.ssl.php @@ -113,6 +113,15 @@ return array( 'cronmodule' => 'froxlor/letsencrypt', 'save_method' => 'storeSettingField' ), + 'system_letsencryptacmeconf' => array( + 'label' => $lng['serversettings']['letsencryptacmeconf'], + 'settinggroup' => 'system', + 'varname' => 'letsencryptacmeconf', + 'type' => 'string', + 'string_type' => 'file', + 'default' => '/etc/apache2/conf-enabled/acme.conf', + 'save_method' => 'storeSettingField' + ), 'system_leapiversion' => array( 'label' => $lng['serversettings']['leapiversion'], 'settinggroup' => 'system', @@ -126,15 +135,6 @@ return array( ), 'save_method' => 'storeSettingField' ), - 'system_letsencryptacmeconf' => array( - 'label' => $lng['serversettings']['letsencryptacmeconf'], - 'settinggroup' => 'system', - 'varname' => 'letsencryptacmeconf', - 'type' => 'string', - 'string_type' => 'file', - 'default' => '/etc/apache2/conf-enabled/acme.conf', - 'save_method' => 'storeSettingField' - ), 'system_letsencryptca' => array( 'label' => $lng['serversettings']['letsencryptca'], 'settinggroup' => 'system', From 840b5ea2292ce7ada0ac900c3f41b2579a06e53c Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 28 Jan 2018 14:33:00 +0100 Subject: [PATCH 150/179] add new feature: import/export of settings Signed-off-by: Michael Kaufmann (d00p) --- admin_settings.php | 32 +++++ lib/classes/settings/class.SImExporter.php | 114 ++++++++++++++++++ .../output/function.standard_error.php | 12 ++ lng/english.lng.php | 3 +- lng/german.lng.php | 1 + .../admin/settings/importexport/index.tpl | 26 ++++ templates/Sparkle/admin/settings/settings.tpl | 3 +- .../admin/settings/settings_overview.tpl | 3 +- 8 files changed, 191 insertions(+), 3 deletions(-) create mode 100644 lib/classes/settings/class.SImExporter.php create mode 100644 templates/Sparkle/admin/settings/importexport/index.tpl diff --git a/admin_settings.php b/admin_settings.php index 49e2bd8c..538df344 100644 --- a/admin_settings.php +++ b/admin_settings.php @@ -290,6 +290,38 @@ if ($page == 'overview' && $userinfo['change_serversettings'] == '1') { } eval("echo \"" . getTemplate("settings/integritycheck") . "\";"); } +elseif ($page == 'importexport' && $userinfo['change_serversettings'] == '1') +{ + if (isset($_GET['action']) && $_GET['action'] == "export") { + // export + try { + $json_export = SImExporter::export(); + } catch(Exception $e) { + dynamic_error($e->getMessage()); + } + header('Content-disposition: attachment; filename=Froxlor_settings-'.$version.'-'.$dbversion.'_'.date('d.m.Y').'.json'); + header('Content-type: application/json'); + echo $json_export; + exit; + } elseif (isset($_GET['action']) && $_GET['action'] == "import") { + // import + if (isset($_POST['send']) && $_POST['send'] == 'send') { + // get uploaded file + if (isset($_FILES["import_file"]["tmp_name"])) { + $imp_content = file_get_contents($_FILES["import_file"]["tmp_name"]); + try { + SImExporter::import($imp_content); + } catch(Exception $e) { + dynamic_error($e->getMessage()); + } + standard_success('settingsimported', '', array('filename' => 'admin_settings.php')); + } + dynamic_error("Upload failed"); + } + } else { + eval("echo \"" . getTemplate("settings/importexport/index") . "\";"); + } +} elseif ($page == 'testmail') { if (isset($_POST['send']) && $_POST['send'] == 'send') diff --git a/lib/classes/settings/class.SImExporter.php b/lib/classes/settings/class.SImExporter.php new file mode 100644 index 00000000..206f4e1d --- /dev/null +++ b/lib/classes/settings/class.SImExporter.php @@ -0,0 +1,114 @@ + + * @author Froxlor team (2018-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Classes + * + * @since 0.9.39 + * + */ + +/** + * Class SImExporter + * + * Import/Export settings to JSON + * + * @copyright (c) the authors + * @author Michael Kaufmann + * @author Froxlor team (2018-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Classes + */ +class SImExporter +{ + + /** + * settings which are not being exported + * + * @var array + */ + private static $_no_export = [ + 'panel.adminmail', + 'admin.show_news_feed', + 'system.lastaccountnumber', + 'system.lastguid', + 'system.ipaddress', + 'system.last_traffic_run', + 'system.hostname', + 'system.mysql_access_host', + 'system.lastcronrun', + 'system.defaultip', + 'system.last_tasks_run', + 'system.last_archive_run', + 'system.leprivatekey', + 'system.lepublickey' + ]; + + public static function export() + { + $result_stmt = Database::query(" + SELECT * FROM `" . TABLE_PANEL_SETTINGS . "` ORDER BY `settingid` ASC + "); + $_data = array(); + while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) { + $index = $row['settinggroup'] . "." . $row['varname']; + if (! in_array($index, self::$_no_export)) { + $_data[$index] = $row['value']; + } + } + // add checksum for validation + $_data['_sha'] = sha1(var_export($_data, true)); + $_export = json_encode($_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + if (! $_export) { + throw new Exception("Error exporting settings: " . json_last_error_msg()); + } + return $_export; + } + + public static function import($json_str = null) + { + // decode data + $_data = json_decode($json_str, true); + if ($_data) { + // get validity check data + $_sha = isset($_data['_sha']) ? $_data['_sha'] : false; + $_version = isset($_data['panel.version']) ? $_data['panel.version'] : false; + $_dbversion = isset($_data['panel.db_version']) ? $_data['panel.db_version'] : false; + // check if we have everything we need + if (! $_sha || ! $_version || ! $_dbversion) { + throw new Exception("Invalid froxlor settings data. Unable to import."); + } + // validate import file + unset($_data['_sha']); + // compare + if ($_sha != sha1(var_export($_data, true))) { + throw new Exception("SHA check of import data failed. Unable to import."); + } + // do not import version info - but we need that to possibily update settings + // when there were changes in the variable-name or similar + unset($_data['panel.version']); + unset($_data['panel.db_version']); + /* + // store new data + foreach ($_data as $index => $value) { + Settings::Set($index, $value); + } + // save to DB + Settings::Flush(); + */ + // all good + return true; + } + throw new Exception("Invalid JSON data: " . json_last_error_msg()); + } +} diff --git a/lib/functions/output/function.standard_error.php b/lib/functions/output/function.standard_error.php index d202a2c4..03fb272f 100644 --- a/lib/functions/output/function.standard_error.php +++ b/lib/functions/output/function.standard_error.php @@ -63,3 +63,15 @@ function standard_error($errors = '', $replacer = '') { eval("echo \"" . getTemplate('misc/error', '1') . "\";"); exit; } + +function dynamic_error($message) { + global $userinfo, $s, $header, $footer, $lng, $theme; + $_SESSION['requestData'] = $_POST; + $link = ''; + if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== false) { + $link = ''.$lng['panel']['back'].''; + } + $error = $message; + eval("echo \"" . getTemplate('misc/error', '1') . "\";"); + exit; +} diff --git a/lng/english.lng.php b/lng/english.lng.php index bb58842e..64d12df9 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2101,4 +2101,5 @@ $lng['phpfpm']['ini_values'] = 'Enter possible php_values for p $lng['phpfpm']['ini_admin_flags'] = 'Enter possible php_admin_flags for php.ini. One entry per line'; $lng['phpfpm']['ini_admin_values'] = 'Enter possible php_admin_values for php.ini. One entry per line'; $lng['serversettings']['phpfpm_settings']['envpath'] = 'Paths to add to the PATH environment. Leave empty for no PATH environment variable'; - +$lng['admin']['configfiles']['importexport'] = 'Import/Export'; +$lng['success']['settingsimported'] = 'Settings imported successfully'; diff --git a/lng/german.lng.php b/lng/german.lng.php index b822aa3b..f9d86ab2 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1752,3 +1752,4 @@ $lng['phpfpm']['ini_values'] = 'Mögliche php_values für die p $lng['phpfpm']['ini_admin_flags'] = 'Mögliche php_admin_flags für die php.ini. Pro Zeile eine Direktive'; $lng['phpfpm']['ini_admin_values'] = 'Mögliche php_admin_values für die php.ini. Pro Zeile eine Direktive'; $lng['serversettings']['phpfpm_settings']['envpath'] = 'Pfade für die PATH Umgebungsvariable. Leerlassen, um keine PATH Umgebungsvariable zu setzen.'; +$lng['success']['settingsimported'] = 'Einstellungnen erfolgreich importiert'; diff --git a/templates/Sparkle/admin/settings/importexport/index.tpl b/templates/Sparkle/admin/settings/importexport/index.tpl new file mode 100644 index 00000000..41da2dfb --- /dev/null +++ b/templates/Sparkle/admin/settings/importexport/index.tpl @@ -0,0 +1,26 @@ +$header +
+
+

+   + {$lng['admin']['configfiles']['importexport']} +

+
+ +
+ + + +
+

+
+
+ + + + + +
+
+
+$footer diff --git a/templates/Sparkle/admin/settings/settings.tpl b/templates/Sparkle/admin/settings/settings.tpl index 7a3075ed..12082722 100644 --- a/templates/Sparkle/admin/settings/settings.tpl +++ b/templates/Sparkle/admin/settings/settings.tpl @@ -3,7 +3,8 @@

  {$lng['admin']['serversettings']}   - [{$lng['admin']['configfiles']['compactoverview']}] + [{$lng['admin']['configfiles']['compactoverview']}]   + [{$lng['admin']['configfiles']['importexport']}]

diff --git a/templates/Sparkle/admin/settings/settings_overview.tpl b/templates/Sparkle/admin/settings/settings_overview.tpl index c1cd32ac..4a59c4c7 100644 --- a/templates/Sparkle/admin/settings/settings_overview.tpl +++ b/templates/Sparkle/admin/settings/settings_overview.tpl @@ -3,7 +3,8 @@

  {$lng['admin']['serversettings']}   - [{$lng['admin']['configfiles']['overview']}] + [{$lng['admin']['configfiles']['overview']}]   + [{$lng['admin']['configfiles']['importexport']}]

From c62dd2ecf4396b25d3a5ca617c25e48e35006e6a Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 29 Jan 2018 20:04:54 +0100 Subject: [PATCH 151/179] fix mysql-strict-mode issue (hopefully for good), enhance error-reporting when importing froxlor.sql on installation Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/lib/class.FroxlorInstall.php | 298 ++++++++++++++------------- 2 files changed, 161 insertions(+), 139 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index a54798a4..35ea8098 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -66,7 +66,7 @@ CREATE TABLE `mail_virtual` ( `id` int(11) NOT NULL auto_increment, `email` varchar(255) NOT NULL default '', `email_full` varchar(255) NOT NULL default '', - `destination` text NOT NULL default '', + `destination` text, `domainid` int(11) NOT NULL default '0', `customerid` int(11) NOT NULL default '0', `popaccountid` int(11) NOT NULL default '0', diff --git a/install/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index d253d59b..50d83898 100644 --- a/install/lib/class.FroxlorInstall.php +++ b/install/lib/class.FroxlorInstall.php @@ -28,7 +28,7 @@ * @author Froxlor team (2010-) * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt * @package Install - * + * */ class FroxlorInstall { @@ -74,10 +74,17 @@ class FroxlorInstall /** * currently used language * - * @var unknown + * @var string */ private $_activelng = 'english'; + /** + * check whether to abort due to errors + * + * @var bool + */ + private $_abort = false; + /** * Class constructor */ @@ -154,7 +161,7 @@ class FroxlorInstall $this->_guessServerName(); $this->_guessServerIP(); $this->_guessWebserver(); - + $this->_getPostField('mysql_host', '127.0.0.1'); $this->_getPostField('mysql_database', 'froxlor'); $this->_getPostField('mysql_unpriv_user', 'froxlor'); @@ -169,22 +176,22 @@ class FroxlorInstall $this->_getPostField('httpuser', $posixusername['name']); $posixgroup = posix_getgrgid(posix_getgid()); $this->_getPostField('httpgroup', $posixgroup['name']); - + if ($this->_data['mysql_host'] == 'localhost' || $this->_data['mysql_host'] == '127.0.0.1') { $this->_data['mysql_access_host'] = $this->_data['mysql_host']; } else { $this->_data['mysql_access_host'] = $this->_data['serverip']; } - + // check system-hostname to be a FQDN if ($this->_validate_ip($this->_data['servername']) !== false) { $this->_data['servername'] = ''; } - + if (empty($this->_data['serverip']) || $this->_validate_ip($this->_data['serverip']) == false) { return false; } - + if (isset($_POST['installstep']) && $_POST['installstep'] == '1' && $this->_data['admin_pass1'] == $this->_data['admin_pass2'] && $this->_data['admin_pass1'] != '' && $this->_data['admin_pass2'] != '' && $this->_data['mysql_unpriv_pass'] != '' && $this->_data['mysql_root_pass'] != '' && $this->_data['servername'] != '' && $this->_data['serverip'] != '' && $this->_data['httpuser'] != '' && $this->_data['httpgroup'] != '' && $this->_data['mysql_unpriv_user'] != $this->_data['mysql_root_user']) { return true; } @@ -199,10 +206,10 @@ class FroxlorInstall private function _doInstall() { $content = ""; - + // check for mysql-root-connection $content .= $this->_status_message('begin', $this->_lng['install']['testing_mysql']); - + $options = array( 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'SET names utf8,sql_mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' ); @@ -227,9 +234,9 @@ class FroxlorInstall $fatal_fail = true; } } - + if (! $fatal_fail) { - + // ok, if we are here, the database connection is up and running $content .= $this->_status_message('green', "OK"); // check for existing db and create backup if so @@ -238,36 +245,37 @@ class FroxlorInstall $content .= $this->_createDatabaseAndUser($db_root); // importing data to new database $content .= $this->_importDatabaseData(); - // create DB object for new database - $options = array( - 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'SET names utf8,sql_mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' - ); - $dsn = "mysql:host=" . $this->_data['mysql_host'] . ";dbname=" . $this->_data['mysql_database'] . ";"; - $another_fail = false; - try { - $db = new PDO($dsn, $this->_data['mysql_unpriv_user'], $this->_data['mysql_unpriv_pass'], $options); - } catch (PDOException $e) { - // dafuq? this should have happened in _importDatabaseData() - $content .= $this->_status_message('red', $e->getMessage()); - $another_fail = true; - } - ; + if (! $this->_abort) { + // create DB object for new database + $options = array( + 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'SET names utf8,sql_mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' + ); + $dsn = "mysql:host=" . $this->_data['mysql_host'] . ";dbname=" . $this->_data['mysql_database'] . ";"; + $another_fail = false; + try { + $db = new PDO($dsn, $this->_data['mysql_unpriv_user'], $this->_data['mysql_unpriv_pass'], $options); + } catch (PDOException $e) { + // dafuq? this should have happened in _importDatabaseData() + $content .= $this->_status_message('red', $e->getMessage()); + $another_fail = true; + } - if (! $another_fail) { - // change settings accordingly - $content .= $this->_doSettings($db); - // create entries - $content .= $this->_doDataEntries($db); - $db = null; - // create config-file - $content .= $this->_createUserdataConf(); + if (! $another_fail) { + // change settings accordingly + $content .= $this->_doSettings($db); + // create entries + $content .= $this->_doDataEntries($db); + $db = null; + // create config-file + $content .= $this->_createUserdataConf(); + } } } - + $content .= "
"; - + // check if we have unrecoverable errors - if ($fatal_fail || $another_fail) { + if ($fatal_fail || $another_fai || $this->_abort) { // D'oh $navigation = ''; $msgcolor = 'red'; @@ -282,9 +290,9 @@ class FroxlorInstall $link = '../index.php'; $linktext = $this->_lng['click_here_to_login']; } - + eval("\$navigation .= \"" . $this->_getTemplate("pagebottom") . "\";"); - + return array( 'pagecontent' => $content, 'pagenavigation' => $navigation @@ -297,7 +305,7 @@ class FroxlorInstall private function _createUserdataConf() { $content = ""; - + $content .= $this->_status_message('begin', $this->_lng['install']['creating_configfile']); $userdata = ""; - + // test if we can store the userdata.inc.php in ../lib if ($fp = @fopen(dirname(dirname(dirname(__FILE__))) . '/lib/userdata.inc.php', 'w')) { $result = @fputs($fp, $userdata, strlen($userdata)); @@ -329,7 +337,7 @@ class FroxlorInstall $escpduserdata = nl2br(htmlspecialchars($userdata)); eval("\$content .= \"" . $this->_getTemplate("textarea") . "\";"); } - + return $content; } @@ -343,9 +351,9 @@ class FroxlorInstall private function _doDataEntries(&$db) { $content = ""; - + $content .= $this->_status_message('begin', $this->_lng['install']['creating_entries']); - + // and lets insert the default ip and port $stmt = $db->prepare(" INSERT INTO `" . TABLE_PANEL_IPSANDPORTS . "` SET @@ -359,7 +367,7 @@ class FroxlorInstall 'serverip' => $this->_data['serverip'] )); $defaultip = $db->lastInsertId(); - + // insert the defaultip $upd_stmt = $db->prepare(" UPDATE `" . TABLE_PANEL_SETTINGS . "` SET @@ -369,9 +377,9 @@ class FroxlorInstall $upd_stmt->execute(array( 'defaultip' => $defaultip )); - + $content .= $this->_status_message('green', 'OK'); - + // last but not least create the main admin $content .= $this->_status_message('begin', $this->_lng['install']['adding_admin_user']); $ins_data = array( @@ -406,11 +414,11 @@ class FroxlorInstall `subdomains` = -1, `traffic` = -1048576 "); - + $ins_stmt->execute($ins_data); - + $content .= $this->_status_message('green', 'OK'); - + return $content; } @@ -441,14 +449,14 @@ class FroxlorInstall private function _doSettings(&$db) { $content = ""; - + $content .= $this->_status_message('begin', $this->_lng['install']['changing_data']); $upd_stmt = $db->prepare(" UPDATE `" . TABLE_PANEL_SETTINGS . "` SET `value` = :value WHERE `settinggroup` = :group AND `varname` = :varname "); - + $this->_updateSetting($upd_stmt, 'admin@' . $this->_data['servername'], 'panel', 'adminmail'); $this->_updateSetting($upd_stmt, $this->_data['serverip'], 'system', 'ipaddress'); $this->_updateSetting($upd_stmt, $this->_data['servername'], 'system', 'hostname'); @@ -457,7 +465,7 @@ class FroxlorInstall $this->_updateSetting($upd_stmt, $this->_data['webserver'], 'system', 'webserver'); $this->_updateSetting($upd_stmt, $this->_data['httpuser'], 'system', 'httpuser'); $this->_updateSetting($upd_stmt, $this->_data['httpgroup'], 'system', 'httpgroup'); - + // necessary changes for webservers != apache2 if ($this->_data['webserver'] == "apache24") { $this->_updateSetting($upd_stmt, 'apache2', 'system', 'webserver'); @@ -477,25 +485,25 @@ class FroxlorInstall $this->_updateSetting($upd_stmt, '/etc/nginx/nginx.pem', 'system', 'ssl_cert_file'); $this->_updateSetting($upd_stmt, '/var/run/', 'phpfpm', 'fastcgi_ipcdir'); } - + $this->_updateSetting($upd_stmt, $this->_data['activate_newsfeed'], 'admin', 'show_news_feed'); $this->_updateSetting($upd_stmt, dirname(dirname(dirname(__FILE__))), 'system', 'letsencryptchallengepath'); - + // insert the lastcronrun to be the installation date $this->_updateSetting($upd_stmt, time(), 'system', 'lastcronrun'); - + // set specific times for some crons (traffic only at night, etc.) $ts = mktime(0, 0, 0, date('m', time()), date('d', time()), date('Y', time())); $db->query("UPDATE `" . TABLE_PANEL_CRONRUNS . "` SET `lastrun` = '" . $ts . "' WHERE `cronfile` ='cron_traffic.php';"); $ts = mktime(1, 0, 0, date('m', time()), date('d', time()), date('Y', time())); $db->query("UPDATE `" . TABLE_PANEL_CRONRUNS . "` SET `lastrun` = '" . $ts . "' WHERE `cronfile` ='cron_used_tickets_reset.php';"); $db->query("UPDATE `" . TABLE_PANEL_CRONRUNS . "` SET `lastrun` = '" . $ts . "' WHERE `cronfile` ='cron_ticketarchive.php';"); - + // insert task 99 to generate a correct cron.d-file automatically $db->query("INSERT INTO `" . TABLE_PANEL_TASKS . "` SET `type` = '99';"); - + $content .= $this->_status_message('green', 'OK'); - + return $content; } @@ -517,16 +525,22 @@ class FroxlorInstall $fatal_fail = false; try { $db = new PDO($dsn, $this->_data['mysql_unpriv_user'], $this->_data['mysql_unpriv_pass'], $options); + $attributes = array( + 'ATTR_ERRMODE' => 'ERRMODE_EXCEPTION' + ); + // set attributes + foreach ($attributes as $k => $v) { + $db->setAttribute(constant("PDO::" . $k), constant("PDO::" . $v)); + } } catch (PDOException $e) { $content .= $this->_status_message('red', $e->getMessage()); $fatal_fail = true; } - ; - + if (! $fatal_fail) { - + $content .= $this->_status_message('green', 'OK'); - + $content .= $this->_status_message('begin', $this->_lng['install']['importing_data']); $db_schema = dirname(dirname(__FILE__)) . '/froxlor.sql'; $sql_query = @file_get_contents($db_schema); @@ -534,14 +548,23 @@ class FroxlorInstall $sql_query = $this->_split_sql_file($sql_query, ';'); for ($i = 0; $i < sizeof($sql_query); $i ++) { if (trim($sql_query[$i]) != '') { - $result = $db->query($sql_query[$i]); + try { + $result = $db->query($sql_query[$i]); + } catch (\PDOException $e) { + $content .= $this->_status_message('red', $e->getMessage()); + $fatal_fail = true; + $this->_abort = true; + break; + } } } + + if (! $fatal_fail) { + $content .= $this->_status_message('green', 'OK'); + } $db = null; - - $content .= $this->_status_message('green', 'OK'); } - + return $content; } @@ -555,56 +578,56 @@ class FroxlorInstall private function _createDatabaseAndUser(&$db_root) { $content = ""; - + // so first we have to delete the database and // the user given for the unpriv-user if they exit $content .= $this->_status_message('begin', $this->_lng['install']['prepare_db']); - + $del_stmt = $db_root->prepare("DELETE FROM `mysql`.`user` WHERE `User` = :user AND `Host` = :accesshost"); $del_stmt->execute(array( 'user' => $this->_data['mysql_unpriv_user'], 'accesshost' => $this->_data['mysql_access_host'] )); - + $del_stmt = $db_root->prepare("DELETE FROM `mysql`.`db` WHERE `User` = :user AND `Host` = :accesshost"); $del_stmt->execute(array( 'user' => $this->_data['mysql_unpriv_user'], 'accesshost' => $this->_data['mysql_access_host'] )); - + $del_stmt = $db_root->prepare("DELETE FROM `mysql`.`tables_priv` WHERE `User` = :user AND `Host` =:accesshost"); $del_stmt->execute(array( 'user' => $this->_data['mysql_unpriv_user'], 'accesshost' => $this->_data['mysql_access_host'] )); - + $del_stmt = $db_root->prepare("DELETE FROM `mysql`.`columns_priv` WHERE `User` = :user AND `Host` = :accesshost"); $del_stmt->execute(array( 'user' => $this->_data['mysql_unpriv_user'], 'accesshost' => $this->_data['mysql_access_host'] )); - + $del_stmt = $db_root->prepare("DROP DATABASE IF EXISTS `" . str_replace('`', '', $this->_data['mysql_database']) . "`;"); $del_stmt->execute(); - + $db_root->query("FLUSH PRIVILEGES;"); $content .= $this->_status_message('green', 'OK'); - + // we have to create a new user and database for the froxlor unprivileged mysql access $content .= $this->_status_message('begin', $this->_lng['install']['create_mysqluser_and_db']); $ins_stmt = $db_root->prepare("CREATE DATABASE `" . str_replace('`', '', $this->_data['mysql_database']) . "` CHARACTER SET=utf8 COLLATE=utf8_general_ci"); $ins_stmt->execute(); - + $mysql_access_host_array = array_map('trim', explode(',', $this->_data['mysql_access_host'])); - + if (in_array('127.0.0.1', $mysql_access_host_array) && ! in_array('localhost', $mysql_access_host_array)) { $mysql_access_host_array[] = 'localhost'; } - + if (! in_array('127.0.0.1', $mysql_access_host_array) && in_array('localhost', $mysql_access_host_array)) { $mysql_access_host_array[] = '127.0.0.1'; } - + $mysql_access_host_array[] = $this->_data['serverip']; foreach ($mysql_access_host_array as $mysql_access_host) { $_db = str_replace('`', '', $this->_data['mysql_database']); @@ -623,11 +646,11 @@ class FroxlorInstall "password" => $this->_data['mysql_unpriv_pass'] )); } - + $db_root->query("FLUSH PRIVILEGES;"); $this->_data['mysql_access_host'] = implode(',', $mysql_access_host_array); $content .= $this->_status_message('green', 'OK'); - + return $content; } @@ -641,7 +664,7 @@ class FroxlorInstall private function _backupExistingDatabase(&$db_root) { $content = ""; - + // check for existing of former database $tables_exist = false; $sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = :database"; @@ -650,19 +673,19 @@ class FroxlorInstall 'database' => $this->_data['mysql_database'] )); $rows = $db_root->query("SELECT FOUND_ROWS()")->fetchColumn(); - + // check result if ($result_stmt !== false && $rows > 0) { $tables_exist = true; } - + if ($tables_exist) { // tell whats going on $content .= $this->_status_message('begin', $this->_lng['install']['backup_old_db']); - + // create temporary backup-filename $filename = "/tmp/froxlor_backup_" . date('YmdHi') . ".sql"; - + // look for mysqldump $do_backup = false; if (file_exists("/usr/bin/mysqldump")) { @@ -672,7 +695,7 @@ class FroxlorInstall $do_backup = true; $mysql_dump = '/usr/local/bin/mysqldump'; } - + if ($do_backup) { $command = $mysql_dump . " " . $this->_data['mysql_database'] . " -u " . $this->_data['mysql_root_user'] . " --password='" . $this->_data['mysql_root_pass'] . "' --result-file=" . $filename; $output = exec($command); @@ -685,7 +708,7 @@ class FroxlorInstall $content .= $this->_status_message('red', $this->_lng['install']['backup_binary_missing']); } } - + return $content; } @@ -707,7 +730,7 @@ class FroxlorInstall } // get language-form-template eval("\$content .= \"" . $this->_getTemplate("lngform") . "\";"); - + // form-data $formdata = ""; /** @@ -747,7 +770,7 @@ class FroxlorInstall $style = ''; } $formdata .= $this->_getSectionItemString('mysql_root_pass', true, $style, 'password'); - + /** * admin data */ @@ -771,7 +794,7 @@ class FroxlorInstall $formdata .= $this->_getSectionItemString('admin_pass2', true, $style, 'password'); // activate newsfeed? $formdata .= $this->_getSectionItemYesNo('activate_newsfeed', true); - + /** * Server data */ @@ -818,11 +841,11 @@ class FroxlorInstall $style = ''; } $formdata .= $this->_getSectionItemString('httpgroup', true, $style); - + // get data-form-template $language = htmlspecialchars($this->_activelng); eval("\$content .= \"" . $this->_getTemplate("dataform2") . "\";"); - + $navigation = ''; return array( 'pagecontent' => $content, @@ -839,7 +862,7 @@ class FroxlorInstall * optional css * @param string $type * optional type of input-box (default: text) - * + * * @return string */ private function _getSectionItemString($fieldname = null, $required = false, $style = "", $type = 'text') @@ -899,26 +922,26 @@ class FroxlorInstall */ private function _requirementCheck() { - + // indicator whether we need to abort or not $_die = false; - + $content = ""; - + // check for correct php version $content .= $this->_status_message('begin', $this->_lng['requirements']['phpversion']); - + if (version_compare("5.3.0", PHP_VERSION, ">=")) { $content .= $this->_status_message('red', $this->_lng['requirements']['notfound'] . ' (' . PHP_VERSION . ')'); $_die = true; } else { if (version_compare("5.6.0", PHP_VERSION, ">=")) { - $content .= $this->_status_message('orange', $this->_lng['requirements']['newerphpprefered'] . ' (' .PHP_VERSION . ')'); + $content .= $this->_status_message('orange', $this->_lng['requirements']['newerphpprefered'] . ' (' . PHP_VERSION . ')'); } else { $content .= $this->_status_message('green', PHP_VERSION); } } - + // Check if magic_quotes_runtime is active | get_magic_quotes_runtime() is always FALSE since 5.4 if (version_compare(PHP_VERSION, "5.4.0", "<")) { $content .= $this->_status_message('begin', $this->_lng['requirements']['phpmagic_quotes_runtime']); @@ -930,85 +953,85 @@ class FroxlorInstall $content .= $this->_status_message('green', 'off'); } } - + // check for php_pdo and pdo_mysql $content .= $this->_status_message('begin', $this->_lng['requirements']['phppdo']); - + if (! extension_loaded('pdo') || in_array("mysql", PDO::getAvailableDrivers()) == false) { $content .= $this->_status_message('red', $this->_lng['requirements']['notinstalled']); $_die = true; } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } - + // check for xml-extension $content .= $this->_status_message('begin', $this->_lng['requirements']['phpxml']); - + if (! extension_loaded('xml')) { $content .= $this->_status_message('red', $this->_lng['requirements']['notinstalled']); $_die = true; } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } - + // check for filter-extension $content .= $this->_status_message('begin', $this->_lng['requirements']['phpfilter']); - + if (! extension_loaded('filter')) { $content .= $this->_status_message('red', $this->_lng['requirements']['notinstalled']); $_die = true; } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } - + // check for posix-extension $content .= $this->_status_message('begin', $this->_lng['requirements']['phpposix']); - + if (! extension_loaded('posix')) { $content .= $this->_status_message('red', $this->_lng['requirements']['notinstalled']); $_die = true; } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } - + // check for bstring-extension $content .= $this->_status_message('begin', $this->_lng['requirements']['phpmbstring']); - + if (! extension_loaded('mbstring')) { $content .= $this->_status_message('red', $this->_lng['requirements']['notinstalled']); $_die = true; } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } - + // check for curl extension $content .= $this->_status_message('begin', $this->_lng['requirements']['phpcurl']); - + if (! extension_loaded('curl')) { $content .= $this->_status_message('red', $this->_lng['requirements']['notinstalled']); $_die = true; } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } - + // check for bcmath extension $content .= $this->_status_message('begin', $this->_lng['requirements']['phpbcmath']); - + if (! extension_loaded('bcmath')) { $content .= $this->_status_message('orange', $this->_lng['requirements']['notinstalled'] . "
" . $this->_lng['requirements']['bcmathdescription']); } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } - + // check for zip extension $content .= $this->_status_message('begin', $this->_lng['requirements']['phpzip']); - + if (! extension_loaded('zip')) { $content .= $this->_status_message('orange', $this->_lng['requirements']['notinstalled'] . "
" . $this->_lng['requirements']['zipdescription']); } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } - + // check for open_basedir $content .= $this->_status_message('begin', $this->_lng['requirements']['openbasedir']); $php_ob = @ini_get("open_basedir"); @@ -1018,7 +1041,7 @@ class FroxlorInstall $content .= $this->_status_message('green', 'off'); } $content .= "
"; - + // check if we have unrecoverable errors $navigation = ''; if ($_die) { @@ -1033,7 +1056,7 @@ class FroxlorInstall $linktext = $this->_lng['click_here_to_continue']; } eval("\$navigation .= \"" . $this->_getTemplate("pagebottom") . "\";"); - + return array( 'pagecontent' => $content, 'pagenavigation' => $navigation @@ -1050,7 +1073,7 @@ class FroxlorInstall header("Pragma: no-cache"); header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', time())); header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time())); - + // ensure that default timezone is set if (function_exists("date_default_timezone_set") && function_exists("date_default_timezone_get")) { @date_default_timezone_set(@date_default_timezone_get()); @@ -1068,7 +1091,7 @@ class FroxlorInstall // includes the usersettings (MySQL-Username/Passwort) // to test if Froxlor is already installed require $this->_basepath . '/lib/userdata.inc.php'; - + if (isset($sql) && is_array($sql)) { // use sparkle theme for the notice $installed_hint = file_get_contents($this->_basepath . '/templates/Sparkle/misc/alreadyinstalledhint.tpl'); @@ -1085,7 +1108,7 @@ class FroxlorInstall { // set default $standardlanguage = 'english'; - + // check either _GET or _POST if (isset($_GET['language']) && isset($this->_languages[$_GET['language']])) { $this->_activelng = $_GET['language']; @@ -1106,7 +1129,7 @@ class FroxlorInstall break; } } - + $lngfile = $this->_basepath . '/install/lng/' . $this->_activelng . '.lng.php'; if (file_exists($lngfile)) { // includes file /lng/$language.lng.php if it exists @@ -1120,7 +1143,7 @@ class FroxlorInstall * * @param string $template * name of the template including subdirectory - * + * * @return string */ private function _getTemplate($template = null) @@ -1137,7 +1160,7 @@ class FroxlorInstall } else { $templatefile = 'TEMPLATE NOT FOUND: ' . $filename; } - + return $templatefile; } @@ -1168,14 +1191,13 @@ class FroxlorInstall $this->_data['servername'] = $_POST['servername']; return; // from $_SERVER - } else - if (! empty($_SERVER['SERVER_NAME'])) { - // no ips - if ($this->_validate_ip($_SERVER['SERVER_NAME']) == false) { - $this->_data['servername'] = $_SERVER['SERVER_NAME']; - return; - } + } else if (! empty($_SERVER['SERVER_NAME'])) { + // no ips + if ($this->_validate_ip($_SERVER['SERVER_NAME']) == false) { + $this->_data['servername'] = $_SERVER['SERVER_NAME']; + return; } + } // empty $this->_data['servername'] = ''; } @@ -1294,17 +1316,17 @@ class FroxlorInstall */ private function _split_sql_file($sql, $delimiter) { - + // Split up our string into "possible" SQL statements. $tokens = explode($delimiter, $sql); - + // try to save mem. $sql = ""; $output = array(); - + // we don't actually care about the matches preg gives us. $matches = array(); - + // this is faster than calling count($tokens) every time through the loop. $token_count = count($tokens); for ($i = 0; $i < $token_count; $i ++) { @@ -1312,12 +1334,12 @@ class FroxlorInstall if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0))) { // This is the total number of single quotes in the token. $total_quotes = preg_match_all("/'/", $tokens[$i], $matches); - + // Counts single quotes that are preceded by an odd number of backslashes, // which means they're escaped quotes. $escaped_quotes = preg_match_all("/(? Date: Tue, 30 Jan 2018 07:58:24 +0100 Subject: [PATCH 152/179] add requirement check for php-json as settings import/export uses json_decode/json_encode Signed-off-by: Michael Kaufmann (d00p) --- admin_settings.php | 5 +++++ install/lib/class.FroxlorInstall.php | 9 +++++++++ install/lng/english.lng.php | 2 ++ install/lng/german.lng.php | 2 ++ lng/english.lng.php | 1 + lng/german.lng.php | 1 + 6 files changed, 20 insertions(+) diff --git a/admin_settings.php b/admin_settings.php index 538df344..ac8ff85c 100644 --- a/admin_settings.php +++ b/admin_settings.php @@ -292,6 +292,11 @@ if ($page == 'overview' && $userinfo['change_serversettings'] == '1') { } elseif ($page == 'importexport' && $userinfo['change_serversettings'] == '1') { + // check for json-stuff + if (! extension_loaded('json')) { + standard_error('jsonextensionnotfound'); + } + if (isset($_GET['action']) && $_GET['action'] == "export") { // export try { diff --git a/install/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index 50d83898..96c82c74 100644 --- a/install/lib/class.FroxlorInstall.php +++ b/install/lib/class.FroxlorInstall.php @@ -1031,7 +1031,16 @@ class FroxlorInstall } else { $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); } + + // check for json extension + $content .= $this->_status_message('begin', $this->_lng['requirements']['phpjson']); + if (! extension_loaded('json')) { + $content .= $this->_status_message('orange', $this->_lng['requirements']['notinstalled'] . "
" . $this->_lng['requirements']['jsondescription']); + } else { + $content .= $this->_status_message('green', $this->_lng['requirements']['installed']); + } + // check for open_basedir $content .= $this->_status_message('begin', $this->_lng['requirements']['openbasedir']); $php_ob = @ini_get("open_basedir"); diff --git a/install/lng/english.lng.php b/install/lng/english.lng.php index 409421a5..8651bb83 100644 --- a/install/lng/english.lng.php +++ b/install/lng/english.lng.php @@ -35,8 +35,10 @@ $lng['requirements']['phpbcmath'] = 'PHP bcmath-extension...'; $lng['requirements']['phpcurl'] = 'PHP curl-extension...'; $lng['requirements']['phpmbstring'] = 'PHP mbstring-extension...'; $lng['requirements']['phpzip'] = 'PHP zip-extension...'; +$lng['requirements']['phpjson'] = 'PHP json-extension...'; $lng['requirements']['bcmathdescription'] = 'Traffic-calculation related functions will not work correctly!'; $lng['requirements']['zipdescription'] = 'The auto-update feature requires the zip extension.'; +$lng['requirements']['jsondescription'] = 'The settings import/export feature requires the json extension.'; $lng['requirements']['openbasedir'] = 'open_basedir...'; $lng['requirements']['openbasedirenabled'] = 'Froxlor will not work properly with open_basedir enabled. Please disable open_basedir for Froxlor in the coresponding php.ini'; $lng['requirements']['diedbecauseofrequirements'] = 'Cannot install Froxlor without these requirements! Try to fix them and retry.'; diff --git a/install/lng/german.lng.php b/install/lng/german.lng.php index 02dd9b8d..d18e94c0 100644 --- a/install/lng/german.lng.php +++ b/install/lng/german.lng.php @@ -35,8 +35,10 @@ $lng['requirements']['phpbcmath'] = 'PHP bcmath-Erweiterung...'; $lng['requirements']['phpcurl'] = 'PHP curl-Erweiterung...'; $lng['requirements']['phpmbstring'] = 'PHP mbstring-Erweiterung...'; $lng['requirements']['phpzip'] = 'PHP zip-Erweiterung...'; +$lng['requirements']['phpjson'] = 'PHP json-Erweiterung...'; $lng['requirements']['bcmathdescription'] = 'Traffic-Berechnungs bezogene Funktionen stehen nicht vollständig zur Verfügung!'; $lng['requirements']['zipdescription'] = 'Die Auto-Update Funktion benötigt die zip Erweiterung.'; +$lng['requirements']['jsondescription'] = 'Die Einstellungen Import/Export Funktion benötigt die json Erweiterung.'; $lng['requirements']['openbasedir'] = 'open_basedir genutzt wird...'; $lng['requirements']['openbasedirenabled'] = 'Froxlor wird mit aktiviertem open_basedir nicht vollständig funktionieren. Bitte deaktivieren Sie open_basedir für Froxlor in der entsprechenden php.ini'; $lng['requirements']['diedbecauseofrequirements'] = 'Kann Froxlor ohne diese Voraussetzungen nicht installieren! Beheben Sie die angezeigten Probleme und versuchen Sie es erneut.'; diff --git a/lng/english.lng.php b/lng/english.lng.php index 64d12df9..3123a1db 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2103,3 +2103,4 @@ $lng['phpfpm']['ini_admin_values'] = 'Enter possible php_admin_value Date: Tue, 30 Jan 2018 14:41:56 +0100 Subject: [PATCH 153/179] fix typo Signed-off-by: Michael Kaufmann (d00p) --- install/lib/class.FroxlorInstall.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index 96c82c74..128a7104 100644 --- a/install/lib/class.FroxlorInstall.php +++ b/install/lib/class.FroxlorInstall.php @@ -275,7 +275,7 @@ class FroxlorInstall $content .= ""; // check if we have unrecoverable errors - if ($fatal_fail || $another_fai || $this->_abort) { + if ($fatal_fail || $another_fail || $this->_abort) { // D'oh $navigation = ''; $msgcolor = 'red'; From f38a0fd8b656aa942bd387b11ae580d6aa09bad6 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 5 Feb 2018 08:36:25 +0100 Subject: [PATCH 154/179] remove unnecessary and out-of-date info from README, fixed variable typo in lib/init.php Signed-off-by: Michael Kaufmann (d00p) --- README.md | 19 +++---------------- lib/init.php | 2 +- 2 files changed, 4 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 35d9a624..33cb17cb 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ irc://chat.freenode.net/froxlor ### Forum -The community is located on http://forum.froxlor.org +The community is located on https://forum.froxlor.org/ ### Wiki @@ -44,7 +44,7 @@ May be found in COPYING ## Downloads ### Tarball -http://files.froxlor.org/releases/froxlor-latest.tar.gz [MD5](http://files.froxlor.org/releases/froxlor-latest.tar.gz.md5) [SHA1](http://files.froxlor.org/releases/froxlor-latest.tar.gz.sha1) +https://files.froxlor.org/releases/froxlor-latest.tar.gz [MD5](https://files.froxlor.org/releases/froxlor-latest.tar.gz.md5) [SHA1](https://files.froxlor.org/releases/froxlor-latest.tar.gz.sha1) ### Debian repository @@ -57,20 +57,7 @@ http://files.froxlor.org/releases/froxlor-latest.tar.gz [MD5](http://files.froxl [HowTo](https://github.com/Froxlor/Froxlor/wiki/Install-froxlor-on-gentoo) -http://files.froxlor.org/gentoo/repositories.xml - -## Let's Encrypt support - -This version of Froxlor contains a test implementation of support for [Let's Encrypt](https://letsencrypt.org). This is (as Let's Encrypt is in itself) -still a beta version and may break your system. The way it currently works is by creating a (sub-)domain with the default system - certificate, -after which the Let's Encrypt cronjob orders the certificate for this (sub-)domain and inserts the certificates in the database. With the next run -of the default cronjob, the certificates will be updated on the disk and the webserver reloaded. - -This has 2 known side-effects at the moment: -* The basic ip/port combinations don't work with the Froxlor - integration of Let's Encrypt, since it needs a certificate for the very first creation -* After creating a domain, it will have the default certificate for a short time (by default 5 minutes until the cronjob runs the next time) - -It may be possible to fix these issues, but they are not a priority at the moment +https://files.froxlor.org/gentoo/repositories.xml ## Contributing diff --git a/lib/init.php b/lib/init.php index 3436b237..3dc69df7 100644 --- a/lib/init.php +++ b/lib/init.php @@ -157,7 +157,7 @@ if (version_compare(PHP_VERSION, "5.4.0", "<")) { $in = array(&$_GET, &$_POST, &$_COOKIE); $_in = $in; - foreach ($in as $k => $v) { + foreach ($_in as $k => $v) { foreach ($v as $key => $val) { if (!is_array($val)) { $in[$k][$key] = stripslashes($val); From 0aa707ebc98dd5431b9840651bc4df0d55c626cf Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 6 Feb 2018 12:19:21 +0100 Subject: [PATCH 155/179] set version to 0.9.39 for upcoming release Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 6 ++++++ lib/configfiles/wheezy.xml | 2 +- lib/version.inc.php | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index 35ea8098..25e4c506 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -686,7 +686,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.38.8'), + ('panel', 'version', '0.9.39'), ('panel', 'db_version', '201801260'); diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 6c9fa665..cfca0ef6 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3874,3 +3874,9 @@ if (isDatabaseVersion('201801110')) { updateToDbVersion('201801260'); } + +if (isFroxlorVersion('0.9.38.8')) { + + showUpdateStep("Updating from 0.9.38.8 to 0.9.39 final", false); + updateToVersion('0.9.39'); +} diff --git a/lib/configfiles/wheezy.xml b/lib/configfiles/wheezy.xml index b6fe5698..871e64b5 100644 --- a/lib/configfiles/wheezy.xml +++ b/lib/configfiles/wheezy.xml @@ -1,6 +1,6 @@ - + diff --git a/lib/version.inc.php b/lib/version.inc.php index 5ebe2f3b..2f62182e 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.38.8'; +$version = '0.9.39'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201801260'; From ec21e28000a5ff360e2d08be9aa96c855b66ffb5 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 7 Feb 2018 15:10:59 +0100 Subject: [PATCH 156/179] use md5() instead of base64_encode for dummy-fpm-socket name to avoid possible equal-sign in string which leads to an invalid socket, fixes #513 Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/phpinterface/class.phpinterface_fpm.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/classes/phpinterface/class.phpinterface_fpm.php b/lib/classes/phpinterface/class.phpinterface_fpm.php index daf358ad..8ec93b3e 100644 --- a/lib/classes/phpinterface/class.phpinterface_fpm.php +++ b/lib/classes/phpinterface/class.phpinterface_fpm.php @@ -361,7 +361,7 @@ class phpinterface_fpm $config = makeCorrectFile($configdir . '/dummy.conf'); $dummy = "[dummy] user = ".Settings::Get('system.httpuser')." -listen = /run/" . base64_encode($configdir) . "-fpm.sock +listen = /run/" . md5($configdir) . "-fpm.sock pm = static pm.max_children = 1 "; From b4dd35eed2a4bac838eedc7bb28b9648e0072016 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Thu, 8 Feb 2018 07:35:06 +0100 Subject: [PATCH 157/179] correct description of nsswitch.conf file Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/jessie.xml | 4 ++-- lib/configfiles/precise.xml | 4 ++-- lib/configfiles/stretch.xml | 4 ++-- lib/configfiles/trusty.xml | 4 ++-- lib/configfiles/wheezy.xml | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/configfiles/jessie.xml b/lib/configfiles/jessie.xml index ccdbe9a3..da0faefe 100644 --- a/lib/configfiles/jessie.xml +++ b/lib/configfiles/jessie.xml @@ -4643,8 +4643,8 @@ aliases: files Date: Fri, 9 Feb 2018 07:33:28 +0100 Subject: [PATCH 158/179] fix selected phpfpm daemon when editing php-configuration, fixes #514 Signed-off-by: Michael Kaufmann (d00p) --- admin_phpsettings.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/admin_phpsettings.php b/admin_phpsettings.php index f43ce116..f76b4dcd 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -349,7 +349,7 @@ if ($page == 'overview') { $fpmconfigs = ''; $configs = Database::query("SELECT * FROM `" . TABLE_PANEL_FPMDAEMONS . "` ORDER BY `description` ASC"); while ($row = $configs->fetch(PDO::FETCH_ASSOC)) { - $fpmconfigs .= makeoption($row['description'], $row['id'], $id, true, true); + $fpmconfigs .= makeoption($row['description'], $row['id'], $result['fpmsettingid'], true, true); } $phpconfig_edit_data = include_once dirname(__FILE__) . '/lib/formfields/admin/phpconfig/formfield.phpconfig_edit.php'; From 05b4c58aa83856fcb21edcfaa6dfa439eaad6eb0 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 9 Feb 2018 09:20:46 +0100 Subject: [PATCH 159/179] fix updating wrong column when deleting a fpm configuration Signed-off-by: Michael Kaufmann (d00p) --- admin_phpsettings.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/admin_phpsettings.php b/admin_phpsettings.php index f76b4dcd..1d922b3f 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -496,7 +496,7 @@ if ($page == 'overview') { // set default fpm daemon config for all php-config that use this config that is to be deleted $upd_stmt = Database::prepare(" UPDATE `" . TABLE_PANEL_PHPCONFIGS . "` SET - `phpsettingid` = '1' WHERE `phpsettingid` = :id"); + `fpmsettingid` = '1' WHERE `fpmsettingid` = :id"); Database::pexecute($upd_stmt, array( 'id' => $id )); From 4d3fa6eca510329542ec4518c4bc029533051d01 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 9 Feb 2018 10:50:14 +0100 Subject: [PATCH 160/179] get rid of the need for allow_url_fopen Signed-off-by: Michael Kaufmann (d00p) --- admin_autoupdate.php | 238 ++++++++++++++------------ admin_index.php | 52 +++--- lib/ajax.php | 82 +++++---- lib/classes/cURL/class.HttpClient.php | 60 +++++++ lib/classes/ssl/class.lescript.php | 5 +- lib/classes/ssl/class.lescript_v2.php | 9 +- 6 files changed, 254 insertions(+), 192 deletions(-) create mode 100644 lib/classes/cURL/class.HttpClient.php diff --git a/admin_autoupdate.php b/admin_autoupdate.php index da4da2ae..701e8011 100644 --- a/admin_autoupdate.php +++ b/admin_autoupdate.php @@ -17,7 +17,6 @@ * @since 0.9.35 * */ - define('AREA', 'admin'); require './lib/init.php'; @@ -26,177 +25,188 @@ define('UPDATE_URI', "https://version.froxlor.org/Froxlor/legacy/" . $version); define('RELEASE_URI', "https://autoupdate.froxlor.org/froxlor-{version}.zip"); define('CHECKSUM_URI', "https://autoupdate.froxlor.org/froxlor-{version}.zip.sha256"); -// check for allow_url_fopen -if (ini_get('allow_url_fopen') === false) { - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 1)); -} - // check for archive-stuff if (! extension_loaded('zip')) { - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 2)); + redirectTo($filename, array( + 's' => $s, + 'page' => 'error', + 'errno' => 2 + )); } // display initial version check if ($page == 'overview') { - + // log our actions $log->logAction(ADM_ACTION, LOG_NOTICE, "checking auto-update"); - + // check for new version - $latestversion = @file(UPDATE_URI); - - if (isset($latestversion[0])) { - $latestversion = explode('|', $latestversion[0]); - - if (is_array($latestversion) - && count($latestversion) >= 1 - ) { - $_version = $latestversion[0]; - $_message = isset($latestversion[1]) ? $latestversion[1] : ''; - $_link = isset($latestversion[2]) ? $latestversion[2] : htmlspecialchars($filename . '?s=' . urlencode($s) . '&page=' . urlencode($page) . '&lookfornewversion=yes'); - - // add the branding so debian guys are not gettings confused - // about their version-number - $version_label = $_version.$branding; - $version_link = $_link; - $message_addinfo = $_message; - - // not numeric -> error-message - if (!preg_match('/^((\d+\\.)(\d+\\.)(\d+\\.)?(\d+)?(\-(svn|dev|rc)(\d+))?)$/', $_version)) { - // check for customized version to not output - // "There is a newer version of froxlor" besides the error-message - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 3)); - } elseif (version_compare2($version, $_version) == -1) { - // there is a newer version - yay - $isnewerversion = 1; - } else { - // nothing new - $isnewerversion = 0; - } - - // anzeige über version-status mit ggfls. formular - // zum update schritt #1 -> download - if ($isnewerversion == 1) { - $text = 'There is a newer version available. Update to version '.$_version.' now?
(Your current version is: '.$version.')'; - $hiddenparams = ''; - $yesfile = $filename.'?s='.$s.'&page=getdownload'; - eval("echo \"" . getTemplate("misc/question_yesno", true) . "\";"); - exit; - } - elseif ($isnewerversion == 0) { - // all good - standard_success ('noupdatesavail'); - } else { - standard_error ('customized_version'); - } + $latestversion = HttpClient::urlGet(UPDATE_URI); + + $latestversion = explode('|', $latestversion); + + if (is_array($latestversion) && count($latestversion) >= 1) { + $_version = $latestversion[0]; + $_message = isset($latestversion[1]) ? $latestversion[1] : ''; + $_link = isset($latestversion[2]) ? $latestversion[2] : htmlspecialchars($filename . '?s=' . urlencode($s) . '&page=' . urlencode($page) . '&lookfornewversion=yes'); + + // add the branding so debian guys are not gettings confused + // about their version-number + $version_label = $_version . $branding; + $version_link = $_link; + $message_addinfo = $_message; + + // not numeric -> error-message + if (! preg_match('/^((\d+\\.)(\d+\\.)(\d+\\.)?(\d+)?(\-(svn|dev|rc)(\d+))?)$/', $_version)) { + // check for customized version to not output + // "There is a newer version of froxlor" besides the error-message + redirectTo($filename, array( + 's' => $s, + 'page' => 'error', + 'errno' => 3 + )); + } elseif (version_compare2($version, $_version) == - 1) { + // there is a newer version - yay + $isnewerversion = 1; + } else { + // nothing new + $isnewerversion = 0; + } + + // anzeige über version-status mit ggfls. formular + // zum update schritt #1 -> download + if ($isnewerversion == 1) { + $text = 'There is a newer version available. Update to version ' . $_version . ' now?
(Your current version is: ' . $version . ')'; + $hiddenparams = ''; + $yesfile = $filename . '?s=' . $s . '&page=getdownload'; + eval("echo \"" . getTemplate("misc/question_yesno", true) . "\";"); + exit(); + } elseif ($isnewerversion == 0) { + // all good + standard_success('noupdatesavail'); + } else { + standard_error('customized_version'); } } - // error (something weird came from version.froxlor.org) - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 5)); -} -// download the new archive +}// download the new archive elseif ($page == 'getdownload') { - + // retrieve the new version from the form $newversion = isset($_POST['newversion']) ? $_POST['newversion'] : null; - + // valid? if ($newversion !== null) { - + // define files to get $toLoad = str_replace('{version}', $newversion, RELEASE_URI); $toCheck = str_replace('{version}', $newversion, CHECKSUM_URI); - - // get archive data - $newArchive = @file_get_contents($toLoad); - + // check for local destination folder - if (!is_dir(FROXLOR_INSTALL_DIR.'/updates/')) { - mkdir(FROXLOR_INSTALL_DIR.'/updates/'); + if (! is_dir(FROXLOR_INSTALL_DIR . '/updates/')) { + mkdir(FROXLOR_INSTALL_DIR . '/updates/'); } - + // name archive - $localArchive = FROXLOR_INSTALL_DIR.'/updates/'.basename($toLoad); - - $log->logAction(ADM_ACTION, LOG_NOTICE, "Downloading ".$toLoad." to ".$localArchive); - + $localArchive = FROXLOR_INSTALL_DIR . '/updates/' . basename($toLoad); + + $log->logAction(ADM_ACTION, LOG_NOTICE, "Downloading " . $toLoad . " to " . $localArchive); + // remove old archive if (file_exists($localArchive)) { @unlink($localArchive); } - - // store archive - $fh = fopen($localArchive, 'w'); - if (!fwrite($fh, $newArchive)) { - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 4)); + + // get archive data + try { + HttpClient::fileGet($toLoad, $localArchive); + } catch (Exception $e) { + redirectTo($filename, array( + 's' => $s, + 'page' => 'error', + 'errno' => 4 + )); } - - // close file-handle - fclose($fh); - + // validate the integrity of the downloaded file - $_shouldsum = @file_get_contents($toCheck); - if (!empty($_shouldsum)) { + $_shouldsum = HttpClient::urlGet($toCheck); + if (! empty($_shouldsum)) { $_t = explode(" ", $_shouldsum); $shouldsum = $_t[0]; } else { $shouldsum = null; } $filesum = hash_file('sha256', $localArchive); - + if ($filesum != $shouldsum) { - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 9)); + redirectTo($filename, array( + 's' => $s, + 'page' => 'error', + 'errno' => 9 + )); } - + // to the next step - redirectTo($filename, array('s' => $s, 'page' => 'extract', 'archive' => basename($localArchive))); + redirectTo($filename, array( + 's' => $s, + 'page' => 'extract', + 'archive' => basename($localArchive) + )); } - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 6)); -} -// extract and install new version + redirectTo($filename, array( + 's' => $s, + 'page' => 'error', + 'errno' => 6 + )); +}// extract and install new version elseif ($page == 'extract') { - + $toExtract = isset($_GET['archive']) ? $_GET['archive'] : null; - $localArchive = FROXLOR_INSTALL_DIR.'/updates/'.$toExtract; - - if (isset($_POST['send']) - && $_POST['send'] == 'send' - ) { + $localArchive = FROXLOR_INSTALL_DIR . '/updates/' . $toExtract; + + if (isset($_POST['send']) && $_POST['send'] == 'send') { // decompress from zip - $zip = new ZipArchive; + $zip = new ZipArchive(); $res = $zip->open($localArchive); if ($res === true) { - $log->logAction(ADM_ACTION, LOG_NOTICE, "Extracting ".$localArchive." to ".FROXLOR_INSTALL_DIR); + $log->logAction(ADM_ACTION, LOG_NOTICE, "Extracting " . $localArchive . " to " . FROXLOR_INSTALL_DIR); $zip->extractTo(FROXLOR_INSTALL_DIR); $zip->close(); // success - remove unused archive @unlink($localArchive); } else { // error - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 8)); + redirectTo($filename, array( + 's' => $s, + 'page' => 'error', + 'errno' => 8 + )); } - + // redirect to update-page? - redirectTo('admin_updates.php', array('s' => $s)); + redirectTo('admin_updates.php', array( + 's' => $s + )); } - - if (!file_exists($localArchive)) { - redirectTo($filename, array('s' => $s, 'page' => 'error', 'errno' => 7)); + + if (! file_exists($localArchive)) { + redirectTo($filename, array( + 's' => $s, + 'page' => 'error', + 'errno' => 7 + )); } - - $text = 'Extract downloaded archive "'.$toExtract.'"?'; + + $text = 'Extract downloaded archive "' . $toExtract . '"?'; $hiddenparams = ''; - $yesfile = $filename.'?s='.$s.'&page=extract&archive='.$toExtract; + $yesfile = $filename . '?s=' . $s . '&page=extract&archive=' . $toExtract; eval("echo \"" . getTemplate("misc/question_yesno", true) . "\";"); } - // display error elseif ($page == 'error') { - + // retrieve error-number via url-parameter - $errno = isset($_GET['errno']) ? (int)$_GET['errno'] : 0; - - // 1 = no allow_url_fopen + $errno = isset($_GET['errno']) ? (int) $_GET['errno'] : 0; + // 2 = no Zlib // 3 = custom version detected // 4 = could not store archive to local hdd @@ -205,5 +215,5 @@ elseif ($page == 'error') { // 7 = local archive does not exist // 8 = could not extract archive // 9 = checksum mismatch - standard_error ('autoupdate_'.$errno); + standard_error('autoupdate_' . $errno); } diff --git a/admin_index.php b/admin_index.php index dae69d6d..4650a24e 100644 --- a/admin_index.php +++ b/admin_index.php @@ -86,41 +86,31 @@ if ($page == 'overview') { || (isset($lookfornewversion) && $lookfornewversion == 'yes') ) { $update_check_uri = 'http://version.froxlor.org/Froxlor/legacy/' . $version; + $latestversion = HttpClient::urlGet($update_check_uri); + $latestversion = explode('|', $latestversion); - if (ini_get('allow_url_fopen')) { - $latestversion = @file($update_check_uri); + if (is_array($latestversion) + && count($latestversion) >= 1 + ) { + $_version = $latestversion[0]; + $_message = isset($latestversion[1]) ? $latestversion[1] : ''; + $_link = isset($latestversion[2]) ? $latestversion[2] : htmlspecialchars($filename . '?s=' . urlencode($s) . '&page=' . urlencode($page) . '&lookfornewversion=yes'); - if (isset($latestversion[0])) { - $latestversion = explode('|', $latestversion[0]); + // add the branding so debian guys are not gettings confused + // about their version-number + $lookfornewversion_lable = $_version.$branding; + $lookfornewversion_link = $_link; + $lookfornewversion_addinfo = $_message; - if (is_array($latestversion) - && count($latestversion) >= 1 - ) { - $_version = $latestversion[0]; - $_message = isset($latestversion[1]) ? $latestversion[1] : ''; - $_link = isset($latestversion[2]) ? $latestversion[2] : htmlspecialchars($filename . '?s=' . urlencode($s) . '&page=' . urlencode($page) . '&lookfornewversion=yes'); - - // add the branding so debian guys are not gettings confused - // about their version-number - $lookfornewversion_lable = $_version.$branding; - $lookfornewversion_link = $_link; - $lookfornewversion_addinfo = $_message; - - // not numeric -> error-message - if (!preg_match('/^((\d+\\.)(\d+\\.)(\d+\\.)?(\d+)?(\-(svn|dev|rc)(\d+))?)$/', $_version)) { - // check for customized version to not output - // "There is a newer version of froxlor" besides the error-message - $isnewerversion = 2; - } elseif (version_compare2($version, $_version) == -1) { - $isnewerversion = 1; - } else { - $isnewerversion = 0; - } - } else { - redirectTo($update_check_uri.'/pretty', NULL, false); - } + // not numeric -> error-message + if (!preg_match('/^((\d+\\.)(\d+\\.)(\d+\\.)?(\d+)?(\-(svn|dev|rc)(\d+))?)$/', $_version)) { + // check for customized version to not output + // "There is a newer version of froxlor" besides the error-message + $isnewerversion = 2; + } elseif (version_compare2($version, $_version) == -1) { + $isnewerversion = 1; } else { - redirectTo($update_check_uri.'/pretty', NULL, false); + $isnewerversion = 0; } } else { redirectTo($update_check_uri.'/pretty', NULL, false); diff --git a/lib/ajax.php b/lib/ajax.php index 23370663..4765f91d 100644 --- a/lib/ajax.php +++ b/lib/ajax.php @@ -18,7 +18,7 @@ // Load the user settings define('FROXLOR_INSTALL_DIR', dirname(dirname(__FILE__))); -if (!file_exists('./userdata.inc.php')) { +if (! file_exists('./userdata.inc.php')) { die(); } require './userdata.inc.php'; @@ -27,10 +27,11 @@ require './classes/database/class.Database.php'; require './classes/settings/class.Settings.php'; require './functions/validate/function.validate_ip.php'; require './functions/validate/function.validateDomain.php'; +require './lib/classes/cURL/class.HttpClient.php'; -if(isset($_POST['action'])) { +if (isset($_POST['action'])) { $action = $_POST['action']; -} elseif(isset($_GET['action'])) { +} elseif (isset($_GET['action'])) { $action = $_GET['action']; } else { $action = ""; @@ -42,51 +43,31 @@ if ($action == "newsfeed") { } else { $feed = "https://inside.froxlor.org/news/"; } - + if (function_exists("simplexml_load_file") == false) { - die(); + outputItem("Newsfeed not available due to missing php-simplexml extension", "Please install the php-simplexml extension in order to view our newsfeed."); + exit(); } - + if (function_exists('curl_version')) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $feed); - curl_setopt($ch, CURLOPT_USERAGENT, 'Froxlor/'.$version); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - $output = curl_exec($ch); - curl_close($ch); + $output = HttpClient::urlGet($feed); $news = simplexml_load_string(trim($output)); } else { - if (ini_get('allow_url_fopen')) { - ini_set('user_agent', 'Froxlor/'.$version); - $news = simplexml_load_file($feed, null, LIBXML_NOCDATA); - } else { - $news = false; - } + outputItem("Newsfeed not available due to missing php-curl extension", "Please install the php-curl extension in order to view our newsfeed."); + exit(); } - + if ($news !== false) { - for ($i = 0; $i < 3; $i++) { + for ($i = 0; $i < 3; $i ++) { $item = $news->channel->item[$i]; - - $title = (string)$item->title; - $link = (string)$item->link; + + $title = (string) $item->title; + $link = (string) $item->link; $date = date("Y-m-d G:i", strtotime($item->pubDate)); $content = preg_replace("/[\r\n]+/", " ", strip_tags($item->description)); $content = substr($content, 0, 150) . "..."; - - echo "
  • -
    -
    - {$title} - - {$date} - -
    -

    - {$content} -

    -
    -
  • "; + + outputItem($title, $content, $link, $date); } } else { echo ""; @@ -94,3 +75,30 @@ if ($action == "newsfeed") { } else { echo "No action set."; } + +function outputItem($title, $content, $link = null, $date = null) +{ + echo "
  • +
    +
    + "; + if (! empty($link)) { + echo ""; + } + echo $title; + if (! empty($link)) { + echo ""; + } + echo ""; + if (! empty($date)) { + echo " + {$date} + "; + } + echo "
    +

    + {$content} +

    +
    +
  • "; +} diff --git a/lib/classes/cURL/class.HttpClient.php b/lib/classes/cURL/class.HttpClient.php new file mode 100644 index 00000000..53a52114 --- /dev/null +++ b/lib/classes/cURL/class.HttpClient.php @@ -0,0 +1,60 @@ + array('header' => "User-Agent: Froxlor/".$this->version)); - $selfcheckContext = stream_context_create($selfcheckContextOptions); - if ($payload !== trim(@file_get_contents($uri, false, $selfcheckContext))) { + $selfcheckpayload = HttpClient::urlGet($uri); + if ($payload !== trim($selfcheckpayload)) { $errmsg = json_encode(error_get_last()); if ($errmsg != "null") { $errmsg = "; PHP error: " . $errmsg; diff --git a/lib/classes/ssl/class.lescript_v2.php b/lib/classes/ssl/class.lescript_v2.php index 074def62..448222eb 100644 --- a/lib/classes/ssl/class.lescript_v2.php +++ b/lib/classes/ssl/class.lescript_v2.php @@ -233,13 +233,8 @@ class lescript_v2 // simple self check if (Settings::Get('system.disable_le_selfcheck') == '0') { - $selfcheckContextOptions = array( - 'http' => array( - 'header' => "User-Agent: Froxlor/" . $this->version - ) - ); - $selfcheckContext = stream_context_create($selfcheckContextOptions); - if ($payload !== trim(@file_get_contents($uri, false, $selfcheckContext))) { + $selfcheckpayload = HttpClient::urlGet($uri); + if ($payload !== trim($selfcheckpayload)) { $errmsg = json_encode(error_get_last()); if ($errmsg != "null") { $errmsg = "; PHP error: " . $errmsg; From 5612720342e1f95ae2f01bb75232dd3b78940f7b Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Fri, 9 Feb 2018 13:57:23 +0100 Subject: [PATCH 161/179] only let admin select php-configs that the customer is allowed to use to avoid unwanted php-config changes when customer edits domain, refs #514 Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 18 ++++++- lib/functions/output/function.makeoption.php | 6 ++- .../Sparkle/admin/domains/domains_add.tpl | 1 + templates/Sparkle/assets/js/domains.js | 52 +++++++++++++++++++ 4 files changed, 74 insertions(+), 3 deletions(-) create mode 100644 templates/Sparkle/assets/js/domains.js diff --git a/admin_domains.php b/admin_domains.php index 6ce493ac..34418fdc 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -2209,12 +2209,19 @@ if ($page == 'domains' || $page == 'overview') { FROM `" . TABLE_PANEL_PHPCONFIGS . "` c LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid "); + $c_allowed_configs = getCustomerDetail($result['customerid'], 'allowed_phpconfigs'); + if (!empty($c_allowed_configs)) { + $c_allowed_configs = json_decode($c_allowed_configs, true); + } else { + $c_allowed_configs = array(); + } while ($phpconfigs_row = $phpconfigs_result_stmt->fetch(PDO::FETCH_ASSOC)) { + $disabled = !empty($c_allowed_configs) && !in_array($phpconfigs_row['id'], $c_allowed_configs); if ((int) Settings::Get('phpfpm.enabled') == 1) { - $phpconfigs .= makeoption($phpconfigs_row['description'] . " [".$phpconfigs_row['interpreter']."]", $phpconfigs_row['id'], $result['phpsettingid'], true, true); + $phpconfigs .= makeoption($phpconfigs_row['description'] . " [".$phpconfigs_row['interpreter']."]", $phpconfigs_row['id'], $result['phpsettingid'], true, true, null, $disabled); } else { - $phpconfigs .= makeoption($phpconfigs_row['description'], $phpconfigs_row['id'], $result['phpsettingid'], true, true); + $phpconfigs .= makeoption($phpconfigs_row['description'], $phpconfigs_row['id'], $result['phpsettingid'], true, true, null, $disabled); } } @@ -2231,6 +2238,13 @@ if ($page == 'domains' || $page == 'overview') { eval("echo \"" . getTemplate("domains/domains_edit") . "\";"); } } + } elseif ($action == 'jqGetCustomerPHPConfigs') { + + $customerid = intval($_POST['customerid']); + $allowed_phpconfigs = getCustomerDetail($customerid, 'allowed_phpconfigs'); + echo !empty($allowed_phpconfigs) ? $allowed_phpconfigs : json_encode(array()); + exit; + } elseif ($action == 'import') { if (isset($_POST['send']) && $_POST['send'] == 'send') { diff --git a/lib/functions/output/function.makeoption.php b/lib/functions/output/function.makeoption.php index 936610b4..a0072137 100644 --- a/lib/functions/output/function.makeoption.php +++ b/lib/functions/output/function.makeoption.php @@ -29,7 +29,7 @@ * @author Florian Lippert */ -function makeoption($title, $value, $selvalue = NULL, $title_trusted = false, $value_trusted = false, $id = NULL) +function makeoption($title, $value, $selvalue = NULL, $title_trusted = false, $value_trusted = false, $id = NULL, $disabled = false) { if($selvalue !== NULL && ((is_array($selvalue) && in_array($value, $selvalue)) || $value == $selvalue)) @@ -40,6 +40,10 @@ function makeoption($title, $value, $selvalue = NULL, $title_trusted = false, $v { $selected = ''; } + + if ($disabled) { + $selected .= ' disabled="disabled"'; + } if(!$title_trusted) { diff --git a/templates/Sparkle/admin/domains/domains_add.tpl b/templates/Sparkle/admin/domains/domains_add.tpl index f760faed..ebce2ce6 100644 --- a/templates/Sparkle/admin/domains/domains_add.tpl +++ b/templates/Sparkle/admin/domains/domains_add.tpl @@ -6,6 +6,7 @@ $header {$title} +
    diff --git a/templates/Sparkle/assets/js/domains.js b/templates/Sparkle/assets/js/domains.js new file mode 100644 index 00000000..b95e04de --- /dev/null +++ b/templates/Sparkle/assets/js/domains.js @@ -0,0 +1,52 @@ +$(document).ready(function() { + + var getUrlParameter = function getUrlParameter(sParam) { + var sPageURL = decodeURIComponent(window.location.search.substring(1)), + sURLVariables = sPageURL.split('&'), + sParameterName, + i; + + for (i = 0; i < sURLVariables.length; i++) { + sParameterName = sURLVariables[i].split('='); + + if (sParameterName[0] === sParam) { + return sParameterName[1] === undefined ? true : sParameterName[1]; + } + } + }; + + /** + * disable unusable php-configuration by customer settings + */ + $('#customerid').change(function() { + var cid = $(this).val(); + var sid = getUrlParameter('s'); + var page = getUrlParameter('page'); + + $.ajax({ + url: "admin_domains.php?s="+sid+"&page="+page+"&action=jqGetCustomerPHPConfigs", + type: "POST", + data: { + customerid: cid + }, + dataType: "json", + success: function(json) { + if (json.length > 0) { + $('#phpsettingid option').each(function() { + var pid = $(this).val(); + $(this).attr("disabled", "disabled"); + for (i in json) { + if (pid == json[i]) { + $(this).removeAttr("disabled"); + } + } + }); + } + }, + error: function(a, b) { + console.log(a, b); + } + }); + }); + +}); From 29803975450a0954ea1971ddcb373b43e9615d44 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 10 Feb 2018 10:13:55 +0100 Subject: [PATCH 162/179] fix include path in lib/ajax.php Signed-off-by: Michael Kaufmann (d00p) --- lib/ajax.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/ajax.php b/lib/ajax.php index 4765f91d..3b17e436 100644 --- a/lib/ajax.php +++ b/lib/ajax.php @@ -27,7 +27,7 @@ require './classes/database/class.Database.php'; require './classes/settings/class.Settings.php'; require './functions/validate/function.validate_ip.php'; require './functions/validate/function.validateDomain.php'; -require './lib/classes/cURL/class.HttpClient.php'; +require './classes/cURL/class.HttpClient.php'; if (isset($_POST['action'])) { $action = $_POST['action']; From 13b1503bf289668fc6b6a9b4cbd57bbd9c116cdc Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sat, 10 Feb 2018 16:06:57 +0100 Subject: [PATCH 163/179] set version to 0.9.39.1 for maintenance release Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 6 ++++++ lib/version.inc.php | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index 25e4c506..cfaec5ce 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -686,7 +686,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.39'), + ('panel', 'version', '0.9.39.1'), ('panel', 'db_version', '201801260'); diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index cfca0ef6..0c53d244 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3880,3 +3880,9 @@ if (isFroxlorVersion('0.9.38.8')) { showUpdateStep("Updating from 0.9.38.8 to 0.9.39 final", false); updateToVersion('0.9.39'); } + +if (isFroxlorVersion('0.9.39')) { + + showUpdateStep("Updating from 0.9.39 to 0.9.39.1", false); + updateToVersion('0.9.39.1'); +} diff --git a/lib/version.inc.php b/lib/version.inc.php index 2f62182e..336be49b 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.39'; +$version = '0.9.39.1'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201801260'; From ca4c93ac927c9615847251f392ad8c04211dfb0d Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 11 Feb 2018 13:57:07 +0100 Subject: [PATCH 164/179] set default dns server in config-templates; separate CmdLineHandler from switch-server-ip script for further usage Signed-off-by: Michael Kaufmann (d00p) --- install/scripts/switch-server-ip.php | 231 ++++---------------- lib/classes/output/class.CmdLineHandler.php | 196 +++++++++++++++++ lib/configfiles/gentoo.xml | 2 +- lib/configfiles/jessie.xml | 2 +- lib/configfiles/precise.xml | 2 +- lib/configfiles/stretch.xml | 2 +- lib/configfiles/trusty.xml | 2 +- lib/configfiles/wheezy.xml | 2 +- 8 files changed, 240 insertions(+), 199 deletions(-) create mode 100644 lib/classes/output/class.CmdLineHandler.php diff --git a/install/scripts/switch-server-ip.php b/install/scripts/switch-server-ip.php index d8f098f9..b8fcbe4c 100644 --- a/install/scripts/switch-server-ip.php +++ b/install/scripts/switch-server-ip.php @@ -13,46 +13,33 @@ * @author Froxlor team (2016-) * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt * @package Cron - * + * */ // Check if we're in the CLI -if(@php_sapi_name() !== 'cli') { +if (@php_sapi_name() !== 'cli') { die('This script will only work in the shell.'); } -// give control to command line handler -try { - CmdLineHandler::processParameters($argc, $argv); -} catch (Exception $e) { - CmdLineHandler::printerr($e->getMessage()); -} +require dirname(dirname(__DIR__)) . '/lib/classes/output/class.CmdLineHandler.php'; -class CmdLineHandler +class SwitchServerIp extends CmdLineHandler { /** - * internal variable for passed arguments + * list of valid switches * * @var array */ - private static $args = null; - - /** - * Action object read from commandline/config - * - * @var Action - */ - private $_action = null; - - /** - * list of valid parameters/switches - */ public static $switches = array( - /* 'd', // debug / output information for everything */ 'h' ); - // same as --help + + /** + * list of valid parameters + * + * @var array + */ public static $params = array( 'switch', 'list', @@ -60,131 +47,7 @@ class CmdLineHandler 'help' ); - /** - * Returns a CmdLineHandler object with given - * arguments from command line - * - * @param int $argc - * @param array $argv - * - * @return CmdLineHandler - */ - public static function processParameters($argc, $argv) - { - return new CmdLineHandler($argc, $argv); - } - - /** - * returns the Action object generated in - * the class constructor - * - * @return Action - */ - public function getAction() - { - return $this->_action; - } - - /** - * class constructor, validates the command line parameters - * and sets the Action-object if valid - * - * @param int $argc - * @param string[] $argv - * - * @return null - * @throws Exception - */ - private function __construct($argc, $argv) - { - self::$args = $this->_parseArgs($argv); - $this->_action = $this->_createAction(); - } - - /** - * Parses the arguments given via the command line; - * three types are supported: - * 1. - * --parm1 or --parm2=value - * 2. -xyz (multiple switches in one) or -a=value - * 3. parm1 parm2 - * - * The 1. will be mapped as - * ["parm1"] => true, ["parm2"] => "value" - * The 2. as - * ["x"] => true, ["y"] => true, ["z"] => true, ["a"] => "value" - * And the 3. as - * [0] => "parm1", [1] => "parm2" - * - * @param array $argv - * - * @return array - */ - private function _parseArgs($argv) - { - array_shift($argv); - $o = array(); - foreach ($argv as $a) { - if (substr($a, 0, 2) == '--') { - $eq = strpos($a, '='); - if ($eq !== false) { - $o[substr($a, 2, $eq - 2)] = substr($a, $eq + 1); - } else { - $k = substr($a, 2); - if (! isset($o[$k])) { - $o[$k] = true; - } - } - } else - if (substr($a, 0, 1) == '-') { - if (substr($a, 2, 1) == '=') { - $o[substr($a, 1, 1)] = substr($a, 3); - } else { - foreach (str_split(substr($a, 1)) as $k) { - if (! isset($o[$k])) { - $o[$k] = true; - } - } - } - } else { - $o[] = $a; - } - } - return $o; - } - - /** - * Creates an Action-Object for the Action-Handler - * - * @return Action - * @throws Exception - */ - private function _createAction() - { - - // Test for help-switch - if (empty(self::$args) || array_key_exists("help", self::$args) || array_key_exists("h", self::$args)) { - self::printHelp(); - // end of execution - } - // check if no unknown parameters are present - foreach (self::$args as $arg => $value) { - - if (is_numeric($arg)) { - throw new Exception("Unknown parameter '" . $value . "' in argument list"); - } elseif (! in_array($arg, self::$params) && ! in_array($arg, self::$switches)) { - throw new Exception("Unknown parameter '" . $arg . "' in argument list"); - } - } - - // set debugger switch - if (isset(self::$args["d"]) && self::$args["d"] == true) { - // Debugger::getInstance()->setEnabled(true); - // Debugger::getInstance()->debug("debug output enabled"); - } - - return new Action(self::$args); - } + public static $action_class = 'Action'; public static function printHelp() { @@ -207,34 +70,9 @@ class CmdLineHandler // self::println("-d\t\t\tenable debug output"); self::println("-h\t\t\tsame as --help"); self::println(""); - + die(); // end of execution } - - public static function println($msg = "") - { - print $msg . PHP_EOL; - } - - private static function _printcolor($msg = "", $color = "0") - { - print "\033[" . $color . "m" . $msg . "\033[0m" . PHP_EOL; - } - - public static function printerr($msg = "") - { - self::_printcolor($msg, "31"); - } - - public static function printsucc($msg = "") - { - self::_printcolor($msg, "32"); - } - - public static function printwarn($msg = "") - { - self::_printcolor($msg, "33"); - } } class Action @@ -268,11 +106,11 @@ class Action if (array_key_exists("list", $this->_args) || array_key_exists("switch", $this->_args)) { $need_config = true; } - + $this->_checkConfigParam($need_config); - + $this->_parseConfig(); - + if (array_key_exists("list", $this->_args)) { $this->_listIPs(); } @@ -300,11 +138,11 @@ class Action private function _switchIPs() { $ip_list = $this->_args['switch']; - + if (empty($ip_list) || is_bool($ip_list)) { throw new Exception("No paramters given for --switch action."); } - + $ips_to_switch = array(); $ip_list = explode(" ", $ip_list); foreach ($ip_list as $ips_combo) { @@ -324,22 +162,22 @@ class Action } $ips_to_switch[] = $ip_pair; } - + if (count($ips_to_switch) > 0) { $upd_stmt = Database::prepare("UPDATE panel_ipsandports SET `ip` = :newip WHERE `ip` = :oldip"); - + // system.ipaddress $check_sysip_stmt = Database::prepare("SELECT `value` FROM `panel_settings` WHERE `settinggroup` = 'system' and `varname` = 'ipaddress'"); $check_sysip = Database::pexecute_first($check_sysip_stmt); - + // system.mysql_access_host $check_mysqlip_stmt = Database::prepare("SELECT `value` FROM `panel_settings` WHERE `settinggroup` = 'system' and `varname` = 'mysql_access_host'"); $check_mysqlip = Database::pexecute_first($check_mysqlip_stmt); - + // system.axfrservers $check_axfrip_stmt = Database::prepare("SELECT `value` FROM `panel_settings` WHERE `settinggroup` = 'system' and `varname` = 'axfrservers'"); $check_axfrip = Database::pexecute_first($check_axfrip_stmt); - + foreach ($ips_to_switch as $ip_pair) { echo "Switching IP \033[1m" . $ip_pair[0] . "\033[0m to IP \033[1m" . $ip_pair[1] . "\033[0m" . PHP_EOL; Database::pexecute($upd_stmt, array( @@ -347,11 +185,11 @@ class Action 'oldip' => $ip_pair[0] )); $rows_updated = $upd_stmt->rowCount(); - + if ($rows_updated == 0) { CmdLineHandler::printwarn("Note: " . $ip_pair[0] . " not updated to " . $ip_pair[1] . " (possibly no entry found in froxlor database. Use --list to see what IP addresses are added in froxlor"); } - + // check whether the system.ipaddress needs updating if ($check_sysip['value'] == $ip_pair[0]) { $upd2_stmt = Database::prepare("UPDATE `panel_settings` SET `value` = :newip WHERE `settinggroup` = 'system' and `varname` = 'ipaddress'"); @@ -360,7 +198,7 @@ class Action )); CmdLineHandler::printsucc("Updated system-ipaddress from '" . $ip_pair[0] . "' to '" . $ip_pair[1] . "'"); } - + // check whether the system.mysql_access_host needs updating if (strstr($check_mysqlip['value'], $ip_pair[0]) !== false) { $new_mysqlip = str_replace($ip_pair[0], $ip_pair[1], $check_mysqlip['value']); @@ -370,7 +208,7 @@ class Action )); CmdLineHandler::printsucc("Updated mysql_access_host from '" . $check_mysqlip['value'] . "' to '" . $new_mysqlip . "'"); } - + // check whether the system.axfrservers needs updating if (strstr($check_axfrip['value'], $ip_pair[0]) !== false) { $new_axfrip = str_replace($ip_pair[0], $ip_pair[1], $check_axfrip['value']); @@ -382,7 +220,7 @@ class Action } } } - + echo PHP_EOL; CmdLineHandler::printwarn("*** ATTENTION *** Remember to replace IP addresses in configuration files if used anywhere."); CmdLineHandler::printsucc("IP addresses updated"); @@ -391,10 +229,10 @@ class Action private function _parseConfig() { define('FROXLOR_INSTALL_DIR', $this->_args['froxlor-dir']); - if (!file_exists(FROXLOR_INSTALL_DIR . '/lib/classes/database/class.Database.php')) { - throw new Exception("Could not find froxlor's Database class. Is froxlor really installed to '".FROXLOR_INSTALL_DIR."'?"); + if (! file_exists(FROXLOR_INSTALL_DIR . '/lib/classes/database/class.Database.php')) { + throw new Exception("Could not find froxlor's Database class. Is froxlor really installed to '" . FROXLOR_INSTALL_DIR . "'?"); } - if (!file_exists(FROXLOR_INSTALL_DIR . '/lib/userdata.inc.php')) { + if (! file_exists(FROXLOR_INSTALL_DIR . '/lib/userdata.inc.php')) { throw new Exception("Could not find froxlor's userdata.inc.php file. You should use this script only with a fully installed and setup froxlor system."); } require FROXLOR_INSTALL_DIR . '/lib/classes/database/class.Database.php'; @@ -415,3 +253,10 @@ class Action } } } + +// give control to command line handler +try { + SwitchServerIp::processParameters($argc, $argv); +} catch (Exception $e) { + SwitchServerIp::printerr($e->getMessage()); +} diff --git a/lib/classes/output/class.CmdLineHandler.php b/lib/classes/output/class.CmdLineHandler.php new file mode 100644 index 00000000..20e22fe6 --- /dev/null +++ b/lib/classes/output/class.CmdLineHandler.php @@ -0,0 +1,196 @@ + (2018-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Cron + * + */ +abstract class CmdLineHandler +{ + + /** + * internal variable for passed arguments + * + * @var array + */ + private static $args = null; + + /** + * Action object read from commandline/config + * + * @var Action + */ + private $_action = null; + + /** + * Returns a CmdLineHandler object with given + * arguments from command line + * + * @param int $argc + * @param array $argv + * + * @return CmdLineHandler + */ + public static function processParameters($argc, $argv) + { + $me = get_called_class(); + return new $me($argc, $argv); + } + + /** + * returns the Action object generated in + * the class constructor + * + * @return Action + */ + public function getAction() + { + return $this->_action; + } + + /** + * class constructor, validates the command line parameters + * and sets the Action-object if valid + * + * @param int $argc + * @param string[] $argv + * + * @return null + * @throws Exception + */ + private function __construct($argc, $argv) + { + self::$args = $this->_parseArgs($argv); + $this->_action = $this->_createAction(); + } + + /** + * Parses the arguments given via the command line; + * three types are supported: + * 1. + * --parm1 or --parm2=value + * 2. -xyz (multiple switches in one) or -a=value + * 3. parm1 parm2 + * + * The 1. will be mapped as + * ["parm1"] => true, ["parm2"] => "value" + * The 2. as + * ["x"] => true, ["y"] => true, ["z"] => true, ["a"] => "value" + * And the 3. as + * [0] => "parm1", [1] => "parm2" + * + * @param array $argv + * + * @return array + */ + private function _parseArgs($argv) + { + array_shift($argv); + $o = array(); + foreach ($argv as $a) { + if (substr($a, 0, 2) == '--') { + $eq = strpos($a, '='); + if ($eq !== false) { + $o[substr($a, 2, $eq - 2)] = substr($a, $eq + 1); + } else { + $k = substr($a, 2); + if (! isset($o[$k])) { + $o[$k] = true; + } + } + } else if (substr($a, 0, 1) == '-') { + if (substr($a, 2, 1) == '=') { + $o[substr($a, 1, 1)] = substr($a, 3); + } else { + foreach (str_split(substr($a, 1)) as $k) { + if (! isset($o[$k])) { + $o[$k] = true; + } + } + } + } else { + $o[] = $a; + } + } + return $o; + } + + /** + * Creates an Action-Object for the Action-Handler + * + * @return Action + * @throws Exception + */ + private function _createAction() + { + + // Test for help-switch + if (empty(self::$args) || array_key_exists("help", self::$args) || array_key_exists("h", self::$args)) { + static::printHelp(); + // end of execution + } + // check if no unknown parameters are present + foreach (self::$args as $arg => $value) { + + if (is_numeric($arg)) { + throw new Exception("Unknown parameter '" . $value . "' in argument list"); + } elseif (! in_array($arg, static::$params) && ! in_array($arg, static::$switches)) { + throw new Exception("Unknown parameter '" . $arg . "' in argument list"); + } + } + + // set debugger switch + if (isset(self::$args["d"]) && self::$args["d"] == true) { + // Debugger::getInstance()->setEnabled(true); + // Debugger::getInstance()->debug("debug output enabled"); + } + + return new static::$action_class(self::$args); + } + + public static function getInput($prompt = "#", $default = "") + { + if (! empty($default)) { + $prompt .= " [" . $default . "]"; + } + $result = readline($prompt . ":"); + if (empty($result) && ! empty($default)) { + $result = $default; + } + return mb_strtolower($result); + } + + public static function println($msg = "") + { + print $msg . PHP_EOL; + } + + private static function _printcolor($msg = "", $color = "0") + { + print "\033[" . $color . "m" . $msg . "\033[0m" . PHP_EOL; + } + + public static function printerr($msg = "") + { + self::_printcolor($msg, "31"); + } + + public static function printsucc($msg = "") + { + self::_printcolor($msg, "32"); + } + + public static function printwarn($msg = "") + { + self::_printcolor($msg, "33"); + } +} diff --git a/lib/configfiles/gentoo.xml b/lib/configfiles/gentoo.xml index cbcda2db..aa7845d6 100644 --- a/lib/configfiles/gentoo.xml +++ b/lib/configfiles/gentoo.xml @@ -353,7 +353,7 @@ exit "$RETVAL" - + - + > /etc/bind/named.conf.local]]> diff --git a/lib/configfiles/precise.xml b/lib/configfiles/precise.xml index ffd68e48..606c6172 100644 --- a/lib/configfiles/precise.xml +++ b/lib/configfiles/precise.xml @@ -334,7 +334,7 @@ exit "$RETVAL" - + > /etc/bind/named.conf]]> diff --git a/lib/configfiles/stretch.xml b/lib/configfiles/stretch.xml index 1ab9cdb2..2ad8cba3 100644 --- a/lib/configfiles/stretch.xml +++ b/lib/configfiles/stretch.xml @@ -354,7 +354,7 @@ exit "$RETVAL" - + > /etc/bind/named.conf.local]]> diff --git a/lib/configfiles/trusty.xml b/lib/configfiles/trusty.xml index f230f997..d04848fa 100644 --- a/lib/configfiles/trusty.xml +++ b/lib/configfiles/trusty.xml @@ -367,7 +367,7 @@ exit "$RETVAL" - + > /etc/bind/named.conf]]> diff --git a/lib/configfiles/wheezy.xml b/lib/configfiles/wheezy.xml index 1ed4e82a..82a25576 100644 --- a/lib/configfiles/wheezy.xml +++ b/lib/configfiles/wheezy.xml @@ -407,7 +407,7 @@ exit "$RETVAL" - + > /etc/bind/named.conf.local]]> From 295fbae6f5fd26459b103163fb9be71232491412 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Sun, 11 Feb 2018 16:10:10 +0100 Subject: [PATCH 165/179] create bash script to generate proftpd-certificates in case system does not use /bin/bash as shell Signed-off-by: Michael Kaufmann (d00p) --- lib/configfiles/gentoo.xml | 15 +++++++++++---- lib/configfiles/jessie.xml | 15 +++++++++++---- lib/configfiles/precise.xml | 15 +++++++++++---- lib/configfiles/stretch.xml | 15 +++++++++++---- lib/configfiles/trusty.xml | 15 +++++++++++---- lib/configfiles/wheezy.xml | 15 +++++++++++---- 6 files changed, 66 insertions(+), 24 deletions(-) diff --git a/lib/configfiles/gentoo.xml b/lib/configfiles/gentoo.xml index aa7845d6..7b68d374 100644 --- a/lib/configfiles/gentoo.xml +++ b/lib/configfiles/gentoo.xml @@ -3422,10 +3422,17 @@ MAILDIRPATH=.maildir > /etc/portage/package.use]]> - - "]]> - "]]> - + + " +[ -f /etc/ssl/certs/proftpd_ec.crt ] || openssl req -new -x509 -nodes -newkey ec:<(openssl ecparam -name secp521r1) -keyout /etc/ssl/private/proftpd_ec.key -out /etc/ssl/certs/proftpd_ec.crt -days 3650 -subj "/C=US/ST=Some-State/O=Internet Widgits Pty Ltd/CN=" +chmod 0600 /etc/ssl/private/proftpd.key /etc/ssl/private/proftpd_ec.key +]]> + + + + + diff --git a/lib/configfiles/jessie.xml b/lib/configfiles/jessie.xml index dc098d08..10ee0a2f 100644 --- a/lib/configfiles/jessie.xml +++ b/lib/configfiles/jessie.xml @@ -3814,10 +3814,17 @@ plugin { - - "]]> - "]]> - + + " +[ -f /etc/ssl/certs/proftpd_ec.crt ] || openssl req -new -x509 -nodes -newkey ec:<(openssl ecparam -name secp521r1) -keyout /etc/ssl/private/proftpd_ec.key -out /etc/ssl/certs/proftpd_ec.crt -days 3650 -subj "/C=US/ST=Some-State/O=Internet Widgits Pty Ltd/CN=" +chmod 0600 /etc/ssl/private/proftpd.key /etc/ssl/private/proftpd_ec.key +]]> + + + + + diff --git a/lib/configfiles/precise.xml b/lib/configfiles/precise.xml index 606c6172..9983959d 100644 --- a/lib/configfiles/precise.xml +++ b/lib/configfiles/precise.xml @@ -1143,10 +1143,17 @@ MYSQL_AUXOPTIONS_FIELD CONCAT("allowimap=",imap,",allowpop3=",pop3) - - "]]> - "]]> - + + " +[ -f /etc/ssl/certs/proftpd_ec.crt ] || openssl req -new -x509 -nodes -newkey ec:<(openssl ecparam -name secp521r1) -keyout /etc/ssl/private/proftpd_ec.key -out /etc/ssl/certs/proftpd_ec.crt -days 3650 -subj "/C=US/ST=Some-State/O=Internet Widgits Pty Ltd/CN=" +chmod 0600 /etc/ssl/private/proftpd.key /etc/ssl/private/proftpd_ec.key +]]> + + + + + diff --git a/lib/configfiles/stretch.xml b/lib/configfiles/stretch.xml index 2ad8cba3..7d9eab6b 100644 --- a/lib/configfiles/stretch.xml +++ b/lib/configfiles/stretch.xml @@ -3882,10 +3882,17 @@ plugin { - - "]]> - "]]> - + + " +[ -f /etc/ssl/certs/proftpd_ec.crt ] || openssl req -new -x509 -nodes -newkey ec:<(openssl ecparam -name secp521r1) -keyout /etc/ssl/private/proftpd_ec.key -out /etc/ssl/certs/proftpd_ec.crt -days 3650 -subj "/C=US/ST=Some-State/O=Internet Widgits Pty Ltd/CN=" +chmod 0600 /etc/ssl/private/proftpd.key /etc/ssl/private/proftpd_ec.key +]]> + + + + + diff --git a/lib/configfiles/trusty.xml b/lib/configfiles/trusty.xml index d04848fa..2df05eeb 100644 --- a/lib/configfiles/trusty.xml +++ b/lib/configfiles/trusty.xml @@ -1152,10 +1152,17 @@ MYSQL_AUXOPTIONS_FIELD CONCAT("allowimap=",imap,",allowpop3=",pop3) - - "]]> - "]]> - + + " +[ -f /etc/ssl/certs/proftpd_ec.crt ] || openssl req -new -x509 -nodes -newkey ec:<(openssl ecparam -name secp521r1) -keyout /etc/ssl/private/proftpd_ec.key -out /etc/ssl/certs/proftpd_ec.crt -days 3650 -subj "/C=US/ST=Some-State/O=Internet Widgits Pty Ltd/CN=" +chmod 0600 /etc/ssl/private/proftpd.key /etc/ssl/private/proftpd_ec.key +]]> + + + + + diff --git a/lib/configfiles/wheezy.xml b/lib/configfiles/wheezy.xml index 82a25576..55ba59d4 100644 --- a/lib/configfiles/wheezy.xml +++ b/lib/configfiles/wheezy.xml @@ -4716,10 +4716,17 @@ MYSQL_AUXOPTIONS_FIELD CONCAT("allowimap=",imap,",allowpop3=",pop3) - - "]]> - "]]> - + + " +[ -f /etc/ssl/certs/proftpd_ec.crt ] || openssl req -new -x509 -nodes -newkey ec:<(openssl ecparam -name secp521r1) -keyout /etc/ssl/private/proftpd_ec.key -out /etc/ssl/certs/proftpd_ec.crt -days 3650 -subj "/C=US/ST=Some-State/O=Internet Widgits Pty Ltd/CN=" +chmod 0600 /etc/ssl/private/proftpd.key /etc/ssl/private/proftpd_ec.key +]]> + + + + + From 05f1bf0a1fbc4bea5b94f5353bb3cdd9a5de8227 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 12 Feb 2018 07:46:38 +0100 Subject: [PATCH 166/179] meh, forgot to uncomment the settings storage for settings-import Signed-off-by: Michael Kaufmann (d00p) --- lib/classes/settings/class.SImExporter.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/classes/settings/class.SImExporter.php b/lib/classes/settings/class.SImExporter.php index 206f4e1d..428d8beb 100644 --- a/lib/classes/settings/class.SImExporter.php +++ b/lib/classes/settings/class.SImExporter.php @@ -98,14 +98,14 @@ class SImExporter // when there were changes in the variable-name or similar unset($_data['panel.version']); unset($_data['panel.db_version']); - /* + // store new data foreach ($_data as $index => $value) { Settings::Set($index, $value); } // save to DB Settings::Flush(); - */ + // all good return true; } From 216f013c9627c51bb43718bf68c246926da594cb Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 12 Feb 2018 07:47:51 +0100 Subject: [PATCH 167/179] add script to automatically configure services from shell without the need of copy/paste from the interface Signed-off-by: Michael Kaufmann (d00p) --- install/scripts/config-services.php | 427 +++++++++++++++++++++++++++ install/scripts/switch-server-ip.php | 0 2 files changed, 427 insertions(+) create mode 100755 install/scripts/config-services.php mode change 100644 => 100755 install/scripts/switch-server-ip.php diff --git a/install/scripts/config-services.php b/install/scripts/config-services.php new file mode 100755 index 00000000..1236fbf5 --- /dev/null +++ b/install/scripts/config-services.php @@ -0,0 +1,427 @@ +#!/usr/bin/php + (2018-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Cron + * + */ + +// Check if we're in the CLI +if (@php_sapi_name() !== 'cli') { + die('This script will only work in the shell.'); +} + +require dirname(dirname(__DIR__)) . '/lib/classes/output/class.CmdLineHandler.php'; + +class ConfigServicesCmd extends CmdLineHandler +{ + + /** + * list of valid switches + * + * @var array + */ + public static $switches = array( + 'h' + ); + + /** + * list of valid parameters + * + * @var array + */ + public static $params = array( + 'create', + 'apply', + 'daemon', + 'list-daemons', + 'froxlor-dir', + 'help' + ); + + public static $action_class = 'Action'; + + public static function printHelp() + { + self::println(""); + self::println("Help / command line parameters:"); + self::println(""); + // commands + self::println("--create\t\tlets you create a services list configuration for the 'apply' command"); + self::println(""); + self::println("--apply\t\t\tconfigure your services by given configuration file. To create one run the --create command"); + self::println("\t\t\tExample: --apply=/path/to/my-config.json"); + self::println(""); + self::println("--list-daemons\t\tOutput the services that are going to be configured using a given config file. No services will be configured."); + self::println("\t\t\tExample: --apply=/path/to/my-config.json --list-daemons"); + self::println(""); + self::println("--daemon\t\tWhen running --apply you can specify a daemon. This will be the only service that gets configured"); + self::println("\t\t\tExample: --apply=/path/to/my-config.json --daemon=apache24"); + self::println(""); + self::println("--froxlor-dir\t\tpath to froxlor installation"); + self::println("\t\t\tExample: --froxlor-dir=/var/www/froxlor/"); + self::println(""); + self::println("--help\t\t\tshow help screen (this)"); + self::println(""); + // switches + // self::println("-d\t\t\tenable debug output"); + self::println("-h\t\t\tsame as --help"); + self::println(""); + + die(); // end of execution + } +} + +class Action +{ + + private $_args = null; + + private $_name = null; + + private $_db = null; + + public function __construct($args) + { + $this->_args = $args; + $this->_validate(); + } + + public function getActionName() + { + return $this->_name; + } + + /** + * validates the parsed command line parameters + * + * @throws Exception + */ + private function _validate() + { + $this->_checkConfigParam(true); + $this->_parseConfig(); + + require FROXLOR_INSTALL_DIR . '/lib/tables.inc.php'; + require FROXLOR_INSTALL_DIR . '/lib/functions.php'; + require FROXLOR_INSTALL_DIR . '/lib/classes/settings/class.Settings.php'; + require FROXLOR_INSTALL_DIR . '/lib/classes/config/class.ConfigParser.php'; + require FROXLOR_INSTALL_DIR . '/lib/classes/config/class.ConfigService.php'; + require FROXLOR_INSTALL_DIR . '/lib/classes/config/class.ConfigDaemon.php'; + + if (array_key_exists("create", $this->_args)) { + $this->_createConfig(); + } elseif (array_key_exists("apply", $this->_args)) { + $this->_applyConfig(); + } elseif (array_key_exists("list-daemons", $this->_args) || array_key_exists("daemon", $this->_args)) { + CmdLineHandler::printwarn("--list-daemons and --daemon only work together with --apply"); + } + } + + private function _createConfig() + { + $_daemons_config = array( + 'distro' => "" + ); + + $config_dir = FROXLOR_INSTALL_DIR . '/lib/configfiles/'; + // show list of available distro's + $distros = glob($config_dir . '*.xml'); + // tmp array + $distributions_select_data = array(); + // read in all the distros + foreach ($distros as $_distribution) { + // get configparser object + $dist = new ConfigParser($_distribution); + // get distro-info + $dist_display = $this->getCompleteDistroName($dist); + // store in tmp array + $distributions_select_data[$dist_display] = str_replace(".xml", "", strtolower(basename($_distribution))); + } + + // sort by distribution name + ksort($distributions_select_data); + + // list all distributions + $mask = "|%-50.50s |%-50.50s |\n"; + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + printf($mask, 'dist', 'name'); + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + foreach ($distributions_select_data as $name => $filename) { + printf($mask, $filename, $name); + } + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + echo PHP_EOL; + + while (! in_array($_daemons_config['distro'], $distributions_select_data)) { + $_daemons_config['distro'] = CmdLineHandler::getInput("choose distribution", "stretch"); + } + + // go through all services and let user check whether to include it or not + $configfiles = new ConfigParser($config_dir . '/' . $_daemons_config['distro'] . ".xml"); + $services = $configfiles->getServices(); + + foreach ($services as $si => $service) { + echo PHP_EOL . "--- " . strtoupper($si) . " ---" . PHP_EOL . PHP_EOL; + $_daemons_config[$si] = ""; + + $daemons = $service->getDaemons(); + $mask = "|%-50.50s |%-50.50s |\n"; + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + printf($mask, 'value', 'name'); + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + $default_daemon = ""; + foreach ($daemons as $di => $dd) { + $title = $dd->title; + if ($dd->default) { + $default_daemon = $di; + $title = $title . " (default)"; + } + printf($mask, $di, $title); + } + printf($mask, "x", "No " . $si); + $daemons['x'] = 'x'; + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + echo PHP_EOL; + if ($si == 'system') { + $_daemons_config[$si] = array(); + // for the system/other services we need a multiple choice possibility + CmdLineHandler::println("Select every service you need. Enter empty value when done"); + $sysservice = ""; + do { + $sysservice = CmdLineHandler::getInput("choose service"); + if (! empty($sysservice)) { + $_daemons_config[$si][] = $sysservice; + } + } while (! empty($sysservice)); + } else { + // for all others -> only one value + while (! array_key_exists($_daemons_config[$si], $daemons)) { + $_daemons_config[$si] = CmdLineHandler::getInput("choose service", $default_daemon); + } + } + } + + echo PHP_EOL . PHP_EOL; + $daemons_config = json_encode($_daemons_config); + $output = CmdLineHandler::getInput("choose output-filename", "/tmp/froxlor-config-" . date('Ymd') . ".json"); + file_put_contents($output, $daemons_config); + CmdLineHandler::printsucc("Successfully generated service-configfile '" . $output . "'"); + } + + private function getCompleteDistroName($cparser) + { + // get distro-info + $dist_display = $cparser->distributionName; + if ($cparser->distributionCodename != '') { + $dist_display .= " " . $cparser->distributionCodename; + } + if ($cparser->distributionVersion != '') { + $dist_display .= " (" . $cparser->distributionVersion . ")"; + } + if ($cparser->deprecated) { + $dist_display .= " [deprecated]"; + } + return $dist_display; + } + + private function _applyConfig() + { + if (! is_file($this->_args["apply"])) { + throw new Exception("Given config file is not a file"); + } elseif (! file_exists($this->_args["apply"])) { + throw new Exception("Given config file cannot be found ('" . $this->_args["apply"] . "')"); + } elseif (! is_readable($this->_args["apply"])) { + throw new Exception("Given config file cannot be read ('" . $this->_args["apply"] . "')"); + } + + $config = file_get_contents($this->_args["apply"]); + $decoded_config = json_decode($config, true); + + if (array_key_exists("list-daemons", $this->_args)) { + $mask = "|%-50.50s |%-50.50s |\n"; + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + printf($mask, 'service', 'daemon'); + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + foreach ($decoded_config as $service => $daemon) { + if (is_array($daemon) && count($daemon) > 0) { + foreach ($daemon as $sysdaemon) { + printf($mask, $service, $sysdaemon); + } + } else { + if ($daemon == 'x') { + $daemon = '--- skipped ---'; + } + printf($mask, $service, $daemon); + } + } + printf($mask, str_repeat("-", 50), str_repeat("-", 50)); + echo PHP_EOL; + exit(); + } + + $only_daemon = null; + if (array_key_exists("daemon", $this->_args)) { + $only_daemon = $this->_args['daemon']; + } + + if (! empty($decoded_config)) { + $config_dir = FROXLOR_INSTALL_DIR . '/lib/configfiles/'; + $configfiles = new ConfigParser($config_dir . '/' . $decoded_config['distro'] . ".xml"); + $services = $configfiles->getServices(); + $replace_arr = $this->_getReplacerArray(); + + foreach ($services as $si => $service) { + echo PHP_EOL . "--- Configuring: " . strtoupper($si) . " ---" . PHP_EOL . PHP_EOL; + if (! isset($decoded_config[$si]) || $decoded_config[$si] == 'x') { + CmdLineHandler::printwarn("Skipping " . strtoupper($si) . " configuration as desired"); + continue; + } + $daemons = $service->getDaemons(); + foreach ($daemons as $di => $dd) { + // check for desired service + if (($si != 'system' && $decoded_config[$si] != $di) || (is_array($decoded_config[$si]) && ! in_array($di, $decoded_config[$si]))) { + continue; + } + CmdLineHandler::println("Configuring '" . $di . "'"); + + if (! empty($only_daemon) && $only_daemon != $di) { + CmdLineHandler::printwarn("Skipping " . $di . " configuration as desired"); + continue; + } + // run all cmds + $confarr = $dd->getConfig(); + foreach ($confarr as $idx => $action) { + switch ($action['type']) { + case "install": + CmdLineHandler::println("Installing required packages"); + passthru(strtr($action['content'], $replace_arr), $result); + if (strlen($result) > 1) { + echo $result; + } + break; + case "command": + exec(strtr($action['content'], $replace_arr)); + break; + case "file": + if (array_key_exists('content', $action)) { + CmdLineHandler::printwarn("Creating file '" . $action['name'] . "'"); + file_put_contents($action['name'], strtr($action['content'], $replace_arr)); + } elseif (array_key_exists('subcommands', $action)) { + foreach ($action['subcommands'] as $fileaction) { + if (array_key_exists('execute', $fileaction) && $fileaction['execute'] == "pre") { + exec(strtr($fileaction['content'], $replace_arr)); + } elseif (array_key_exists('execute', $fileaction) && $fileaction['execute'] == "post") { + exec(strtr($fileaction['content'], $replace_arr)); + } elseif ($fileaction['type'] == 'file') { + CmdLineHandler::printwarn("Creating file '" . $fileaction['name'] . "'"); + file_put_contents($fileaction['name'], strtr($fileaction['content'], $replace_arr)); + } + } + } + break; + } + } + } + } + CmdLineHandler::printsucc("All services have been configured"); + } else { + CmdLineHandler::printerr("Unable to decode given JSON file"); + } + } + + private function _getReplacerArray() + { + $customer_tmpdir = '/tmp/'; + if (Settings::Get('system.mod_fcgid') == '1' && Settings::Get('system.mod_fcgid_tmpdir') != '') { + $customer_tmpdir = Settings::Get('system.mod_fcgid_tmpdir'); + } elseif (Settings::Get('phpfpm.enabled') == '1' && Settings::Get('phpfpm.tmpdir') != '') { + $customer_tmpdir = Settings::Get('phpfpm.tmpdir'); + } + + // try to convert namserver hosts to ip's + $ns_ips = ""; + if (Settings::Get('system.nameservers') != '') { + $nameservers = explode(',', Settings::Get('system.nameservers')); + foreach ($nameservers as $nameserver) { + $nameserver = trim($nameserver); + $nameserver_ips = gethostbynamel($nameserver); + if (is_array($nameserver_ips) && count($nameserver_ips) > 0) { + $ns_ips .= implode(",", $nameserver_ips); + } + } + } + + Database::needSqlData(); + $sql = Database::getSqlData(); + + $replace_arr = array( + '' => $sql['user'], + '' => $sql['passwd'], + '' => $sql['db'], + '' => $sql['host'], + '' => isset($sql['socket']) ? $sql['socket'] : null, + '' => Settings::Get('system.hostname'), + '' => Settings::Get('system.ipaddress'), + '' => Settings::Get('system.nameservers'), + '' => $ns_ips, + '' => Settings::Get('system.axfrservers'), + '' => Settings::Get('system.vmail_homedir'), + '' => Settings::Get('system.vmail_uid'), + '' => Settings::Get('system.vmail_gid'), + '' => (Settings::Get('system.use_ssl') == '1') ? 'imaps pop3s' : '', + '' => makeCorrectDir($customer_tmpdir), + '' => makeCorrectDir(FROXLOR_INSTALL_DIR), + '' => makeCorrectDir(Settings::Get('system.bindconf_directory')), + '' => Settings::Get('system.apachereload_command'), + '' => makeCorrectDir(Settings::Get('system.logfiles_directory')), + '' => makeCorrectDir(Settings::Get('phpfpm.fastcgi_ipcdir')), + '' => Settings::Get('system.httpgroup') + ); + return $replace_arr; + } + + private function _parseConfig() + { + define('FROXLOR_INSTALL_DIR', $this->_args['froxlor-dir']); + if (! file_exists(FROXLOR_INSTALL_DIR . '/lib/classes/database/class.Database.php')) { + throw new Exception("Could not find froxlor's Database class. Is froxlor really installed to '" . FROXLOR_INSTALL_DIR . "'?"); + } + if (! file_exists(FROXLOR_INSTALL_DIR . '/lib/userdata.inc.php')) { + throw new Exception("Could not find froxlor's userdata.inc.php file. You should use this script only with a fully installed and setup froxlor system."); + } + require FROXLOR_INSTALL_DIR . '/lib/classes/database/class.Database.php'; + } + + private function _checkConfigParam($needed = false) + { + if ($needed) { + if (! isset($this->_args["froxlor-dir"])) { + throw new Exception("No configuration given (missing --froxlor-dir parameter?)"); + } elseif (! is_dir($this->_args["froxlor-dir"])) { + throw new Exception("Given --froxlor-dir parameter is not a directory"); + } elseif (! file_exists($this->_args["froxlor-dir"])) { + throw new Exception("Given froxlor directory cannot be found ('" . $this->_args["froxlor-dir"] . "')"); + } elseif (! is_readable($this->_args["froxlor-dir"])) { + throw new Exception("Given froxlor direcotry cannot be read ('" . $this->_args["froxlor-dir"] . "')"); + } + } + } +} + +// give control to command line handler +try { + ConfigServicesCmd::processParameters($argc, $argv); +} catch (Exception $e) { + ConfigServicesCmd::printerr($e->getMessage()); +} diff --git a/install/scripts/switch-server-ip.php b/install/scripts/switch-server-ip.php old mode 100644 new mode 100755 From 017396197ee1e1933d2ca6104823741657ff5efb Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 12 Feb 2018 07:49:07 +0100 Subject: [PATCH 168/179] set version to 0.9.39.2 for bugfix release Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 6 ++++++ lib/version.inc.php | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index cfaec5ce..567743ac 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -686,7 +686,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.39.1'), + ('panel', 'version', '0.9.39.2'), ('panel', 'db_version', '201801260'); diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 0c53d244..e89a18fd 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3886,3 +3886,9 @@ if (isFroxlorVersion('0.9.39')) { showUpdateStep("Updating from 0.9.39 to 0.9.39.1", false); updateToVersion('0.9.39.1'); } + +if (isFroxlorVersion('0.9.39.1')) { + + showUpdateStep("Updating from 0.9.39.1 to 0.9.39.2", false); + updateToVersion('0.9.39.2'); +} diff --git a/lib/version.inc.php b/lib/version.inc.php index 336be49b..f2d10dde 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.39.1'; +$version = '0.9.39.2'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201801260'; From bb792f228f866986fe48fc1a598e25933b498ae9 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 12 Feb 2018 13:28:13 +0100 Subject: [PATCH 169/179] add new hosting-plans feature Signed-off-by: Michael Kaufmann (d00p) --- admin_customers.php | 28 + admin_plans.php | 492 ++++++++++++++++++ install/froxlor.sql | 15 +- .../updates/froxlor/0.9/update_0.9.inc.php | 21 + .../admin/customer/formfield.customer_add.php | 12 + .../customer/formfield.customer_edit.php | 12 + .../admin/plans/formfield.plans_add.php | 41 ++ .../admin/plans/formfield.plans_edit.php | 43 ++ lib/navigation/00.froxlor.main.php | 5 + lib/tables.inc.php | 1 + lib/version.inc.php | 2 +- lng/english.lng.php | 10 + lng/german.lng.php | 10 + .../Sparkle/admin/customers/customers_add.tpl | 1 + .../admin/customers/customers_edit.tpl | 1 + templates/Sparkle/admin/plans/plans.tpl | 59 +++ templates/Sparkle/admin/plans/plans_add.tpl | 26 + templates/Sparkle/admin/plans/plans_edit.tpl | 27 + templates/Sparkle/admin/plans/plans_plan.tpl | 14 + templates/Sparkle/assets/js/customers.js | 74 +++ 20 files changed, 892 insertions(+), 2 deletions(-) create mode 100644 admin_plans.php create mode 100644 lib/formfields/admin/plans/formfield.plans_add.php create mode 100644 lib/formfields/admin/plans/formfield.plans_edit.php create mode 100644 templates/Sparkle/admin/plans/plans.tpl create mode 100644 templates/Sparkle/admin/plans/plans_add.tpl create mode 100644 templates/Sparkle/admin/plans/plans_edit.tpl create mode 100644 templates/Sparkle/admin/plans/plans_plan.tpl create mode 100644 templates/Sparkle/assets/js/customers.js diff --git a/admin_customers.php b/admin_customers.php index 74dc10b8..ddd139db 100644 --- a/admin_customers.php +++ b/admin_customers.php @@ -1073,6 +1073,20 @@ if ($page == 'customers' } } + // hosting plans + $hosting_plans = ""; + $plans = Database::query(" + SELECT * + FROM `" . TABLE_PANEL_PLANS . "` + ORDER BY name ASC + "); + if (Database::num_rows() > 0){ + $hosting_plans .= makeoption("---", 0, 0, true, true); + } + while ($row = $plans->fetch(PDO::FETCH_ASSOC)) { + $hosting_plans .= makeoption($row['name'], $row['id'], 0, true, true); + } + $customer_add_data = include_once dirname(__FILE__).'/lib/formfields/admin/customer/formfield.customer_add.php'; $customer_add_form = htmlform::genHTMLForm($customer_add_data); @@ -1755,6 +1769,20 @@ if ($page == 'customers' } } + // hosting plans + $hosting_plans = ""; + $plans = Database::query(" + SELECT * + FROM `" . TABLE_PANEL_PLANS . "` + ORDER BY name ASC + "); + if (Database::num_rows() > 0){ + $hosting_plans .= makeoption("---", 0, 0, true, true); + } + while ($row = $plans->fetch(PDO::FETCH_ASSOC)) { + $hosting_plans .= makeoption($row['name'], $row['id'], 0, true, true); + } + $customer_edit_data = include_once dirname(__FILE__).'/lib/formfields/admin/customer/formfield.customer_edit.php'; $customer_edit_form = htmlform::genHTMLForm($customer_edit_data); diff --git a/admin_plans.php b/admin_plans.php new file mode 100644 index 00000000..6ff53949 --- /dev/null +++ b/admin_plans.php @@ -0,0 +1,492 @@ + (2010-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Panel + * + */ +define('AREA', 'admin'); +require './lib/init.php'; + +if (isset($_POST['id'])) { + $id = intval($_POST['id']); +} elseif (isset($_GET['id'])) { + $id = intval($_GET['id']); +} + +if ($page == '' || $page == 'overview') { + + if ($action == '') { + + $log->logAction(ADM_ACTION, LOG_NOTICE, "viewed admin_plans"); + $fields = array( + 'p.name' => $lng['admin']['plans']['name'], + 'p.description' => $lng['admin']['plans']['description'], + 'adminname' => $lng['admin']['admin'], + 'p.ts' => $lng['admin']['plans']['last_update'] + ); + $paging = new paging($userinfo, TABLE_PANEL_PLANS, $fields); + $plans = ''; + $result_stmt = Database::prepare(" + SELECT p.*, a.loginname as adminname + FROM `" . TABLE_PANEL_PLANS . "` p, `" . TABLE_PANEL_ADMINS . "` a + WHERE " . ($userinfo['customers_see_all'] ? '' : " `p`.`adminid` = :adminid AND ") . " + `p`.`adminid` = `a`.`adminid` " . $paging->getSqlWhere(false) . " " . $paging->getSqlOrderBy() . " " . $paging->getSqlLimit()); + Database::pexecute($result_stmt, array( + 'adminid' => $userinfo['adminid'] + )); + $paging->setEntries(Database::num_rows()); + $sortcode = $paging->getHtmlSortCode($lng); + $arrowcode = $paging->getHtmlArrowCode($filename . '?page=' . $page . '&s=' . $s); + $searchcode = $paging->getHtmlSearchCode($lng); + $pagingcode = $paging->getHtmlPagingCode($filename . '?page=' . $page . '&s=' . $s); + $i = 0; + $count = 0; + + while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) { + + if ($paging->checkDisplay($i)) { + $row = htmlentities_array($row); + $row['ts_format'] = date("d.m.Y H:i", $row['ts']); + eval("\$plans.=\"" . getTemplate("plans/plans_plan") . "\";"); + $count ++; + } + $i ++; + } + + eval("echo \"" . getTemplate("plans/plans") . "\";"); + } elseif ($action == 'delete' && $id != 0) { + + $result_stmt = Database::prepare(" + SELECT * FROM `" . TABLE_PANEL_PLANS . "` WHERE `id` = :id"); + $result = Database::pexecute_first($result_stmt, array( + 'id' => $id + )); + + if ($result['id'] != 0 && $result['id'] == $id && (int) $userinfo['adminid'] == $result['adminid']) { + if (isset($_POST['send']) && $_POST['send'] == 'send') { + + $del_stmt = Database::prepare(" + DELETE FROM `" . TABLE_PANEL_PLANS . "` WHERE `id` = :id"); + Database::pexecute($del_stmt, array( + 'id' => $id + )); + + $log->logAction(ADM_ACTION, LOG_INFO, "Plan '" . $result['name'] . "' has been deleted by '" . $userinfo['loginname'] . "'"); + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); + } else { + ask_yesno('plan_reallydelete', $filename, array( + 'id' => $id, + 'page' => $page, + 'action' => $action + ), $result['name']); + } + } else { + standard_error('nopermissionsorinvalidid'); + } + } elseif ($action == 'add') { + + if (isset($_POST['send']) && $_POST['send'] == 'send') { + $name = validate($_POST['name'], 'name'); + $description = validate(str_replace("\r\n", "\n", $_POST['description']), 'description', '/^[^\0]*$/'); + + $value_arr = array(); + + $value_arr['diskspace'] = intval_ressource($_POST['diskspace']); + if (isset($_POST['diskspace_ul'])) { + $value_arr['diskspace'] = - 1; + } + + $value_arr['traffic'] = doubleval_ressource($_POST['traffic']); + if (isset($_POST['traffic_ul'])) { + $value_arr['traffic'] = - 1; + } + + $value_arr['subdomains'] = intval_ressource($_POST['subdomains']); + if (isset($_POST['subdomains_ul'])) { + $value_arr['subdomains'] = - 1; + } + + $value_arr['emails'] = intval_ressource($_POST['emails']); + if (isset($_POST['emails_ul'])) { + $value_arr['emails'] = - 1; + } + + $value_arr['email_accounts'] = intval_ressource($_POST['email_accounts']); + if (isset($_POST['email_accounts_ul'])) { + $value_arr['email_accounts'] = - 1; + } + + $value_arr['email_forwarders'] = intval_ressource($_POST['email_forwarders']); + if (isset($_POST['email_forwarders_ul'])) { + $value_arr['email_forwarders'] = - 1; + } + + if (Settings::Get('system.mail_quota_enabled') == '1') { + $value_arr['email_quota'] = validate($_POST['email_quota'], 'email_quota', '/^\d+$/', 'vmailquotawrong', array( + '0', + '' + )); + if (isset($_POST['email_quota_ul'])) { + $value_arr['email_quota'] = - 1; + } + } else { + $value_arr['email_quota'] = - 1; + } + + $value_arr['email_imap'] = 0; + if (isset($_POST['email_imap'])) { + $value_arr['email_imap'] = intval_ressource($_POST['email_imap']); + } + + $value_arr['email_pop3'] = 0; + if (isset($_POST['email_pop3'])) { + $value_arr['email_pop3'] = intval_ressource($_POST['email_pop3']); + } + + $value_arr['ftps'] = intval_ressource($_POST['ftps']); + if (isset($_POST['ftps_ul'])) { + $value_arr['ftps'] = - 1; + } + + $value_arr['tickets'] = (Settings::Get('ticket.enabled') == 1 ? intval_ressource($_POST['tickets']) : 0); + if (isset($_POST['tickets_ul']) && Settings::Get('ticket.enabled') == '1') { + $value_arr['tickets'] = - 1; + } + + $value_arr['mysqls'] = intval_ressource($_POST['mysqls']); + if (isset($_POST['mysqls_ul'])) { + $value_arr['mysqls'] = - 1; + } + + $value_arr['phpenabled'] = 0; + if (isset($_POST['phpenabled'])) { + $value_arr['phpenabled'] = intval($_POST['phpenabled']); + } + + $value_arr['allowed_phpconfigs'] = array(); + if (isset($_POST['allowed_phpconfigs']) && is_array($_POST['allowed_phpconfigs'])) { + foreach ($_POST['allowed_phpconfigs'] as $allowed_phpconfig) { + $allowed_phpconfig = intval($allowed_phpconfig); + $value_arr['allowed_phpconfigs'][] = $allowed_phpconfig; + } + } + + $value_arr['perlenabled'] = 0; + if (isset($_POST['perlenabled'])) { + $value_arr['perlenabled'] = intval($_POST['perlenabled']); + } + + $value_arr['dnsenabled'] = 0; + if (isset($_POST['dnsenabled'])) { + $value_arr['dnsenabled'] = intval($_POST['dnsenabled']); + } + + $ins_stmt = Database::prepare(" + INSERT INTO `" . TABLE_PANEL_PLANS . "` + SET `adminid` = :adminid, `name` = :name, `description` = :desc, `value` = :valuearr, `ts` = UNIX_TIMESTAMP(); + "); + $ins_data = array( + 'adminid' => $userinfo['adminid'], + 'name' => $name, + 'desc' => $description, + 'valuearr' => json_encode($value_arr) + ); + Database::pexecute($ins_stmt, $ins_data); + + $log->logAction(ADM_ACTION, LOG_WARNING, "added plan '" . $name . "'"); + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); + } else { + + $diskspace_ul = makecheckbox('diskspace_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $traffic_ul = makecheckbox('traffic_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $subdomains_ul = makecheckbox('subdomains_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $emails_ul = makecheckbox('emails_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $email_accounts_ul = makecheckbox('email_accounts_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $email_forwarders_ul = makecheckbox('email_forwarders_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $email_quota_ul = makecheckbox('email_quota_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $ftps_ul = makecheckbox('ftps_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $tickets_ul = makecheckbox('tickets_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + $mysqls_ul = makecheckbox('mysqls_ul', $lng['customer']['unlimited'], '-1', false, '0', true, true); + + $phpconfigs = array(); + $configs = Database::query(" + SELECT c.*, fc.description as interpreter + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid + "); + while ($row = $configs->fetch(PDO::FETCH_ASSOC)) { + if ((int) Settings::Get('phpfpm.enabled') == 1) { + $phpconfigs[] = array( + 'label' => $row['description'] . " [" . $row['interpreter'] . "]
    ", + 'value' => $row['id'] + ); + } else { + $phpconfigs[] = array( + 'label' => $row['description'] . "
    ", + 'value' => $row['id'] + ); + } + } + + $plans_add_data = include_once dirname(__FILE__) . '/lib/formfields/admin/plans/formfield.plans_add.php'; + $cust_add_data = include_once dirname(__FILE__) . '/lib/formfields/admin/customer/formfield.customer_add.php'; + // unset unneeded stuff + unset($cust_add_data['customer_add']['sections']['section_a']); + unset($cust_add_data['customer_add']['sections']['section_b']); + unset($cust_add_data['customer_add']['sections']['section_cpre']); + // merge + $plans_add_data['plans_add']['sections'] = array_merge($plans_add_data['plans_add']['sections'], $cust_add_data['customer_add']['sections']); + $plans_add_form = htmlform::genHTMLForm($plans_add_data); + + $title = $plans_add_data['plans_add']['title']; + $image = $plans_add_data['plans_add']['image']; + + eval("echo \"" . getTemplate("plans/plans_add") . "\";"); + } + } elseif ($action == 'edit' && $id != 0) { + $result_stmt = Database::prepare(" + SELECT * FROM `" . TABLE_PANEL_PLANS . "` WHERE `id` = :id"); + $result = Database::pexecute_first($result_stmt, array( + 'id' => $id + )); + + if ($result['name'] != '') { + + $result['value'] = json_decode($result['value'], true); + $result = htmlentities_array($result); + + foreach ($result['value'] as $index => $value) { + $result[$index] = $value; + } + $result['allowed_phpconfigs'] = json_encode($result['allowed_phpconfigs']); + + if (isset($_POST['send']) && $_POST['send'] == 'send') { + + $name = validate($_POST['name'], 'name'); + $description = validate(str_replace("\r\n", "\n", $_POST['description']), 'description', '/^[^\0]*$/'); + + $value_arr = array(); + + $value_arr['diskspace'] = intval_ressource($_POST['diskspace']); + if (isset($_POST['diskspace_ul'])) { + $value_arr['diskspace'] = - 1; + } + + $value_arr['traffic'] = doubleval_ressource($_POST['traffic']); + if (isset($_POST['traffic_ul'])) { + $value_arr['traffic'] = - 1; + } + + $value_arr['subdomains'] = intval_ressource($_POST['subdomains']); + if (isset($_POST['subdomains_ul'])) { + $value_arr['subdomains'] = - 1; + } + + $value_arr['emails'] = intval_ressource($_POST['emails']); + if (isset($_POST['emails_ul'])) { + $value_arr['emails'] = - 1; + } + + $value_arr['email_accounts'] = intval_ressource($_POST['email_accounts']); + if (isset($_POST['email_accounts_ul'])) { + $value_arr['email_accounts'] = - 1; + } + + $value_arr['email_forwarders'] = intval_ressource($_POST['email_forwarders']); + if (isset($_POST['email_forwarders_ul'])) { + $value_arr['email_forwarders'] = - 1; + } + + if (Settings::Get('system.mail_quota_enabled') == '1') { + $value_arr['email_quota'] = validate($_POST['email_quota'], 'email_quota', '/^\d+$/', 'vmailquotawrong', array( + '0', + '' + )); + if (isset($_POST['email_quota_ul'])) { + $value_arr['email_quota'] = - 1; + } + } else { + $value_arr['email_quota'] = - 1; + } + + $value_arr['email_imap'] = 0; + if (isset($_POST['email_imap'])) { + $value_arr['email_imap'] = intval_ressource($_POST['email_imap']); + } + + $value_arr['email_pop3'] = 0; + if (isset($_POST['email_pop3'])) { + $value_arr['email_pop3'] = intval_ressource($_POST['email_pop3']); + } + + $value_arr['ftps'] = intval_ressource($_POST['ftps']); + if (isset($_POST['ftps_ul'])) { + $value_arr['ftps'] = - 1; + } + + $value_arr['tickets'] = (Settings::Get('ticket.enabled') == 1 ? intval_ressource($_POST['tickets']) : 0); + if (isset($_POST['tickets_ul']) && Settings::Get('ticket.enabled') == '1') { + $value_arr['tickets'] = - 1; + } + + $value_arr['mysqls'] = intval_ressource($_POST['mysqls']); + if (isset($_POST['mysqls_ul'])) { + $value_arr['mysqls'] = - 1; + } + + $value_arr['phpenabled'] = 0; + if (isset($_POST['phpenabled'])) { + $value_arr['phpenabled'] = intval($_POST['phpenabled']); + } + + $value_arr['allowed_phpconfigs'] = array(); + if (isset($_POST['allowed_phpconfigs']) && is_array($_POST['allowed_phpconfigs'])) { + foreach ($_POST['allowed_phpconfigs'] as $allowed_phpconfig) { + $allowed_phpconfig = intval($allowed_phpconfig); + $value_arr['allowed_phpconfigs'][] = $allowed_phpconfig; + } + } + + $value_arr['perlenabled'] = 0; + if (isset($_POST['perlenabled'])) { + $value_arr['perlenabled'] = intval($_POST['perlenabled']); + } + + $value_arr['dnsenabled'] = 0; + if (isset($_POST['dnsenabled'])) { + $value_arr['dnsenabled'] = intval($_POST['dnsenabled']); + } + + $ins_stmt = Database::prepare(" + UPDATE `" . TABLE_PANEL_PLANS . "` + SET `name` = :name, `description` = :desc, `value` = :valuearr, `ts` = UNIX_TIMESTAMP() + WHERE `id` = :id + "); + $ins_data = array( + 'name' => $name, + 'desc' => $description, + 'valuearr' => json_encode($value_arr), + 'id' => $id + ); + Database::pexecute($ins_stmt, $ins_data); + + $log->logAction(ADM_ACTION, LOG_WARNING, "updated plan '" . $name . "'"); + redirectTo($filename, array( + 'page' => $page, + 's' => $s + )); + } else { + + $diskspace_ul = makecheckbox('diskspace_ul', $lng['customer']['unlimited'], '-1', false, $result['diskspace'], true, true); + if ($result['diskspace'] == '-1') { + $result['diskspace'] = ''; + } + + $traffic_ul = makecheckbox('traffic_ul', $lng['customer']['unlimited'], '-1', false, $result['traffic'], true, true); + if ($result['traffic'] == '-1') { + $result['traffic'] = ''; + } + + $subdomains_ul = makecheckbox('subdomains_ul', $lng['customer']['unlimited'], '-1', false, $result['subdomains'], true, true); + if ($result['subdomains'] == '-1') { + $result['subdomains'] = ''; + } + + $emails_ul = makecheckbox('emails_ul', $lng['customer']['unlimited'], '-1', false, $result['emails'], true, true); + if ($result['emails'] == '-1') { + $result['emails'] = ''; + } + + $email_accounts_ul = makecheckbox('email_accounts_ul', $lng['customer']['unlimited'], '-1', false, $result['email_accounts'], true, true); + if ($result['email_accounts'] == '-1') { + $result['email_accounts'] = ''; + } + + $email_forwarders_ul = makecheckbox('email_forwarders_ul', $lng['customer']['unlimited'], '-1', false, $result['email_forwarders'], true, true); + if ($result['email_forwarders'] == '-1') { + $result['email_forwarders'] = ''; + } + + $email_quota_ul = makecheckbox('email_quota_ul', $lng['customer']['unlimited'], '-1', false, $result['email_quota'], true, true); + if ($result['email_quota'] == '-1') { + $result['email_quota'] = ''; + } + + $ftps_ul = makecheckbox('ftps_ul', $lng['customer']['unlimited'], '-1', false, $result['ftps'], true, true); + if ($result['ftps'] == '-1') { + $result['ftps'] = ''; + } + + $tickets_ul = makecheckbox('tickets_ul', $lng['customer']['unlimited'], '-1', false, $result['tickets'], true, true); + if ($result['tickets'] == '-1') { + $result['tickets'] = ''; + } + + $mysqls_ul = makecheckbox('mysqls_ul', $lng['customer']['unlimited'], '-1', false, $result['mysqls'], true, true); + if ($result['mysqls'] == '-1') { + $result['mysqls'] = ''; + } + + $phpconfigs = array(); + $configs = Database::query(" + SELECT c.*, fc.description as interpreter + FROM `" . TABLE_PANEL_PHPCONFIGS . "` c + LEFT JOIN `" . TABLE_PANEL_FPMDAEMONS . "` fc ON fc.id = c.fpmsettingid + "); + while ($row = $configs->fetch(PDO::FETCH_ASSOC)) { + if ((int) Settings::Get('phpfpm.enabled') == 1) { + $phpconfigs[] = array( + 'label' => $row['description'] . " [" . $row['interpreter'] . "]
    ", + 'value' => $row['id'] + ); + } else { + $phpconfigs[] = array( + 'label' => $row['description'] . "
    ", + 'value' => $row['id'] + ); + } + } + + $plans_edit_data = include_once dirname(__FILE__) . '/lib/formfields/admin/plans/formfield.plans_edit.php'; + $cust_edit_data = include_once dirname(__FILE__) . '/lib/formfields/admin/customer/formfield.customer_edit.php'; + // unset unneeded stuff + unset($cust_edit_data['customer_edit']['sections']['section_a']); + unset($cust_edit_data['customer_edit']['sections']['section_b']); + unset($cust_edit_data['customer_edit']['sections']['section_cpre']); + // merge + $plans_edit_data['plans_edit']['sections'] = array_merge($plans_edit_data['plans_edit']['sections'], $cust_edit_data['customer_edit']['sections']); + $plans_edit_form = htmlform::genHTMLForm($plans_edit_data); + + $title = $plans_edit_data['plans_edit']['title']; + $image = $plans_edit_data['plans_edit']['image']; + + eval("echo \"" . getTemplate("plans/plans_edit") . "\";"); + } + } + } elseif ($action == 'jqGetPlanValues') { + $planid = isset($_POST['planid']) ? (int)$_POST['planid'] : 0; + $result_stmt = Database::prepare(" + SELECT * FROM `" . TABLE_PANEL_PLANS . "` WHERE `id` = :id"); + $result = Database::pexecute_first($result_stmt, array( + 'id' => $planid + )); + echo $result['value']; + exit; + } +} diff --git a/install/froxlor.sql b/install/froxlor.sql index 567743ac..21c0a32d 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -687,7 +687,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.39.2'), - ('panel', 'db_version', '201801260'); + ('panel', 'db_version', '201802120'); DROP TABLE IF EXISTS `panel_tasks`; @@ -1028,3 +1028,16 @@ CREATE TABLE `domain_dns_entries` ( PRIMARY KEY (`id`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; + +DROP TABLE IF EXISTS `panel_plans`; +CREATE TABLE `panel_plans` ( + `id` int(11) NOT NULL auto_increment, + `adminid` int(11) NOT NULL default '0', + `name` varchar(255) NOT NULL default '', + `description` text NOT NULL, + `value` longtext NOT NULL, + `ts` int(15) NOT NULL default '0', + PRIMARY KEY (id), + KEY adminid (adminid) +) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; + diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index e89a18fd..81cf8b8e 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3892,3 +3892,24 @@ if (isFroxlorVersion('0.9.39.1')) { showUpdateStep("Updating from 0.9.39.1 to 0.9.39.2", false); updateToVersion('0.9.39.2'); } + +if (isDatabaseVersion('201801260')) { + + showUpdateStep("Adding new plans table"); + Database::query("DROP TABLE IF EXISTS `panel_plans`;"); + $sql = "CREATE TABLE `panel_plans` ( + `id` int(11) NOT NULL auto_increment, + `adminid` int(11) NOT NULL default '0', + `name` varchar(255) NOT NULL default '', + `description` text NOT NULL, + `value` longtext NOT NULL, + `ts` int(15) NOT NULL default '0', + PRIMARY KEY (id), + KEY adminid (adminid) + ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci;"; + Database::query($sql); + lastStepStatus(0); + + updateToDbVersion('201802120'); +} + diff --git a/lib/formfields/admin/customer/formfield.customer_add.php b/lib/formfields/admin/customer/formfield.customer_add.php index 9d3d26ef..c123f161 100644 --- a/lib/formfields/admin/customer/formfield.customer_add.php +++ b/lib/formfields/admin/customer/formfield.customer_add.php @@ -158,6 +158,18 @@ return array( ) ) ), + 'section_cpre' => array( + 'visible' => !empty($hosting_plans), + 'title' => $lng['admin']['plans']['use_plan'], + 'image' => 'icons/user_add.png', + 'fields' => array( + 'use_plan' => array( + 'label' => $lng['admin']['plans']['use_plan'], + 'type' => 'select', + 'select_var' => $hosting_plans + ) + ) + ), 'section_c' => array( 'title' => $lng['admin']['servicedata'], 'image' => 'icons/user_add.png', diff --git a/lib/formfields/admin/customer/formfield.customer_edit.php b/lib/formfields/admin/customer/formfield.customer_edit.php index c5f74d74..70654183 100644 --- a/lib/formfields/admin/customer/formfield.customer_edit.php +++ b/lib/formfields/admin/customer/formfield.customer_edit.php @@ -150,6 +150,18 @@ return array( ) ) ), + 'section_cpre' => array( + 'visible' => !empty($hosting_plans), + 'title' => $lng['admin']['plans']['use_plan'], + 'image' => 'icons/user_add.png', + 'fields' => array( + 'use_plan' => array( + 'label' => $lng['admin']['plans']['use_plan'], + 'type' => 'select', + 'select_var' => $hosting_plans + ) + ) + ), 'section_c' => array( 'title' => $lng['admin']['servicedata'], 'image' => 'icons/user_edit.png', diff --git a/lib/formfields/admin/plans/formfield.plans_add.php b/lib/formfields/admin/plans/formfield.plans_add.php new file mode 100644 index 00000000..dcb0d1c7 --- /dev/null +++ b/lib/formfields/admin/plans/formfield.plans_add.php @@ -0,0 +1,41 @@ + (2010-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Formfields + * + */ + +return array( + 'plans_add' => array( + 'title' => $lng['admin']['plans']['add'], + 'image' => 'icons/templates_add_big.png', + 'sections' => array( + 'section_a' => array( + 'title' => $lng['admin']['plans']['plan_details'], + 'image' => 'icons/templates_add_big.png', + 'fields' => array( + 'name' => array( + 'label' => $lng['admin']['plans']['name'], + 'type' => 'text' + ), + 'description' => array( + 'label' => $lng['admin']['plans']['description'], + 'type' => 'textarea', + 'cols' => 60, + 'rows' => 12 + ) + ) + ) + ) + ) +); diff --git a/lib/formfields/admin/plans/formfield.plans_edit.php b/lib/formfields/admin/plans/formfield.plans_edit.php new file mode 100644 index 00000000..551977d4 --- /dev/null +++ b/lib/formfields/admin/plans/formfield.plans_edit.php @@ -0,0 +1,43 @@ + (2010-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Formfields + * + */ + +return array( + 'plans_edit' => array( + 'title' => $lng['admin']['plans']['edit'], + 'image' => 'icons/templates_edit_big.png', + 'sections' => array( + 'section_a' => array( + 'title' => $lng['admin']['plans']['plan_details'], + 'image' => 'icons/templates_edit_big.png', + 'fields' => array( + 'name' => array( + 'label' => $lng['admin']['plans']['name'], + 'type' => 'text', + 'value' => $result['name'] + ), + 'description' => array( + 'label' => $lng['admin']['plans']['description'], + 'type' => 'textarea', + 'cols' => 60, + 'rows' => 12, + 'value' => $result['description'] + ) + ) + ) + ) + ) +); diff --git a/lib/navigation/00.froxlor.main.php b/lib/navigation/00.froxlor.main.php index fd077c3c..a02a3a07 100644 --- a/lib/navigation/00.froxlor.main.php +++ b/lib/navigation/00.froxlor.main.php @@ -214,6 +214,11 @@ return array( 'label' => $lng['admin']['ipsandports']['ipsandports'], 'required_resources' => 'change_serversettings' ), + array( + 'url' => 'admin_plans.php?page=overview', + 'label' => $lng['admin']['plans']['plans'], + 'required_resources' => 'customers' + ), array( 'url' => 'admin_settings.php?page=updatecounters', 'label' => $lng['admin']['updatecounters'], diff --git a/lib/tables.inc.php b/lib/tables.inc.php index c9f71112..207612f0 100644 --- a/lib/tables.inc.php +++ b/lib/tables.inc.php @@ -52,5 +52,6 @@ define('TABLE_PANEL_DOMAIN_SSL_SETTINGS', 'domain_ssl_settings'); define('TABLE_DOMAINTOIP', 'panel_domaintoip'); define('TABLE_DOMAIN_DNS', 'domain_dns_entries'); define('TABLE_PANEL_FPMDAEMONS', 'panel_fpmdaemons'); +define('TABLE_PANEL_PLANS', 'panel_plans'); require dirname(__FILE__).'/version.inc.php'; diff --git a/lib/version.inc.php b/lib/version.inc.php index f2d10dde..329a4c90 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.39.2'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201801260'; +$dbversion = '201802120'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index 3123a1db..df6ce8ce 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2104,3 +2104,13 @@ $lng['serversettings']['phpfpm_settings']['envpath'] = 'Paths to add to the PATH $lng['admin']['configfiles']['importexport'] = 'Import/Export'; $lng['success']['settingsimported'] = 'Settings imported successfully'; $lng['error']['jsonextensionnotfound'] = 'This feature requires the php json-extension.'; + +// added in froxlor 0.9.39 +$lng['admin']['plans']['name'] = 'Plan name'; +$lng['admin']['plans']['description'] = 'Description'; +$lng['admin']['plans']['last_update'] = 'Last updated'; +$lng['admin']['plans']['plans'] = 'Hosting plans'; +$lng['admin']['plans']['plan_details'] = 'Plan details'; +$lng['admin']['plans']['add'] = 'Add new plan'; +$lng['admin']['plans']['edit'] = 'Edit plan'; +$lng['admin']['plans']['use_plan'] = 'Apply plan'; diff --git a/lng/german.lng.php b/lng/german.lng.php index e5257bcd..90592c13 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1754,3 +1754,13 @@ $lng['phpfpm']['ini_admin_values'] = 'Mögliche php_admin_value $lng['serversettings']['phpfpm_settings']['envpath'] = 'Pfade für die PATH Umgebungsvariable. Leerlassen, um keine PATH Umgebungsvariable zu setzen.'; $lng['success']['settingsimported'] = 'Einstellungnen erfolgreich importiert'; $lng['error']['jsonextensionnotfound'] = 'Diese Funktion benötigt die PHP json-Erweiterung.'; + +// added in froxlor 0.9.39 +$lng['admin']['plans']['name'] = 'Plan Name'; +$lng['admin']['plans']['description'] = 'Beschreibung'; +$lng['admin']['plans']['last_update'] = 'Zuletzt aktualisiert'; +$lng['admin']['plans']['plans'] = 'Hosting Pläne'; +$lng['admin']['plans']['plan_details'] = 'Plan Details'; +$lng['admin']['plans']['add'] = 'Neuen Plan anlegen'; +$lng['admin']['plans']['edit'] = 'Plan editieren'; +$lng['admin']['plans']['use_plan'] = 'Plan übernehmen'; diff --git a/templates/Sparkle/admin/customers/customers_add.tpl b/templates/Sparkle/admin/customers/customers_add.tpl index ffabf7d9..472c6b54 100644 --- a/templates/Sparkle/admin/customers/customers_add.tpl +++ b/templates/Sparkle/admin/customers/customers_add.tpl @@ -6,6 +6,7 @@ $header {$title} +
    diff --git a/templates/Sparkle/admin/customers/customers_edit.tpl b/templates/Sparkle/admin/customers/customers_edit.tpl index f9d751ec..5d4d1c34 100644 --- a/templates/Sparkle/admin/customers/customers_edit.tpl +++ b/templates/Sparkle/admin/customers/customers_edit.tpl @@ -6,6 +6,7 @@ $header {$title} +
    diff --git a/templates/Sparkle/admin/plans/plans.tpl b/templates/Sparkle/admin/plans/plans.tpl new file mode 100644 index 00000000..963c1dbf --- /dev/null +++ b/templates/Sparkle/admin/plans/plans.tpl @@ -0,0 +1,59 @@ +$header +
    +
    +

    +   + {$lng['admin']['plans']['plans']} +

    +
    + +
    + +
    + + +
    + {$searchcode} +
    + + + + + + + + + + + + + + + + + + + + + + + + $plans + +
    {$lng['admin']['plans']['name']} {$arrowcode['p.name']}{$lng['admin']['plans']['description']} {$arrowcode['p.description']}{$lng['admin']['admin']} {$arrowcode['a.adminname']}{$lng['admin']['plans']['last_update']} {$arrowcode['p.ts']}{$lng['panel']['options']}
    {$pagingcode}
    +
    + + + + + +
    + +
    +$footer diff --git a/templates/Sparkle/admin/plans/plans_add.tpl b/templates/Sparkle/admin/plans/plans_add.tpl new file mode 100644 index 00000000..ac434237 --- /dev/null +++ b/templates/Sparkle/admin/plans/plans_add.tpl @@ -0,0 +1,26 @@ +$header +
    +
    +

    + {$title}  + {$title} +

    +
    + +
    + +
    + + + + + + + {$plans_add_form} +
    +
    + +
    + +
    +$footer diff --git a/templates/Sparkle/admin/plans/plans_edit.tpl b/templates/Sparkle/admin/plans/plans_edit.tpl new file mode 100644 index 00000000..a812f803 --- /dev/null +++ b/templates/Sparkle/admin/plans/plans_edit.tpl @@ -0,0 +1,27 @@ +$header +
    +
    +

    + {$title}  + {$title} +

    +
    + +
    + +
    + + + + + + + + {$plans_edit_form} +
    +
    + +
    + +
    +$footer diff --git a/templates/Sparkle/admin/plans/plans_plan.tpl b/templates/Sparkle/admin/plans/plans_plan.tpl new file mode 100644 index 00000000..a49c703c --- /dev/null +++ b/templates/Sparkle/admin/plans/plans_plan.tpl @@ -0,0 +1,14 @@ + + {$row['name']} + {$row['description']} + {$row['adminname']} + {$row['ts_format']} + + + {$lng['panel']['edit']} +   + + {$lng['panel']['delete']} + + + diff --git a/templates/Sparkle/assets/js/customers.js b/templates/Sparkle/assets/js/customers.js new file mode 100644 index 00000000..04c7ee89 --- /dev/null +++ b/templates/Sparkle/assets/js/customers.js @@ -0,0 +1,74 @@ +$(document).ready(function() { + + var getUrlParameter = function getUrlParameter(sParam) { + var sPageURL = decodeURIComponent(window.location.search.substring(1)), + sURLVariables = sPageURL.split('&'), + sParameterName, + i; + + for (i = 0; i < sURLVariables.length; i++) { + sParameterName = sURLVariables[i].split('='); + + if (sParameterName[0] === sParam) { + return sParameterName[1] === undefined ? true : sParameterName[1]; + } + } + }; + + /** + * disable unusable php-configuration by customer settings + */ + $('#use_plan').change(function() { + var pid = $(this).val(); + if (pid > 0) { + var sid = getUrlParameter('s'); + $.ajax({ + url: "admin_plans.php?s="+sid+"&page=overview&action=jqGetPlanValues", + type: "POST", + data: { + planid: pid + }, + dataType: "json", + success: function(json) { + for (i in json) { + if (i == 'email_imap' || i == 'email_pop3' || i == 'perlenabled' || i == 'phpenabled' || i == 'dnsenabled') { + /** handle checkboxes **/ + if (json[i] == 1) { + $("input[name='"+i+"']").attr('checked', 'checked'); + } else { + $("input[name='"+i+"']").removeAttr('checked'); + } + } else if (i == 'allowed_phpconfigs') { + /** handle array of values **/ + $("input[name='allowed_phpconfigs[]']").each(function(index) { + $(this).removeAttr('checked'); + for (j in json[i]) { + if ($(this).val() == json[i][j]) { + $(this).attr('checked', 'checked'); + } + } + }); + } else if (json[i] == -1) { + /** handle unlimited checkboxes **/ + $("input[name='" + i + "_ul']").attr('checked', 'checked'); + $("input[name='"+i+"']").prop({ + readonly: true + }); + } else { + /** handle normal value **/ + $("input[name='"+i+"']").val(json[i]); + $("input[name='"+i+"']").prop({ + readonly: false + }); + $("input[name='" + i + "_ul']").removeAttr('checked'); + } + } + }, + error: function(a, b) { + console.log(a, b); + } + }); + } + }); + +}); From 4d7ceb9efe5abd301bfc230b45d4da8c50e98339 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 12 Feb 2018 13:33:29 +0100 Subject: [PATCH 170/179] add missing question-string Signed-off-by: Michael Kaufmann (d00p) --- lng/english.lng.php | 1 + lng/german.lng.php | 1 + 2 files changed, 2 insertions(+) diff --git a/lng/english.lng.php b/lng/english.lng.php index df6ce8ce..b8171b15 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2114,3 +2114,4 @@ $lng['admin']['plans']['plan_details'] = 'Plan details'; $lng['admin']['plans']['add'] = 'Add new plan'; $lng['admin']['plans']['edit'] = 'Edit plan'; $lng['admin']['plans']['use_plan'] = 'Apply plan'; +$lng['question']['plan_reallydelete'] = 'Do you really want to delete the hosting plan %s?'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 90592c13..0055230e 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1764,3 +1764,4 @@ $lng['admin']['plans']['plan_details'] = 'Plan Details'; $lng['admin']['plans']['add'] = 'Neuen Plan anlegen'; $lng['admin']['plans']['edit'] = 'Plan editieren'; $lng['admin']['plans']['use_plan'] = 'Plan übernehmen'; +$lng['question']['plan_reallydelete'] = 'Wollen Sie den Hosting-Plan "%s" wirklich löschen?'; From de70dbb888634d9eb2a98654e71bfb79ecc5672f Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Mon, 12 Feb 2018 14:58:17 +0100 Subject: [PATCH 171/179] fix checked-property when applying hosting-plan for allowed-phpconfigs Signed-off-by: Michael Kaufmann (d00p) --- install/updates/froxlor/0.9/update_0.9.inc.php | 1 - .../admin/customer/formfield.customer_add.php | 4 ++-- templates/Sparkle/assets/js/customers.js | 11 ++++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 81cf8b8e..77ac58e3 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3912,4 +3912,3 @@ if (isDatabaseVersion('201801260')) { updateToDbVersion('201802120'); } - diff --git a/lib/formfields/admin/customer/formfield.customer_add.php b/lib/formfields/admin/customer/formfield.customer_add.php index c123f161..bba95e12 100644 --- a/lib/formfields/admin/customer/formfield.customer_add.php +++ b/lib/formfields/admin/customer/formfield.customer_add.php @@ -302,9 +302,9 @@ return array( 'values' => $phpconfigs, 'value' => ((int) Settings::Get('system.mod_fcgid') == 1 ? array( Settings::Get('system.mod_fcgid_defaultini') - ) : (int) Settings::Get('phpfpm.enabled') == 1) ? array( + ) : (int) Settings::Get('phpfpm.enabled') == 1 ? array( Settings::Get('phpfpm.defaultini') - ) : array(), + ) : array()), 'is_array' => 1 ), 'perlenabled' => array( diff --git a/templates/Sparkle/assets/js/customers.js b/templates/Sparkle/assets/js/customers.js index 04c7ee89..7863f345 100644 --- a/templates/Sparkle/assets/js/customers.js +++ b/templates/Sparkle/assets/js/customers.js @@ -34,17 +34,18 @@ $(document).ready(function() { if (i == 'email_imap' || i == 'email_pop3' || i == 'perlenabled' || i == 'phpenabled' || i == 'dnsenabled') { /** handle checkboxes **/ if (json[i] == 1) { - $("input[name='"+i+"']").attr('checked', 'checked'); + $("input[name='"+i+"']").prop('checked', true); } else { - $("input[name='"+i+"']").removeAttr('checked'); + $("input[name='"+i+"']").prop('checked', false); } } else if (i == 'allowed_phpconfigs') { /** handle array of values **/ $("input[name='allowed_phpconfigs[]']").each(function(index) { - $(this).removeAttr('checked'); + $(this).prop('checked', false); for (j in json[i]) { if ($(this).val() == json[i][j]) { - $(this).attr('checked', 'checked'); + $(this).prop('checked', true); + break; } } }); @@ -60,7 +61,7 @@ $(document).ready(function() { $("input[name='"+i+"']").prop({ readonly: false }); - $("input[name='" + i + "_ul']").removeAttr('checked'); + $("input[name='" + i + "_ul']").prop('checked', false); } } }, From 372ab5d9c807a0133bcecc9c0faa5d5a98e32b2e Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 13 Feb 2018 08:12:58 +0100 Subject: [PATCH 172/179] add domain flag to avoid generation of nginx try_files directive in webroot which is not suitable for some applications; fixes #461 Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 11 +++++++++++ install/froxlor.sql | 3 ++- install/updates/froxlor/0.9/update_0.9.inc.php | 9 +++++++++ .../admin/domains/formfield.domains_add.php | 13 +++++++++++++ .../admin/domains/formfield.domains_edit.php | 15 +++++++++++++++ lib/version.inc.php | 2 +- lng/english.lng.php | 2 ++ lng/german.lng.php | 2 ++ scripts/jobs/cron_tasks.inc.http.30.nginx.php | 6 ++++-- 9 files changed, 59 insertions(+), 4 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index 34418fdc..6dc7cae2 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -429,6 +429,7 @@ if ($page == 'domains' || $page == 'overview') { } $specialsettings = validate(str_replace("\r\n", "\n", $_POST['specialsettings']), 'specialsettings', '/^[^\0]*$/'); + $notryfiles = isset($_POST['notryfiles']) && (int)$_POST['notryfiles'] == 1 ? 1 : 0; validate($_POST['documentroot'], 'documentroot'); // If path is empty and 'Use domain name as default value for DocumentRoot path' is enabled in settings, @@ -451,6 +452,7 @@ if ($page == 'domains' || $page == 'overview') { $zonefile = ''; $dkim = '1'; $specialsettings = ''; + $notryfiles = '0'; } if ($userinfo['caneditphpsettings'] == '1' || $userinfo['change_serversettings'] == '1') { @@ -801,6 +803,7 @@ if ($page == 'domains' || $page == 'overview') { 'mod_fcgid_starter' => $mod_fcgid_starter, 'mod_fcgid_maxrequests' => $mod_fcgid_maxrequests, 'specialsettings' => $specialsettings, + 'notryfiles' => $notryfiles, 'registration_date' => $registration_date, 'termination_date' => $termination_date, 'issubof' => $issubof, @@ -850,6 +853,7 @@ if ($page == 'domains' || $page == 'overview') { 'openbasedir' => $openbasedir, 'speciallogfile' => $speciallogfile, 'specialsettings' => $specialsettings, + 'notryfiles' => $notryfiles, 'ssl_redirect' => $ssl_redirect, 'add_date' => time(), 'registration_date' => $registration_date, @@ -889,6 +893,7 @@ if ($page == 'domains' || $page == 'overview') { `openbasedir` = :openbasedir, `speciallogfile` = :speciallogfile, `specialsettings` = :specialsettings, + `notryfiles` = :notryfiles, `ssl_redirect` = :ssl_redirect, `add_date` = :add_date, `registration_date` = :registration_date, @@ -1338,6 +1343,7 @@ if ($page == 'domains' || $page == 'overview') { $specialsettings = validate(str_replace("\r\n", "\n", $_POST['specialsettings']), 'specialsettings', '/^[^\0]*$/'); $ssfs = (isset($_POST['specialsettingsforsubdomains']) && intval($_POST['specialsettingsforsubdomains']) == 1) ? 1 : 0; + $notryfiles = isset($_POST['notryfiles']) && (int)$_POST['notryfiles'] == 1 ? 1 : 0; $documentroot = validate($_POST['documentroot'], 'documentroot'); if ($documentroot == '') { @@ -1359,6 +1365,7 @@ if ($page == 'domains' || $page == 'overview') { $dkim = $result['dkim']; $specialsettings = $result['specialsettings']; $ssfs = (empty($specialsettings) ? 0 : 1); + $notryfiles = $result['notryfiles']; $documentroot = $result['documentroot']; } @@ -1655,6 +1662,7 @@ if ($page == 'domains' || $page == 'overview') { 'mod_fcgid_maxrequests' => $mod_fcgid_maxrequests, 'specialsettings' => $specialsettings, 'specialsettingsforsubdomains' => $ssfs, + 'notryfiles' => $notryfiles, 'registration_date' => $registration_date, 'termination_date' => $termination_date, 'issubof' => $issubof, @@ -1697,6 +1705,7 @@ if ($page == 'domains' || $page == 'overview') { $mod_fcgid_starter != $result['mod_fcgid_starter'] || $mod_fcgid_maxrequests != $result['mod_fcgid_maxrequests'] || $specialsettings != $result['specialsettings'] || + $notryfiles != $result['notryfiles'] || $aliasdomain != $result['aliasdomain'] || $issubof != $result['ismainbutsubto'] || $email_only != $result['email_only'] || @@ -1855,6 +1864,7 @@ if ($page == 'domains' || $page == 'overview') { $update_data['mod_fcgid_starter'] = $mod_fcgid_starter; $update_data['mod_fcgid_maxrequests'] = $mod_fcgid_maxrequests; $update_data['specialsettings'] = $specialsettings; + $update_data['notryfiles'] = $notryfiles; $update_data['registration_date'] = $registration_date; $update_data['termination_date'] = $termination_date; $update_data['ismainbutsubto'] = $issubof; @@ -1889,6 +1899,7 @@ if ($page == 'domains' || $page == 'overview') { `mod_fcgid_starter` = :mod_fcgid_starter, `mod_fcgid_maxrequests` = :mod_fcgid_maxrequests, `specialsettings` = :specialsettings, + `notryfiles` = :notryfiles, `registration_date` = :registration_date, `termination_date` = :termination_date, `ismainbutsubto` = :ismainbutsubto, diff --git a/install/froxlor.sql b/install/froxlor.sql index 21c0a32d..a8ab851d 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -260,6 +260,7 @@ CREATE TABLE `panel_domains` ( `hsts_preload` tinyint(1) NOT NULL default '0', `ocsp_stapling` tinyint(1) DEFAULT '0', `http2` tinyint(1) DEFAULT '0', + `notryfiles` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `customerid` (`customerid`), KEY `parentdomain` (`parentdomainid`), @@ -687,7 +688,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), ('panel', 'version', '0.9.39.2'), - ('panel', 'db_version', '201802120'); + ('panel', 'db_version', '201802130'); DROP TABLE IF EXISTS `panel_tasks`; diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 77ac58e3..36bb2e59 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3912,3 +3912,12 @@ if (isDatabaseVersion('201801260')) { updateToDbVersion('201802120'); } + +if (isDatabaseVersion('201802120')) { + + showUpdateStep("Adding domain field for try_files flag"); + Database::query("ALTER TABLE `" . TABLE_PANEL_DOMAINS . "` ADD `notryfiles` tinyint(1) DEFAULT '0';"); + lastStepStatus(0); + + updateToDbVersion('201802130'); +} diff --git a/lib/formfields/admin/domains/formfield.domains_add.php b/lib/formfields/admin/domains/formfield.domains_add.php index 71116996..7cb4f546 100644 --- a/lib/formfields/admin/domains/formfield.domains_add.php +++ b/lib/formfields/admin/domains/formfield.domains_add.php @@ -131,6 +131,19 @@ return array( 'type' => 'textarea', 'cols' => 60, 'rows' => 12 + ), + 'notryfiles' => array( + 'visible' => (Settings('system.webserver') == 'nginx' && $userinfo['change_serversettings'] == '1'), + 'label' => $lng['admin']['notryfiles']['title'], + 'desc' => $lng['admin']['notryfiles']['description'], + 'type' => 'checkbox', + 'values' => array( + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array() ) ) ), diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index d37f4806..734619c8 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -161,6 +161,21 @@ return array( 'value' => array( '1' ) + ), + 'notryfiles' => array( + 'visible' => (Settings('system.webserver') == 'nginx' && $userinfo['change_serversettings'] == '1'), + 'label' => $lng['admin']['notryfiles']['title'], + 'desc' => $lng['admin']['notryfiles']['description'], + 'type' => 'checkbox', + 'values' => array( + array( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + $result['notryfiles'] + ) ) ) ), diff --git a/lib/version.inc.php b/lib/version.inc.php index 329a4c90..dac2b1c4 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -19,7 +19,7 @@ $version = '0.9.39.2'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201802120'; +$dbversion = '201802130'; // Distribution branding-tag (used for Debian etc.) $branding = ''; diff --git a/lng/english.lng.php b/lng/english.lng.php index b8171b15..a5d33367 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -2115,3 +2115,5 @@ $lng['admin']['plans']['add'] = 'Add new plan'; $lng['admin']['plans']['edit'] = 'Edit plan'; $lng['admin']['plans']['use_plan'] = 'Apply plan'; $lng['question']['plan_reallydelete'] = 'Do you really want to delete the hosting plan %s?'; +$lng['admin']['notryfiles']['title'] = 'No autogenerated try_files'; +$lng['admin']['notryfiles']['description'] = 'Say yes here if you want to specify a custom try_files directive in specialsettings (needed for some wordpress plugins for example).'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 0055230e..1f6ee8f9 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -1765,3 +1765,5 @@ $lng['admin']['plans']['add'] = 'Neuen Plan anlegen'; $lng['admin']['plans']['edit'] = 'Plan editieren'; $lng['admin']['plans']['use_plan'] = 'Plan übernehmen'; $lng['question']['plan_reallydelete'] = 'Wollen Sie den Hosting-Plan "%s" wirklich löschen?'; +$lng['admin']['notryfiles']['title'] = 'Keine generierte try_files Anweisung'; +$lng['admin']['notryfiles']['description'] = 'Wähle "Ja", wenn eine eigene try_files Direktive in den "eigenen Vhost Einstellungen" angegeben werden soll (z.B. nötig für manche Wordpress Plugins).'; diff --git a/scripts/jobs/cron_tasks.inc.http.30.nginx.php b/scripts/jobs/cron_tasks.inc.http.30.nginx.php index d4d27c77..7f86f605 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -916,7 +916,9 @@ class nginx extends HttpConfigBase if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { $webroot_text .= "\t" . 'index index.php index.html index.htm;' . "\n"; - $webroot_text .= "\t\t" . 'try_files $uri $uri/ @rewrites;' . "\n"; + if ($domain['notryfiles'] != 1) { + $webroot_text .= "\t\t" . 'try_files $uri $uri/ @rewrites;' . "\n"; + } } else { $webroot_text .= "\t" . 'index index.html index.htm;' . "\n"; } @@ -927,7 +929,7 @@ class nginx extends HttpConfigBase } $webroot_text .= "\t" . '}' . "\n\n"; - if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1') { + if ($domain['phpenabled_customer'] == 1 && $domain['phpenabled_vhost'] == '1' && $domain['notryfiles'] != 1) { $webroot_text .= "\tlocation @rewrites {\n"; $webroot_text .= "\t\trewrite ^ /index.php last;\n"; $webroot_text .= "\t}\n\n"; From 7a664a99909be149fd0a308aa773d4b14b3b910a Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 13 Feb 2018 08:21:45 +0100 Subject: [PATCH 173/179] clean up panel_diskspace/panel_diskspace_admins when removing customer/admin Signed-off-by: Michael Kaufmann (d00p) --- admin_admins.php | 5 +++++ admin_customers.php | 2 ++ 2 files changed, 7 insertions(+) diff --git a/admin_admins.php b/admin_admins.php index f0ede7de..4e5a54d5 100644 --- a/admin_admins.php +++ b/admin_admins.php @@ -170,6 +170,11 @@ if ($page == 'admins' "); Database::pexecute($del_stmt, array('adminid' => $id)); + $del_stmt = Database::prepare(" + DELETE FROM `" . TABLE_PANEL_DISKSPACE_ADMINS . "` WHERE `adminid` = :adminid + "); + Database::pexecute($del_stmt, array('adminid' => $id)); + $upd_stmt = Database::prepare(" UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `adminid` = :userid WHERE `adminid` = :adminid diff --git a/admin_customers.php b/admin_customers.php index ddd139db..1ccb9a19 100644 --- a/admin_customers.php +++ b/admin_customers.php @@ -307,6 +307,8 @@ if ($page == 'customers' Database::pexecute($stmt, array('id' => $id)); $stmt = Database::prepare("DELETE FROM `" . TABLE_PANEL_TRAFFIC . "` WHERE `customerid` = :id"); Database::pexecute($stmt, array('id' => $id)); + $stmt = Database::prepare("DELETE FROM `" . TABLE_PANEL_DISKSPACE . "` WHERE `customerid` = :id"); + Database::pexecute($stmt, array('id' => $id)); $stmt = Database::prepare("DELETE FROM `" . TABLE_MAIL_USERS . "` WHERE `customerid` = :id"); Database::pexecute($stmt, array('id' => $id)); $stmt = Database::prepare("DELETE FROM `" . TABLE_MAIL_VIRTUAL . "` WHERE `customerid` = :id"); From 482e8c9a11ac4fa5381d273c9209ff4096e5e561 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 13 Feb 2018 09:06:49 +0100 Subject: [PATCH 174/179] set version to 0.9.39.3 for maintenance release and upcoming debian package so the new hosting-plan feature is included Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 6 ++++++ lib/version.inc.php | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index a8ab851d..e484024d 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -687,7 +687,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.39.2'), + ('panel', 'version', '0.9.39.3'), ('panel', 'db_version', '201802130'); diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index 36bb2e59..b7be4833 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3921,3 +3921,9 @@ if (isDatabaseVersion('201802120')) { updateToDbVersion('201802130'); } + +if (isFroxlorVersion('0.9.39.2')) { + + showUpdateStep("Updating from 0.9.39.2 to 0.9.39.3", false); + updateToVersion('0.9.39.3'); +} diff --git a/lib/version.inc.php b/lib/version.inc.php index dac2b1c4..b8e701dc 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.39.2'; +$version = '0.9.39.3'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201802130'; From fc0c796b68dc368b0fd3902bcebd2e5f78b8433c Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 13 Feb 2018 10:58:06 +0100 Subject: [PATCH 175/179] avoid undefined variables/indexes Signed-off-by: Michael Kaufmann (d00p) --- admin_plans.php | 31 ++++++++++++++++++++++++- templates/Sparkle/admin/plans/plans.tpl | 2 +- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/admin_plans.php b/admin_plans.php index 6ff53949..d37f04cd 100644 --- a/admin_plans.php +++ b/admin_plans.php @@ -244,6 +244,11 @@ if ($page == '' || $page == 'overview') { } } + // dummy to avoid unknown variables + $language_options = null; + $gender_options = null; + $hosting_plans = null; + $plans_add_data = include_once dirname(__FILE__) . '/lib/formfields/admin/plans/formfield.plans_add.php'; $cust_add_data = include_once dirname(__FILE__) . '/lib/formfields/admin/customer/formfield.customer_add.php'; // unset unneeded stuff @@ -462,7 +467,31 @@ if ($page == '' || $page == 'overview') { ); } } - + + // dummy to avoid unknown variables + $result['loginname'] = null; + $result['documentroot'] = null; + $result['standardsubdomain'] = null; + $result['deactivated'] = null; + $language_options = null; + $result['firstname'] = null; + $gender_options = null; + $result['company'] = null; + $result['street'] = null; + $result['zipcode'] = null; + $result['city'] = null; + $result['phone'] = null; + $result['fax'] = null; + $result['email'] = null; + $result['customernumber'] = null; + $result['custom_notes'] = null; + $result['custom_notes_show'] = null; + $hosting_plans = null; + $result['imap'] = null; + $result['pop3'] = null; + $admin_select_cnt = null; + $admin_select = null; + $plans_edit_data = include_once dirname(__FILE__) . '/lib/formfields/admin/plans/formfield.plans_edit.php'; $cust_edit_data = include_once dirname(__FILE__) . '/lib/formfields/admin/customer/formfield.customer_edit.php'; // unset unneeded stuff diff --git a/templates/Sparkle/admin/plans/plans.tpl b/templates/Sparkle/admin/plans/plans.tpl index 963c1dbf..ed9c4432 100644 --- a/templates/Sparkle/admin/plans/plans.tpl +++ b/templates/Sparkle/admin/plans/plans.tpl @@ -26,7 +26,7 @@ $header {$lng['admin']['plans']['name']} {$arrowcode['p.name']} {$lng['admin']['plans']['description']} {$arrowcode['p.description']} - {$lng['admin']['admin']} {$arrowcode['a.adminname']} + {$lng['admin']['admin']} {$arrowcode['adminname']} {$lng['admin']['plans']['last_update']} {$arrowcode['p.ts']} {$lng['panel']['options']} From 27f8c8b4384a1a5fb0a9bd8cda3d24ff562ee0e5 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 13 Feb 2018 11:49:15 +0100 Subject: [PATCH 176/179] show domains of disabled customers also as disabled Signed-off-by: Michael Kaufmann (d00p) --- admin_domains.php | 2 +- templates/Sparkle/admin/domains/domains_domain.tpl | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/admin_domains.php b/admin_domains.php index 6dc7cae2..f731d59c 100644 --- a/admin_domains.php +++ b/admin_domains.php @@ -55,7 +55,7 @@ if ($page == 'domains' || $page == 'overview') { $syshostname = "AND `d`.`id` <> " . Settings::Get('system.hostname_id'); } $result_stmt = Database::prepare(" - SELECT `d`.*, `c`.`loginname`, `c`.`name`, `c`.`firstname`, `c`.`company`, `c`.`standardsubdomain`, `ad`.`id` AS `aliasdomainid`, `ad`.`domain` AS `aliasdomain` + SELECT `d`.*, `c`.`loginname`, `c`.`deactivated`, `c`.`name`, `c`.`firstname`, `c`.`company`, `c`.`standardsubdomain`, `ad`.`id` AS `aliasdomainid`, `ad`.`domain` AS `aliasdomain` FROM `" . TABLE_PANEL_DOMAINS . "` `d` LEFT JOIN `" . TABLE_PANEL_CUSTOMERS . "` `c` USING(`customerid`) LEFT JOIN `" . TABLE_PANEL_DOMAINS . "` `ad` ON `d`.`aliasdomain`=`ad`.`id` diff --git a/templates/Sparkle/admin/domains/domains_domain.tpl b/templates/Sparkle/admin/domains/domains_domain.tpl index 4ccf717c..8e9140c5 100644 --- a/templates/Sparkle/admin/domains/domains_domain.tpl +++ b/templates/Sparkle/admin/domains/domains_domain.tpl @@ -1,8 +1,8 @@ - + - + class="disabled"> {$row['domain']} From 6befe85656d96327e8597f623fc190a12c12db3e Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Tue, 13 Feb 2018 12:23:05 +0100 Subject: [PATCH 177/179] fix add/edit domain due to wrong access to settings; setting version to 0.9.39.4 for bugfix release Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 6 ++++++ lib/formfields/admin/domains/formfield.domains_add.php | 2 +- lib/formfields/admin/domains/formfield.domains_edit.php | 2 +- lib/version.inc.php | 2 +- 5 files changed, 10 insertions(+), 4 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index e484024d..034d561e 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -687,7 +687,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.39.3'), + ('panel', 'version', '0.9.39.4'), ('panel', 'db_version', '201802130'); diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index b7be4833..ca951369 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3927,3 +3927,9 @@ if (isFroxlorVersion('0.9.39.2')) { showUpdateStep("Updating from 0.9.39.2 to 0.9.39.3", false); updateToVersion('0.9.39.3'); } + +if (isFroxlorVersion('0.9.39.3')) { + + showUpdateStep("Updating from 0.9.39.3 to 0.9.39.4", false); + updateToVersion('0.9.39.4'); +} diff --git a/lib/formfields/admin/domains/formfield.domains_add.php b/lib/formfields/admin/domains/formfield.domains_add.php index 7cb4f546..a18018b7 100644 --- a/lib/formfields/admin/domains/formfield.domains_add.php +++ b/lib/formfields/admin/domains/formfield.domains_add.php @@ -133,7 +133,7 @@ return array( 'rows' => 12 ), 'notryfiles' => array( - 'visible' => (Settings('system.webserver') == 'nginx' && $userinfo['change_serversettings'] == '1'), + 'visible' => (Settings::Get('system.webserver') == 'nginx' && $userinfo['change_serversettings'] == '1'), 'label' => $lng['admin']['notryfiles']['title'], 'desc' => $lng['admin']['notryfiles']['description'], 'type' => 'checkbox', diff --git a/lib/formfields/admin/domains/formfield.domains_edit.php b/lib/formfields/admin/domains/formfield.domains_edit.php index 734619c8..5e791da7 100644 --- a/lib/formfields/admin/domains/formfield.domains_edit.php +++ b/lib/formfields/admin/domains/formfield.domains_edit.php @@ -163,7 +163,7 @@ return array( ) ), 'notryfiles' => array( - 'visible' => (Settings('system.webserver') == 'nginx' && $userinfo['change_serversettings'] == '1'), + 'visible' => (Settings::Get('system.webserver') == 'nginx' && $userinfo['change_serversettings'] == '1'), 'label' => $lng['admin']['notryfiles']['title'], 'desc' => $lng['admin']['notryfiles']['description'], 'type' => 'checkbox', diff --git a/lib/version.inc.php b/lib/version.inc.php index b8e701dc..06e38b36 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.39.3'; +$version = '0.9.39.4'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201802130'; From edd5ef0ca047b132863a922183ef1c28f26788fe Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 14 Feb 2018 07:40:39 +0100 Subject: [PATCH 178/179] fix correct display of selected checkbox imap/pop3 when editing hosting plan Signed-off-by: Michael Kaufmann (d00p) --- admin_plans.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/admin_plans.php b/admin_plans.php index d37f04cd..eaee22b2 100644 --- a/admin_plans.php +++ b/admin_plans.php @@ -468,6 +468,9 @@ if ($page == '' || $page == 'overview') { } } + $result['imap'] = $result['email_imap']; + $result['pop3'] = $result['email_pop3']; + // dummy to avoid unknown variables $result['loginname'] = null; $result['documentroot'] = null; @@ -487,8 +490,6 @@ if ($page == '' || $page == 'overview') { $result['custom_notes'] = null; $result['custom_notes_show'] = null; $hosting_plans = null; - $result['imap'] = null; - $result['pop3'] = null; $admin_select_cnt = null; $admin_select = null; From 5c30961d3c0a3dc9262b09f39b56e52f4e902694 Mon Sep 17 00:00:00 2001 From: "Michael Kaufmann (d00p)" Date: Wed, 14 Feb 2018 13:31:39 +0100 Subject: [PATCH 179/179] set version to 0.9.39.5 for bugfix release (imap/pop3 ticks not enabled if active in hosting plan when editing hosting plan) Signed-off-by: Michael Kaufmann (d00p) --- install/froxlor.sql | 2 +- install/updates/froxlor/0.9/update_0.9.inc.php | 6 ++++++ lib/version.inc.php | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/install/froxlor.sql b/install/froxlor.sql index 034d561e..870e30d4 100644 --- a/install/froxlor.sql +++ b/install/froxlor.sql @@ -687,7 +687,7 @@ opcache.interned_strings_buffer'), ('panel', 'password_special_char_required', '0'), ('panel', 'password_special_char', '!?<>§$%+#=@'), ('panel', 'customer_hide_options', ''), - ('panel', 'version', '0.9.39.4'), + ('panel', 'version', '0.9.39.5'), ('panel', 'db_version', '201802130'); diff --git a/install/updates/froxlor/0.9/update_0.9.inc.php b/install/updates/froxlor/0.9/update_0.9.inc.php index ca951369..0abab0fe 100644 --- a/install/updates/froxlor/0.9/update_0.9.inc.php +++ b/install/updates/froxlor/0.9/update_0.9.inc.php @@ -3933,3 +3933,9 @@ if (isFroxlorVersion('0.9.39.3')) { showUpdateStep("Updating from 0.9.39.3 to 0.9.39.4", false); updateToVersion('0.9.39.4'); } + +if (isFroxlorVersion('0.9.39.4')) { + + showUpdateStep("Updating from 0.9.39.4 to 0.9.39.5", false); + updateToVersion('0.9.39.5'); +} diff --git a/lib/version.inc.php b/lib/version.inc.php index 06e38b36..49935fb7 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,7 +16,7 @@ */ // Main version variable -$version = '0.9.39.4'; +$version = '0.9.39.5'; // Database version (YYYYMMDDC where C is a daily counter) $dbversion = '201802130';