pax_global_header 0000666 0000000 0000000 00000000064 13522573065 0014522 g ustar 00root root 0000000 0000000 52 comment=3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe
ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/ 0000775 0000000 0000000 00000000000 13522573065 0023674 5 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/ispc3-ai.sh 0000775 0000000 0000000 00000002576 13522573065 0025655 0 ustar 00root root 0000000 0000000 #!/bin/bash
CURDIR=$(pwd) ;
BASEDIR=$(dirname $0) ;
BASEDIR=$(realpath ${BASEDIR}) ;
CURL=$(which curl) ;
WGET=$(which wget) ;
PHP=$(which php) ;
if [ "$CURL" = "" ] ; then
if [ "$WGET" = "" ] ; then
echo "Curl and Wget missing, trying to install." ;
apt-get update -qq && apt-get -y -qq install wget ;
WGET=$(which wget) ;
fi
if [ "$WGET" = "" ] ; then
echo "Wget and curl are missing. Please install either wget or curl package." ;
exit 1 ;
fi
fi
if [ "$PHP" = "" ] ; then
echo "PHP cli missing, trying to install." ;
apt-get update -qq && apt-get -y -qq install php-cli ;
PHP=$(which php) ;
fi
if [ "$PHP" = "" ] ; then
echo "PHP cli is missing. Please install package php-cli." ;
exit 1;
fi
if [ "$CURL" != "" ] ; then
$CURL -s -o /tmp/ispconfig-ai.tar.gz "https://www.ispconfig.org/downloads/ispconfig-ai.tar.gz" >/dev/null 2>&1
else
$WGET -q -O /tmp/ispconfig-ai.tar.gz "https://www.ispconfig.org/downloads/ispconfig-ai.tar.gz" >/dev/null 2>&1
fi
if [ ! -f "/tmp/ispconfig-ai.tar.gz" ] ; then
echo "Failed downloading Autoinstaller" ;
exit 1;
fi
rm -rf /tmp/ispconfig-ai ;
mkdir /tmp/ispconfig-ai ;
tar -C /tmp/ispconfig-ai/ -xzf /tmp/ispconfig-ai.tar.gz || (echo "Failed extracting Autoinstaller" ; exit 1)
rm -f /tmp/ispconfig-ai.tar.gz ;
cd /tmp/ispconfig-ai ;
${PHP} -q ${BASEDIR}/ispconfig.ai.php $@ && exit 0 || exit 1;
cd ${CURDIR} ;
rm -rf /tmp/ispconfig-ai ; ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/ispconfig.ai.php 0000664 0000000 0000000 00000000761 13522573065 0026762 0 ustar 00root root 0000000 0000000 ' . $e->getMessage(), true);
//var_dump($e);
exit;
} ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/ 0000775 0000000 0000000 00000000000 13522573065 0024442 5 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/class.ISPConfig.inc.php 0000664 0000000 0000000 00000007117 13522573065 0030616 0 ustar 00root root 0000000 0000000 LIB_DIR . '/libbashcolor.inc.php'
);
private static function init() {
if(php_sapi_name() == 'cli') {
self::$is_cli_run = true;
$argc = 0;
$argv = array();
if(isset($_SERVER['argc'])) {
$argc = $_SERVER['argc'];
}
if(isset($_SERVER['argv'])) {
$argv = $_SERVER['argv'];
}
if(isset($argv[0])) {
self::$cli_script = basename($argv[0]);
}
for($a = 1; $a < $argc; $a++) {
if(substr($argv[$a], 0, 2) == '--') {
$sArg = substr($argv[$a], 2);
if(strpos($sArg, '=') !== false) {
list($sKey, $sValue) = explode('=', $sArg);
} else {
$sKey = $sArg;
$sValue = true;
}
$_GET[$sKey] = $sValue;
}
}
}
}
/**
* @param string $class_name
* @throws ISPConfigClassException
*/
public static function autoload($class_name) {
if(preg_match('/^\w+$/', $class_name) === false) {
throw new ISPConfigClassException($class_name . ' is not a valid class name.');
}
$class_dir = LIB_DIR;
if(preg_match('/Exception$/', $class_name)) {
$class_dir .= '/exceptions';
} elseif(preg_match('/Module$/', $class_name)) {
$class_dir .= '/modules';
} elseif(preg_match('/API$/', $class_name)) {
$class_dir .= '/api';
} elseif(preg_match('/OS$/', $class_name)) {
$class_dir .= '/os';
}
$use_file = null;
if(isset(self::$autoload_files[$class_name])) {
$use_file = self::$autoload_files[$class_name];
} elseif(file_exists($class_dir . '/class.' . $class_name . '.inc.php')) {
$use_file = $class_dir . '/class.' . $class_name . '.inc.php';
} elseif(file_exists($class_dir . '/class.' . strtolower($class_name) . '.inc.php')) {
$use_file = $class_dir . '/class.' . strtolower($class_name) . '.inc.php';
} elseif(preg_match('/^ISPConfig\w+Exception$/', $class_name)) {
$use_file = LIB_DIR . '/exceptions/class.ISPConfigException.inc.php';
} else {
throw new ISPConfigClassException('No class file for ' . $class_name . ' found.');
}
if($class_name != 'ISPConfigLog') {
ISPConfigLog::debug('Trying to autoload class file "' . $use_file . '" for class "' . $class_name . '"');
}
if(!file_exists($use_file)) {
throw new ISPConfigClassException('File ' . $use_file . ' not found for class ' . $class_name . '.');
}
include_once $use_file;
if(!class_exists($class_name)) {
throw new ISPConfigClassException($class_name . ' not found in file ' . LIB_DIR . '/class.' . $class_name . '.inc.php.');
}
}
/**
* @return boolean
*/
public static function isCLI() {
return self::$is_cli_run;
}
/**
* @return string
*/
public static function getScriptName() {
return self::$cli_script;
}
/**
* @throws ISPConfigModuleException
*/
public static function run() {
self::init();
if(isset($_GET['debug']) && $_GET['debug']) {
ISPConfigLog::setLogPriority(ISPConfigLog::PRIO_DEBUG);
}
// get operating system
try {
$os = ISPConfigBaseOS::getOSVersion();
ISPConfigLog::info('Starting perfect server setup for ' . $os['NAME'], true);
$installer = ISPConfigBaseOS::getOSInstance();
$installer->runPerfectSetup();
ISPConfigLog::warn('Please delete the log files in var/log/setup-* once you don\'t need them anymore because they contain your passwords!', true);
} catch(Exception $ex) {
throw $ex;
}
exit;
}
}
class.ISPConfigConnector.inc.php 0000664 0000000 0000000 00000012253 13522573065 0032407 0 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib query_one($qrystr, $username);
if(!$client) {
return false;
} else {
return $client['client_id'];
}
}
public static function generateKeyPair() {
if(!@is_dir(TMP_DIR)) {
if(!@mkdir(TMP_DIR, 0777, true)) {
throw new ISPConfigLogException('Temp path ' . TMP_DIR . ' could not be created.');
}
}
if(!function_exists('openssl_pkey_get_private')) {
throw new ISPConfigException('OpenSSL extension missing. Cannot generate keys.');
}
$program = explode("\n", shell_exec('which ssh-keygen'));
$program = reset($program);
if(!$program || !is_executable($program)) {
throw new ISPConfigException('Could not generate key pair. Missing ssh-keygen.');
}
$trys = 0;
while(true) {
$trys++;
$file_name = TMP_DIR . '/' . sha1(uniqid('ssh-', true));
if(file_exists($file_name)) {
if($trys < 25) {
continue;
}
throw new ISPConfigException('Could not generate key pair unique file name.');
}
break;
}
$out = null;
$retval = 0;
exec('echo | ' . $program . ' -b 4096 -t rsa -f ' . escapeshellarg($file_name) . ' -q -N "" >/dev/null 2>&1', $out, $retval);
if($retval != 0) {
throw new ISPConfigException('Could not generate key pair. ssh-keygen returned non-zero code: ' . $retval);
} elseif(!file_exists($file_name) || !file_exists($file_name . '.pub')) {
throw new ISPConfigException('Could not generate key pair. Key files missing.');
}
$fprint = trim(shell_exec($program . ' -E md5 -lf ' . escapeshellarg($file_name . '.pub') . ' | awk \'{print $2}\''));
if(substr($fprint, 0, 4) === 'MD5:') {
$fprint = substr($fprint, 4);
}
$key = array(
'private' => trim(file_get_contents($file_name)),
'public' => trim(file_get_contents($file_name . '.pub')),
'fingerprint' => $fprint
);
if(!$key['private']) {
throw new ISPConfigException('Could not read private key.');
}
$res = openssl_pkey_get_private($key['private']);
if(!$res) {
throw new ISPConfigException('Could not verify private key.');
}
openssl_pkey_free($res);
if(!$key['public']) {
throw new ISPConfigException('Could not read public key.');
}
unlink($file_name);
unlink($file_name . '.pub');
return $key;
}
} ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/class.ISPConfigDatabase.inc.php0000664 0000000 0000000 00000057352 13522573065 0032251 0 ustar 00root root 0000000 0000000 sHost = $sHost;
$this->sUserName = $sUser;
$this->sPassword = $sPassword;
$this->sDataBase = $dbname;
$this->sPort = intval($sPort);
if(!isset($this->sPort) || !$this->sPort) {
$this->sPort = 3306;
}
$this->_iReconnects = $iReconnects;
if(!$this->_connect()) {
throw new ISPConfigDatabaseException('Could not establish database connection to ' . $sHost . ':' . $this->sPort . ' (' . $dbname . ') with user ' . $sUser . ' and pw *****.');
}
}
/** #@+
* @access private
*/
public function __destruct() {
$this->close();
}
private function _start_timer() {
$iStart = microtime();
list($iBegs, $iBegm) = explode(' ', $iStart);
$this->_iStartTime = $iBegs + $iBegm;
}
private function _end_timer() {
$iEnd = microtime();
list($iBegs, $iBegm) = explode(' ', $iEnd);
$this->_iEndTime = $iBegs + $iBegm;
return $this->_iEndTime - $this->_iStartTime;
}
//Database-Connect
//Datenbank-Verbindung aufbauen
private function _connect() {
if($this->_iReadId) {
return true;
}
$this->_iReadId = mysqli_connect($this->sHost, $this->sUserName, $this->sPassword, '', $this->sPort);
$try = 0;
while((!is_object($this->_iReadId) || mysqli_connect_error()) && ($try <= $this->_iReconnects || $this->_iReconnects === true)) {
if($try > 0) {
sleep(1);
}
$try++;
$this->_iReadId = mysqli_connect($this->sHost, $this->sUserName, $this->sPassword, '', $this->sPort);
}
if(!is_object($this->_iReadId)) {
$this->_sqlerror('Zugriff auf Datenbankserver fehlgeschlagen! / Database server not accessible!');
return false;
}
if($this->sDataBase) {
if(!((bool) mysqli_query($this->_iReadId, 'USE `' . $this->sDataBase . '`'))) {
$this->close();
$this->_sqlerror('Datenbank nicht gefunden / Database not found');
return false;
}
}
// Wenn eine separate Verbindung für schreibende Zugriffe gewünscht ist, neue kreieren
// sonst Verweis auf bestehende read Verbindung
if($this->_bSeparate == true) {
$this->_iWriteId = mysqli_connect($this->sHost, $this->sUserName, $this->sPassword, '', $this->sPort);
while((!is_object($this->_iWriteId) || mysqli_connect_error()) && ($try <= $this->_iReconnects || $this->_iReconnects === true)) {
if($try > 0) {
sleep(1);
}
$try++;
$this->_iWriteId = mysqli_connect($this->sHost, $this->sUserName, $this->sPassword, '', $this->sPort);
}
if(!is_object($this->_iWriteId)) {
$this->_sqlerror('Zugriff auf Datenbankserver fehlgeschlagen! / Database server not accessible!', true);
return false;
}
if($this->sDataBase) {
if(!((bool) mysqli_query($this->_iWriteId, 'USE `' . $this->sDataBase . '`'))) {
$this->close();
$this->_sqlerror('Datenbank nicht gefunden / Database not found', true);
return false;
}
}
} else {
$this->_iWriteId = & $this->_iReadId;
}
$this->_setCharset();
return true;
}
public function close() {
if(is_object($this->_iReadId)) {
mysqli_close($this->_iReadId);
}
if($this->_bSeparate == true && is_object($this->_iWriteId)) {
mysqli_close($this->_iWriteId);
}
$this->_iReadId = null;
$this->_iWriteId = null;
}
public function _build_query_string($sQuery = '') {
$iArgs = func_num_args();
if($iArgs > 1) {
$aArgs = func_get_args();
if($iArgs == 3 && $aArgs[1] === true && is_array($aArgs[2])) {
$aArgs = $aArgs[2];
$iArgs = count($aArgs);
} else {
array_shift($aArgs); // delete the query string that is the first arg!
}
$iPos = 0;
$iPos2 = 0;
foreach($aArgs as $sValue) {
$iPos2 = strpos($sQuery, '??', $iPos2);
$iPos = strpos($sQuery, '?', $iPos);
if($iPos === false && $iPos2 === false) {
break;
}
if($iPos2 !== false && ($iPos === false || $iPos2 <= $iPos)) {
$sTxt = $this->escape($sValue);
if(strpos($sTxt, '.') !== false) {
$sTxt = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $sTxt);
$sTxt = str_replace('.`*`', '.*', $sTxt);
} else {
$sTxt = '`' . $sTxt . '`';
}
$sQuery = substr_replace($sQuery, $sTxt, $iPos2, 2);
$iPos2 += strlen($sTxt);
$iPos = $iPos2;
} else {
if(is_int($sValue) || is_float($sValue)) {
$sTxt = $sValue;
} elseif(is_null($sValue) || (is_string($sValue) && (strcmp($sValue, '#NULL#') == 0))) {
$sTxt = 'NULL';
} elseif(is_array($sValue)) {
if(isset($sValue['SQL'])) {
$sTxt = $sValue['SQL'];
} else {
$sTxt = '';
foreach($sValue as $sVal) {
$sTxt .= ',\'' . $this->escape($sVal) . '\'';
}
$sTxt = '(' . substr($sTxt, 1) . ')';
if($sTxt == '()') {
$sTxt = '(0)';
}
}
} else {
$sTxt = '\'' . $this->escape($sValue) . '\'';
}
$sQuery = substr_replace($sQuery, $sTxt, $iPos, 1);
$iPos += strlen($sTxt);
$iPos2 = $iPos;
}
}
}
return $sQuery;
}
/** #@- */
/** #@+
* @access private
*/
private function _setCharset() {
$charset = 'utf8';
mysqli_query($this->_iReadId, 'SET NAMES ' . $charset);
mysqli_query($this->_iReadId, "SET character_set_results = '" . $charset . "', character_set_client = '" . $charset . "', character_set_connection = '" . $charset . "', character_set_database = '" . $charset . "', character_set_server = '" . $charset . "'");
if($this->_bSeparate == true && is_object($this->_iWriteId)) {
mysqli_query($this->_iWriteId, 'SET NAMES ' . $charset);
mysqli_query($this->_iWriteId, "SET character_set_results = '" . $charset . "', character_set_client = '" . $charset . "', character_set_connection = '" . $charset . "', character_set_database = '" . $charset . "', character_set_server = '" . $charset . "'");
}
}
/**
* construct a where string
*
* Takes a limit array and constructs a where string for the db query.
*
* @access public
* @param array $limit associative array containing the limits - see sample modules for usage
* @param bool $or internal param
* @param bool $no_ending_and internal param
* @param string $type internal param
* @return string where-string for db query
*/
public function array_to_where($limit, $or = false, $no_ending_and = false, $type = '') {
$type = strtoupper($type);
$where = '';
if(is_array($limit) && count($limit) > 0) {
$i = 0;
foreach($limit as $col => $val) {
$i++;
if(is_array($val)) {
if(is_numeric($col) && array_key_exists('col', $val)) {
$col = $val['col'];
}
if(array_key_exists('HAVING', $val) && $type != 'HAVING') {
continue;
} elseif(!array_key_exists('HAVING', $val) && $type == 'HAVING') {
continue;
} elseif(array_key_exists('HAVING', $val)) {
$where .= '(' . $this->array_to_where($val['HAVING'], false, true) . ')';
} elseif(array_key_exists('OR', $val)) {
$where .= '(' . $this->array_to_where($val['OR'], true, true) . ')';
} elseif(array_key_exists('OR NOT', $val)) {
$where .= 'NOT (' . $this->array_to_where($val['OR NOT'], true, true) . ')';
} elseif(array_key_exists('AND', $val)) {
$where .= '(' . $this->array_to_where($val['AND'], false, true) . ')';
} elseif(array_key_exists('AND NOT', $val)) {
$where .= 'NOT (' . $this->array_to_where($val['AND NOT'], false, true) . ')';
} elseif(array_key_exists('IN', $val) && is_array($val['IN'])) {
if(count($val['IN']) > 0) {
$where .= $col . ' IN (';
$a = 0;
foreach($val['IN'] as $data) {
if($a > 0) {
$where .= ', ';
}
$where .= '\'' . $this->escape($data) . '\'';
$a++;
}
$where .= ')';
} else {
$where .= '1 = 2'; // impossible situation!
}
} elseif($val['type'] == 'LIKE') {
$where .= $col . ' LIKE \'%' . $this->escape($val['search']) . '%\'';
} elseif($val['type'] == 'NOT LIKE') {
$where .= $col . ' NOT LIKE \'%' . $this->escape($val['search']) . '%\'';
} elseif($val['type'] == 'FULLTEXT') {
$where .= 'MATCH(' . $col . ') AGAINST (\'' . $this->escape($val['search']) . '\' IN BOOLEAN MODE)';
} elseif($val['type'] == 'NULL') {
$where .= $col . ' IS NULL';
} elseif($val['type'] == 'NOT NULL') {
$where .= $col . ' IS NOT NULL';
} elseif($val['type'] == 'IN' && is_array($val['search'])) {
$sTxt = '';
foreach($val['search'] as $sVal) {
$sTxt .= ',\'' . $this->escape($sVal) . '\'';
}
$sTxt = '(' . substr($sTxt, 1) . ')';
if($sTxt == '()') {
$sTxt = '(NULL)';
}
$where .= $col . ' IN ' . $sTxt;
} elseif(preg_match('/^(!=|=|<=|>=|<|>|&|\||\^)$/', $val['type'])) {
$where .= $col . ' ' . $val['type'] . ' ' . (isset($val['no_escape']) && $val['no_escape'] ? $val['search'] : (is_int($val['search']) || is_float($val['search']) ? $val['search'] : '\'' . $this->escape($val['search']) . '\''));
} else {
$where .= $col . ' = ' . ($val['no_escape'] ? $val['search'] : (is_int($val['search']) || is_float($val['search']) ? $val['search'] : '\'' . $this->escape($val['search']) . '\''));
}
} else {
if($type == 'HAVING') {
continue;
}
$where .= $col . ' = \'' . $this->escape($val) . '\'';
}
if($no_ending_and == false || $i != count($limit)) {
$where .= ' ' . ($or ? 'OR' : 'AND') . ' ';
}
}
}
return ($type == 'HAVING' && trim($where) != '' ? ' HAVING ' : '') . $where;
}
/**
* Execute a count query
*
* Executes a query and returns the count of results.
* Query has to return the count in the first result column like SELECT COUNT(*) FROM `column` WHERE 1
*
* @access public
* @param string $sQuery query to execute
* @param bool $bReturnNumber if set to true, returns an int, else returns an array with key "count" and the value
* @return mixed int or array as described in param $bReturnNumber
*/
public function counter_query($sQuery = '', $bReturnNumber = false) {
$oResult = $this->query_one($sQuery);
if($oResult) {
$iCount = array_shift($oResult);
} else {
$iCount = 0;
}
unset($oResult);
if($bReturnNumber == true) {
return $iCount;
} else {
return array('count' => $iCount);
}
}
/**
* Executes a query
*
* Executes a given query string, has a variable amount of parameters:
* - 1 parameter
* executes the given query
* - 2 parameters
* executes the given query, replaces the first ? in the query with the second parameter
* - 3 parameters
* if the 2nd parameter is a boolean true, the 3rd parameter has to be an array containing all the replacements for every occuring ? in the query, otherwise the second parameter replaces the first ?, the third parameter replaces the second ? in the query
* - 4 or more parameters
* all ? in the query are replaced from left to right by the parameters 2 to x
*
* @access public
* @param string $sQuery query string
* @param mixed ... one or more parameters
* @return ISPConfigDatabaseResult|boolean the result object of the query
*/
public function query($sQuery = '') {
$bUseRead = true;
if($this->_bSeparate == true) {
if(substr(strtolower($sQuery, 0, 7)) == 'select ') {
$bUseRead = true;
} else {
$bUseRead = false;
}
}
$try = 0;
do {
$try++;
$ok = false;
if($try == 1) {
if($bUseRead && is_object($this->_iReadId)) {
$ok = mysqli_ping($this->_iReadId);
} elseif(!$bUseRead && is_object($this->_iWriteId)) {
$ok = mysqli_ping($this->_iWriteId);
}
}
if(!$ok) {
// close connection
if($bUseRead && is_object($this->_iReadId)) {
mysqli_close($this->_iReadId);
$this->_iReadId = null;
} elseif(!$bUseRead && is_object($this->_iWriteId)) {
mysqli_close($this->_iWriteId);
$this->_iWriteId = null;
}
ISPConfigLog::info('MySQL ping failed, trying reconnect.');
$useCon = @mysqli_connect($this->sHost, $this->sUserName, $this->sPassword, $this->sDataBase, $this->sPort);
$this->errorNumber = mysqli_connect_errno();
if(!is_object($useCon) || $this->errorNumber) {
if($this->errorNumber == '111') {
// server is not available
ISPConfigLog::info('MySQL server unreachable at the moment. Waiting for next reconnect try.');
sleep(30); // additional seconds, please!
} elseif($this->errorNumber == '2006') {
ISPConfigLog::info('MySQL server has gone away. Waiting for next reconnect try.');
sleep(5);
} elseif($this->errorNumber == '2002') {
ISPConfigLog::info('MySQL server socket unreachable at the moment. Waiting for next reconnect try.');
sleep(5);
}
if($this->_iReconnects !== true && $try > $this->_iReconnects) {
$this->_sqlerror('DB::query -> reconnect');
return false;
} else {
$pause_for = 1;
if($try > 20) {
$pause_for = 20;
} elseif($try > 7) {
$pause_for = 5;
}
sleep($pause_for);
}
} else {
ISPConfigLog::info('Reconnected to MySQL.');
if($bUseRead) {
$this->_iReadId = &$useCon;
} else {
$this->_iWriteId = &$useCon;
}
$this->_setCharset();
$ok = true;
}
}
} while($ok == false);
$aArgs = func_get_args();
if($bUseRead == true) {
return call_user_func_array(array(&$this, '_read_query'), $aArgs);
} else {
return call_user_func_array(array(&$this, '_write_query'), $aArgs);
}
}
/** #@+
* @access private
*/
/**
* @param string $sQuery
* @return boolean
*/
private function _read_query($sQuery = '') {
if($sQuery == '') {
$this->_sqlerror('Keine Anfrage angegeben / No query given');
return false;
}
$aArgs = func_get_args();
$sQuery = call_user_func_array(array(&$this, '_build_query_string'), $aArgs);
$this->_start_timer(); // DEBUG
$tries = 0;
$this->_iQueryId = false;
while(!$this->_iQueryId) {
$tries++;
$this->_iQueryId = mysqli_query($this->_iReadId, $sQuery);
if(!$this->_iQueryId) {
$errno = mysqli_errno($this->_iReadId);
if($tries >= 3 || ($errno != '1205' && $errno != '1213')) {
$this->_sqlerror('Falsche Anfrage / Wrong Query', false, 'SQL-Query = ' . $sQuery);
return false;
} else {
ISPConfigLog::info('DB Query failed with code ' . $errno . ', retrying.');
}
}
}
$this->_iReadCount += 1;
$iDuration = $this->_end_timer();
ISPConfigLog::debug('DB Query: ' . $sQuery);
ISPConfigLog::debug('DB Query duration: ' . $iDuration);
return is_bool($this->_iQueryId) ? $this->_iQueryId : new ISPConfigDatabaseResult($this->_iQueryId, $this->_iReadId);
}
/**
* @param string $sQuery
* @return boolean
*/
private function _write_query($sQuery = '') {
if($sQuery == '') {
$this->_sqlerror('Keine Anfrage angegeben / No query given', true);
return false;
}
$aArgs = func_get_args();
$sQuery = call_user_func_array(array(&$this, '_build_query_string'), $aArgs);
$this->_start_timer(); // DEBUG
$tries = 0;
$this->_iQueryId = false;
while(!$this->_iQueryId) {
$tries++;
$this->_iQueryId = mysqli_query($this->_iWriteId, $sQuery);
if(!$this->_iQueryId) {
$errno = mysqli_errno($this->_iWriteId);
if($tries >= 3 || ($errno != '1205' && $errno != '1213')) {
$this->_sqlerror('Falsche Anfrage / Wrong Query', false, 'SQL-Query = ' . $sQuery);
return false;
} else {
ISPConfigLog::info('DB Query failed with code ' . $errno . ', retrying.');
}
}
}
$this->_iWriteCount += 1;
$iDuration = $this->_end_timer();
ISPConfigLog::debug('DB Query: ' . $sQuery);
ISPConfigLog::debug('DB Query duration: ' . $iDuration);
return is_bool($this->_iQueryId) ? $this->_iQueryId : new ISPConfigDatabaseResult($this->_iQueryId, $this->_iWriteId);
}
/** #@- */
/**
* Execute a query and get first result array
*
* Executes a query and returns the first result row as an array
* This is like calling $result = $db->query(), $result->get(), $result->free()
* Use of this function @see query
*
* @access public
* @param string $sQuery query to execute
* @param ... further params (see query())
* @return array result row or NULL if none found
*/
public function query_one($sQuery = '') {
if(!preg_match('/limit \d+(\s*,\s*\d+)?$/i', $sQuery)) {
$sQuery .= ' LIMIT 0,1';
}
$aArgs = func_get_args();
$oResult = call_user_func_array(array(&$this, 'query'), $aArgs);
if(!$oResult) {
return null;
}
$aReturn = $oResult->get();
$oResult->free();
return $aReturn;
}
public function queryOne($sQuery = '') {
return $this->query_one($sQuery);
}
/**
* Execute a query and return all rows
*
* Executes a query and returns all result rows in an array
* Use this with extreme care!!! Uses lots of memory on big result sets.
*
* @access public
* @param string $sQuery query to execute
* @param ... further params (see query())
* @return array all the rows in the result set
*/
public function query_all($sQuery = '') {
$aArgs = func_get_args();
$oResult = call_user_func_array(array(&$this, 'query'), $aArgs);
if(!$oResult) {
return array();
}
$aResults = array();
while($aRow = $oResult->get()) {
$aResults[] = $aRow;
}
$oResult->free();
return $aResults;
}
/**
* Execute a query and return all rows as simple array
*
* Executes a query and returns all result rows in an array with elements
* Only first column is returned Uses lots of memory on big result sets.
*
* @access public
* @param string $sQuery query to execute
* @param ... further params (see query())
* @return array all the rows in the result set
*/
public function query_all_array($sQuery = '') {
$aArgs = func_get_args();
$oResult = call_user_func_array(array(&$this, 'query'), $aArgs);
if(!$oResult) {
return array();
}
$aResults = array();
while($aRow = $oResult->get()) {
$aResults[] = reset($aRow);
}
$oResult->free();
return $aResults;
}
public function queryAll($sQuery = '') {
return $this->query_all($sQuery);
}
public function queryAllArray($sQuery = '') {
return $this->query_all_array($sQuery);
}
/**
* Get id of last inserted row
*
* Gives you the id of the last inserted row in a table with an auto-increment primary key
*
* @access public
* @return int id of last inserted row or 0 if none
*/
public function insert_id() {
$iRes = mysqli_query($this->_iWriteId, 'SELECT LAST_INSERT_ID() as `newid`');
if(!is_object($iRes)) {
return false;
}
$aReturn = mysqli_fetch_assoc($iRes);
mysqli_free_result($iRes);
return $aReturn['newid'];
}
/**
* get affected row count
*
* Gets the amount of rows affected by the previous query
*
* @access public
* @return int affected rows
*/
public function affected() {
if(!is_object($this->_iWriteId)) {
return 0;
}
$iRows = mysqli_affected_rows($this->_iWriteId);
if(!$iRows) {
$iRows = 0;
}
return $iRows;
}
/**
* Escape a string for usage in a query
*
* @access public
* @param string $sString query string to escape
* @return string escaped string
*/
public function escape($sString) {
if(!is_string($sString) && !is_numeric($sString)) {
ISPConfigLog::warn('NON-String given in escape function! (' . gettype($sString) . ')', true);
$sAddMsg = getDebugBacktrace();
ISPConfigLog::info($sAddMsg);
$sString = '';
}
$cur_encoding = mb_detect_encoding($sString);
if($cur_encoding != "UTF-8") {
if($cur_encoding != 'ASCII') {
if($cur_encoding) {
$sString = mb_convert_encoding($sString, 'UTF-8', $cur_encoding);
} else {
$sString = mb_convert_encoding($sString, 'UTF-8');
}
}
} elseif(!ISPConfigFunctions::check_utf8($sString)) {
$sString = utf8_encode($sString);
}
if($this->_bSeparate == true && is_object($this->_iWriteId)) {
return mysqli_real_escape_string($this->_iWriteId, $sString);
} elseif(is_object($this->_iReadId)) {
return mysqli_real_escape_string($this->_iReadId, $sString);
} else {
return addslashes($sString);
}
}
/**
*
*
* @access private
*/
private function _sqlerror($sErrormsg = 'Unbekannter Fehler', $bWrite = false, $sAddMsg = '') {
if($bWrite) {
$mysql_error = (is_object($this->_iWriteId) ? mysqli_error($this->_iWriteId) : mysqli_connect_error());
$mysql_errno = (is_object($this->_iWriteId) ? mysqli_errno($this->_iWriteId) : mysqli_connect_errno());
} else {
$mysql_error = (is_object($this->_iReadId) ? mysqli_error($this->_iReadId) : mysqli_connect_error());
$mysql_errno = (is_object($this->_iReadId) ? mysqli_errno($this->_iReadId) : mysqli_connect_errno());
}
$sAddMsg .= getDebugBacktrace();
ISPConfigLog::warn('Database query failed: ' . $mysql_error . ' (' . $mysql_errno . ') ' . $sAddMsg, true);
}
}
/**
* database query result class
*
* @package pxFramework
*
*/
class ISPConfigDatabaseResult {
/**
*
*
* @access private
*/
private $_iResId = null;
private $_iConnection = null;
/**
*
*
* @access private
*/
public function __construct($iResId, $iConnection) {
$this->_iResId = $iResId;
$this->_iConnection = $iConnection;
}
/**
* get count of result rows
*
* Returns the amount of rows in the result set
*
* @access public
* @return int amount of rows
*/
public function rows() {
if(!is_object($this->_iResId)) {
return 0;
}
$iRows = mysqli_num_rows($this->_iResId);
if(!$iRows) {
$iRows = 0;
}
return $iRows;
}
/**
* Get number of affected rows
*
* Returns the amount of rows affected by the previous query
*
* @access public
* @return int amount of affected rows
*/
public function affected() {
if(!is_object($this->_iConnection)) {
return 0;
}
$iRows = mysqli_affected_rows($this->_iConnection);
if(!$iRows) {
$iRows = 0;
}
return $iRows;
}
/**
* Frees the result set
*
* @access public
*/
public function free() {
if(!is_object($this->_iResId)) {
return;
}
mysqli_free_result($this->_iResId);
return;
}
/**
* Get a result row (associative)
*
* Returns the next row in the result set. To be used in a while loop like while($currow = $result->get()) { do something ... }
*
* @access public
* @return array result row
*/
public function get() {
$aItem = null;
if(is_object($this->_iResId)) {
$aItem = mysqli_fetch_assoc($this->_iResId);
if(!$aItem) {
$aItem = null;
}
}
return $aItem;
}
/**
* Get a result row (array with numeric index)
*
* @access public
* @return array result row
*/
public function getAsRow() {
$aItem = null;
if(is_object($this->_iResId)) {
$aItem = mysqli_fetch_row($this->_iResId);
if(!$aItem) {
$aItem = null;
}
}
return $aItem;
}
}
class.ISPConfigFunctions.inc.php 0000664 0000000 0000000 00000012701 13522573065 0032423 0 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib = 65 && $ord <= 90) || ($ord >= 48 && $ord <= 57 && $prev_type == 'char')) {
$result .= '_';
}
$result .= strtolower($char);
if($ord >= 48 && $ord <= 57) {
$prev_type = 'number';
} else {
$prev_type = 'char';
}
}
return $result;
}
/**
* @param string $value
* @return string
*/
public static function toCamelCase($value) {
$result = '';
$ucase = true;
for($s = 0; $s < strlen($value); $s++) {
$char = $value[$s];
if($char === '_') {
$ucase = true;
continue;
} elseif($ucase === true) {
$result .= strtoupper($char);
} else {
$result .= strtolower($char);
}
$ucase = false;
}
return $result;
}
/**
* check if a utf8 string is valid
*
* @access public
* @param string $str the string to check
* @return bool true if it is valid utf8, false otherwise
*/
public static function check_utf8($str) {
$len = strlen($str);
for($i = 0; $i < $len; $i++) {
$c = ord($str[$i]);
if($c > 128) {
if(($c > 247)) {
return false;
} elseif($c > 239) {
$bytes = 4;
} elseif($c > 223) {
$bytes = 3;
} elseif($c > 191) {
$bytes = 2;
} else {
return false;
}
if(($i + $bytes) > $len) {
return false;
}
while($bytes > 1) {
$i++;
$b = ord($str[$i]);
if($b < 128 || $b > 191) {
return false;
}
$bytes--;
}
}
}
return true;
}
/**
* Gzipped equivalent to file_get_contents
*
* @param string $file_name
* @return boolean|string
*/
public static function gz_file_get_contents($file_name) {
$fp = @gzopen($file_name, 'r');
if(!$fp) {
return false;
}
$data = '';
while(!gzeof($fp) && ($line = gzgets($fp)) !== false) {
$data .= $line;
}
gzclose($fp);
return $data;
}
/**
* Gzipped equivalent to file_put_contents
*
* @param string $file_name
* @param string $data
* @return boolean
*/
public static function gz_file_put_contents($file_name, $data) {
$fp = @gzopen($file_name, 'w');
if(!$fp) {
return false;
}
if(!gzwrite($fp, $data)) {
return false;
}
gzclose($fp);
return true;
}
/**
* create a password (random string)
*
* Creates a random string of the chars a-z, A-Z, 1-9 in a given length
*
* @access public
* @param int $length amount of chars to create
* @return string password/random string
*/
public static function generatePassword($length = 8, $use_special = false) {
// Verfügbare Zeichen für Passwort
$available = "abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789";
if($use_special == true) {
$available .= '%_/-_&+.<>';
}
if($length < 1) {
$length = 8;
}
$passwd = "";
$force_special = ($use_special == true ? mt_rand(1, $length) : 0);
for($i=1;$i<=$length;$i++) {
// Passwort mit zufälligen Zeichen füllen bis Länge erreicht
if($i == $force_special) {
$passwd .= substr($available, mt_rand(57, strlen($available) - 1), 1);
} else {
$passwd .= substr($available, mt_rand(0, strlen($available) - 1), 1);
}
}
// kreiertes Passwort zurückgeben
return $passwd;
}
public static function ini_read($file, $initial_sect = '', $has_variables = false) {
if(!is_file($file)) {
return false;
}
$fp = @fopen($file, 'r');
$ini = array();
$match = array();
$sect = $initial_sect;
$sect_data = array();
if(!$fp) {
return false;
}
while(!feof($fp)) {
$line = trim(fgets($fp));
if($line == '') {
continue;
} elseif(substr($line, 0, 1) === '#' || substr($line, 0, 1) === ';') {
// comments
continue;
} elseif(substr($line, 0, 2) === '//') {
// comments
continue;
} elseif(preg_match('/^\s*\[(\w+)\]\s*$/', $line, $match)) {
if($sect != '') {
$ini[$sect] = $sect_data;
}
$sect = $match[1];
$sect_data = array();
continue;
}
if(strpos($line, '=') === false) {
continue;
} // invalid setting
list($key, $value) = explode('=', $line);
$key = trim($key);
$value = trim($value);
if($has_variables == true) {
if(substr($key, 0, 1) === '$') {
$key = substr($key, 1);
}
if(preg_match('/\w+\s*\[\s*(["\'])([^\]]*?)\\1\s*\]/', $key, $match)) {
$key = $match[2];
}
if(substr($key, 0, 1) === "'" || substr($key, 0, 1) === '"') {
$key = substr($key, 1, -1);
}
if(!$key) {
continue;
} // error or unsupported type
$pos = strpos($value, '//');
if($pos !== false) {
$value = trim(substr($value, 0, $pos));
}
if(substr($value, -1) === ';') {
$value = substr($value, 0, -1);
}
if(substr($value, 0, 1) === "'" || substr($value, 0, 1) === '"') {
$value = substr($value, 1, -1);
} elseif(!preg_match('/^[0-9](?:\.[0-9]*)$/', $value)) {
// not string and not numeric -> unsupported
continue;
}
} elseif(preg_match('/^".*"$/', $value)) {
$value = preg_replace('/^"(.*)"$/', '$1', $value);
}
$sect_data[$key] = $value;
}
fclose($fp);
if($sect != '') {
$ini[$sect] = $sect_data;
} elseif($initial_sect == '') {
return $sect_data;
}
return $ini;
}
} ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/class.ISPConfigHTTP.inc.php 0000664 0000000 0000000 00000022571 13522573065 0031317 0 ustar 00root root 0000000 0000000 false,
'user_agent' => 'ISPConfig (ISPConfigHTTP/1.0)',
'force_ipv4' => false,
'use_tls_1_2' => true,
'legacy_http' => false,
'store_in_file' => false
);
private static $_redirects_left = 0;
/**
* @param string $url
* @param string $method GET|POST|PUT|DELETE
* @param array $add_headers
* @param mixed $send_data
* @return boolean|ISPConfigHTTPResponse
*/
private static function _read($url, $method = 'GET', $add_headers = array(), $send_data = null) {
if(self::getOption('follow_redirects') === true) {
self::$_redirects_left--;
}
if(!is_array($add_headers)) {
$add_headers = array();
}
$method = strtoupper($method);
if(in_array($method, array('GET', 'POST', 'PUT', 'DELETE'), true) === false) {
return false;
}
$context = stream_context_create();
ISPConfigLog::debug('Calling url ' . $url . ' with ' . $method . ' and send data ' . ($send_data ? json_encode($send_data) : ''));
if($method === 'GET' || $method === 'DELETE') {
if(is_array($send_data) && !empty($send_data)) {
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($send_data);
}
}
$url_info = parse_url($url);
$use_connection = (isset($url_info['host']) ? $url_info['host'] : '');
if(self::getOption('force_ipv4') == true) {
stream_context_set_option($context, "ssl", "peer_name", $url_info['host']);
stream_context_set_option($context, "ssl", "allow_self_signed", true);
stream_context_set_option($context, "ssl", "verify_peer", false);
stream_context_set_option($context, "ssl", "verify_peer_name", false);
stream_context_set_option($context, "ssl", "verify_depth", 0);
$ipv4 = dns_get_record($url_info['host'], DNS_A);
if($ipv4 && isset($ipv4[0]['ip'])) {
$use_connection = $ipv4[0]['ip'];
ISPConfigLog::debug('Force IPv4 ' . $url_info['host'] . ' -> ' . $use_connection);
}
}
$transport = 'tls';
if(self::getOption('use_tls_1_2')) {
$transport = 'tlsv1.2';
}
$errno = 0;
$errstr = '';
if((isset($url_info['scheme']) && $url_info['scheme'] == 'https') || (isset($url_info['port']) && $url_info['port'] == 443)) {
$port = isset($url_info['port']) ? $url_info['port'] : 443;
$fp = stream_socket_client($transport . '://' . $use_connection . ':' . $port, $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $context);
} else {
$port = isset($url_info['port']) ? $url_info['port'] : 80;
$fp = fsockopen($use_connection, $port, $errno, $errstr, 10);
}
if(!$fp) {
return false;
}
$store_in = self::getOption('store_in_file');
if($store_in) {
$outfp = fopen($store_in, 'w');
if(!$outfp) {
return false;
}
}
$user_agent = self::getOption('user_agent');
stream_set_timeout($fp, 10);
$header = $method . ' ' . (isset($url_info['path']) ? $url_info['path'] : '/') . (isset($url_info['query']) ? '?' . $url_info['query'] : '') . " HTTP/1." . (self::getOption('legacy_http') ? '0' : '1') . "\r\n";
$header .= "Host: " . (isset($url_info['host']) ? $url_info['host'] : '') . "\r\n";
$header .= "User-Agent: " . $user_agent . "\r\n";
if(isset($url_info['user'])) {
if(!array_key_exists('pass', $url_info)) {
$url_info['pass'] = '';
}
$header .= "Authorization: basic " . base64_encode(rawurldecode($url_info['user']) . ':' . rawurldecode($url_info['pass'])) . "\r\n";
}
if(is_array($add_headers) && !empty($add_headers)) {
foreach($add_headers as $key => $value) {
if(is_array($value)) {
for($v = 0; $v < count($value); $v++) {
$header .= $key . ': ' . $value[$v] . "\r\n";
}
} else {
$header .= $key . ': ' . $value . "\r\n";
}
}
}
$header .= "Accept: */*\r\n";
$header .= "Connection: close\r\n";
if($method === 'POST' || $method === 'PUT') {
if(!is_array($add_headers) || !array_key_exists('content-type', array_change_key_case($add_headers, CASE_LOWER))) {
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
}
$header .= "Content-Length: " . strlen($send_data) . "\r\n\r\n";
$header .= $send_data . "\r\n";
}
$header .= "\r\n";
fwrite($fp, $header);
$response = '';
$eoheader = false;
$header = '';
$tmpdata = '';
$chunked = false;
$chunklen = 0;
$headers = array();
while(!feof($fp)) {
if(($header = fgets($fp, 1024)) !== false) {
if($eoheader == true) {
if($store_in) {
fwrite($outfp, $header);
} else {
$response .= $header;
}
continue;
}
if($header == "\r\n") {
$eoheader = true;
continue;
} else {
$tmpdata .= $header;
if(preg_match('/Transfer-Encoding:\s+chunked/i', $tmpdata)) {
$chunked = true;
}
}
$sc_pos = strpos($header, ':');
if($sc_pos === false) {
$headers['status'] = $header;
$headers['http_code'] = intval(preg_replace('/^HTTP\/\d+\.\d+\s+(\d+)\s+.*$/', '$1', $header));
} else {
$label = substr($header, 0, $sc_pos);
$value = substr($header, $sc_pos + 1);
if(strtolower($label) === 'set-cookie' && isset($headers['set-cookie'])) {
if(!is_array($headers['set-cookie'])) {
$headers['set-cookie'] = array($headers['set-cookie']);
}
$headers['set-cookie'][] = trim($value);
} else {
$headers[strtolower($label)] = trim($value);
}
}
}
}
if($chunked == true) {
$lines = explode("\n", $response);
$response = '';
$chunklen = 0;
foreach($lines as $line) {
$line .= "\n";
if($chunklen <= 0) {
if(preg_match('/^([0-9a-f]+)\s*$/is', $line, $matches)) {
$chunklen = hexdec($matches[1]);
}
continue;
}
if(strlen($line) > $chunklen) {
//echo "Warnung: " . strlen($line) . " > " . $chunklen . "\n";
$line = substr($line, 0, $chunklen);
}
$response .= $line;
$chunklen -= strlen($line);
}
$start = strpos($response, '');
if($start !== false && $end !== false) {
$response = substr($response, $start, $end - $start + 1);
}
}
fclose($fp);
if(!isset($headers)) {
return false;
}
if(isset($headers['http_code']) && isset($headers['location']) && ($headers['http_code'] == 301 || $headers['http_code'] == 302) && self::getOption('follow_redirects') === true && self::$_redirects_left > 0) {
if($store_in) {
fclose($outfp);
}
ISPConfigLog::debug('Got code 301 ' . $url . ' -> ' . $headers['location']);
return self::_read($headers['location'], 'GET', $add_headers);
}
if($store_in) {
fclose($outfp);
return new ISPConfigHTTPResponse($headers['http_code'], $headers, $store_in);
} else {
return new ISPConfigHTTPResponse($headers['http_code'], $headers, $response);
}
}
/**
* @param string $key
* @param mixed $value
* @return boolean
*/
public static function setOption($key, $value) {
if(array_key_exists($key, self::$options) === false) {
return false;
} else {
self::$options[$key] = $value;
}
}
/**
* @param string $key
* @return string|boolean
*/
public static function getOption($key) {
if(array_key_exists($key, self::$options) === false) {
return null;
} else {
return self::$options[$key];
}
}
/**
* Get data
*
* Calls an url and returns a response object
*
* @param string $url the url to call
* @param array $add_headers additional headers to send
* @param string $store_in store result in file instead of response object
* @return ISPConfigHTTPResponse
*/
public static function get($url, $add_headers = null, $store_in = null) {
if(self::getOption('follow_redirects') === true) {
self::$_redirects_left = 5;
}
if($store_in) {
self::setOption('store_in_file', $store_in);
} else {
self::setOption('store_in_file', false);
}
return self::_read($url, 'GET', $add_headers);
}
/**
* Make a post request and get data
*
* Calls an url with a post request and returns the data - and optionally the header content
*
* @param string $url the url to call
* @param string $data the post data to send
* @param array $add_headers additional headers to send
* @param string $store_in store result in file instead of response object
* @return ISPConfigHTTPResponse
*/
public static function post($url, $data, $add_headers = null, $store_in = null) {
if(self::getOption('follow_redirects') === true) {
self::$_redirects_left = 5;
}
if($store_in) {
self::setOption('store_in_file', $store_in);
} else {
self::setOption('store_in_file', false);
}
return self::_read($url, 'POST', $add_headers, $data);
}
/**
* Make a post request and get data
*
* Calls an url with a post request and returns the data - and optionally the header content
*
* @param string $url the url to call
* @param string $data the post data to send
* @param array $add_headers additional headers to send
* @param string $store_in store result in file instead of response object
* @return ISPConfigHTTPResponse
*/
public static function request($method, $url, $data = null, $add_headers = null, $store_in = null) {
if(self::getOption('follow_redirects') === true) {
self::$_redirects_left = 5;
}
if($store_in) {
self::setOption('store_in_file', $store_in);
} else {
self::setOption('store_in_file', false);
}
return self::_read($url, $method, $add_headers, $data);
}
}
class.ISPConfigHTTPResponse.inc.php 0000664 0000000 0000000 00000002746 13522573065 0032761 0 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib headers = $headers;
$this->body = $body;
$this->http_code = $http_code;
$content_type = $this->getHeader('Content-Type');
if(!$content_type) {
$content_type = '';
}
if(strpos($content_type, ';') !== false) {
list($content_type, ) = explode(';', $content_type);
}
$content_type = strtolower($content_type);
if(preg_match('/^application\/(?:x-)?json/', $content_type)) {
$this->json_body = json_decode($body, true);
if(!$this->json_body) {
$this->json_body = null;
}
}
}
public function __toString() {
return serialize($this);
}
/**
* @return int
*/
public function getHTTPCode() {
return $this->http_code;
}
/**
* @return array
*/
public function getHeaders() {
return $this->headers;
}
/**
* @param string $name
* @return string
*/
public function getHeader($name) {
$name = strtolower($name);
if(isset($this->headers[$name])) {
return $this->headers[$name];
} else {
return null;
}
}
/**
* @return string
*/
public function getResponse() {
return $this->body;
}
/**
* @return array
*/
public function getJSON() {
return $this->json_body;
}
}
ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/class.ISPConfigLog.inc.php 0000664 0000000 0000000 00000007124 13522573065 0031256 0 ustar 00root root 0000000 0000000 'DEBUG',
1 => 'INFO',
2 => 'WARN',
3 => 'ERROR'
);
public static function setLogPriority($priority) {
if(array_key_exists($priority, self::PRIORITY_TEXT)) {
self::$priority = $priority;
} else {
throw new ISPConfigLogException('Invalid logging priority: ' . $priority);
}
}
public static function setLogFile($filename) {
if(strpos($filename, '/') !== false || strpos($filename, '..') !== false) {
throw new ISPConfigLogException('Insecure log filename: ' . $filename);
}
if(!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $filename)) {
throw new ISPConfigLogException('Invalid log filename: ' . $filename);
}
if(!$filename) {
self::$logfile = 'ispconfig.log';
} else {
self::$logfile = $filename;
}
return true;
}
/**
* @param string $message
* @param int $priority
* @param boolean $output
* @throws ISPConfigLogException
*/
private static function log($message, $priority = ISPConfigLog::PRIO_INFO, $output = false) {
if(self::$priority > $priority) {
return;
}
if(!@is_dir(LOG_DIR)) {
if(!@mkdir(LOG_DIR, 0777, true)) {
throw new ISPConfigLogException('Log path ' . LOG_DIR . ' could not be created.');
}
}
if(!isset(self::PRIORITY_TEXT[$priority])) {
throw new ISPConfigLogException('Invalid logging priority ' . $priority . ' provided.');
}
$log_file = LOG_DIR . '/' . self::$logfile;
$caller = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
array_shift($caller);
if(count($caller) > 0) {
$caller = array_shift($caller);
}
if(substr($caller['file'], 0, strlen(APP_DIR)) === APP_DIR) {
$caller['file'] = substr($caller['file'], strlen(APP_DIR));
}
$fp = @fopen($log_file, 'a');
if(!$fp) {
throw new ISPConfigLogException('Could not open logfile ' . $log_file . '.');
}
if(!@fwrite($fp, strftime("%d.%m.%Y-%H:%M:%S", time()) . ' - ' . $caller['file'] . ':' . $caller['line'] . ': [' . self::PRIORITY_TEXT[$priority] . '] ' . $message . "\n")) {
throw new ISPConfigLogException('Could not write to logfile ' . $log_file . '.');
}
fclose($fp);
if($output === true) {
$pre = '[' . self::PRIORITY_TEXT[$priority] . ']';
if($priority === self::PRIO_ERROR) {
$pre = '' . $pre . '';
} elseif($priority === self::PRIO_WARN) {
$pre = '' . $pre . '';
}
$add_message = '';
if($priority >= self::PRIO_WARN) {
$add_message .= ' (' . $caller['file'] . ':' . $caller['line'] . ')';
}
print PXBashColor::getString($pre . ' ' . $message . $add_message . "\n");
}
}
/**
* @param string $message
* @param boolean $output
*/
public static function debug($message, $output = false) {
self::log($message, ISPConfigLog::PRIO_DEBUG, $output);
}
/**
* @param string $message
* @param boolean $output
*/
public static function info($message, $output = false) {
self::log($message, ISPConfigLog::PRIO_INFO, $output);
}
/**
* @param string $message
* @param boolean $output
*/
public static function warn($message, $output = false) {
self::log($message, ISPConfigLog::PRIO_WARN, $output);
}
/**
* @param string $message
* @param boolean $output
*/
public static function error($message, $output = false) {
self::log($message, ISPConfigLog::PRIO_ERROR, $output);
}
}
ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/exceptions/ 0000775 0000000 0000000 00000000000 13522573065 0026623 5 ustar 00root root 0000000 0000000 class.ISPConfigException.inc.php 0000664 0000000 0000000 00000001023 13522573065 0034565 0 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/exceptions $os['ID'],
'VERSION' => $os['VERSION_ID'],
'NAME' => (isset($os['PRETTY_NAME']) ? $os['PRETTY_NAME'] : ucfirst($os['ID']) . ' ' . (isset($os['VERSION']) ? $os['VERSION'] : $os['VERSION_ID']))
);
} else {
throw new ISPConfigOSException('Unknown or unsupported OS.');
}
}
return self::$os_data;
}
/**
* @return ISPConfigBaseOS
* @throws Exception
*/
public static function getOSInstance() {
try {
$os = self::getOSVersion();
$class_name = 'ISPConfig' . ucfirst($os['ID']) . $os['VERSION'] . 'OS';
if(!is_file(LIB_DIR . '/os/class.' . $class_name . '.inc.php')) {
$class_name = 'ISPConfig' . ucfirst($os['ID']) . 'OS';
}
return new $class_name;
} catch(Exception $ex) {
throw $ex;
}
}
public function __construct() {
}
public function exec($cmd, $returncodes_ok = array(), $tries = 1, $retry_codes = null) {
$result = false;
while($result === false && $tries > 0) {
$return_var = 0;
$output = array();
$result = exec($cmd, $output, $return_var);
ISPConfigLog::debug('CMD: ' . $cmd . ' returned code ' . $return_var);
if($return_var === 0 || (!empty($returncodes_ok) && is_array($returncodes_ok) && in_array($return_var, $returncodes_ok, true))) {
$result = implode("\n", $output);
} elseif(is_array($retry_codes) && !empty($retry_codes) && !in_array($return_var, $retry_codes)) {
break;
}
$tries--;
}
return $result;
}
protected function addLines($file, $entries, $add_if_existing = false) {
if(!is_array($entries)) {
$entries = array($entries);
}
$content = '';
if(is_file($file)) {
$content = file_get_contents($file);
}
foreach($entries as $line) {
if($add_if_existing === true || !preg_match('/^' . preg_quote($line) . '$/m', $content)) {
$content .= "\n" . $line . "\n";
}
}
file_put_contents($file, $content);
return;
}
protected function uncommentLines($file, $entries, $commenter = '#') {
return $this->commentUncommentLines($file, $entries, true, $commenter);
}
protected function commentLines($file, $entries, $commenter = '#') {
return $this->commentUncommentLines($file, $entries, false, $commenter);
}
private function commentUncommentLines($file, $entries, $uncomment = false, $commenter = '#') {
if(!is_array($entries)) {
throw new ISPConfigOSException('Invalid entries array provided.');
}
if(!is_file($file)) {
throw new ISPConfigOSException('File ' . $file . ' does not exist.');
}
$content = file_get_contents($file);
$active_entry = false;
$lines = explode("\n", $content);
$new_lines = array();
for($l = 0; $l < count($lines); $l++) {
$line = $lines[$l];
if($active_entry) {
if(!isset($active_entry['last_line']) || !$active_entry['last_line']) {
$active_entry = false;
} elseif(preg_match($active_entry['last_line'], $line)) {
$active_entry = false;
if($uncomment === true) {
$line = preg_replace('/^(\s*)' . preg_quote($commenter, '/') . '+[ \t]*/', '$1', $line);
} else {
$line = $commenter . $line;
}
} elseif(isset($active_entry['search']) && $active_entry['search']) {
if(!is_array($active_entry['search'])) {
$active_entry['search'] = array($active_entry['search']);
}
for($i = 0; $i < count($active_entry['search']); $i++) {
if(preg_match($active_entry['search'][$i], $line)) {
if($uncomment === true) {
$line = preg_replace('/^(\s*)' . preg_quote($commenter, '/') . '+[ \t]/', '$1', $line);
} else {
$line = $commenter . $line;
}
break;
}
}
}
} else {
for($i = 0; $i < count($entries); $i++) {
$entry = $entries[$i];
if(!isset($entry['first_line'])) {
throw new ISPConfigOSException('Invalid entry (no last or first line).');
}
if(preg_match($entry['first_line'], $line)) {
if($uncomment === true) {
$line = preg_replace('/^(\s*)' . preg_quote($commenter, '/') . '+[ \t]/', '$1', $line);
} else {
$line = $commenter . $line;
}
$active_entry = $entry;
break;
}
}
if($active_entry && isset($active_entry['add_lines'])) {
$add = $active_entry['add_lines'];
if(!is_array($add)) {
$add = array($add);
}
$line .= "\n" . implode("\n", $add);
}
}
$new_lines[] = $line;
}
$content = implode("\n", $new_lines);
unset($new_lines);
unset($lines);
copy($file, $file . '~' . strftime('%Y%m%d%H%M%S', time()));
file_put_contents($file, $content);
return true;
}
/**
* @param string $file
* @param array $replacements
* @param boolean $add_if_missing
* @param string $add_to_section
* @return boolean
* @throws ISPConfigOSException
*/
protected function replaceContents($file, $replacements, $add_if_missing = false, $add_to_section = null) {
if(!is_array($replacements)) {
throw new ISPConfigOSException('Invalid replacement array provided.');
}
$content = '';
$matches = array();
if(is_file($file) == false) {
file_put_contents($file, '');
} else {
$content = file_get_contents($file);
}
foreach($replacements as $search => $replace) {
$if_not = false;
if(is_array($replace)) {
$if_not = $replace['ifnot'];
$replace = $replace['replace'];
}
$need_to_add = false;
if(preg_match('/^\/.*\/[igmsuS]*$/', $search)) {
if($add_if_missing == true && !preg_match($search, $content)) {
$need_to_add = true;
} else {
if($if_not) {
if(preg_match($search, $content, $matches)) {
if(strpos($matches[0], $if_not) !== false) {
// dont add!
continue;
}
}
}
$content = preg_replace($search, $replace, $content);
}
} else {
if($add_if_missing == true && !strpos($content, $search)) {
$need_to_add = true;
} else {
$content = str_replace($search, $replace, $content);
}
}
if($need_to_add === true) {
if($add_to_section) {
$section_found = false;
$lines = explode("\n", $content);
$new_lines = array();
$in_section = false;
for($l = 0; $l < count($lines); $l++) {
$line = $lines[$l];
if(preg_match('/^\[([^\]]+)?\]/', $line, $matches)) {
if($matches[1] == $add_to_section) {
$in_section = true;
$section_found = true;
} elseif($in_section === true) {
$new_lines[] = "\n" . $replace . "\n";
$in_section = false;
}
}
$new_lines[] = $line;
}
$content = implode("\n", $new_lines);
unset($lines);
unset($new_lines);
if($section_found === false) {
$content .= "\n\n" . '[' . $add_to_section . ']' . "\n" . $replace . "\n";
}
} else {
$content .= "\n" . $replace;
}
}
}
copy($file, $file . '~' . strftime('%Y%m%d%H%M%S', time()));
file_put_contents($file, $content);
return true;
}
protected function getInstallCommand($packages) {
if(is_string($packages)) {
$packages = array($packages);
}
$cmd = $this->getUpdateCommand('install');
$cmd = str_replace('', implode(' ', $packages), $cmd);
return $cmd;
}
protected function updatePackageList() {
$cmd = $this->getUpdateCommand('prepare');
return $this->exec($cmd, null, 3, array('100'));
}
protected function installPackages($packages) {
$cmd = $this->getInstallCommand($packages);
return $this->exec($cmd, null, 3);//, array('100'));
}
protected function restartService($service_name) {
$cmd = $this->getRestartServiceCommand($service_name);
return $this->exec($cmd);
}
protected function startService($service_name) {
$cmd = $this->getRestartServiceCommand($service_name, 'start');
return $this->exec($cmd);
}
protected function stopService($service_name) {
$cmd = $this->getRestartServiceCommand($service_name, 'stop');
return $this->exec($cmd);
}
protected function isServiceRunning($service_name) {
$cmd = $this->getRestartServiceCommand($service_name, 'status');
$result = $this->exec($cmd);
if($result === false) {
return false;
} else {
return true;
}
}
protected function afterPackageInstall($section = '') {
}
protected function beforePackageInstall($section = '') {
}
public function getPackageVersion($package) {
}
public function getPackageAlias($package) {
}
public function getUpdateCommand($mode = 'update') {
}
public function getUpdatePackageRegex() {
}
public function getInstallPackageRegex($mode = '') {
}
public function getRestartServiceCommand($service, $command = 'restart') {
}
public function runPerfectSetup() {
}
}
class.ISPConfigDebian10OS.inc.php 0000664 0000000 0000000 00000013442 13522573065 0032664 0 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/os replaceContents('/etc/mysql/debian.cnf', array('/^password\s*=.*$/m' => 'password = ' . $mysql_root_pw));
$this->replaceContents('/etc/mysql/mariadb.conf.d/50-server.cnf', array('/^bind-address/m' => '#bind-address'), true, 'mysqld');
}
public function getRestartServiceCommand($service, $command = 'restart') {
if($command != 'start' && $command != 'stop' && $command != 'status') {
$command = 'restart';
}
switch($service) {
case 'mysql':
case 'mariadb':
$service = 'mariadb';
break;
case 'pureftpd':
$service = 'pure-ftpd-mysql';
break;
}
return 'systemctl ' . $command . ' ' . escapeshellarg($service) . ' 2>&1';
}
protected function getPackagesToInstall($section) {
if($section === 'mail') {
$packages = parent::getPackagesToInstall($section);
$packages[] = 'p7zip';
$packages[] = 'p7zip-full';
$packages[] = 'unrar';
$packages[] = 'lrzip';
}
return $packages;
}
protected function setDefaultPHP() {
ISPConfigLog::info('Settings default system php version.', true);
$cmd = 'update-alternatives --set php /usr/bin/php7.3 ; update-alternatives --set php-cgi /usr/bin/php-cgi7.3';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
}
protected function installPHPMyAdmin($mysql_root_pw) {
ISPConfigLog::info('Installing package phpmyadmin', true);
if(!is_dir('/usr/share/phpmyadmin')) {
mkdir('/usr/share/phpmyadmin', 0755, true);
}
if(!is_dir('/etc/phpmyadmin')) {
mkdir('/etc/phpmyadmin', 0755);
}
if(!is_dir('/var/lib/phpmyadmin/tmp')) {
mkdir('/var/lib/phpmyadmin/tmp', 0777, true);
}
touch('/etc/phpmyadmin/htpasswd.setup');
$cmd = 'chown -R www-data:www-data ' . escapeshellarg('/var/lib/phpmyadmin') . ' ; cd /tmp ; rm -f phpMyAdmin-4.9.0.1-all-languages.tar.gz ; wget "https://files.phpmyadmin.net/phpMyAdmin/4.9.0.1/phpMyAdmin-4.9.0.1-all-languages.tar.gz" 2>/dev/null && tar xfz phpMyAdmin-4.9.0.1-all-languages.tar.gz && mv phpMyAdmin-4.9.0.1-all-languages/* /usr/share/phpmyadmin/ && rm -f phpMyAdmin-4.9.0.1-all-languages.tar.gz && rm -rf phpMyAdmin-4.9.0.1-all-languages';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
copy('/usr/share/phpmyadmin/config.sample.inc.php', '/usr/share/phpmyadmin/config.inc.php');
$replacements = array(
'/^(?:\s*\/\/)?\s*\$cfg\[\'blowfish_secret\'\]\s*=.*$/m' => '$cfg[\'blowfish_secret\'] = \'' . substr(sha1(uniqid('pre', true)), 0, 32) . '\';',
'/^(?:\s*\/\/)?\s*\$cfg\[\'TempDir\'\]\s*=.*$/m' => '$cfg[\'TempDir\'] = \'/var/lib/phpmyadmin/tmp\';'
);
$this->replaceContents('/usr/share/phpmyadmin/config.inc.php', $replacements, true);
$contents = '# phpMyAdmin default Apache configuration
Alias /phpmyadmin /usr/share/phpmyadmin
Options FollowSymLinks
DirectoryIndex index.php
AddType application/x-httpd-php .php
php_flag magic_quotes_gpc Off
php_flag track_vars On
php_flag register_globals Off
php_value include_path .
# Authorize for setup
AuthType Basic
AuthName "phpMyAdmin Setup"
AuthUserFile /etc/phpmyadmin/htpasswd.setup
Require valid-user
# Disallow web access to directories that don\'t need it
Order Deny,Allow
Deny from All
Order Deny,Allow
Deny from All
';
file_put_contents('/etc/apache2/conf-available/phpmyadmin.conf', $contents);
$cmd = 'a2enconf phpmyadmin';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$this->restartService('apache2');
$pma_pass = ISPConfigFunctions::generatePassword(15);
$pma_pass_enc = preg_replace('/[\'\\\\]/', '\\$1', $pma_pass);
$queries = array(
'CREATE DATABASE phpmyadmin;',
'CREATE USER \'pma\'@\'localhost\' IDENTIFIED BY \'' . $pma_pass_enc . '\';',
'GRANT ALL PRIVILEGES ON phpmyadmin.* TO \'pma\'@\'localhost\' IDENTIFIED BY \'' . $pma_pass_enc . '\' WITH GRANT OPTION;',
'FLUSH PRIVILEGES;'
);
foreach($queries as $query) {
$cmd = 'mysql --defaults-file=/etc/mysql/debian.cnf -e ' . escapeshellarg($query) . ' 2>&1';
$result = $this->exec($cmd);
if($result === false) {
ISPConfigLog::warn('Query ' . $query . ' failed.', true);
}
}
$cmd = 'mysql --defaults-file=/etc/mysql/debian.cnf -D phpmyadmin < /usr/share/phpmyadmin/sql/create_tables.sql';
$result = $this->exec($cmd);
if($result === false) {
ISPConfigLog::warn('Command ' . $cmd . ' failed.', true);
}
$uncomment = array(
array(
'first_line' => '/^(?:\s*\/\/)?\s*\$cfg\[\'Servers\'\]\[\$i\]/',
'last_line' => '/####nomatch###/',
'search' => '/^(?:\s*\/\/)?\s*\$cfg\[\'Servers\'\]\[\$i\]/'
)
);
$this->uncommentLines('/usr/share/phpmyadmin/config.inc.php', $uncomment, '//');
$replacements = array(
'/^(?:\s*\/\/)?\s*(\$cfg\[\'Servers\'\]\[\$i\]\[\'controlhost\'\])\s*=.*$/m' => '$1 = \'localhost\';',
'/^(?:\s*\/\/)?\s*(\$cfg\[\'Servers\'\]\[\$i\]\[\'controlport\'\])\s*=.*$/m' => '$1 = \'\';',
'/^(?:\s*\/\/)?\s*(\$cfg\[\'Servers\'\]\[\$i\]\[\'controluser\'\])\s*=.*$/m' => '$1 = \'pma\';',
'/^(?:\s*\/\/)?\s*(\$cfg\[\'Servers\'\]\[\$i\]\[\'controlpass\'\])\s*=.*$/m' => '$1 = \'' . $pma_pass_enc . '\';',
);
$this->replaceContents('/usr/share/phpmyadmin/config.inc.php', $replacements, false);
}
}
class.ISPConfigDebianOS.inc.php 0000664 0000000 0000000 00000075656 13522573065 0032542 0 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/os &1';
$result = $this->exec($cmd);
$version = false;
$matches = array();
if(preg_match_all('/^ii\s+\S+\s+(\S+)(?:\s|$)/m', $result, $matches, PREG_SET_ORDER)) {
for($i = 0; $i < count($matches); $i++) {
$tmp_version = $matches[$i][1];
if(!$version || ISPProtectFunctions::version_compare($version, $tmp_version, '<')) {
$version = $tmp_version;
}
}
}
return $version;
}
public function getPackageAlias($package) {
switch($package) {
case 'libssl':
$package = 'libssl[0-9]*';
break;
case 'kernel':
$package = 'linux-image-[0-9]*';
break;
}
return $package;
}
public function getUpdateCommand($mode = 'update') {
$cmd = false;
if($mode == 'prepare') {
$cmd = 'DEBIAN_FRONTEND="noninteractive" apt-get update -qq -y';
} elseif($mode == 'update') {
// for updating all updateable packages
$cmd = 'DEBIAN_FRONTEND="noninteractive" apt-get dist-upgrade -qq -y';
} elseif($mode == 'install' || $mode == 'partly_update') {
// for installing / updating specific packages
$cmd = 'DEBIAN_FRONTEND="noninteractive" apt-get install -qq -y';
$cmd .= ' ';
}
$cmd = 'while fuser /var/lib/dpkg/lock >/dev/null 2>&1 || fuser /var/lib/apt/lists/lock >/dev/null 2>&1 ; do sleep 2; done; ' . $cmd . ' 2>&1';
return $cmd;
}
public function getUpdatePackageRegex() {
$regex = '^\w+\s+(?P\S+)\s+(?:\[(?P\S+)\]\s*)?(?:\((?P\S+))?(?:\s|$)';
return $regex;
}
public function getInstallPackageRegex($mode = '') {
if($mode == 'oldversion') {
$regex = '(?P\S+)\s+(?:(?P\d\S+)\s+)?\(.*\.deb';
} elseif($mode == 'newversion') {
$regex = '(?:^|\s+)(?P\S+)\s+\((?P\d\S*)\)\s+';
} else {
$regex = ''; // not on debian!
}
return $regex;
}
public function getRestartServiceCommand($service, $command = 'restart') {
if($command != 'start' && $command != 'stop' && $command != 'status') {
$command = 'restart';
}
switch($service) {
case 'apache':
$service = 'apache2';
break;
case 'pureftpd':
$service = 'pure-ftpd-mysql';
break;
}
return 'service ' . escapeshellarg($service) . ' ' . $command . ' 2>&1';
}
protected function updateMySQLConfig($mysql_root_pw) {
ISPConfigLog::info('Writing MySQL config files.', true);
$this->replaceContents('/etc/mysql/debian.cnf', array('/^password\s*=.*$/m' => 'password = ' . $mysql_root_pw));
$this->replaceContents('/etc/mysql/mariadb.conf.d/50-server.cnf', array('/^bind-address/m' => '#bind-address', '/^sql-mode\s*=.*?$/m' => 'sql-mode = "NO_ENGINE_SUBSTITUTION"'), true, 'mysqld');
}
protected function getPackagesToInstall($section) {
if($section === 'mail') {
$packages = array(
'spamassassin',
'dnsutils',
'rspamd',
'redis-server',
'resolvconf',
'clamav',
'clamav-daemon',
'unzip',
'bzip2',
'arj',
'nomarch',
'lzop',
'cabextract',
'apt-listchanges',
'libnet-ldap-perl',
'libauthen-sasl-perl',
'clamav-docs',
'daemon',
'libio-string-perl',
'libio-socket-ssl-perl',
'libnet-ident-perl',
'zip',
'libnet-dns-perl',
'libdbd-mysql-perl',
'postgrey',
'bind9',
'dnsutils'
);
}
return $packages;
}
protected function getApacheModulesToEnable() {
$modules = array('suexec', 'rewrite', 'ssl', 'actions', 'include', 'dav_fs', 'dav', 'auth_digest', 'cgi', 'headers', 'proxy_fcgi', 'alias');
return $modules;
}
protected function setDefaultPHP() {
ISPConfigLog::info('Settings default system php version.', true);
$cmd = 'update-alternatives --set php /usr/bin/php7.0 ; update-alternatives --set php-cgi /usr/bin/php-cgi7.0';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
}
protected function installPHPMyAdmin($mysql_root_pw) {
$cmd = 'APP_PASS="' . ISPConfigFunctions::generatePassword(15) . '"' . "\n";
$cmd .= 'ROOT_PASS="' . $mysql_root_pw . '"' . "\n";
$cmd .= 'APP_DB_PASS="' . ISPConfigFunctions::generatePassword(15) . '"' . "\n";
$cmd .= 'echo "phpmyadmin phpmyadmin/dbconfig-install boolean true" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "phpmyadmin phpmyadmin/app-password-confirm password $APP_PASS" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "phpmyadmin phpmyadmin/mysql/admin-user string root" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "phpmyadmin phpmyadmin/mysql/admin-pass password $ROOT_PASS" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "phpmyadmin phpmyadmin/mysql/app-pass password $APP_DB_PASS" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2" | debconf-set-selections 2>&1' . "\n";
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
ISPConfigLog::info('Installing package phpmyadmin', true);
$result = $this->installPackages('phpmyadmin');
if($result !== false) {
ISPConfigLog::info('Installed package phpmyadmin', true);
} else {
throw new ISPConfigOSException('Installing package failed.');
}
}
protected function fixDbconfigCommon() {
ISPConfigLog::info('Fixing dbconfig-common if neccessary');
$replacements = array(
'/_dbc_nodb="yes" dbc_mysql_exec/' => '_dbc_nodb="yes"; dbc_mysql_exec'
);
$this->replaceContents('/usr/share/dbconfig-common/internal/mysql', $replacements, false);
}
protected function setPHPTimezone() {
if(!is_file('/etc/timezone')) {
return;
}
$tz = trim(file_get_contents('/etc/timezone'));
if(!in_array($tz, timezone_identifiers_list())) {
return;
}
// set in all php inis
$ini_files = array(
'/etc/php/5.6/cgi/php.ini',
'/etc/php/5.6/cli/php.ini',
'/etc/php/5.6/fpm/php.ini',
'/etc/php/5.6/apache2/php.ini',
'/etc/php/7.0/cgi/php.ini',
'/etc/php/7.0/cli/php.ini',
'/etc/php/7.0/fpm/php.ini',
'/etc/php/7.0/apache2/php.ini',
'/etc/php/7.1/cgi/php.ini',
'/etc/php/7.1/cli/php.ini',
'/etc/php/7.1/fpm/php.ini',
'/etc/php/7.1/apache2/php.ini',
'/etc/php/7.2/cgi/php.ini',
'/etc/php/7.2/cli/php.ini',
'/etc/php/7.2/fpm/php.ini',
'/etc/php/7.2/apache2/php.ini',
'/etc/php/7.3/cgi/php.ini',
'/etc/php/7.3/cli/php.ini',
'/etc/php/7.3/fpm/php.ini',
'/etc/php/7.3/apache2/php.ini'
);
$replace = array(
'/^;?\s*date\.timezone\s+=.*$/' => 'date.timezone = ' . $tz
);
foreach($ini_files as $ini) {
if(is_file($ini)) {
$this->replaceContents($ini, $replace);
}
}
}
protected function configureApt() {
// enable contrib and non-free
ISPConfigLog::info('Enabling contrib and non-free repositories.', true);
$replacements = array(
'/^(deb.*\s+main)\s*$/' => '$1 contrib non-free'
);
$this->replaceContents('/etc/apt/sources.list', $replacements);
}
protected function addSuryRepo() {
ISPConfigLog::info('Activating sury php repository.', true);
$cmd = 'wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg >/dev/null 2>&1 ; echo "deb https://packages.sury.org/php/ $(lsb_release -c -s) main" > /etc/apt/sources.list.d/php.list';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
}
protected function getFail2BanJail() {
$jk_jail = '[pure-ftpd]
enabled = true
port = ftp
filter = pure-ftpd
logpath = /var/log/syslog
maxretry = 3
[dovecot]
enabled = true
filter = dovecot
logpath = /var/log/mail.log
maxretry = 5
[postfix-sasl]
enabled = true
port = smtp
filter = postfix-sasl
logpath = /var/log/mail.log
maxretry = 3';
return $jk_jail;
}
public function runPerfectSetup() {
$log_filename = 'setup-' . strftime('%Y%m%d%H%M%S', time()) . '.log';
ISPConfigLog::setLogFile($log_filename);
if(is_file('/usr/local/ispconfig/server/lib/config.inc.php')) {
ISPConfigLog::error('The server already has ISPConfig installed. Aborting.', true);
return false;
}
$this->configureApt();
$this->updatePackageList();
ISPConfigLog::info('Updating packages', true);
$cmd = $this->getUpdateCommand('update');
$result = $this->exec($cmd);
if($result !== false) {
ISPConfigLog::info('Updated packages', true);
} else {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
try {
$this->beforePackageInstall();
} catch (Exception $ex) {
throw $ex;
}
$packages = array(
'ssh',
'openssh-server',
'nano',
'vim-nox',
'ntp',
'lsb-release',
'apt-transport-https',
'ca-certificates',
'wget',
'git'
);
ISPConfigLog::info('Installing packages ' . implode(', ', $packages), true);
$result = $this->installPackages($packages);
if($result !== false) {
ISPConfigLog::info('Installed packages ' . implode(', ', $packages), true);
} else {
throw new ISPConfigOSException('Installing packages failed.');
}
ISPConfigLog::info('Activating rspamd repository.', true);
$cmd = 'wget -O - "https://rspamd.com/apt-stable/gpg.key" 2>/dev/null | apt-key add - 2>/dev/null ; echo "deb http://rspamd.com/apt-stable/ $(lsb_release -c -s) main" > /etc/apt/sources.list.d/rspamd.list';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$this->addSuryRepo();
$this->updatePackageList();
ISPConfigLog::info('Updating packages (after enabling sury and rspamd repos).', true);
$cmd = $this->getUpdateCommand('update');
$result = $this->exec($cmd);
if($result !== false) {
ISPConfigLog::info('Updated packages', true);
} else {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
/*$hostname_changed = false;
ISPConfigLog::info('Setting hostname to ' . $host_name, true);
$dotpos = strpos($host_name, '.');
if($dotpos !== false) {
$short_hostname = substr($host_name, 0, $dotpos);
} else {
$short_hostname = '';
}
$hosts_entry = $this->ip_address . "\t" . $host_name . ($short_hostname ? ' ' . $short_hostname : '');
if(is_file('/etc/cloud/templates/hosts.tmpl')) {
$use_hosts_file = '/etc/cloud/templates/hosts.tmpl';
} else {
$use_hosts_file = '/etc/hosts';
}
$content = file_get_contents($use_hosts_file);
if(preg_match('/^\s*' . preg_quote($this->ip_address, '/') . ' (.*?)$/m', $content, $matches)) {
ISPConfigLog::info('Hostname is currently set to ' . $matches[1]);
$content = str_replace($matches[0], $hosts_entry, $content);
if($matches[0] != $hosts_entry) {
$hostname_changed = true;
}
} else {
ISPConfigLog::info('Hostname not found in hosts file.');
$content .= "\n" . $hosts_entry;
$hostname_changed = true;
}
file_put_contents($use_hosts_file, $content);
$content = trim(file_get_contents('/etc/hostname'));
if($content != $short_hostname) {
ISPConfigLog::info('/etc/hostname is currently set to ' . $content, true);
$hostname_changed = true;
file_put_contents('/etc/hostname', $short_hostname);
}
ISPConfigLog::info('Hostname saved.', true);
if($hostname_changed) {
ISPConfigLog::info('Rebooting server.', true);
$ok = $this->exec('shutdown -r now >/dev/null 2>&1', array(0, 255));
if($ok === false) {
throw new ISPConfigOSException('Command for server reboot failed.');
}
$ok = $this->waitForReboot(30, 1200);
if(!$ok) {
throw new ISPConfigOSException('Timeout waiting for server to come up.');
}
ISPConfigLog::info('Server online again.', true);
}*/
ISPConfigLog::info('Checking hostname.', true);
$host_name = false;
$cmd = 'hostname -f 2>&1';
$check = $this->exec($cmd);
if($check === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
} else {
$host_name = $check;
}/* elseif(trim($check) !== $host_name) {
ISPConfigLog::warn('Hostname mismatch: ' . $check . ' != ' . $host_name);
}*/
$cmd = 'hostname 2>&1';
$check = $this->exec($cmd);
if($check === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}/* elseif(trim($check) !== $short_hostname) {
ISPConfigLog::warn('Short hostname mismatch: ' . $check . ' != ' . $short_hostname);
}*/
if($host_name == '') {
ISPConfigLog::error('Could not read the host name of your server. Please check it is correctly set.', true);
throw new ISPConfigOSException('Invalid host name or host name not found.');
} elseif(substr_count($host_name, '.') < 2) {
ISPConfigLog::error('The host name ' . $host_name . ' of your server is no fully qualified domain name (xyz.domain.com). Please check it is correctly set.', true);
throw new ISPConfigOSException('Host name is no FQDN.');
}
$cmd = 'readlink /bin/sh 2>&1';
$check = trim($this->exec($cmd));
if($check === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
} elseif($check !== 'bash') {
//debconf-show dash
ISPConfigLog::info('Default shell is currently ' . $check . '.', true);
ISPConfigLog::info('Setting bash as default shell.', true);
$cmd = 'echo "dash dash/sh boolean false" | debconf-set-selections && DEBIAN_FRONTEND=noninteractive dpkg-reconfigure dash 2>&1';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$cmd = 'readlink /bin/sh 2>&1';
$check = trim($this->exec($cmd));
ISPConfigLog::info('Default shell is now ' . $check . '.', true);
}
$cmd = 'echo "postfix postfix/mailname string ' . $host_name . '" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "postfix postfix/main_mailer_type select Internet Site" | debconf-set-selections 2>&1';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$packages = array(
'dbconfig-common',
'postfix',
'postfix-mysql',
'postfix-doc',
'mariadb-client',
'mariadb-server',
'openssl',
'getmail4',
'rkhunter',
'binutils',
'dovecot-imapd',
'dovecot-pop3d',
'dovecot-mysql',
'dovecot-sieve',
'dovecot-managesieved',
'dovecot-lmtpd',
'sudo'
);
ISPConfigLog::info('Installing packages ' . implode(', ', $packages), true);
$result = $this->installPackages($packages);
if($result !== false) {
ISPConfigLog::info('Installed packages ' . implode(', ', $packages), true);
} else {
throw new ISPConfigOSException('Installing packages failed.');
}
ISPConfigLog::info('Generating mySQL password.', true);
// generate random password
$mysql_root_pw = ISPConfigFunctions::generatePassword(20);
$escaped_pw = preg_replace('/[\'\\\\]/', '\\$1', $mysql_root_pw);
$queries = array(
'DELETE FROM mysql.user WHERE User=\'\';',
'DELETE FROM mysql.user WHERE User=\'root\' AND Host NOT IN (\'localhost\', \'127.0.0.1\', \'::1\');',
'DROP DATABASE IF EXISTS test;',
'DELETE FROM mysql.db WHERE Db=\'test\' OR Db=\'test\\_%\';',
'UPDATE mysql.user SET Password=PASSWORD(\'' . $escaped_pw . '\') WHERE User=\'root\';',
'UPDATE mysql.user SET plugin = \'mysql_native_password\' WHERE User=\'root\';',
'FLUSH PRIVILEGES;'
);
foreach($queries as $query) {
$cmd = 'mysql --defaults-file=/etc/mysql/debian.cnf -e ' . escapeshellarg($query) . ' 2>&1';
$result = $this->exec($cmd);
if($result === false) {
ISPConfigLog::warn('Query ' . $query . ' failed.', true);
}
}
$this->updateMySQLConfig($mysql_root_pw);
ISPConfigLog::info('Configuring postfix.', true);
$entries = array(
array(
'first_line' => '/^#?submission\s+inet/',
'last_line' => null,
'search' => null,
'add_lines' => array(
' -o syslog_name=postfix/submission',
' -o smtpd_tls_security_level=encrypt',
' -o smtpd_sasl_auth_enable=yes',
' -o smtpd_client_restrictions=permit_sasl_authenticated,reject'
)
),
array(
'first_line' => '/^#?smtps\s+inet/',
'last_line' => null,
'search' => null,
'add_lines' => array(
' -o syslog_name=postfix/smtps',
' -o smtpd_tls_wrappermode=yes',
' -o smtpd_sasl_auth_enable=yes',
' -o smtpd_client_restrictions=permit_sasl_authenticated,reject'
)
)
);
$this->uncommentLines('/etc/postfix/master.cf', $entries);
ISPConfigLog::info('Restarting postfix', true);
$this->restartService('postfix');
$replacements = array(
'/^mysql\s+soft\s+nofile\s+.*/' => 'mysql soft nofile 65535',
'/^mysql\s+hard\s+nofile\s+.*/' => 'mysql hard nofile 65535'
);
$this->replaceContents('/etc/security/limits.conf', $replacements, true);
if(!is_dir('/etc/systemd/system/mysql.service.d/')) {
mkdir('/etc/systemd/system/mysql.service.d/', 0777, true);
}
$replacements = array(
'/^\s*LimitNOFILE\s*=.*?$/m' => 'LimitNOFILE=infinity'
);
$this->replaceContents('/etc/systemd/system/mysql.service.d/limits.conf', $replacements, true, 'Service');
$this->exec('systemctl daemon-reload 2>&1');
$this->restartService('mysql');
$packages = $this->getPackagesToInstall('mail');
ISPConfigLog::info('Installing packages ' . implode(', ', $packages), true);
$result = $this->installPackages($packages);
if($result !== false) {
ISPConfigLog::info('Installed packages ' . implode(', ', $packages), true);
} else {
throw new ISPConfigOSException('Installing packages failed.');
}
ISPConfigLog::info('Stopping Rspamd.', true);
$this->stopService('rspamd');
ISPConfigLog::info('(Re)starting Bind.', true);
$this->restartService('bind9');
ISPConfigLog::info('Disabling spamassassin daemon.', true);
$this->stopService('spamassassin');
$this->exec('systemctl disable spamassassin 2>&1');
$this->afterPackageInstall('mail');
//$cmd = 'sudo -u unbound unbound-anchor -a /var/lib/unbound/root.key';
/*$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$this->restartService('unbound');
*/
if(!is_dir('/etc/resolvconf/resolv.conf.d')) {
mkdir('/etc/resolvconf/resolv.conf.d', 0755);
}
$this->addLines('/etc/resolvconf/resolv.conf.d/head', 'nameserver 127.0.0.1', false);
$cmd = 'resolvconf -u 2>&1';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
ISPConfigLog::info('Checking local dns resolver.', true);
$cmd = 'nslookup denic.de | grep Server';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
} elseif(strpos($result, '127.0.0.1') === false) {
ISPConfigLog::warn('Unexpected resolver response: ' . $result, true);
}
$packages = array(
'apache2',
'apache2-doc',
'apache2-utils',
'libapache2-mod-fcgid',
'apache2-suexec-pristine',
'libapache2-mod-php',
'php-pear',
'php-memcache',
'php-imagick',
'php-gettext',
'mcrypt',
'imagemagick',
'libruby',
'libapache2-mod-python',
'memcached',
'libapache2-mod-passenger',
'php-apcu'
);
$php_versions = array(
'5.6',
'7.0',
'7.1',
'7.2',
'7.3'
);
$php_modules = array(
'common',
'gd',
'mysql',
'imap',
'cli',
'cgi',
'mcrypt',
'curl',
'intl',
'pspell',
'recode',
'sqlite3',
'tidy',
'xmlrpc',
'xsl',
'zip',
'mbstring',
'soap',
'fpm',
'opcache'
);
foreach($php_versions as $curver) {
$packages[] = 'php' . $curver;
reset($php_modules);
foreach($php_modules as $curmod) {
if(version_compare($curver, '7.2', '>=') && in_array($curmod, array('mcrypt'), true)) {
continue;
}
$packages[] = 'php' . $curver . '-' . $curmod;
}
}
ISPConfigLog::info('Installing packages ' . implode(', ', $packages), true);
$result = $this->installPackages($packages);
if($result !== false) {
ISPConfigLog::info('Installed packages ' . implode(', ', $packages), true);
} else {
throw new ISPConfigOSException('Installing packages failed.');
}
ISPConfigLog::info('Enabling apache modules.', true);
$modules = $this->getApacheModulesToEnable();
$cmd = 'a2enmod ' . implode(' ', $modules) . ' 2>&1';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
try {
$this->setPHPTimezone();
$this->setDefaultPHP();
} catch (Exception $ex) {
throw $ex;
}
foreach($php_versions as $curver) {
$this->restartService('php' . $curver . '-fpm');
}
try{
$this->installPHPMyAdmin($mysql_root_pw);
} catch(Exception $ex) {
throw $ex;
}
ISPConfigLog::info('HTTPoxy config.', true);
$httpoxy = '' . "\n" . ' RequestHeader unset Proxy early' . "\n" . '';
file_put_contents('/etc/apache2/conf-available/httpoxy.conf', $httpoxy);
$cmd = 'a2enconf httpoxy 2>&1';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$this->restartService('apache2');
ISPConfigLog::info('Installing letsencrypt (acme.sh).', true);
$cmd = 'cd /tmp ; wget -O - https://get.acme.sh 2>/dev/null | sh 2>/dev/null';
$result = $this->exec($cmd);
if($result === false) {
ISPConfigLog::warn('Installing letsencrypt failed.', true);
} else {
ISPConfigLog::info('Letsencrypt installed.', true);
}
/* TODO: mailman */
$cmd = 'echo "pure-ftpd-common pure-ftpd/standalone-or-inetd select standalone" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "pure-ftpd-common pure-ftpd/virtualchroot boolean true" | debconf-set-selections 2>&1';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$packages = array(
'pure-ftpd-common',
'pure-ftpd-mysql',
'quota',
'quotatool',
'haveged',
'webalizer',
'awstats',
'geoip-database',
'libclass-dbi-mysql-perl',
'libtimedate-perl'
);
ISPConfigLog::info('Installing packages ' . implode(', ', $packages), true);
$result = $this->installPackages($packages);
if($result !== false) {
ISPConfigLog::info('Installed packages ' . implode(', ', $packages), true);
} else {
throw new ISPConfigOSException('Installing packages failed.');
}
/* TODO FTP TLS! */
$this->restartService('pure-ftpd-mysql');
ISPConfigLog::info('Adding quota to fstab.', true);
$replacements = array(
'/^(\S+\s+\/\s+ext\d)\s+(\S+)\s+(\d\s+\d)\s*$/m' => array(
'replace' => '$1 $2,usrjquota=quota.user,grpjquota=quota.group,jqfmt=vfsv0 $3',
'ifnot' => 'usrjquota='
)
);
$this->replaceContents('/etc/fstab', $replacements);
$cmd = 'mount -o remount / 2>&1 && quotaoff -avug 2>&1 && quotacheck -avugm 2>&1 && quotaon -avug 2>&1';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
ISPConfigLog::info('Disabling awstats cron.', true);
$entries = array(
array(
'first_line' => '/.*/',
'last_line' => '/####nomatch###/',
'search' => '/.*/'
)
);
$this->commentLines('/etc/cron.d/awstats', $entries);
$packages = array(
'build-essential',
'autoconf',
'automake',
'libtool',
'flex',
'bison',
'debhelper',
'binutils'
);
ISPConfigLog::info('Installing packages ' . implode(', ', $packages), true);
$result = $this->installPackages($packages);
if($result !== false) {
ISPConfigLog::info('Installed packages ' . implode(', ', $packages), true);
} else {
throw new ISPConfigOSException('Installing packages failed.');
}
$cmd = 'cd /tmp ; ( wget -O jailkit-2.20.tar.gz "http://olivier.sessink.nl/jailkit/jailkit-2.20.tar.gz" > /dev/null 2>&1 && tar xzf jailkit-2.20.tar.gz 2>&1 ) && ( cd jailkit-2.20 ; echo 5 > debian/compat ; ./debian/rules binary 2>&1 ) && ( cd /tmp ; dpkg -i jailkit_2.20-1_*.deb 2>&1 ; rm -rf jailkit-2.20* )';
$result = $this->exec($cmd, array(), 3);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$packages = array(
'fail2ban',
'ufw'
);
ISPConfigLog::info('Installing packages ' . implode(', ', $packages), true);
$result = $this->installPackages($packages);
if($result !== false) {
ISPConfigLog::info('Installed packages ' . implode(', ', $packages), true);
} else {
throw new ISPConfigOSException('Installing packages failed.');
}
$jk_jail = $this->getFail2BanJail();
file_put_contents('/etc/fail2ban/jail.local', $jk_jail);
unset($jk_jail);
$this->restartService('fail2ban');
$this->fixDbconfigCommon();
ISPConfigLog::info('Installing roundcube.', true);
$cmd = 'APP_PASS="' . ISPConfigFunctions::generatePassword(15) . '"' . "\n";
$cmd .= 'ROOT_PASS="' . $mysql_root_pw . '"' . "\n";
$cmd .= 'APP_DB_PASS="' . ISPConfigFunctions::generatePassword(15) . '"' . "\n";
$cmd .= 'echo "roundcube-core roundcube/dbconfig-install boolean true" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "roundcube-core roundcube/database-type select mysql" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "roundcube-core roundcube/mysql/admin-user string root" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "roundcube-core roundcube/mysql/admin-pass password $ROOT_PASS" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "roundcube-core roundcube/mysql/app-pass password $APP_DB_PASS" | debconf-set-selections 2>&1' . "\n";
$cmd .= 'echo "roundcube-core roundcube/reconfigure-webserver multiselect apache2" | debconf-set-selections 2>&1' . "\n";
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$packages = array(
'roundcube',
'roundcube-core',
'roundcube-mysql',
'roundcube-plugins'
);
ISPConfigLog::info('Installing packages ' . implode(', ', $packages), true);
$result = $this->installPackages($packages);
if($result !== false) {
ISPConfigLog::info('Installed packages ' . implode(', ', $packages), true);
} else {
throw new ISPConfigOSException('Installing packages failed.');
}
$replacements = array(
'/^\s*\$config\s*\[["\']default_host["\']\]\s*=.*$/m' => '$config[\'default_host\'] = \'localhost\';',
'/^\s*\$config\s*\[["\']smtp_server["\']\]\s*=.*$/m' => '$config[\'smtp_server\'] = \'%h\';',
'/^\s*\$config\s*\[["\']smtp_user["\']\]\s*=.*$/m' => '$config[\'smtp_user\'] = \'%u\';',
'/^\s*\$config\s*\[["\']smtp_pass["\']\]\s*=.*$/m' => '$config[\'smtp_pass\'] = \'%p\';'
);
$result = $this->replaceContents('/etc/roundcube/config.inc.php', $replacements);
$replacements = array(
'/^\s*#*\s*Alias\s+\/roundcube\s+\/var\/lib\/roundcube\s*$/m' => 'Alias /webmail /var/lib/roundcube'
);
$result = $this->replaceContents('/etc/apache2/conf-enabled/roundcube.conf', $replacements);
$this->restartService('apache2');
ISPConfigLog::info('Installing ISPConfig3.', true);
$ispconfig_admin_pw = ISPConfigFunctions::generatePassword(15);
$autoinstall = '[install]
language=en
install_mode=expert
hostname=' . $host_name . '
mysql_hostname=localhost
mysql_port=3306
mysql_root_user=root
mysql_root_password=' . $mysql_root_pw . '
mysql_database=dbispconfig
mysql_charset=utf8
http_server=apache
ispconfig_port=8080
ispconfig_use_ssl=y
ispconfig_admin_password=' . $ispconfig_admin_pw . '
[ssl_cert]
ssl_cert_country=DE
ssl_cert_state=Dummy
ssl_cert_locality=Dummy
ssl_cert_organisation=Dummy
ssl_cert_organisation_unit=IT
ssl_cert_common_name=' . $host_name . '
ssl_cert_email=
[expert]
mysql_ispconfig_user=ispconfig
mysql_ispconfig_password=' . ISPConfigFunctions::generatePassword(15) . '
join_multiserver_setup=n
mysql_master_hostname=
mysql_master_root_user=
mysql_master_root_password=
mysql_master_database=
configure_mail=y
configure_jailkit=y
configure_ftp=y
configure_dns=y
configure_apache=y
configure_nginx=y
configure_firewall=y
configure_webserver=y
install_ispconfig_web_interface=y
[update]
do_backup=yes
mysql_root_password=' . $mysql_root_pw . '
mysql_master_hostname=
mysql_master_root_user=
mysql_master_root_password=
mysql_master_database=
reconfigure_permissions_in_master_database=no
reconfigure_services=yes
ispconfig_port=8080
create_new_ispconfig_ssl_cert=no
reconfigure_crontab=yes
; These are for service-detection (defaulting to old behaviour where alle changes were automatically accepted)
svc_detect_change_mail_server=yes
svc_detect_change_web_server=yes
svc_detect_change_dns_server=yes
svc_detect_change_xmpp_server=yes
svc_detect_change_firewall_server=yes
svc_detect_change_vserver_server=yes
svc_detect_change_db_server=yes';
file_put_contents('/tmp/ispconfig.autoinstall.ini', $autoinstall);
$cmd = 'cd /tmp ; rm -rf ispconfig3_install 2>&1 ; wget -O ispconfig.tar.gz "https://www.ispconfig.org/downloads/ISPConfig-3-stable.tar.gz" >/dev/null 2>&1 ; tar xzf ispconfig.tar.gz ; cd ispconfig3_install ; cd install ; php -q install.php --autoinstall=/tmp/ispconfig.autoinstall.ini 2>&1 ; cd /tmp ; rm -rf ispconfig3_install 2>&1'; // ispconfig.autoinstall.ini removal!
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
ISPConfigLog::info('Adding php versions to ISPConfig.', true);
$server_id = 0;
$ispc_config = ISPConfigConnector::getLocalConfig();
if(!$ispc_config || !isset($ispc_config['server_id']) || !$ispc_config['server_id']) {
throw new ISPConfigOSException('Could not read ISPConfig settings file.');
}
$server_id = $ispc_config['server_id'];
foreach($php_versions as $curver) {
$qry = 'INSERT IGNORE INTO `dbispconfig`.`server_php` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `client_id`, `name`, `php_fastcgi_binary`, `php_fastcgi_ini_dir`, `php_fpm_init_script`, `php_fpm_ini_dir`, `php_fpm_pool_dir`, `active`) VALUES (1, 1, \'riud\', \'riud\', \'\', ' . intval($server_id) . ', 0, \'PHP ' . $curver . '\', \'/usr/bin/php-cgi' . $curver . '\', \'/etc/php/' . $curver . '/cgi/php.ini\', \'/etc/init.d/php' . $curver . '-fpm\', \'/etc/php/' . $curver . '/fpm/php.ini\', \'/etc/php/' . $curver . '/fpm/pool.d\', \'y\')'; $cmd = 'mysql --defaults-file=/etc/mysql/debian.cnf -e ' . escapeshellarg($qry);
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
}
$this->restartService('clamav-daemon');
ISPConfigLog::info('Checking all services are running.', true);
$check_services = array(
'apache2',
'mysql',
'rspamd',
'clamav-daemon',
'pureftpd',
'postfix',
'dovecot',
'bind9',
'redis-server'
);
foreach($check_services as $service) {
$status = $this->isServiceRunning($service);
ISPConfigLog::info($service . ' :' . ($status ? 'OK' : 'FAILED'), true);
if(!$status) {
ISPConfigLog::warn($service . ' seems not to be running!', true);
}
}
ISPConfigLog::info('Installation ready.', true);
ISPConfigLog::info('Your ISPConfig admin password is: ' . $ispconfig_admin_pw, true);
ISPConfigLog::info('Your MySQL root password is: ' . $mysql_root_pw, true);
return true;
}
}
class.ISPConfigUbuntuOS.inc.php 0000664 0000000 0000000 00000005657 13522573065 0032634 0 ustar 00root root 0000000 0000000 ispconfig-autoinstaller-3c7c92306cca46e8bca4849dbb4e0e8f2656bcbe/lib/os stopService('apparmor');
$this->stopService('sendmail');
$cmd = 'update-rc.d -f apparmor remove ; update-rc.d -f sendmail remove ; apt-get -y -qq remove apparmor apparmor-utils';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
}
protected function getPackagesToInstall($section) {
if($section === 'mail') {
$packages = parent::getPackagesToInstall($section);
}
return $packages;
}
protected function afterPackageInstall($section = '') {
if($section === 'mail') {
$cmd = 'freshclam';
$result = $this->exec($cmd, array(62));
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
$this->startService('clamav-daemon');
}
}
protected function addSuryRepo() {
ISPConfigLog::info('Activating sury php repository.', true);
$cmd = 'add-apt-repository -y ppa:ondrej/php';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
}
protected function getFail2BanJail() {
$jk_jail = '[pure-ftpd]
enabled = true
port = ftp
filter = pure-ftpd
logpath = /var/log/syslog
maxretry = 3
[dovecot]
enabled = true
filter = dovecot
action = iptables-multiport[name=dovecot-pop3imap, port="pop3,pop3s,imap,imaps", protocol=tcp]
logpath = /var/log/mail.log
maxretry = 5
[postfix-sasl]
enabled = true
port = smtp
filter = postfix
logpath = /var/log/mail.log
maxretry = 3';
return $jk_jail;
}
protected function setDefaultPHP() {
ISPConfigLog::info('Settings default system php version.', true);
$cmd = 'update-alternatives --set php /usr/bin/php7.2 ; update-alternatives --set php-cgi /usr/bin/php-cgi7.2';
$result = $this->exec($cmd);
if($result === false) {
throw new ISPConfigOSException('Command ' . $cmd . ' failed.');
}
}
}