From c3cc3d1f6231d72faf723a986ac95182bd33673c Mon Sep 17 00:00:00 2001 From: Michael Kaufmann Date: Tue, 18 Dec 2018 08:38:34 +0100 Subject: [PATCH] started to refactor functions to classes and use PSR-4 autoloader and namespacing Signed-off-by: Michael Kaufmann --- .../Database}/class.Database.php | 274 ++++++++------ lib/Froxlor/FileDir.php | 356 ++++++++++++++++++ lib/Froxlor/PhpHelper.php | 147 ++++++++ .../Settings.php} | 8 +- .../filedir/function.fileImmutable.php | 57 --- .../filedir/function.makeCorrectDir.php | 42 --- .../filedir/function.makeCorrectFile.php | 51 --- .../filedir/function.makeSecurePath.php | 52 --- .../function.mkDirWithCorrectOwnership.php | 109 ------ lib/functions/filedir/function.safe_exec.php | 57 --- .../phphelpers/function.array_trim.php | 41 -- .../phphelpers/function.gethostbynamel6.php | 33 -- .../phphelpers/function.replace_variables.php | 58 --- .../phphelpers/function.size_readable.php | 36 -- 14 files changed, 660 insertions(+), 661 deletions(-) rename lib/{classes/database => Froxlor/Database}/class.Database.php (62%) create mode 100644 lib/Froxlor/FileDir.php create mode 100644 lib/Froxlor/PhpHelper.php rename lib/{classes/settings/class.Settings.php => Froxlor/Settings.php} (98%) delete mode 100644 lib/functions/filedir/function.fileImmutable.php delete mode 100644 lib/functions/filedir/function.makeCorrectDir.php delete mode 100644 lib/functions/filedir/function.makeCorrectFile.php delete mode 100644 lib/functions/filedir/function.makeSecurePath.php delete mode 100644 lib/functions/filedir/function.mkDirWithCorrectOwnership.php delete mode 100644 lib/functions/filedir/function.safe_exec.php delete mode 100644 lib/functions/phphelpers/function.array_trim.php delete mode 100644 lib/functions/phphelpers/function.gethostbynamel6.php delete mode 100644 lib/functions/phphelpers/function.replace_variables.php delete mode 100644 lib/functions/phphelpers/function.size_readable.php diff --git a/lib/classes/database/class.Database.php b/lib/Froxlor/Database/class.Database.php similarity index 62% rename from lib/classes/database/class.Database.php rename to lib/Froxlor/Database/class.Database.php index b5c3f0b7..fb768566 100644 --- a/lib/classes/database/class.Database.php +++ b/lib/Froxlor/Database/class.Database.php @@ -1,4 +1,5 @@ - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Classes - * - * @since 0.9.31 - * + * @copyright (c) the authors + * @author Michael Kaufmann + * @author Froxlor team (2010-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Classes + * + * @since 0.9.31 + * */ /** @@ -23,25 +24,26 @@ * * Wrapper-class for PHP-PDO * - * @copyright (c) the authors - * @author Michael Kaufmann - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Classes - * + * @copyright (c) the authors + * @author Michael Kaufmann + * @author Froxlor team (2010-) + * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt + * @package Classes + * * @method static \PDOStatement prepare($statement, array $driver_options = null) Prepares a statement for execution and returns a statement object * @method static \PDOStatement query ($statement) Executes an SQL statement, returning a result set as a PDOStatement object * @method static string lastInsertId ($name = null) Returns the ID of the last inserted row or sequence value * @method static string quote ($string, $parameter_type = null) Quotes a string for use in a query. */ -class Database { +class Database +{ /** * current database link * * @var object */ - private static $_link = null ; + private static $_link = null; /** * indicator whether to use root-connection or not @@ -62,20 +64,24 @@ class Database { * sql-access data */ private static $_needsqldata = false; + private static $_sqldata = null; /** * Wrapper for PDOStatement::execute so we can catch the PDOException * and display the error nicely on the panel * - * @param PDOStatement $stmt - * @param array $params (optional) - * @param bool $showerror suppress errordisplay (default true) + * @param \PDOStatement $stmt + * @param array $params + * (optional) + * @param bool $showerror + * suppress errordisplay (default true) */ - public static function pexecute(&$stmt, $params = null, $showerror = true, $json_response = false) { + public static function pexecute(&$stmt, $params = null, $showerror = true, $json_response = false) + { try { $stmt->execute($params); - } catch (PDOException $e) { + } catch (\PDOException $e) { self::_showerror($e, $showerror, $json_response, $stmt); } } @@ -85,15 +91,18 @@ class Database { * and display the error nicely on the panel - also fetches the * result from the statement and returns the resulting array * - * @param PDOStatement $stmt - * @param array $params (optional) - * @param bool $showerror suppress errordisplay (default true) - * + * @param \PDOStatement $stmt + * @param array $params + * (optional) + * @param bool $showerror + * suppress errordisplay (default true) + * * @return array */ - public static function pexecute_first(&$stmt, $params = null, $showerror = true, $json_response = false) { + public static function pexecute_first(&$stmt, $params = null, $showerror = true, $json_response = false) + { self::pexecute($stmt, $params, $showerror, $json_response); - return $stmt->fetch(PDO::FETCH_ASSOC); + return $stmt->fetch(\PDO::FETCH_ASSOC); } /** @@ -101,7 +110,8 @@ class Database { * * @return int */ - public static function num_rows() { + public static function num_rows() + { return Database::query("SELECT FOUND_ROWS()")->fetchColumn(); } @@ -110,7 +120,8 @@ class Database { * * @return string */ - public static function getDbName() { + public static function getDbName() + { return self::$_dbname; } @@ -121,9 +132,11 @@ class Database { * the 'normal' database-connection * * @param bool $needroot - * @param int $dbserver optional + * @param int $dbserver + * optional */ - public static function needRoot($needroot = false, $dbserver = 0) { + public static function needRoot($needroot = false, $dbserver = 0) + { // force re-connecting to the db with corresponding user // and set the $dbserver (mostly to 0 = default) self::_setServer($dbserver); @@ -133,12 +146,13 @@ class Database { /** * enable the temporary access to sql-access data * note: if you want root-sqldata you need to - * call needRoot(true) first. Also, this will + * call needRoot(true) first. + * Also, this will * only give you the data ONCE as it disable itself * after the first access to the data - * */ - public static function needSqlData() { + public static function needSqlData() + { self::$_needsqldata = true; self::$_sqldata = array(); self::$_link = null; @@ -152,16 +166,15 @@ class Database { /** * returns the sql-access data as array using indeces - * 'user', 'passwd' and 'host'. Returns false if not enabled + * 'user', 'passwd' and 'host'. + * Returns false if not enabled * * @return array|bool */ - public static function getSqlData() { + public static function getSqlData() + { $return = false; - if (self::$_sqldata !== null - && is_array(self::$_sqldata) - && isset(self::$_sqldata['user']) - ) { + if (self::$_sqldata !== null && is_array(self::$_sqldata) && isset(self::$_sqldata['user'])) { $return = self::$_sqldata; // automatically disable sql-data self::$_sqldata = null; @@ -179,12 +192,16 @@ class Database { * * @return mixed */ - public static function __callStatic($name, $args) { - $callback = array(self::getDB(), $name); + public static function __callStatic($name, $args) + { + $callback = array( + self::getDB(), + $name + ); $result = null; try { - $result = call_user_func_array($callback, $args ); - } catch (PDOException $e) { + $result = call_user_func_array($callback, $args); + } catch (\PDOException $e) { self::_showerror($e); } return $result; @@ -195,7 +212,8 @@ class Database { * * @param int $dbserver */ - private static function _setServer($dbserver = 0) { + private static function _setServer($dbserver = 0) + { self::$_dbserver = $dbserver; self::$_link = null; } @@ -208,10 +226,10 @@ class Database { * * @return object */ - private static function getDB() { - - if (!extension_loaded('pdo') || in_array("mysql", PDO::getAvailableDrivers()) == false) { - self::_showerror(new Exception("The php PDO extension or PDO-MySQL driver is not available")); + private static function getDB() + { + if (! extension_loaded('pdo') || in_array("mysql", \PDO::getAvailableDrivers()) == false) { + self::_showerror(new \Exception("The php PDO extension or PDO-MySQL driver is not available")); } // do we got a connection already? @@ -221,15 +239,19 @@ class Database { } // include userdata.inc.php - require FROXLOR_INSTALL_DIR."/lib/userdata.inc.php"; + require FROXLOR_INSTALL_DIR . "/lib/userdata.inc.php"; // le format - if (self::$_needroot == true - && isset($sql['root_user']) - && isset($sql['root_password']) - && (!isset($sql_root) || !is_array($sql_root)) - ) { - $sql_root = array(0 => array('caption' => 'Default', 'host' => $sql['host'], 'socket' => (isset($sql['socket']) ? $sql['socket'] : null), 'user' => $sql['root_user'], 'password' => $sql['root_password'])); + if (self::$_needroot == true && isset($sql['root_user']) && isset($sql['root_password']) && (! isset($sql_root) || ! is_array($sql_root))) { + $sql_root = array( + 0 => array( + 'caption' => 'Default', + 'host' => $sql['host'], + 'socket' => (isset($sql['socket']) ? $sql['socket'] : null), + 'user' => $sql['root_user'], + 'password' => $sql['root_password'] + ) + ); unset($sql['root_user']); unset($sql['root_password']); } @@ -254,27 +276,29 @@ class Database { // save sql-access-data if needed if (self::$_needsqldata) { self::$_sqldata = array( - 'user' => $user, - 'passwd' => $password, - 'host' => $host, - 'port' => $port, - 'socket' => $socket, - 'db' => $sql["db"], - 'caption' => $caption + 'user' => $user, + 'passwd' => $password, + 'host' => $host, + 'port' => $port, + 'socket' => $socket, + 'db' => $sql["db"], + 'caption' => $caption ); } // build up connection string $driver = 'mysql'; - $dsn = $driver.":"; + $dsn = $driver . ":"; $options = array( 'PDO::MYSQL_ATTR_INIT_COMMAND' => 'SET names utf8' ); - $attributes = array('ATTR_ERRMODE' => 'ERRMODE_EXCEPTION'); + $attributes = array( + 'ATTR_ERRMODE' => 'ERRMODE_EXCEPTION' + ); $dbconf["dsn"] = array( - 'dbname' => $sql["db"], - 'charset' => 'utf8' + 'dbname' => $sql["db"], + 'charset' => 'utf8' ); if ($socket != null) { @@ -288,7 +312,7 @@ class Database { // add options to dsn-string foreach ($dbconf["dsn"] as $k => $v) { - $dsn .= $k."=".$v.";"; + $dsn .= $k . "=" . $v . ";"; } // clean up @@ -296,22 +320,22 @@ class Database { // try to connect try { - self::$_link = new PDO($dsn, $user, $password, $options); - } catch (PDOException $e) { + self::$_link = new \PDO($dsn, $user, $password, $options); + } catch (\PDOException $e) { self::_showerror($e); } // set attributes foreach ($attributes as $k => $v) { - self::$_link->setAttribute(constant("PDO::".$k), constant("PDO::".$v)); + self::$_link->setAttribute(constant("PDO::" . $k), constant("PDO::" . $v)); } - $version_server = self::$_link->getAttribute(PDO::ATTR_SERVER_VERSION); + $version_server = self::$_link->getAttribute(\PDO::ATTR_SERVER_VERSION); $sql_mode = 'NO_ENGINE_SUBSTITUTION'; if (version_compare($version_server, '8.0.11', '<')) { $sql_mode .= ',NO_AUTO_CREATE_USER'; } - self::$_link->exec('SET sql_mode = "'.$sql_mode.'"'); + self::$_link->exec('SET sql_mode = "' . $sql_mode . '"'); // return PDO instance return self::$_link; @@ -320,26 +344,33 @@ class Database { /** * display a nice error if it occurs and log everything * - * @param PDOException $error - * @param bool $showerror if set to false, the error will be logged but we go on + * @param \PDOException $error + * @param bool $showerror + * if set to false, the error will be logged but we go on */ - private static function _showerror($error, $showerror = true, $json_response = false, PDOStatement $stmt = null) { + private static function _showerror($error, $showerror = true, $json_response = false, \PDOStatement $stmt = null) + { global $userinfo, $theme, $linker; // include userdata.inc.php - require FROXLOR_INSTALL_DIR."/lib/userdata.inc.php"; + require FROXLOR_INSTALL_DIR . "/lib/userdata.inc.php"; // le format - if (isset($sql['root_user']) - && isset($sql['root_password']) - && (!isset($sql_root) || !is_array($sql_root)) - ) { - $sql_root = array(0 => array('caption' => 'Default', 'host' => $sql['host'], 'socket' => (isset($sql['socket']) ? $sql['socket'] : null), 'user' => $sql['root_user'], 'password' => $sql['root_password'])); + if (isset($sql['root_user']) && isset($sql['root_password']) && (! isset($sql_root) || ! is_array($sql_root))) { + $sql_root = array( + 0 => array( + 'caption' => 'Default', + 'host' => $sql['host'], + 'socket' => (isset($sql['socket']) ? $sql['socket'] : null), + 'user' => $sql['root_user'], + 'password' => $sql['root_password'] + ) + ); } $substitutions = array( $sql['password'] => 'DB_UNPRIV_PWD', - $sql_root[0]['password'] => 'DB_ROOT_PWD', + $sql_root[0]['password'] => 'DB_ROOT_PWD' ); // hide username/password in messages @@ -351,48 +382,48 @@ class Database { $error_trace = self::_substitute($error_trace, $substitutions); if ($error->getCode() == 2003) { - $error_message = "Unable to connect to database. Either the mysql-server is not running or your user/password is wrong."; - $error_trace = ""; + $error_message = "Unable to connect to database. Either the mysql-server is not running or your user/password is wrong."; + $error_trace = ""; } /** * log to a file, so we can actually ask people for the error * (no one seems to find the stuff in the syslog) */ - $sl_dir = makeCorrectDir(FROXLOR_INSTALL_DIR."/logs/"); - if (!file_exists($sl_dir)) { + $sl_dir = makeCorrectDir(FROXLOR_INSTALL_DIR . "/logs/"); + if (! file_exists($sl_dir)) { @mkdir($sl_dir, 0755); } openlog("froxlor", LOG_PID | LOG_PERROR, LOG_LOCAL0); syslog(LOG_WARNING, str_replace("\n", " ", $error_message)); - syslog(LOG_WARNING, str_replace("\n", " ", "--- DEBUG: ".$error_trace)); + syslog(LOG_WARNING, str_replace("\n", " ", "--- DEBUG: " . $error_trace)); closelog(); /** * log error for reporting - */ + */ $errid = substr(md5(microtime()), 5, 5); - $err_file = makeCorrectFile($sl_dir."/".$errid."_sql-error.log"); + $err_file = makeCorrectFile($sl_dir . "/" . $errid . "_sql-error.log"); $errlog = @fopen($err_file, 'w'); - @fwrite($errlog, "|CODE ".$error->getCode()."\n"); - @fwrite($errlog, "|MSG ".$error_message."\n"); - @fwrite($errlog, "|FILE ".$error->getFile()."\n"); - @fwrite($errlog, "|LINE ".$error->getLine()."\n"); - @fwrite($errlog, "|TRACE\n".$error_trace."\n"); + @fwrite($errlog, "|CODE " . $error->getCode() . "\n"); + @fwrite($errlog, "|MSG " . $error_message . "\n"); + @fwrite($errlog, "|FILE " . $error->getFile() . "\n"); + @fwrite($errlog, "|LINE " . $error->getLine() . "\n"); + @fwrite($errlog, "|TRACE\n" . $error_trace . "\n"); @fclose($errlog); if (empty($sql['debug'])) { $error_trace = ''; - } elseif (!is_null($stmt)) { - $error_trace .= "

".$stmt->queryString; + } elseif (! is_null($stmt)) { + $error_trace .= "

" . $stmt->queryString; } if ($showerror && $json_response) { $exception_message = $error_message; if (isset($sql['debug']) && $sql['debug'] == true) { - $exception_message .= "\n\n".$error_trace; + $exception_message .= "\n\n" . $error_trace; } - throw new Exception($exception_message, 500); + throw new \Exception($exception_message, 500); } if ($showerror) { @@ -403,11 +434,9 @@ class Database { unset($sql); unset($sql_root); - if ((isset($theme) && $theme != '') - && !isset($_SERVER['SHELL']) || (isset($_SERVER['SHELL']) && $_SERVER['SHELL'] == '') - ) { + if ((isset($theme) && $theme != '') && ! isset($_SERVER['SHELL']) || (isset($_SERVER['SHELL']) && $_SERVER['SHELL'] == '')) { // if we're not on the shell, output a nice error - $_errtpl = dirname($sl_dir).'/templates/'.$theme.'/misc/dberrornice.tpl'; + $_errtpl = dirname($sl_dir) . '/templates/' . $theme . '/misc/dberrornice.tpl'; if (file_exists($_errtpl)) { $err_hint = file_get_contents($_errtpl); // replace values @@ -416,12 +445,13 @@ class Database { $err_hint = str_replace("", date('Y', time()), $err_hint); $err_report_html = ''; - if (is_array($userinfo) && ( - ($userinfo['adminsession'] == '1' && Settings::Get('system.allow_error_report_admin') == '1') - || ($userinfo['adminsession'] == '0' && Settings::Get('system.allow_error_report_customer') == '1')) - ) { + if (is_array($userinfo) && (($userinfo['adminsession'] == '1' && \Froxlor\Settings::Get('system.allow_error_report_admin') == '1') || ($userinfo['adminsession'] == '0' && \Froxlor\Settings::Get('system.allow_error_report_customer') == '1'))) { $err_report_html = 'Report error'; - $err_report_html = str_replace("", $linker->getLink(array('section' => 'index', 'page' => 'send_error_report', 'errorid' => $errid)), $err_report_html); + $err_report_html = str_replace("", $linker->getLink(array( + 'section' => 'index', + 'page' => 'send_error_report', + 'errorid' => $errid + )), $err_report_html); } $err_hint = str_replace("", $err_report_html, $err_hint); @@ -441,18 +471,15 @@ class Database { * @param int $minLength * @return string */ - private static function _substitute($content, array $substitutions, $minLength = 6) { + private static function _substitute($content, array $substitutions, $minLength = 6) + { $replacements = array(); foreach ($substitutions as $search => $replace) { $replacements = $replacements + self::_createShiftedSubstitutions($search, $replace, $minLength); } - $content = str_replace( - array_keys($replacements), - array_values($replacements), - $content - ); + $content = str_replace(array_keys($replacements), array_values($replacements), $content); return $content; } @@ -461,25 +488,26 @@ class Database { * Creates substitutions, shifted by length, e.g. * * _createShiftedSubstitutions('abcdefgh', 'value', 4): - * array( - * 'abcdefgh' => 'value', - * 'abcdefg' => 'value', - * 'abcdef' => 'value', - * 'abcde' => 'value', - * 'abcd' => 'value', - * ) + * array( + * 'abcdefgh' => 'value', + * 'abcdefg' => 'value', + * 'abcdef' => 'value', + * 'abcde' => 'value', + * 'abcd' => 'value', + * ) * * @param string $search * @param string $replace * @param int $minLength * @return array */ - private static function _createShiftedSubstitutions($search, $replace, $minLength) { + private static function _createShiftedSubstitutions($search, $replace, $minLength) + { $substitutions = array(); $length = strlen($search); if ($length > $minLength) { - for ($shiftedLength = $length; $shiftedLength >= $minLength; $shiftedLength--) { + for ($shiftedLength = $length; $shiftedLength >= $minLength; $shiftedLength --) { $substitutions[substr($search, 0, $shiftedLength)] = $replace; } } diff --git a/lib/Froxlor/FileDir.php b/lib/Froxlor/FileDir.php new file mode 100644 index 00000000..fae596c2 --- /dev/null +++ b/lib/Froxlor/FileDir.php @@ -0,0 +1,356 @@ +', + '<', + '`', + '$', + '~', + '?' + ); + + $acheck = false; + if ($allowedChars != null && is_array($allowedChars) && count($allowedChars) > 0) { + $acheck = true; + } + + foreach ($disallowed as $dc) { + if ($acheck && in_array($dc, $allowedChars)) + continue; + // check for bad signs in execute command + if (stristr($exec_string, $dc)) { + die("SECURITY CHECK FAILED!\nThe execute string '" . $exec_string . "' is a possible security risk!\nPlease check your whole server for security problems by hand!\n"); + } + } + + // execute the command and return output + $return = ''; + + // ------------------------------------------------------------------------------- + if ($return_value == false) { + exec($exec_string, $return); + } else { + exec($exec_string, $return, $return_value); + } + + return $return; + } + + /** + * Creates a directory below a users homedir and sets all directories, + * which had to be created below with correct Owner/Group + * (Copied from cron_tasks.php:rev1189 as we'll need this more often in future) + * + * @param string $homeDir + * The homedir of the user + * @param string $dirToCreate + * The dir which should be created + * @param int $uid + * The uid of the user + * @param int $gid + * The gid of the user + * @param bool $placeindex + * Place standard-index.html into the new folder + * @param bool $allow_notwithinhomedir + * Allow creating a directory out of the customers docroot + * + * @return bool true if everything went okay, false if something went wrong + */ + public static function mkDirWithCorrectOwnership($homeDir, $dirToCreate, $uid, $gid, $placeindex = false, $allow_notwithinhomedir = false) + { + if ($homeDir != '' && $dirToCreate != '') { + $homeDir = self::makeCorrectDir($homeDir); + $dirToCreate = self::makeCorrectDir($dirToCreate); + + if (substr($dirToCreate, 0, strlen($homeDir)) == $homeDir) { + $subdir = substr($dirToCreate, strlen($homeDir) - 1); + $within_homedir = true; + } else { + $subdir = $dirToCreate; + $within_homedir = false; + } + + $subdir = self::makeCorrectDir($subdir); + $subdirs = array(); + + if ($within_homedir || ! $allow_notwithinhomedir) { + $subdirlen = strlen($subdir); + $offset = 0; + + while ($offset < $subdirlen) { + $offset = strpos($subdir, '/', $offset); + $subdirelem = substr($subdir, 0, $offset); + $offset ++; + array_push($subdirs, self::makeCorrectDir($homeDir . $subdirelem)); + } + } else { + array_push($subdirs, $dirToCreate); + } + + $subdirs = array_unique($subdirs); + sort($subdirs); + foreach ($subdirs as $sdir) { + if (! is_dir($sdir)) { + $sdir = self::makeCorrectDir($sdir); + self::safe_exec('mkdir -p ' . escapeshellarg($sdir)); + // place index + if ($placeindex) { + // @fixme + $loginname = getLoginNameByUid($uid); + if ($loginname !== false) { + // @fixme + storeDefaultIndex($loginname, $sdir, null); + } + } + self::safe_exec('chown -R ' . (int) $uid . ':' . (int) $gid . ' ' . escapeshellarg($sdir)); + } + } + return true; + } + return false; + } + + /** + * store the default index-file in a given destination folder + * + * @param string $loginname customers loginname + * @param string $destination path where to create the file + * @param object $logger FroxlorLogger object + * @param boolean $force force creation whatever the settings say (needed for task #2, create new user) + * + * @return null + */ + public static function storeDefaultIndex($loginname = null, $destination = null, $logger = null, $force = false) { + + if ($force + || (int)Settings::Get('system.store_index_file_subs') == 1 + ) { + $result_stmt = Database::prepare(" + SELECT `t`.`value`, `c`.`email` AS `customer_email`, `a`.`email` AS `admin_email`, `c`.`loginname` AS `customer_login`, `a`.`loginname` AS `admin_login` + FROM `" . TABLE_PANEL_CUSTOMERS . "` AS `c` INNER JOIN `" . TABLE_PANEL_ADMINS . "` AS `a` + ON `c`.`adminid` = `a`.`adminid` + INNER JOIN `" . TABLE_PANEL_TEMPLATES . "` AS `t` + ON `a`.`adminid` = `t`.`adminid` + WHERE `varname` = 'index_html' AND `c`.`loginname` = :loginname"); + Database::pexecute($result_stmt, array('loginname' => $loginname)); + + if (Database::num_rows() > 0) { + + $template = $result_stmt->fetch(\PDO::FETCH_ASSOC); + + $replace_arr = array( + 'SERVERNAME' => Settings::Get('system.hostname'), + 'CUSTOMER' => $template['customer_login'], + 'ADMIN' => $template['admin_login'], + 'CUSTOMER_EMAIL' => $template['customer_email'], + 'ADMIN_EMAIL' => $template['admin_email'] + ); + + // @fixme replace_variables + $htmlcontent = PhpHelper::replace_variables($template['value'], $replace_arr); + $indexhtmlpath = self::makeCorrectFile($destination . '/index.' . Settings::Get('system.index_file_extension')); + $index_html_handler = fopen($indexhtmlpath, 'w'); + fwrite($index_html_handler, $htmlcontent); + fclose($index_html_handler); + if ($logger !== null) { + $logger->logAction(CRON_ACTION, LOG_NOTICE, 'Creating \'index.' . Settings::Get('system.index_file_extension') . '\' for Customer \'' . $template['customer_login'] . '\' based on template in directory ' . escapeshellarg($indexhtmlpath)); + } + + } else { + $destination = self::makeCorrectDir($destination); + if ($logger !== null) { + $logger->logAction(CRON_ACTION, LOG_NOTICE, 'Running: cp -a ' . FROXLOR_INSTALL_DIR . '/templates/misc/standardcustomer/* ' . escapeshellarg($destination)); + } + self::safe_exec('cp -a ' . FROXLOR_INSTALL_DIR . '/templates/misc/standardcustomer/* ' . escapeshellarg($destination)); + } + } + return; + } + + /** + * Function which returns a correct filename, means to add a slash at the beginning if there wasn't one + * + * @param string $filename + * the filename + * + * @return string the corrected filename + */ + public static function makeCorrectFile($filename) + { + if (! isset($filename) || trim($filename) == '') { + $error = 'Given filename for function ' . __FUNCTION__ . ' is empty.' . "\n"; + $error .= 'This is very dangerous and should not happen.' . "\n"; + $error .= 'Please inform the Froxlor team about this issue so they can fix it.'; + echo $error; + // so we can see WHERE this happened + debug_print_backtrace(); + die(); + } + + if (substr($filename, 0, 1) != '/') { + $filename = '/' . $filename; + } + + $filename = self::makeSecurePath($filename); + return $filename; + } + + /** + * Function which returns a correct dirname, means to add slashes at the beginning and at the end if there weren't some + * + * @param string $path + * the path to correct + * + * @throws \Exception + * @return string the corrected path + */ + public static function makeCorrectDir($dir) + { + if (is_string($dir) && strlen($dir) > 0) { + $dir = trim($dir); + if (substr($dir, - 1, 1) != '/') { + $dir .= '/'; + } + if (substr($dir, 0, 1) != '/') { + $dir = '/' . $dir; + } + return self::makeSecurePath($dir); + } + throw new \Exception("Cannot validate directory in " . __FUNCTION__ . " which is very dangerous."); + } + + /** + * Function which returns a secure path, means to remove all multiple dots and slashes + * + * @param string $path + * the path to secure + * + * @return string the corrected path + */ + public static function makeSecurePath($path) + { + + // check for bad characters, some are allowed with escaping + // but we generally don't want them in our directory-names, + // thx to aaronmueller for this snipped + $badchars = array( + ':', + ';', + '|', + '&', + '>', + '<', + '`', + '$', + '~', + '?', + "\0" + ); + foreach ($badchars as $bc) { + $path = str_replace($bc, "", $path); + } + + $search = array( + '#/+#', + '#\.+#' + ); + $replace = array( + '/', + '.' + ); + $path = preg_replace($search, $replace, $path); + // don't just replace a space with an escaped space + // it might be escaped already + $path = str_replace("\ ", " ", $path); + $path = str_replace(" ", "\ ", $path); + + return $path; + } + + /** + * check if the system is FreeBSD (if exact) + * or BSD-based (NetBSD, OpenBSD, etc. + * if exact = false [default]) + * + * @param boolean $exact + * whether to check explicitly for FreeBSD or *BSD + * + * @return boolean + */ + public static function isFreeBSD($exact = false) + { + if (($exact && PHP_OS == 'FreeBSD') || (! $exact && stristr(PHP_OS, 'BSD'))) { + return true; + } + return false; + } + + /** + * set the immutable flag for a file + * + * @param string $filename + * the file to set the flag for + * + * @return boolean + */ + public static function setImmutable($filename = null) + { + safe_exec(self::getImmutableFunction(false) . escapeshellarg($filename)); + } + + /** + * removes the immutable flag for a file + * + * @param string $filename + * the file to set the flag for + * + * @return boolean + */ + public static function removeImmutable($filename = null) + { + safe_exec(self::getImmutableFunction(true) . escapeshellarg($filename)); + } + + /** + * internal function to check whether + * to use chattr (Linux) or chflags (FreeBSD) + * + * @param boolean $remove + * whether to use +i|schg (false) or -i|noschg (true) + * + * @return string functionname + parameter (not the file) + */ + private static function getImmutableFunction($remove = false) + { + if (self::isFreeBSD()) { + // FreeBSD style + return 'chflags ' . (($remove === true) ? 'noschg ' : 'schg '); + } else { + // Linux style + return 'chattr ' . (($remove === true) ? '-i ' : '+i '); + } + } +} \ No newline at end of file diff --git a/lib/Froxlor/PhpHelper.php b/lib/Froxlor/PhpHelper.php new file mode 100644 index 00000000..3ff055d7 --- /dev/null +++ b/lib/Froxlor/PhpHelper.php @@ -0,0 +1,147 @@ + array( + 'prefix' => array( + 'B', + 'KB', + 'MB', + 'GB', + 'TB', + 'PB' + ), + 'size' => 1000 + ), + 'bi' => array( + 'prefix' => array( + 'B', + 'KiB', + 'MiB', + 'GiB', + 'TiB', + 'PiB' + ), + 'size' => 1024 + ) + ); + $sys = isset($systems[$system]) ? $systems[$system] : $systems['si']; + + // Max unit to display + $depth = count($sys['prefix']) - 1; + if ($max && false !== $d = array_search($max, $sys['prefix'])) { + $depth = $d; + } + // Loop + $i = 0; + while ($size >= $sys['size'] && $i < $depth) { + $size /= $sys['size']; + $i ++; + } + + return sprintf($retstring, $size, $sys['prefix'][$i]); + } + + /** + * Replaces all occurrences of variables defined in the second argument + * in the first argument with their values. + * + * @param string $text + * The string that should be searched for variables + * @param array $vars + * The array containing the variables with their values + * + * @return string The submitted string with the variables replaced. + */ + public static function replace_variables($text, $vars) + { + $pattern = "/\{([a-zA-Z0-9\-_]+)\}/"; + $matches = array(); + + if (count($vars) > 0 && preg_match_all($pattern, $text, $matches)) { + for ($i = 0; $i < count($matches[1]); $i ++) { + $current = $matches[1][$i]; + + if (isset($vars[$current])) { + $var = $vars[$current]; + $text = str_replace("{" . $current . "}", $var, $text); + } + } + } + + $text = str_replace('\n', "\n", $text); + return $text; + } + + /** + * Returns array with all empty-values removed + * + * @param array $source + * The array to trim + * @return array The trim'med array + */ + function array_trim($source) + { + $returnval = array(); + if (is_array($source)) { + $source = array_map('trim', $source); + $source = array_filter($source, function ($value) { + return $value !== ''; + }); + } else { + $returnval = $source; + } + return $returnval; + } +} diff --git a/lib/classes/settings/class.Settings.php b/lib/Froxlor/Settings.php similarity index 98% rename from lib/classes/settings/class.Settings.php rename to lib/Froxlor/Settings.php index 3ab57ecb..e47f6ee3 100644 --- a/lib/classes/settings/class.Settings.php +++ b/lib/Froxlor/Settings.php @@ -1,5 +1,9 @@ fetch(PDO::FETCH_ASSOC)) { + while ($row = $result_stmt->fetch(\PDO::FETCH_ASSOC)) { self::$_data[$row['settinggroup']][$row['varname']] = $row['value']; } return true; diff --git a/lib/functions/filedir/function.fileImmutable.php b/lib/functions/filedir/function.fileImmutable.php deleted file mode 100644 index 2195ff89..00000000 --- a/lib/functions/filedir/function.fileImmutable.php +++ /dev/null @@ -1,57 +0,0 @@ - (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Functions - * - */ - -/** - * set the immutable flag for a file - * - * @param string $filename the file to set the flag for - * - * @return boolean - */ -function setImmutable($filename = null) { - safe_exec(_getImmutableFunction(false).escapeshellarg($filename)); -} - -/** - * removes the immutable flag for a file - * - * @param string $filename the file to set the flag for - * - * @return boolean - */ -function removeImmutable($filename = null) { - safe_exec(_getImmutableFunction(true).escapeshellarg($filename)); -} - -/** - * internal function to check whether - * to use chattr (Linux) or chflags (FreeBSD) - * - * @param boolean $remove whether to use +i|schg (false) or -i|noschg (true) - * - * @return string functionname + parameter (not the file) - */ -function _getImmutableFunction($remove = false) { - - if (isFreeBSD()) { - // FreeBSD style - return 'chflags '.(($remove === true) ? 'noschg ' : 'schg '); - } else { - // Linux style - return 'chattr '.(($remove === true) ? '-i ' : '+i '); - } -} diff --git a/lib/functions/filedir/function.makeCorrectDir.php b/lib/functions/filedir/function.makeCorrectDir.php deleted file mode 100644 index b3ac5cba..00000000 --- a/lib/functions/filedir/function.makeCorrectDir.php +++ /dev/null @@ -1,42 +0,0 @@ - (2003-2009) - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Functions - * - */ - -/** - * Function which returns a correct dirname, means to add slashes at the beginning and at the end if there weren't some - * - * @param string $dir - * The dirname - * - * @return string The corrected dirname - */ -function makeCorrectDir($dir) -{ - if (is_string($dir) && strlen($dir) > 0) { - $dir = trim($dir); - if (substr($dir, - 1, 1) != '/') { - $dir .= '/'; - } - if (substr($dir, 0, 1) != '/') { - $dir = '/' . $dir; - } - $dir = makeSecurePath($dir); - return $dir; - } - throw new Exception("Cannot validate directory in " . __FUNCTION__ . " which is very dangerous."); -} diff --git a/lib/functions/filedir/function.makeCorrectFile.php b/lib/functions/filedir/function.makeCorrectFile.php deleted file mode 100644 index aaa3dee2..00000000 --- a/lib/functions/filedir/function.makeCorrectFile.php +++ /dev/null @@ -1,51 +0,0 @@ - (2003-2009) - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Functions - * - */ - -/** - * Function which returns a correct filename, means to add a slash at the beginning if there wasn't one - * - * @param string filename the filename - * @return string the corrected filename - * @author Florian Lippert - * @author Michael Russ - * @author Martin Burchert - */ - -function makeCorrectFile($filename) -{ - if (!isset($filename) - || trim($filename) == '' - ) { - $error = 'Given filename for function '.__FUNCTION__.' is empty.'."\n"; - $error.= 'This is very dangerous and should not happen.'."\n"; - $error.= 'Please inform the Froxlor team about this issue so they can fix it.'; - echo $error; - // so we can see WHERE this happened - debug_print_backtrace(); - die(); - } - - if(substr($filename, 0, 1) != '/') - { - $filename = '/' . $filename; - } - - $filename = makeSecurePath($filename); - return $filename; -} diff --git a/lib/functions/filedir/function.makeSecurePath.php b/lib/functions/filedir/function.makeSecurePath.php deleted file mode 100644 index 4cc3f9a3..00000000 --- a/lib/functions/filedir/function.makeSecurePath.php +++ /dev/null @@ -1,52 +0,0 @@ - (2003-2009) - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Functions - * - */ - -/** - * Function which returns a secure path, means to remove all multiple dots and slashes - * - * @param string The path - * @return string The corrected path - * @author Florian Lippert - */ -function makeSecurePath($path) { - - // check for bad characters, some are allowed with escaping - // but we generally don't want them in our directory-names, - // thx to aaronmueller for this snipped - $badchars = array(':', ';', '|', '&', '>', '<', '`', '$', '~', '?', "\0"); - foreach ($badchars as $bc) { - $path = str_replace($bc, "", $path); - } - - $search = array( - '#/+#', - '#\.+#' - ); - $replace = array( - '/', - '.' - ); - $path = preg_replace($search, $replace, $path); - // don't just replace a space with an escaped space - // it might be escaped already - $path = str_replace("\ ", " ", $path); - $path = str_replace(" ", "\ ", $path); - - return $path; -} diff --git a/lib/functions/filedir/function.mkDirWithCorrectOwnership.php b/lib/functions/filedir/function.mkDirWithCorrectOwnership.php deleted file mode 100644 index 97e739ba..00000000 --- a/lib/functions/filedir/function.mkDirWithCorrectOwnership.php +++ /dev/null @@ -1,109 +0,0 @@ - (2003-2009) - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Functions - * - */ - -/** - * Creates a directory below a users homedir and sets all directories, - * which had to be created below with correct Owner/Group - * (Copied from cron_tasks.php:rev1189 as we'll need this more often in future) - * - * @param string The homedir of the user - * @param string The dir which should be created - * @param int The uid of the user - * @param int The gid of the user - * @param bool Place standard-index.html into the new folder - * @param bool Allow creating a directory out of the customers docroot - * - * @return bool true if everything went okay, false if something went wrong - * - * @author Florian Lippert - * @author Martin Burchert - */ - -function mkDirWithCorrectOwnership($homeDir, $dirToCreate, $uid, $gid, $placeindex = false, $allow_notwithinhomedir = false) -{ - $returncode = true; - - if($homeDir != '' - && $dirToCreate != '') - { - $homeDir = makeCorrectDir($homeDir); - $dirToCreate = makeCorrectDir($dirToCreate); - - if(substr($dirToCreate, 0, strlen($homeDir)) == $homeDir) - { - $subdir = substr($dirToCreate, strlen($homeDir) - 1); - $within_homedir = true; - } - else - { - $subdir = $dirToCreate; - $within_homedir = false; - } - - $subdir = makeCorrectDir($subdir); - $subdirs = array(); - - if($within_homedir || !$allow_notwithinhomedir) - { - $subdirlen = strlen($subdir); - $offset = 0; - - while($offset < $subdirlen) - { - $offset = strpos($subdir, '/', $offset); - $subdirelem = substr($subdir, 0, $offset); - $offset++; - array_push($subdirs, makeCorrectDir($homeDir . $subdirelem)); - } - } - else - { - array_push($subdirs, $dirToCreate); - } - - $subdirs = array_unique($subdirs); - sort($subdirs); - foreach($subdirs as $sdir) - { - if(!is_dir($sdir)) - { - $sdir = makeCorrectDir($sdir); - safe_exec('mkdir -p ' . escapeshellarg($sdir)); - - /** - * #68 - */ - if ($placeindex) { - $loginname = getLoginNameByUid($uid); - if ($loginname !== false) { - storeDefaultIndex($loginname, $sdir, null); - } - } - - safe_exec('chown -R ' . (int)$uid . ':' . (int)$gid . ' ' . escapeshellarg($sdir)); - } - } - } - else - { - $returncode = false; - } - - return $returncode; -} diff --git a/lib/functions/filedir/function.safe_exec.php b/lib/functions/filedir/function.safe_exec.php deleted file mode 100644 index 98f765fc..00000000 --- a/lib/functions/filedir/function.safe_exec.php +++ /dev/null @@ -1,57 +0,0 @@ - (2003-2009) - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Functions - * - */ - -/** - * Wrapper around the exec command. - * - * @param string $exec_string command to be executed - * @param string $return_value referenced variable where the output is stored - * @param array $allowedChars optional array of allowed characters in path/command - * - * @return string result of exec() - */ -function safe_exec($exec_string, &$return_value = false, $allowedChars = null) { - - $disallowed = array(';', '|', '&', '>', '<', '`', '$', '~', '?'); - - $acheck = false; - if ($allowedChars != null && is_array($allowedChars) && count($allowedChars) > 0) { - $acheck = true; - } - - foreach ($disallowed as $dc) { - if ($acheck && in_array($dc, $allowedChars)) continue; - // check for bad signs in execute command - if (stristr($exec_string, $dc)) { - die("SECURITY CHECK FAILED!\nThe execute string '" . $exec_string . "' is a possible security risk!\nPlease check your whole server for security problems by hand!\n"); - } - } - - // execute the command and return output - $return = ''; - - // ------------------------------------------------------------------------------- - if ($return_value == false) { - exec($exec_string, $return); - } else { - exec($exec_string, $return, $return_value); - } - - return $return; -} diff --git a/lib/functions/phphelpers/function.array_trim.php b/lib/functions/phphelpers/function.array_trim.php deleted file mode 100644 index 4c64ccfd..00000000 --- a/lib/functions/phphelpers/function.array_trim.php +++ /dev/null @@ -1,41 +0,0 @@ - (2003-2009) - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Functions - * - */ - -/** - * Returns Array, whose elements have been checked whether thay are empty or not - * - * @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)) { - foreach ($source as $var => $val) { - if ($val != ' ' && $val != '') { - $returnval[$var] = $val; - } - } - } else { - $returnval = $source; - } - return $returnval; -} diff --git a/lib/functions/phphelpers/function.gethostbynamel6.php b/lib/functions/phphelpers/function.gethostbynamel6.php deleted file mode 100644 index 091d6e45..00000000 --- a/lib/functions/phphelpers/function.gethostbynamel6.php +++ /dev/null @@ -1,33 +0,0 @@ - (2003-2009) - * @author Froxlor team (2010-) - * @license GPLv2 http://files.froxlor.org/misc/COPYING.txt - * @package Functions - * - */ - -/** - * Replaces all occurrences of variables defined in the second argument - * in the first argument with their values. - * - * @param string The string that should be searched for variables - * @param array The array containing the variables with their values - * @return string The submitted string with the variables replaced. - * @author Michael Duergner - */ - -function replace_variables($text, $vars) -{ - $pattern = "/\{([a-zA-Z0-9\-_]+)\}/"; - - // --- martin @ 08.08.2005 ------------------------------------------------------- - // fixing usage of uninitialised variable - - $matches = array(); - - // ------------------------------------------------------------------------------- - - if(count($vars) > 0 - && preg_match_all($pattern, $text, $matches)) - { - for ($i = 0;$i < count($matches[1]);$i++) - { - $current = $matches[1][$i]; - - if(isset($vars[$current])) - { - $var = $vars[$current]; - $text = str_replace("{" . $current . "}", $var, $text); - } - } - } - - $text = str_replace('\n', "\n", $text); - return $text; -} diff --git a/lib/functions/phphelpers/function.size_readable.php b/lib/functions/phphelpers/function.size_readable.php deleted file mode 100644 index 5f6ad0b5..00000000 --- a/lib/functions/phphelpers/function.size_readable.php +++ /dev/null @@ -1,36 +0,0 @@ - - * @version 1.3.0 - * @link http://aidanlister.com/2004/04/human-readable-file-sizes/ - * @param int $size size in bytes - * @param string $max maximum unit - * @param string $system 'si' for SI, 'bi' for binary prefixes - * @param string $retstring return string format - */ - -function size_readable($size, $max = null, $system = 'si', $retstring = '%01.2f %s') -{ - // Pick units - $systems['si']['prefix'] = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); - $systems['si']['size'] = 1000; - $systems['bi']['prefix'] = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'); - $systems['bi']['size'] = 1024; - $sys = isset($systems[$system]) ? $systems[$system] : $systems['si']; - - // Max unit to display - $depth = count($sys['prefix']) - 1; - if ($max && false !== $d = array_search($max, $sys['prefix'])) { - $depth = $d; - } - // Loop - $i = 0; - while ($size >= $sys['size'] && $i < $depth) { - $size /= $sys['size']; - $i++; - } - - return sprintf($retstring, $size, $sys['prefix'][$i]); -}