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 67c8c554..33cb17cb 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ 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! ### Detailed installation -http://redmine.froxlor.org/projects/froxlor/wiki/Installationtarball +https://github.com/Froxlor/Froxlor/wiki/Install-froxlor-from-tarball ## Help @@ -30,12 +30,12 @@ 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 More documentation may be found in the froxlor - wiki: -http://redmine.froxlor.org/projects/froxlor/wiki +https://github.com/Froxlor/Froxlor/wiki ## License @@ -44,31 +44,21 @@ 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 -[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 +https://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 +## Contributing +[see here](.github/CONTRIBUTING.md) 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/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/actions/admin/settings/131.ssl.php b/actions/admin/settings/131.ssl.php index 56c27cd5..7bdeb3e4 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', @@ -79,6 +93,17 @@ 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' => 'shmcb:/var/run/apache2/ocsp-stapling.cache(131072)', + 'visible' => Settings::Get('system.webserver') == "apache2" && Settings::Get('system.apache24') == 1, + 'save_method' => 'storeSettingField' + ), 'system_leenabled' => array( 'label' => $lng['serversettings']['leenabled'], 'settinggroup' => 'system', @@ -95,7 +120,20 @@ return array( 'type' => 'string', 'string_type' => 'file', 'default' => '/etc/apache2/conf-enabled/acme.conf', - 'save_method' => 'storeSettingField', + '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_letsencryptca' => array( 'label' => $lng['serversettings']['letsencryptca'], @@ -105,8 +143,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' ), @@ -153,6 +191,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/actions/admin/settings/135.fcgid.php b/actions/admin/settings/135.fcgid.php index 050ede3b..212c03f7 100644 --- a/actions/admin/settings/135.fcgid.php +++ b/actions/admin/settings/135.fcgid.php @@ -104,7 +104,7 @@ return array( 'type' => 'int', 'default' => 30, 'save_method' => 'storeSettingField' - ), + ) ) ) ) diff --git a/actions/admin/settings/136.phpfpm.php b/actions/admin/settings/136.phpfpm.php index 750a4660..c8b6e0ea 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', @@ -73,9 +64,22 @@ return array( 'varname' => 'peardir', 'type' => 'string', 'string_type' => 'dir', + 'string_delimiter' => ':', + 'string_emptyallowed' => true, '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', @@ -85,72 +89,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', @@ -160,6 +98,38 @@ return array( '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/admin_admins.php b/admin_admins.php index 32e5de12..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 @@ -440,7 +445,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,13 +845,13 @@ 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); } $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/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_configfiles.php b/admin_configfiles.php index efbeba7a..949e9417 100644 --- a/admin_configfiles.php +++ b/admin_configfiles.php @@ -30,15 +30,30 @@ 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', + '' => 'FROXLOR_MYSQL_PASSWORD', '' => $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'), @@ -67,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"); @@ -78,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 == "") { @@ -121,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 = ''; diff --git a/admin_customers.php b/admin_customers.php index f73bfb6c..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"); @@ -532,6 +534,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 +703,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 +744,7 @@ if ($page == 'customers' `mysqls` = :mysqls, `standardsubdomain` = '0', `phpenabled` = :phpenabled, + `allowed_phpconfigs` = :allowed_phpconfigs, `imap` = :imap, `pop3` = :pop3, `perlenabled` = :perlenabled, @@ -910,7 +922,8 @@ if ($page == 'customers' 'customerid' => $customerid, 'adminid' => $userinfo['adminid'], 'docroot' => $documentroot, - 'adddate' => date('Y-m-d') + 'adddate' => time(), + 'phpenabled' => $phpenabled ); $ins_stmt = Database::prepare(" INSERT INTO `" . TABLE_PANEL_DOMAINS . "` SET @@ -928,6 +941,7 @@ if ($page == 'customers' `dkim_id` = '0', `dkim_privkey` = '', `dkim_pubkey` = '', + `phpenabled` = :phpenabled, `add_date` = :adddate" ); Database::pexecute($ins_stmt, $ins_data); @@ -1022,7 +1036,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); } @@ -1041,6 +1055,40 @@ 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'] + ); + } + } + + // 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); @@ -1203,6 +1251,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']); @@ -1281,7 +1337,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 @@ -1455,6 +1511,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, @@ -1488,6 +1545,7 @@ if ($page == 'customers' `mysqls` = :mysqls, `deactivated` = :deactivated, `phpenabled` = :phpenabled, + `allowed_phpconfigs` = :allowed_phpconfigs, `email_quota` = :email_quota, `imap` = :imap, `pop3` = :pop3, @@ -1628,7 +1686,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); } @@ -1693,6 +1751,40 @@ 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'] + ); + } + } + + // 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_domains.php b/admin_domains.php index 43f0811b..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` @@ -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'); } @@ -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,10 +452,12 @@ if ($page == 'domains' || $page == 'overview') { $zonefile = ''; $dkim = '1'; $specialsettings = ''; + $notryfiles = '0'; } 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) { @@ -495,7 +498,9 @@ if ($page == 'domains' || $page == 'overview') { } } else { + $phpenabled = '1'; $openbasedir = '1'; + if ((int) Settings::Get('phpfpm.enabled') == 1) { $phpsettingid = Settings::Get('phpfpm.defaultini'); } else { @@ -587,14 +592,20 @@ 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; $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; + $http2 = 0; // we need this for the serialize // if ssl is disabled or no ssl-ip/port exists $ssl_ipandports[] = - 1; @@ -603,10 +614,14 @@ if ($page == 'domains' || $page == 'overview') { $hsts_maxage = 0; $hsts_sub = 0; $hsts_preload = 0; + + // OCSP stapling + $ocsp_stapling = 0; } } 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; @@ -615,12 +630,20 @@ 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 - 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'); } + // 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) { @@ -691,6 +714,10 @@ if ($page == 'domains' || $page == 'overview') { standard_error('noipportgiven'); } + if ($phpenabled != '1') { + $phpenabled = '0'; + } + if ($openbasedir != '1') { $openbasedir = '0'; } @@ -770,18 +797,22 @@ 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, 'mod_fcgid_maxrequests' => $mod_fcgid_maxrequests, 'specialsettings' => $specialsettings, + 'notryfiles' => $notryfiles, 'registration_date' => $registration_date, 'termination_date' => $termination_date, 'issubof' => $issubof, 'letsencrypt' => $letsencrypt, + 'http2' => $http2, 'hsts_maxage' => $hsts_maxage, 'hsts_sub' => $hsts_sub, - 'hsts_preload' => $hsts_preload + 'hsts_preload' => $hsts_preload, + 'ocsp_stapling' => $ocsp_stapling ); $security_questions = array( @@ -818,9 +849,11 @@ if ($page == 'domains' || $page == 'overview') { 'email_only' => $email_only, 'subcanemaildomain' => $subcanemaildomain, 'caneditdomain' => $caneditdomain, + 'phpenabled' => $phpenabled, 'openbasedir' => $openbasedir, 'speciallogfile' => $speciallogfile, 'specialsettings' => $specialsettings, + 'notryfiles' => $notryfiles, 'ssl_redirect' => $ssl_redirect, 'add_date' => time(), 'registration_date' => $registration_date, @@ -830,9 +863,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 + 'hsts_preload' => $hsts_preload, + 'ocsp_stapling' => $ocsp_stapling ); $ins_stmt = Database::prepare(" @@ -854,9 +889,11 @@ if ($page == 'domains' || $page == 'overview') { `email_only` = :email_only, `subcanemaildomain` = :subcanemaildomain, `caneditdomain` = :caneditdomain, + `phpenabled` = :phpenabled, `openbasedir` = :openbasedir, `speciallogfile` = :speciallogfile, `specialsettings` = :specialsettings, + `notryfiles` = :notryfiles, `ssl_redirect` = :ssl_redirect, `add_date` = :add_date, `registration_date` = :registration_date, @@ -866,9 +903,11 @@ 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 + `hsts_preload` = :hsts_preload, + `ocsp_stapling` = :ocsp_stapling "); Database::pexecute($ins_stmt, $ins_data); $domainid = Database::lastInsertId(); @@ -1048,11 +1087,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); } @@ -1300,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 == '') { @@ -1321,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']; } @@ -1328,7 +1373,9 @@ 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; + $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']; @@ -1358,12 +1405,15 @@ 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']; } } else { + $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']; } @@ -1404,11 +1454,16 @@ 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; $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']); @@ -1438,6 +1493,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; @@ -1446,10 +1502,14 @@ if ($page == 'domains' || $page == 'overview') { $hsts_maxage = 0; $hsts_sub = 0; $hsts_preload = 0; + + // OCSP stapling + $ocsp_stapling = 0; } } 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; @@ -1458,12 +1518,20 @@ 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 - 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'); } + // 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) { @@ -1474,6 +1542,10 @@ if ($page == 'domains' || $page == 'overview') { $documentroot = makeCorrectDir($documentroot); } + if ($phpenabled != '1') { + $phpenabled = '0'; + } + if ($openbasedir != '1') { $openbasedir = '0'; } @@ -1582,12 +1654,15 @@ if ($page == 'domains' || $page == 'overview') { 'dkim' => $dkim, 'selectserveralias' => $serveraliasoption, 'ssl_redirect' => $ssl_redirect, + 'phpenabled' => $phpenabled, 'openbasedir' => $openbasedir, 'phpsettingid' => $phpsettingid, + 'phpsettingsforsubdomains' => $phpfs, 'mod_fcgid_starter' => $mod_fcgid_starter, 'mod_fcgid_maxrequests' => $mod_fcgid_maxrequests, 'specialsettings' => $specialsettings, 'specialsettingsforsubdomains' => $ssfs, + 'notryfiles' => $notryfiles, 'registration_date' => $registration_date, 'termination_date' => $termination_date, 'issubof' => $issubof, @@ -1596,9 +1671,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 + 'hsts_preload' => $hsts_preload, + 'ocsp_stapling' => $ocsp_stapling ); $security_questions = array( @@ -1617,7 +1694,29 @@ 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'] || + $notryfiles != $result['notryfiles'] || + $aliasdomain != $result['aliasdomain'] || + $issubof != $result['ismainbutsubto'] || + $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'] || + $ocsp_stapling != $result['ocsp_stapling'] + ) { inserttask('1'); } @@ -1758,19 +1857,23 @@ 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; $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; $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; + $update_data['ocsp_stapling'] = $ocsp_stapling; $update_data['id'] = $id; $update_stmt = Database::prepare(" @@ -1789,31 +1892,43 @@ if ($page == 'domains' || $page == 'overview') { `zonefile` = :zonefile, `wwwserveralias` = :wwwserveralias, `iswildcarddomain` = :iswildcarddomain, + `phpenabled` = :phpenabled, `openbasedir` = :openbasedir, `speciallogfile` = :speciallogfile, `phpsettingid` = :phpsettingid, `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, `letsencrypt` = :letsencrypt, + `http2` = :http2, `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); $_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; $_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 @@ -1826,11 +1941,11 @@ 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, `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); @@ -2100,10 +2215,25 @@ 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 + "); + $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)) { - $phpconfigs .= makeoption($phpconfigs_row['description'], $phpconfigs_row['id'], $result['phpsettingid'], true, true); + $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, null, $disabled); + } else { + $phpconfigs .= makeoption($phpconfigs_row['description'], $phpconfigs_row['id'], $result['phpsettingid'], true, true, null, $disabled); + } } $result = htmlentities_array($result); @@ -2119,6 +2249,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') { @@ -2143,6 +2280,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/admin_index.php b/admin_index.php index 177278bf..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); @@ -280,7 +270,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_logger.php b/admin_logger.php index a409c021..9c344702 100644 --- a/admin_logger.php +++ b/admin_logger.php @@ -30,11 +30,11 @@ 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); + $logs_count = $result_cnt_stmt->rowCount(); $paging->setEntries($logs_count); $sortcode = $paging->getHtmlSortCode($lng); $arrowcode = $paging->getHtmlArrowCode($filename . '?page=' . $page . '&s=' . $s); @@ -67,7 +67,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 +105,7 @@ if ($page == 'log' eval("\$log.=\"" . getTemplate('logger/logger_log') . "\";"); $count++; $_action = $action; - } + // } $i++; } $i++; diff --git a/admin_phpsettings.php b/admin_phpsettings.php index 4f7f9824..1d922b3f 100644 --- a/admin_phpsettings.php +++ b/admin_phpsettings.php @@ -16,7 +16,6 @@ * @package Panel * */ - define('AREA', 'admin'); require './lib/init.php'; @@ -27,104 +26,111 @@ 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; + $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'; @@ -132,13 +138,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 +154,9 @@ if ($page == 'overview') { `fpm_slowlog` = :fpmslow, `fpm_reqterm` = :fpmreqterm, `fpm_reqslow` = :fpmreqslow, - `phpsettings` = :phpsettings" - ); + `phpsettings` = :phpsettings, + `fpmsettingid` = :fpmsettingid, + `pass_authorizationheader` = :fpmpassauth"); $ins_data = array( 'desc' => $description, 'binary' => $binary, @@ -162,123 +167,133 @@ if ($page == 'overview') { 'fpmslow' => $fpm_enableslowlog, 'fpmreqterm' => $fpm_reqtermtimeout, 'fpmreqslow' => $fpm_reqslowtimeout, - 'phpsettings' => $phpsettings + 'phpsettings' => $phpsettings, + 'fpmsettingid' => $fpm_config_id, + 'fpmpassauth' => $fpm_pass_authorizationheader ); 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; + $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'; @@ -286,13 +301,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 +317,292 @@ if ($page == 'overview') { `fpm_slowlog` = :fpmslow, `fpm_reqterm` = :fpmreqterm, `fpm_reqslow` = :fpmreqslow, - `phpsettings` = :phpsettings - WHERE `id` = :id" - ); + `phpsettings` = :phpsettings, + `fpmsettingid` = :fpmsettingid, + `pass_authorizationheader` = :fpmpassauth + 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, + 'fpmpassauth' => $fpm_pass_authorizationheader, + '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'], $result['fpmsettingid'], 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 = $_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; + $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]+)\ ?)+$/'); + + 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, + `limit_extensions` = :limit_extensions + "); + $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, + 'limit_extensions' => $limit_extensions + ); + 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 + `fpmsettingid` = '1' WHERE `fpmsettingid` = :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 = $_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']; + $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]+)\ ?)+$/'); + + if (strlen($description) == 0 || strlen($description) > 50) { + standard_error('descriptioninvalid'); + } + + $upd_stmt = Database::prepare(" + UPDATE `" . 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, + `limit_extensions` = :limit_extensions + 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, + 'limit_extensions' => $limit_extensions, + '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/admin_plans.php b/admin_plans.php new file mode 100644 index 00000000..eaee22b2 --- /dev/null +++ b/admin_plans.php @@ -0,0 +1,522 @@ + (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'] + ); + } + } + + // 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 + 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'] + ); + } + } + + $result['imap'] = $result['email_imap']; + $result['pop3'] = $result['email_pop3']; + + // 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; + $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 + 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/admin_settings.php b/admin_settings.php index 18289d28..ac8ff85c 100644 --- a/admin_settings.php +++ b/admin_settings.php @@ -290,3 +290,107 @@ if ($page == 'overview' && $userinfo['change_serversettings'] == '1') { } eval("echo \"" . getTemplate("settings/integritycheck") . "\";"); } +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 { + $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') + { + $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'; + } else { + $testmail->SMTPAutoTLS = false; + } + $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/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_domains.php b/customer_domains.php index 06471cb8..a71c77b5 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'); } @@ -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; } @@ -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, @@ -415,6 +419,7 @@ if ($page == 'overview') { `wwwserveralias` = :wwwserveralias, `isemaildomain` = :isemaildomain, `iswildcarddomain` = :iswildcarddomain, + `phpenabled` = :phpenabled, `openbasedir` = :openbasedir, `openbasedir_path` = :openbasedir_path, `speciallogfile` = :speciallogfile, @@ -437,6 +442,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, @@ -517,7 +523,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) { @@ -527,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); @@ -564,6 +596,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) { @@ -571,9 +606,6 @@ if ($page == 'overview') { } else { $path = makeCorrectDir($userinfo['documentroot'] . '/' . $path); } - if (strstr($path, ":") !== FALSE) { - standard_error('pathmaynotcontaincolon'); - } } else { $_doredirect = true; } @@ -617,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 @@ -642,10 +681,15 @@ 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'); } + // 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) { @@ -685,6 +729,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']) . "'"); @@ -699,7 +744,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" ); @@ -715,6 +761,7 @@ if ($page == 'overview') { "hsts" => $hsts_maxage, "hsts_sub" => $hsts_sub, "hsts_preload" => $hsts_preload, + "phpsettingid" => $phpsettingid, "customerid" => $userinfo['customerid'], "id" => $id ); @@ -745,7 +792,7 @@ if ($page == 'overview') { inserttask('4'); } - + print_r($filename); redirectTo($filename, array('page' => $page, 's' => $s)); } } else { @@ -797,8 +844,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'; @@ -834,6 +886,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/customer_email.php b/customer_email.php index 31235f58..4f6aad05 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']) { @@ -164,7 +165,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; @@ -325,7 +326,7 @@ if ($page == 'overview') { $forwarders = ''; $forwarders_count = 0; - while (list($dest_id, $destination) = each($result['destination'])) { + foreach ($result['destination'] as $dest_id => $destination) { $destination = $idna_convert->decode($destination); if ($destination != $result['email_full'] && $destination != '') { @@ -680,7 +681,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, " : '') . " @@ -727,7 +728,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 @@ -862,7 +863,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 { @@ -923,7 +924,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)); 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 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/customer_logger.php b/customer_logger.php index 07e3f8e2..366b9735 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,37 +32,39 @@ 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::prepare($query); + Database::pexecute($result_cnt_stmt, array( + "loginname" => $userinfo['loginname'] + )); + $res_cnt = $result_cnt_stmt->fetch(PDO::FETCH_ASSOC); + $logs_count = $result_cnt_stmt->rowCount(); $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; @@ -72,51 +72,50 @@ if ($page == '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/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'])) { diff --git a/dns_editor.php b/dns_editor.php index 12daca2c..1114948b 100644 --- a/dns_editor.php +++ b/dns_editor.php @@ -56,13 +56,29 @@ 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 + * if ($type != 'SRV' && $type != 'TXT' && $type != "CNAME" ) { $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']; } @@ -112,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']; @@ -171,8 +190,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 .= '.'; } } 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/froxlor.sql b/install/froxlor.sql index b1962ab5..870e30d4 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', @@ -195,8 +195,10 @@ 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', + `allowed_phpconfigs` varchar(500) NOT NULL default '', PRIMARY KEY (`customerid`), UNIQUE KEY `loginname` (`loginname`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; @@ -237,6 +239,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', @@ -255,6 +258,9 @@ 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', + `http2` tinyint(1) DEFAULT '0', + `notryfiles` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `customerid` (`customerid`), KEY `parentdomain` (`parentdomainid`), @@ -280,7 +286,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; @@ -408,6 +415,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'), @@ -417,6 +425,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'), @@ -496,10 +600,11 @@ 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'), + ('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'), ('system', 'axfrservers', ''), @@ -527,6 +632,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'), @@ -544,8 +650,12 @@ 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'), + ('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', ''), @@ -577,8 +687,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.4'), - ('panel', 'db_version', '201611180'); + ('panel', 'version', '0.9.39.5'), + ('panel', 'db_version', '201802130'); DROP TABLE IF EXISTS `panel_tasks`; @@ -744,6 +854,33 @@ 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', + `limit_extensions` varchar(255) NOT NULL default '.php', + 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, @@ -757,14 +894,17 @@ 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', + `pass_authorizationheader` tinyint(1) NOT NULL default '0', + PRIMARY KEY (`id`), + KEY `fpmsettingid` (`fpmsettingid`) ) ENGINE=MyISAM CHARSET=utf8 COLLATE=utf8_general_ci; 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`; @@ -889,3 +1029,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/lib/class.FroxlorInstall.php b/install/lib/class.FroxlorInstall.php index 792e8202..128a7104 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,18 +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'], 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; } @@ -195,12 +206,12 @@ 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' + '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; @@ -223,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 @@ -234,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' - ); - $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_fail || $this->_abort) { // D'oh $navigation = ''; $msgcolor = 'red'; @@ -278,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 @@ -293,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)); @@ -325,7 +337,7 @@ class FroxlorInstall $escpduserdata = nl2br(htmlspecialchars($userdata)); eval("\$content .= \"" . $this->_getTemplate("textarea") . "\";"); } - + return $content; } @@ -339,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 @@ -355,7 +367,7 @@ class FroxlorInstall 'serverip' => $this->_data['serverip'] )); $defaultip = $db->lastInsertId(); - + // insert the defaultip $upd_stmt = $db->prepare(" UPDATE `" . TABLE_PANEL_SETTINGS . "` SET @@ -365,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( @@ -402,11 +414,11 @@ class FroxlorInstall `subdomains` = -1, `traffic` = -1048576 "); - + $ins_stmt->execute($ins_data); - + $content .= $this->_status_message('green', 'OK'); - + return $content; } @@ -437,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'); @@ -453,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'); @@ -473,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; } @@ -507,22 +519,28 @@ 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; 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); @@ -530,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; } @@ -551,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']); @@ -619,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; } @@ -637,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"; @@ -646,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")) { @@ -668,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); @@ -681,7 +708,7 @@ class FroxlorInstall $content .= $this->_status_message('red', $this->_lng['install']['backup_binary_missing']); } } - + return $content; } @@ -698,12 +725,12 @@ 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 eval("\$content .= \"" . $this->_getTemplate("lngform") . "\";"); - + // form-data $formdata = ""; /** @@ -743,7 +770,7 @@ class FroxlorInstall $style = ''; } $formdata .= $this->_getSectionItemString('mysql_root_pass', true, $style, 'password'); - + /** * admin data */ @@ -767,7 +794,7 @@ class FroxlorInstall $formdata .= $this->_getSectionItemString('admin_pass2', true, $style, 'password'); // activate newsfeed? $formdata .= $this->_getSectionItemYesNo('activate_newsfeed', true); - + /** * Server data */ @@ -781,7 +808,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 = ''; @@ -814,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, @@ -835,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') @@ -895,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']); @@ -926,85 +953,94 @@ 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 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"); @@ -1014,7 +1050,7 @@ class FroxlorInstall $content .= $this->_status_message('green', 'off'); } $content .= "
"; - + // check if we have unrecoverable errors $navigation = ''; if ($_die) { @@ -1029,7 +1065,7 @@ class FroxlorInstall $linktext = $this->_lng['click_here_to_continue']; } eval("\$navigation .= \"" . $this->_getTemplate("pagebottom") . "\";"); - + return array( 'pagecontent' => $content, 'pagenavigation' => $navigation @@ -1046,7 +1082,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()); @@ -1064,7 +1100,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'); @@ -1081,7 +1117,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']; @@ -1102,7 +1138,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 @@ -1116,7 +1152,7 @@ class FroxlorInstall * * @param string $template * name of the template including subdirectory - * + * * @return string */ private function _getTemplate($template = null) @@ -1133,7 +1169,7 @@ class FroxlorInstall } else { $templatefile = 'TEMPLATE NOT FOUND: ' . $filename; } - + return $templatefile; } @@ -1164,14 +1200,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'] = ''; } @@ -1204,7 +1239,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")) { @@ -1290,17 +1325,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 ++) { @@ -1308,12 +1343,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("/(? (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 index d8f098f9..b8fcbe4c --- 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/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}

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 c928f465..090fb936 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')) { @@ -3565,3 +3567,388 @@ if(isFroxlorVersion('0.9.37-greylist')) { Settings::AddNew("mail.greylist_disabled_default", "0"); updateToVersion('0.9.37-greylist2'); } + +if (isDatabaseVersion('201611180')) { + + 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); + + 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); + + showUpdateStep("Adding system setting for let's-encrypt registration status"); + Settings::AddNew('system.leregistered', '0'); + lastStepStatus(0); + + 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'); +} + +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'); +} + +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'); +} + +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'); +} + +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'); +} + +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'); +} + +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'); +} + +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'); +} + +if (isDatabaseVersion('201801080')) { + + showUpdateStep("Adding new setting for Let's Encrypt ACME version"); + Settings::AddNew('system.leapiversion', '1'); + lastStepStatus(0); + + 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'); +} + +if (isDatabaseVersion('201801091')) { + + showUpdateStep("Adding new setting for SSL protocols"); + Settings::AddNew('system.ssl_protocols', 'TLSv1,TLSv1.2'); + lastStepStatus(0); + + 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'); +} + +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'); +} + +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'); +} + +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'); +} + +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'); +} + +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'); +} + +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'); +} + +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/install/updates/preconfig/0.9/preconfig_0.9.inc.php b/install/updates/preconfig/0.9/preconfig_0.9.inc.php index a25b78fc..26b47282 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,22 @@ 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") . "\";"); + } + + 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 configurations.

'; + $question = 'Disable Let\'s Encrypt self-check?
'; + $question .= makeyesno('system_disable_le_selfcheck', '1', '0', '0') . '
'; + eval("\$return.=\"" . getTemplate("update/preconfigitem") . "\";"); + } + } } 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/ajax.php b/lib/ajax.php index 23370663..3b17e436 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 './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/bulk/class.DomainBulkAction.php b/lib/classes/bulk/class.DomainBulkAction.php index 9523c5a9..1331cec5 100644 --- a/lib/classes/bulk/class.DomainBulkAction.php +++ b/lib/classes/bulk/class.DomainBulkAction.php @@ -93,6 +93,13 @@ 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', +/* 25 */ 'http2', /* automatically added */ 'adminid', 'customerid', @@ -180,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, @@ -200,7 +208,14 @@ 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, + `http2` = :http2 "); // prepare insert statement for ip/port <> domain @@ -293,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( @@ -311,6 +327,7 @@ class DomainBulkAction // - we'd better skip return false; } + $hasAlias = $domain_data['aliasdomain']; } // check for use_ssl and ssl_redirect @@ -335,6 +352,38 @@ 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; + } + + 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']; @@ -416,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'); 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 @@ + '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/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); } diff --git a/lib/classes/dns/class.DnsEntry.php b/lib/classes/dns/class.DnsEntry.php index c5bcab79..a5685741 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; } } 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 { 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/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 */ 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/lib/classes/phpinterface/class.phpinterface_fpm.php b/lib/classes/phpinterface/class.phpinterface_fpm.php index 5c39d00b..8ec93b3e 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,38 @@ 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' - ) - ); + */ + private $_ini = array(); /** * main constructor - */ - public function __construct($domain) { + */ + 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']); + $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) + { + $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 +86,48 @@ 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']; + $fpm_limit_extensions = $this->_fpm_cfg['limit_extensions']; + 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 +143,40 @@ 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"; + $fpm_config .= 'security.limit_extensions = '.$fpm_limit_extensions . "\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"; - + + $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"; + $openbasedir = ''; if ($this->_domain['loginname'] != 'froxlor.panel') { if ($this->_domain['openbasedir'] == '1') { @@ -251,47 +185,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 +232,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 +254,138 @@ 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_dir']; + $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; } + /** + * 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/" . md5($configdir) . "-fpm.sock +pm = static +pm.max_children = 1 +"; + file_put_contents($config, $dummy); + } + /** * 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/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..ff04b18b 100644 --- a/lib/classes/phpmailer/class.PHPMailer.php +++ b/lib/classes/phpmailer/class.PHPMailer.php @@ -27,3883 +27,4003 @@ */ 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.26'; + + /** + * 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 + * 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. + * @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; + } + //Pick an appropriate debug output format automatically + $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html'); + } + + /** + * 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\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/', + trim($hostentry), + $hostinfo + )) { + // Not a valid host entry + $this->edebug('Ignoring invalid host: ' . $hostentry); + 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', + '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.', + '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 = ''; + + $result .= $this->headerLine('Date', $this->MessageDate == '' ? self::rfcDate() : $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. + * 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. + * @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. + * 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. + * @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. + * 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 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 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 + */ + public function msgHTML($message, $basedir = '', $advanced = false) + { + 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)) { + $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 + ); + } + 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); + // 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 +4032,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 = '' . 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 0c016f12..a3a67baa 100644 --- a/lib/classes/phpmailer/class.SMTP.php +++ b/lib/classes/phpmailer/class.SMTP.php @@ -26,1167 +26,1251 @@ */ 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.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.26'; + + /** + * 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 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 + */ + 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 gmdate('Y-m-d H:i:s') . ' ' . 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 + set_error_handler(array($this, 'errorHandler')); + $crypto_ok = stream_socket_enable_crypto( + $this->smtp_conn, + true, + $crypto_method + ); + restore_error_handler(); + return $crypto_ok; + } + + /** + * 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; 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); + $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. + * 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); + set_error_handler(array($this, 'errorHandler')); + $result = fwrite($this->smtp_conn, $data); + restore_error_handler(); + return $result; + } + + /** + * 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 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 + $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. + * @param string $errfile The file the error occurred in + * @param integer $errline The line number the error occurred on + */ + protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0) + { + $notice = 'Connection failed.'; + $this->setError( + $notice, + $errno, + $errmsg + ); + $this->edebug( + $notice . ' Error #' . $errno . ': ' . $errmsg . " [$errfile line $errline]", + self::DEBUG_CONNECTION + ); + } + + /** + * 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 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() + { + return $this->last_smtp_transaction_id; + } } diff --git a/lib/classes/settings/class.SImExporter.php b/lib/classes/settings/class.SImExporter.php new file mode 100644 index 00000000..428d8beb --- /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/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; } /** diff --git a/lib/classes/ssl/class.lescript.php b/lib/classes/ssl/class.lescript.php index dc8ec83b..cdc848f6 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; @@ -38,6 +37,12 @@ class lescript private $accountKey; + private $customerid; + + private $isFroxlorVhost; + + private $isLeProduction; + private $version; public function __construct($logger, $version = '1') @@ -57,44 +62,59 @@ 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 = (!$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('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)); } - $this->license = $this->client->getAgreementURL(); + $accountUrl=$this->client->getLastLocation(); - // Terms of Servce 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)); - } - $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 +156,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)) { @@ -188,17 +214,18 @@ 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') + { + $selfcheckpayload = HttpClient::urlGet($uri); + if ($payload !== trim($selfcheckpayload)) { + $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); } - @unlink($tokenPath); - $this->logger->logAction(CRON_ACTION, LOG_ERR, "letsencrypt Please check $uri - token not available" . $errmsg); } $this->log("Sending request to challenge"); @@ -309,6 +336,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"); @@ -317,21 +359,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'] )); } @@ -536,13 +573,6 @@ class Client preg_match_all('~Link: <(.+)>;rel="up"~', $this->lastHeader, $matches); return $matches[1]; } - - public function getAgreementURL() - { - preg_match_all('~Link: <(.+)>;rel="terms-of-service"~', $this->lastHeader, $matches); - return $matches[1][0]; - } - } 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..448222eb --- /dev/null +++ b/lib/classes/ssl/class.lescript_v2.php @@ -0,0 +1,594 @@ + +// 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') { + $selfcheckpayload = HttpClient::urlGet($uri); + if ($payload !== trim($selfcheckpayload)) { + $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/lib/classes/webserver/class.ConfigIO.php b/lib/classes/webserver/class.ConfigIO.php index cbe79b10..14e95085 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 -f ' . 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 -f ' . 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 -f ' . 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 /*.conf so we don't delete the directory) + $configdir .= '/*.conf'; + safe_exec('rm -f ' . 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 d67b9868..f16073c8 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,27 +26,45 @@ 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`, - `c`.`phpenabled` AS `phpenabled`, `d`.`mod_fcgid_starter`, - `d`.`mod_fcgid_maxrequests` - FROM `".TABLE_PANEL_DOMAINS."` `d` + `c`.`phpenabled` AS `phpenabled_customer`, + `d`.`phpenabled` AS `phpenabled_vhost`, + `d`.`mod_fcgid_starter`,`d`.`mod_fcgid_maxrequests`, + `d`.`ocsp_stapling` + 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); - + + // 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)) { - + // set whole domain $domains[$domain['domain']] = $domain; // set empty-defaults for non-ssl @@ -55,31 +73,38 @@ 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` - 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_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; + } } } - + return $domains; } - } diff --git a/lib/configfiles/gentoo.xml b/lib/configfiles/gentoo.xml index 69b4dd8d..7b68d374 100644 --- a/lib/configfiles/gentoo.xml +++ b/lib/configfiles/gentoo.xml @@ -353,7 +353,7 @@ 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. @@ -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. @@ -3420,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 99322e4b..10ee0a2f 100644 --- a/lib/configfiles/jessie.xml +++ b/lib/configfiles/jessie.xml @@ -365,7 +365,7 @@ exit "$RETVAL" - + > /etc/bind/named.conf.local]]> @@ -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. @@ -3812,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 +]]> + + + + + @@ -4467,9 +4476,9 @@ PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin @@ -4632,6 +4641,42 @@ aliases: files + + + + + + + + + + + + + + + diff --git a/lib/configfiles/precise.xml b/lib/configfiles/precise.xml index 512415a4..9983959d 100644 --- a/lib/configfiles/precise.xml +++ b/lib/configfiles/precise.xml @@ -334,7 +334,7 @@ exit "$RETVAL" - + > /etc/bind/named.conf]]> @@ -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 @@ -1141,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 +]]> + + + + + @@ -1622,6 +1631,42 @@ netmasks: files netgroup: files bootparams: files +automount: files +aliases: files +]]> + + + + + + + + + + + + + + + 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 diff --git a/lib/configfiles/stretch.xml b/lib/configfiles/stretch.xml new file mode 100644 index 00000000..7d9eab6b --- /dev/null +++ b/lib/configfiles/stretch.xml @@ -0,0 +1,4657 @@ + + + + + + + + + + + {{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 = + } +} +]]> + + + + +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 = + + + + . %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] + + + + + + + + + + " +[ -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 +]]> + + + + + + + + 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/lib/configfiles/trusty.xml b/lib/configfiles/trusty.xml index ba8bdc3f..2df05eeb 100644 --- a/lib/configfiles/trusty.xml +++ b/lib/configfiles/trusty.xml @@ -367,7 +367,7 @@ exit "$RETVAL" - + > /etc/bind/named.conf]]> @@ -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 @@ -1149,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 +]]> + + + + + @@ -1639,6 +1649,42 @@ aliases: files + + + + + + + + + + + + + + + diff --git a/lib/configfiles/wheezy.xml b/lib/configfiles/wheezy.xml index 9d1d5c21..55ba59d4 100644 --- a/lib/configfiles/wheezy.xml +++ b/lib/configfiles/wheezy.xml @@ -1,6 +1,6 @@ - + @@ -407,7 +407,7 @@ exit "$RETVAL" - + > /etc/bind/named.conf.local]]> @@ -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 @@ -4714,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 +]]> + + + + + @@ -5431,6 +5440,42 @@ netmasks: files netgroup: files bootparams: files +automount: files +aliases: files +]]> + + + + + + + + + + + + + + + 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'); diff --git a/lib/formfields/admin/customer/formfield.customer_add.php b/lib/formfields/admin/customer/formfield.customer_add.php index eaa408aa..bba95e12 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,12 +149,27 @@ 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() ) ) ), + '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', @@ -206,18 +235,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 +283,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..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', @@ -260,6 +272,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', diff --git a/lib/formfields/admin/domains/formfield.domains_add.php b/lib/formfields/admin/domains/formfield.domains_add.php index 1f92f599..a18018b7 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() ), @@ -124,6 +131,19 @@ return array( 'type' => 'textarea', 'cols' => 60, 'rows' => 12 + ), + 'notryfiles' => array( + 'visible' => (Settings::Get('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() ) ) ), @@ -146,7 +166,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 +179,23 @@ 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() + ), + 'http2' => array( + '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', + 'values' => array( + array ( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) ), 'value' => array() ), @@ -181,7 +220,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,11 +233,31 @@ 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() ), - ), + '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( 'title' => $lng['admin']['phpserversettings'], @@ -206,23 +268,41 @@ return 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' ) @@ -237,9 +317,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', @@ -256,15 +341,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() ), @@ -278,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('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 cff9b974..5e791da7 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,29 @@ 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' + ) + ), + 'notryfiles' => array( + 'visible' => (Settings::Get('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'] + ) ) ) ), @@ -169,9 +198,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 +213,29 @@ 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'] + ) + ), + 'http2' => array( + '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', + 'values' => array( + array ( + 'label' => $lng['panel']['yes'], + 'value' => '1' + ) + ), + 'value' => array( + $result['http2'] + ) ), 'no_ssl_available_info' => array( 'visible' => ($ssl_ipsandports == '' ? true : false), @@ -204,9 +258,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,9 +273,33 @@ 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'] + ) + ), + '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'] + ) ), ) ), @@ -229,27 +312,60 @@ return 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 ), + '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), + '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'] : '') ) ) ), @@ -262,9 +378,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', @@ -282,17 +403,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'], @@ -304,9 +435,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'] + ) ) ) ) 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..d5e86de2 --- /dev/null +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_add.php @@ -0,0 +1,95 @@ + (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 + ), + 'limit_extensions' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['description'], + 'type' => 'text', + 'value' => '.php' + ) + ) + ) + ) + ) +); 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..74593812 --- /dev/null +++ b/lib/formfields/admin/phpconfig/formfield.fpmconfig_edit.php @@ -0,0 +1,96 @@ + (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' => $pm_select + ), + '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'] + ), + 'limit_extensions' => array( + 'label' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['title'], + 'desc' => $lng['serversettings']['phpfpm_settings']['limit_extensions']['description'], + 'type' => 'text', + 'value' => $result['limit_extensions'] + ) + ) + ) + ) + ) +); diff --git a/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php b/lib/formfields/admin/phpconfig/formfield.phpconfig_add.php index 3bcc4922..6d30adfd 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'], @@ -84,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 d3a9828f..e2e8fd11 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'], @@ -87,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/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/formfields/customer/domains/formfield.domains_add.php b/lib/formfields/customer/domains/formfield.domains_add.php index 1371e579..ad660098 100644 --- a/lib/formfields/customer/domains/formfield.domains_add.php +++ b/lib/formfields/customer/domains/formfield.domains_add.php @@ -70,16 +70,21 @@ 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 ) ) ), '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 +94,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 +104,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 +112,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 +121,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..31910123 100644 --- a/lib/formfields/customer/domains/formfield.domains_edit.php +++ b/lib/formfields/customer/domains/formfield.domains_edit.php @@ -81,16 +81,21 @@ 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 ) ) ), '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 +105,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 +115,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 +123,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 +132,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', diff --git a/lib/functions/dns/function.createDomainZone.php b/lib/functions/dns/function.createDomainZone.php index c1384537..36ffb292 100644 --- a/lib/functions/dns/function.createDomainZone.php +++ b/lib/functions/dns/function.createDomainZone.php @@ -292,7 +292,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); 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") { 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 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; 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/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/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/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/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; +} diff --git a/lib/init.php b/lib/init.php index b4e4c018..3dc69df7 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); @@ -563,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/lib/navigation/00.froxlor.main.php b/lib/navigation/00.froxlor.main.php index faa3feec..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'], @@ -279,6 +284,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'], @@ -313,6 +324,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/lib/tables.inc.php b/lib/tables.inc.php index 39b37e24..207612f0 100644 --- a/lib/tables.inc.php +++ b/lib/tables.inc.php @@ -51,5 +51,7 @@ 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'); +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 6e9c41fb..49935fb7 100644 --- a/lib/version.inc.php +++ b/lib/version.inc.php @@ -16,10 +16,10 @@ */ // Main version variable -$version = '0.9.38.4'; +$version = '0.9.39.5'; // Database version (YYYYMMDDC where C is a daily counter) -$dbversion = '201611180'; +$dbversion = '201802130'; // Distribution branding-tag (used for Debian etc.) $branding = ''; 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 256ebf04..c3ea6f0b 100644 --- a/lng/english.lng.php +++ b/lng/english.lng.php @@ -538,7 +538,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'; @@ -944,6 +944,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.'; @@ -1005,6 +1006,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)'; @@ -1106,7 +1108,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'; @@ -1297,7 +1299,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'; @@ -1660,7 +1662,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'; @@ -1830,7 +1832,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'; @@ -1844,16 +1846,16 @@ $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'; $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 "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)'; @@ -1942,7 +1944,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"; @@ -1976,7 +1978,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."; @@ -2042,8 +2044,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'; @@ -2065,7 +2067,57 @@ $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+)'; +$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'; + +// 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.'; +$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'; +$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)'; +$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."; +$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
    '; +$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'; +$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'; +$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'; +$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/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'; diff --git a/lng/german.lng.php b/lng/german.lng.php index 9462bd4e..2515d1d6 100644 --- a/lng/german.lng.php +++ b/lng/german.lng.php @@ -534,7 +534,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'; @@ -939,6 +939,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'; @@ -1002,6 +1003,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)'; @@ -1080,7 +1082,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'; @@ -1276,7 +1278,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'; @@ -1388,7 +1390,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'; @@ -1556,7 +1558,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'; @@ -1570,16 +1572,16 @@ $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'; $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 "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)'; @@ -1596,7 +1598,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"; @@ -1717,4 +1719,56 @@ $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.'; + +$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'; + +// 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.'; +$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'; +$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)'; +$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."; +$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
    '; +$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'; +$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'; +$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/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'; 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"; diff --git a/scripts/classes/class.Extrausers.php b/scripts/classes/class.Extrausers.php new file mode 100644 index 00000000..2ad38b73 --- /dev/null +++ b/scripts/classes/class.Extrausers.php @@ -0,0 +1,83 @@ + (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, login_enabled FROM ftp_users 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); + + // 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) + { + $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': + 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': + $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..a6d0d817 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,22 @@ 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 passwd 1> /dev/null', $false_val, array('>')); + safe_exec('nscd -i group 1> /dev/null', $false_val, array('>')); + } + } } fwrite($debugHandler, 'Cronfiles have been included' . "\n"); diff --git a/scripts/jobs/cron_letsencrypt.php b/scripts/jobs/cron_letsencrypt.php index 2101fcca..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')) { @@ -43,6 +49,7 @@ $certificates_stmt = Database::query(" dom.`ssl_redirect`, cust.`leprivatekey`, cust.`lepublickey`, + cust.`leregistered`, cust.`customerid`, cust.`loginname` FROM @@ -103,6 +110,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, diff --git a/scripts/jobs/cron_letsencrypt_v2.php b/scripts/jobs/cron_letsencrypt_v2.php new file mode 100644 index 00000000..6b1148d3 --- /dev/null +++ b/scripts/jobs/cron_letsencrypt_v2.php @@ -0,0 +1,294 @@ + + * @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 dom.`iswildcarddomain` = 0 + 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 + AND dom.`iswildcarddomain` = 0 + "); + +$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"); 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(); diff --git a/scripts/jobs/cron_tasks.inc.http.10.apache.php b/scripts/jobs/cron_tasks.inc.http.10.apache.php index b6a9697a..2a7ab516 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,22 @@ 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, 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'])); + } } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'apache::reload: reloading apache'); safe_exec(escapeshellcmd(Settings::Get('system.apachereload_command'))); @@ -77,35 +91,37 @@ class apache extends HttpConfigBase $vhosts_folder = makeCorrectDir(dirname(Settings::Get('system.apacheconf_vhost'))); } $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)); - } + + 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 { - 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"; + // >=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 { - // >=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] .= ' 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 ' . 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)); } - $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; } } @@ -121,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', @@ -151,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') { @@ -180,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') { @@ -207,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"; @@ -226,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') { @@ -242,7 +258,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', @@ -250,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"; @@ -277,8 +293,16 @@ class apache extends HttpConfigBase } $this->virtualhosts_data[$vhosts_filename] .= ' ' . "\n"; } - } - elseif (Settings::Get('phpfpm.enabled') == '1') { + } 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', @@ -290,26 +314,51 @@ 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); $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"; + $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] .= ' 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 ' . $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"; @@ -344,7 +393,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 * @@ -353,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'), @@ -391,34 +448,40 @@ 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"; + $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"; + } + $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"; $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'])) { @@ -427,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'])) { @@ -436,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 @@ -456,7 +519,7 @@ class apache extends HttpConfigBase $close_vhost = false; } } - + if ($close_vhost) { $this->virtualhosts_data[$vhosts_filename] .= '' . "\n"; } @@ -464,12 +527,12 @@ class apache extends HttpConfigBase } unset($vhosts_filename); } - + /** * bug #32 */ $this->_createStandardDirectoryEntry(); - + /** * bug #unknown-yet */ @@ -487,29 +550,31 @@ class apache extends HttpConfigBase protected function composePhpOptions($domain, $ssl_vhost = false) { $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 - + $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 @@ -519,7 +584,7 @@ class apache extends HttpConfigBase $php_options_text .= ' AssignUserID ' . $domain['loginname'] . ' ' . $domain['loginname'] . "\n"; $php_options_text .= ' ' . "\n"; } - + return $php_options_text; } @@ -532,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 . "` @@ -552,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 { @@ -563,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; } @@ -579,16 +644,26 @@ 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"; + $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"; $this->_deactivated = false; } - + return $webroot_text; } @@ -598,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') { @@ -624,7 +699,7 @@ class apache extends HttpConfigBase $stats_text .= ' Alias /awstats-icon "' . makeCorrectDir(Settings::Get('system.awstats_icons')) . '"' . "\n"; } } - + return $stats_text; } @@ -634,7 +709,7 @@ class apache extends HttpConfigBase protected function getLogfiles($domain) { $logfiles_text = ''; - + if ($domain['speciallogfile'] == '1') { if ($domain['parentdomainid'] == '0') { $speciallogfile = '-' . $domain['domain']; @@ -644,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 @@ -673,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 @@ -699,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; } @@ -716,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; } @@ -734,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']; @@ -763,29 +838,30 @@ 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, // but if there is a destination-port != 443 @@ -803,52 +879,63 @@ class apache extends HttpConfigBase $ssldestport = Database::pexecute_first($ssldestport_stmt, array( 'domainid' => $domain['id'] )); - + if ($ssldestport['port'] != '') { $_sslport = ":" . $ssldestport['port']; } - - $domain['documentroot'] = 'https://' . $domain['domain'] . $_sslport . '/'; + + $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"; + $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') { + $vhost_content .= ' Protocols h2 http/1.1' . "\n"; + } + $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"; $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']; @@ -868,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"; @@ -894,10 +981,10 @@ 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 { - + mkDirWithCorrectOwnership($domain['customerroot'], $domain['documentroot'], $domain['guid'], $domain['guid'], true, true); $vhost_content .= $this->getWebroot($domain); if ($this->_deactivated == false) { @@ -905,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; } @@ -931,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); @@ -966,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']; @@ -994,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"; @@ -1020,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"; @@ -1032,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', @@ -1049,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"; @@ -1067,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'); @@ -1094,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)); @@ -1105,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"; } } @@ -1135,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'); @@ -1158,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'); @@ -1171,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(); @@ -1182,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) { @@ -1195,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'); @@ -1233,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.15.apache_fcgid.php b/scripts/jobs/cron_tasks.inc.http.15.apache_fcgid.php index 6e569d8f..acf49948 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']); @@ -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['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 proxy:unix:' . $php->getInterface()->getSocketFile() . '|fcgi://localhost'. "\n"; $php_options_text.= ' ' . "\n"; @@ -54,15 +62,35 @@ 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 ' . $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"; @@ -155,6 +183,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 +205,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 diff --git a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php index a1869a42..99232c8c 100644 --- a/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php +++ b/scripts/jobs/cron_tasks.inc.http.20.lighttpd.php @@ -58,8 +58,22 @@ 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, 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'])); + } } $this->logger->logAction(CRON_ACTION, LOG_INFO, 'lighttpd::reload: reloading lighttpd'); safe_exec(escapeshellcmd(Settings::Get('system.apachereload_command'))); @@ -162,7 +176,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'] != '') { @@ -424,7 +456,7 @@ class lighttpd extends HttpConfigBase $_sslport = ":" . $ssldestport['port']; } - $domain['documentroot'] = 'https://' . $domain['domain'] . $_sslport . '/'; + $domain['documentroot'] = 'https://%1' . $_sslport . '/'; } // avoid using any whitespaces @@ -517,7 +549,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"; 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 a99f41bf..7f86f605 100644 --- a/scripts/jobs/cron_tasks.inc.http.30.nginx.php +++ b/scripts/jobs/cron_tasks.inc.http.30.nginx.php @@ -73,8 +73,22 @@ 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, 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'])); + } } } @@ -196,7 +210,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 +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 && Settings::Get('system.nginx_http2_support') == '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"; } @@ -447,7 +461,7 @@ class nginx extends HttpConfigBase $_sslport = ":" . $ssldestport['port']; } - $domain['documentroot'] = 'https://' . $domain['domain'] . $_sslport . '/'; + $domain['documentroot'] = 'https://$host' . $_sslport . '/'; } // avoid using any whitespaces @@ -609,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"; @@ -634,6 +648,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"; + } } } @@ -711,6 +733,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"; @@ -768,6 +795,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"; @@ -846,7 +878,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"; @@ -882,9 +914,11 @@ 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"; + if ($domain['notryfiles'] != 1) { + $webroot_text .= "\t\t" . 'try_files $uri $uri/ @rewrites;' . "\n"; + } } else { $webroot_text .= "\t" . 'index index.html index.htm;' . "\n"; } @@ -895,7 +929,7 @@ class nginx extends HttpConfigBase } $webroot_text .= "\t" . '}' . "\n\n"; - if ($domain['phpenabled'] == '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"; 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']); diff --git a/scripts/jobs/cron_tasks.php b/scripts/jobs/cron_tasks.php index dd7a754f..b7176a53 100644 --- a/scripts/jobs/cron_tasks.php +++ b/scripts/jobs/cron_tasks.php @@ -168,9 +168,17 @@ 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; + safe_exec('nscd -i passwd 1> /dev/null', $false_val, array('>')); safe_exec('nscd -i group 1> /dev/null', $false_val, array('>')); } } 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 { 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'); } diff --git a/ssl_certificates.php b/ssl_certificates.php index 5a8547d7..875b903e 100644 --- a/ssl_certificates.php +++ b/ssl_certificates.php @@ -23,14 +23,38 @@ 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); + $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 + 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'] + )); + } 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 + )); + $success_message = sprintf($lng['domains']['ssl_certificate_removed'], $id); + } } } @@ -72,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) . "\";"); @@ -127,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 . "
    "; } } } diff --git a/templates/Sparkle/admin/configfiles/configfiles.tpl b/templates/Sparkle/admin/configfiles/configfiles.tpl index f35b4051..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']}
    - -

    - MYSQL_PASSWORD: + FROXLOR_MYSQL_PASSWORD:
    +

    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/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/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']} 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']} diff --git a/templates/Sparkle/admin/plans/plans.tpl b/templates/Sparkle/admin/plans/plans.tpl new file mode 100644 index 00000000..ed9c4432 --- /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['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/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']}]

    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 diff --git a/templates/Sparkle/assets/js/customers.js b/templates/Sparkle/assets/js/customers.js new file mode 100644 index 00000000..7863f345 --- /dev/null +++ b/templates/Sparkle/assets/js/customers.js @@ -0,0 +1,75 @@ +$(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+"']").prop('checked', true); + } else { + $("input[name='"+i+"']").prop('checked', false); + } + } else if (i == 'allowed_phpconfigs') { + /** handle array of values **/ + $("input[name='allowed_phpconfigs[]']").each(function(index) { + $(this).prop('checked', false); + for (j in json[i]) { + if ($(this).val() == json[i][j]) { + $(this).prop('checked', true); + break; + } + } + }); + } 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']").prop('checked', false); + } + } + }, + error: function(a, b) { + console.log(a, b); + } + }); + } + }); + +}); 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); + } + }); + }); + +}); 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); 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 @@