Marius Cramer
2015-04-14 2af58c77572fbc32c1c617764ebdd0252be24292
- finished rewriting of sql statements
82 files modified
2737 ■■■■■ changed files
install/dist/lib/debian60.lib.php 2 ●●● patch | view | raw | blame | history
install/dist/lib/fedora.lib.php 18 ●●●●● patch | view | raw | blame | history
install/dist/lib/gentoo.lib.php 10 ●●●●● patch | view | raw | blame | history
install/dist/lib/opensuse.lib.php 18 ●●●●● patch | view | raw | blame | history
install/lib/installer_base.lib.php 160 ●●●●● patch | view | raw | blame | history
install/lib/mysql.lib.php 986 ●●●● patch | view | raw | blame | history
install/lib/update.lib.php 34 ●●●● patch | view | raw | blame | history
interface/lib/classes/aps_crawler.inc.php 2 ●●● patch | view | raw | blame | history
interface/lib/classes/aps_guicontroller.inc.php 37 ●●●● patch | view | raw | blame | history
interface/lib/classes/db_mysql.inc.php 28 ●●●● patch | view | raw | blame | history
interface/lib/classes/listform.inc.php 4 ●●● patch | view | raw | blame | history
interface/lib/classes/listform_actions.inc.php 1 ●●●● patch | view | raw | blame | history
interface/lib/classes/plugin_dbhistory.inc.php 7 ●●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/client.inc.php 2 ●●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/mail.inc.php 1 ●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/sites.inc.php 1 ●●●● patch | view | raw | blame | history
interface/lib/classes/remoting.inc.php 9 ●●●● patch | view | raw | blame | history
interface/lib/classes/remoting_lib.inc.php 18 ●●●● patch | view | raw | blame | history
interface/lib/classes/searchform.inc.php 10 ●●●● patch | view | raw | blame | history
interface/lib/classes/sites_database_plugin.inc.php 2 ●●● patch | view | raw | blame | history
interface/lib/classes/tform.inc.php 24 ●●●● patch | view | raw | blame | history
interface/lib/classes/tform_base.inc.php 16 ●●●● patch | view | raw | blame | history
interface/lib/classes/tools_sites.inc.php 3 ●●●●● patch | view | raw | blame | history
interface/lib/plugins/mail_user_filter_plugin.inc.php 6 ●●●●● patch | view | raw | blame | history
interface/lib/plugins/sites_web_vhost_domain_plugin.inc.php 10 ●●●● patch | view | raw | blame | history
interface/lib/plugins/vm_openvz_plugin.inc.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/server_config_edit.php 2 ●●● patch | view | raw | blame | history
interface/web/admin/software_package_install.php 8 ●●●● patch | view | raw | blame | history
interface/web/admin/software_package_list.php 50 ●●●● patch | view | raw | blame | history
interface/web/admin/software_update_list.php 12 ●●●● patch | view | raw | blame | history
interface/web/admin/system_config_edit.php 2 ●●● patch | view | raw | blame | history
interface/web/admin/users_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/client/client_edit.php 116 ●●●●● patch | view | raw | blame | history
interface/web/client/client_message.php 4 ●●●● patch | view | raw | blame | history
interface/web/client/reseller_edit.php 75 ●●●● patch | view | raw | blame | history
interface/web/dashboard/ajax_get_json.php 26 ●●●●● patch | view | raw | blame | history
interface/web/login/index.php 6 ●●●● patch | view | raw | blame | history
interface/web/login/password_reset.php 7 ●●●●● patch | view | raw | blame | history
interface/web/mail/mail_alias_edit.php 16 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_aliasdomain_edit.php 9 ●●●●● patch | view | raw | blame | history
interface/web/mail/mail_content_filter_edit.php 2 ●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_catchall_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_del.php 10 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_edit.php 54 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_forward_edit.php 10 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_mailinglist_edit.php 30 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_spamfilter_edit.php 10 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_user_edit.php 34 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_user_filter_edit.php 2 ●●● patch | view | raw | blame | history
interface/web/mail/mail_user_stats.php 8 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_whitelist_edit.php 2 ●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_config_edit.php 4 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_whitelist_edit.php 20 ●●●●● patch | view | raw | blame | history
interface/web/mail/user_quota_stats.php 2 ●●●●● patch | view | raw | blame | history
interface/web/mail/xmpp_domain_edit.php 32 ●●●● patch | view | raw | blame | history
interface/web/sites/ajax_get_ip.php 2 ●●● patch | view | raw | blame | history
interface/web/sites/ajax_get_json.php 37 ●●●● patch | view | raw | blame | history
interface/web/sites/aps_install_package.php 2 ●●● patch | view | raw | blame | history
interface/web/sites/aps_installedpackages_list.php 2 ●●● patch | view | raw | blame | history
interface/web/sites/aps_packagedetails_show.php 2 ●●● patch | view | raw | blame | history
interface/web/sites/database_user_edit.php 28 ●●●● patch | view | raw | blame | history
interface/web/sites/ftp_user_edit.php 38 ●●●● patch | view | raw | blame | history
interface/web/sites/shell_user_edit.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/user_quota_stats.php 4 ●●● patch | view | raw | blame | history
interface/web/sites/web_folder_edit.php 18 ●●●● patch | view | raw | blame | history
interface/web/sites/web_folder_user_edit.php 16 ●●●● patch | view | raw | blame | history
interface/web/sites/web_vhost_domain_del.php 20 ●●●● patch | view | raw | blame | history
interface/web/sites/web_vhost_domain_edit.php 159 ●●●● patch | view | raw | blame | history
interface/web/sites/webdav_user_edit.php 18 ●●●● patch | view | raw | blame | history
interface/web/tools/import_ispconfig.php 14 ●●●● patch | view | raw | blame | history
interface/web/tools/import_vpopmail.php 6 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_action.php 53 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_template_edit.php 9 ●●●●● patch | view | raw | blame | history
interface/web/vm/openvz_vm_edit.php 18 ●●●● patch | view | raw | blame | history
server/lib/app.inc.php 2 ●●● patch | view | raw | blame | history
server/lib/classes/cron.d/500-backup.inc.php 11 ●●●●● patch | view | raw | blame | history
server/lib/classes/db_mysql.inc.php 30 ●●●● patch | view | raw | blame | history
server/plugins-available/apache2_plugin.inc.php 101 ●●●● patch | view | raw | blame | history
server/plugins-available/bind_dlz_plugin.inc.php 34 ●●●●● patch | view | raw | blame | history
server/plugins-available/mongo_clientdb_plugin.inc.php 12 ●●●● patch | view | raw | blame | history
server/plugins-available/nginx_plugin.inc.php 79 ●●●●● patch | view | raw | blame | history
server/plugins-available/xmpp_plugin.inc.php 32 ●●●● patch | view | raw | blame | history
install/dist/lib/debian60.lib.php
@@ -38,7 +38,7 @@
        
        // check if virtual_transport must be changed
        if ($this->is_update) {
            $tmp = $this->db->queryOneRecord("SELECT * FROM ".$conf["mysql"]["database"].".server WHERE server_id = ".$conf['server_id']);
            $tmp = $this->db->queryOneRecord("SELECT * FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . ".server", $conf['server_id']);
            $ini_array = ini_to_array(stripslashes($tmp['config']));
            // ini_array needs not to be checked, because already done in update.php -> updateDbAndIni()
            
install/dist/lib/fedora.lib.php
@@ -182,7 +182,7 @@
        if(!is_user($cf['vmail_username'])) caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
        //* These postconf commands will be executed on installation and update
        $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM server WHERE server_id = ".$conf['server_id']);
        $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM server WHERE server_id = ?", $conf['server_id']);
        $server_ini_array = ini_to_array(stripslashes($server_ini_rec['config']));
        unset($server_ini_rec);
@@ -396,7 +396,7 @@
        
        // check if virtual_transport must be changed
        if ($this->is_update) {
            $tmp = $this->db->queryOneRecord("SELECT * FROM ".$conf["mysql"]["database"].".server WHERE server_id = ".$conf['server_id']);
            $tmp = $this->db->queryOneRecord("SELECT * FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . ".server", $conf['server_id']);
            $ini_array = ini_to_array(stripslashes($tmp['config']));
            // ini_array needs not to be checked, because already done in update.php -> updateDbAndIni()
            
@@ -705,7 +705,7 @@
        $tpl = new tpl('apache_ispconfig.conf.master');
        $tpl->setVar('apache_version',getapacheversion());
        
        $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
        $records = $this->db->queryAllRecords("SELECT * FROM ?? WHERE server_id = ? AND virtualhost = 'y'", $conf['mysql']['master_database'] . '.server_ip', $conf['server_id']);
        $ip_addresses = array();
        
        if(is_array($records) && count($records) > 0) {
@@ -813,7 +813,7 @@
        $tcp_public_services = '';
        $udp_public_services = '';
        $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id']));
        $row = $this->db->queryOneRecord('SELECT * FROM ?? WHERE server_id = ?', $conf["mysql"]["database"] . '.firewall', $conf['server_id']);
        if(trim($row["tcp_port"]) != '' || trim($row["udp_port"]) != ''){
            $tcp_public_services = trim(str_replace(',', ' ', $row["tcp_port"]));
@@ -824,7 +824,7 @@
        }
        if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
            $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
            if($row["tcp_port"] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ',".intval($conf['apache']['vhost_port'])."' WHERE server_id = ".intval($conf['server_id']));
            if($row["tcp_port"] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ? WHERE server_id = ?", ',' . intval($conf['apache']['vhost_port']), $conf['server_id']);
        }
        $content = str_replace("{TCP_PUBLIC_SERVICES}", $tcp_public_services, $content);
@@ -1024,13 +1024,11 @@
        $file_server_enabled = ($conf['services']['file'])?1:0;
        $db_server_enabled = ($conf['services']['db'])?1:0;
        $vserver_server_enabled = ($conf['services']['vserver'])?1:0;
        $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled' WHERE server_id = ".intval($conf['server_id']);
        $sql = "UPDATE `server` SET mail_server = ?, web_server = ?, dns_server = ?, file_server = ?, db_server = ?, vserver_server = ? WHERE server_id = ?";
        $this->db->query($sql, $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $conf['server_id']);
        if($conf['mysql']['master_slave_setup'] == 'y') {
            $this->dbmaster->query($sql);
            $this->db->query($sql);
        } else {
            $this->db->query($sql);
            $this->dbmaster->query($sql, $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $conf['server_id']);
        }
        // chown install dir to root and chmod 755
install/dist/lib/gentoo.lib.php
@@ -540,7 +540,7 @@
        $tpl = new tpl('apache_ispconfig.conf.master');
        $tpl->setVar('apache_version',getapacheversion());
        
        $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
        $records = $this->db->queryAllRecords("SELECT * FROM ?? WHERE server_id = ? AND virtualhost = 'y'", $conf['mysql']['master_database'] . '.server_ip', $conf['server_id']);
        $ip_addresses = array();
        
        if(is_array($records) && count($records) > 0) {
@@ -889,13 +889,11 @@
        $db_server_enabled = ($conf['services']['db'])?1:0;
        $vserver_server_enabled = ($conf['services']['vserver'])?1:0;
        $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled' WHERE server_id = ".intval($conf['server_id']);
        $sql = "UPDATE `server` SET mail_server = ?, web_server = ?, dns_server = ?, file_server = ?, db_server = ?, vserver_server = ? WHERE server_id = ?";
        $this->db->query($sql, $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $conf['server_id']);
        if($conf['mysql']['master_slave_setup'] == 'y') {
            $this->dbmaster->query($sql);
            $this->db->query($sql);
        } else {
            $this->db->query($sql);
            $this->dbmaster->query($sql, $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $conf['server_id']);
        }
        // chown install dir to root and chmod 755
install/dist/lib/opensuse.lib.php
@@ -212,7 +212,7 @@
        if($cf['vmail_mailbox_base'] != '' && strlen($cf['vmail_mailbox_base']) >= 10 && $this->is_update === false) exec('chown -R '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base']);
        //* These postconf commands will be executed on installation and update
        $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM server WHERE server_id = ".$conf['server_id']);
        $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM server WHERE server_id = ?", $conf['server_id']);
        $server_ini_array = ini_to_array(stripslashes($server_ini_rec['config']));
        unset($server_ini_rec);
@@ -451,7 +451,7 @@
        
        // check if virtual_transport must be changed
        if ($this->is_update) {
            $tmp = $this->db->queryOneRecord("SELECT * FROM ".$conf["mysql"]["database"].".server WHERE server_id = ".$conf['server_id']);
            $tmp = $this->db->queryOneRecord("SELECT * FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . ".server", $conf['server_id']);
            $ini_array = ini_to_array(stripslashes($tmp['config']));
            // ini_array needs not to be checked, because already done in update.php -> updateDbAndIni()
            
@@ -737,7 +737,7 @@
        $tpl = new tpl('apache_ispconfig.conf.master');
        $tpl->setVar('apache_version',getapacheversion());
        
        $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
        $records = $this->db->queryAllRecords("SELECT * FROM ?? WHERE server_id = ? AND virtualhost = 'y'", $conf['mysql']['master_database'] . '.server_ip', $conf['server_id']);
        $ip_addresses = array();
        
        if(is_array($records) && count($records) > 0) {
@@ -887,7 +887,7 @@
        $tcp_public_services = '';
        $udp_public_services = '';
        $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id']));
        $row = $this->db->queryOneRecord('SELECT * FROM ?? WHERE server_id = ?', $conf["mysql"]["database"] . '.firewall', $conf['server_id']);
        if(trim($row["tcp_port"]) != '' || trim($row["udp_port"]) != ''){
            $tcp_public_services = trim(str_replace(',', ' ', $row["tcp_port"]));
@@ -899,7 +899,7 @@
        if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
            $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
            if($row["tcp_port"] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ',".intval($conf['apache']['vhost_port'])."' WHERE server_id = ".intval($conf['server_id']));
            if($row["tcp_port"] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ? WHERE server_id = ?", ',' . intval($conf['apache']['vhost_port']), $conf['server_id']);
        }
        $content = str_replace("{TCP_PUBLIC_SERVICES}", $tcp_public_services, $content);
@@ -1097,13 +1097,11 @@
        $file_server_enabled = ($conf['services']['file'])?1:0;
        $db_server_enabled = ($conf['services']['db'])?1:0;
        $vserver_server_enabled = ($conf['services']['vserver'])?1:0;
        $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled' WHERE server_id = ".intval($conf['server_id']);
        $sql = "UPDATE `server` SET mail_server = ?, web_server = ?, dns_server = ?, file_server = ?, db_server = ?, vserver_server = ? WHERE server_id = ?";
        $this->db->query($sql, $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $conf['server_id']););
        if($conf['mysql']['master_slave_setup'] == 'y') {
            $this->dbmaster->query($sql);
            $this->db->query($sql);
        } else {
            $this->db->query($sql);
            $this->dbmaster->query($sql, $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $conf['server_id']););
        }
        // chown install dir to root and chmod 755
install/lib/installer_base.lib.php
@@ -167,7 +167,7 @@
        global $conf;
        //** Create the database
        if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['mysql']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
        if(!$this->db->query('CREATE DATABASE IF NOT EXISTS ?? DEFAULT CHARACTER SET ?', $conf['mysql']['database'], $conf['mysql']['charset'])) {
            $this->error('Unable to create MySQL database: '.$conf['mysql']['database'].'.');
        }
@@ -192,8 +192,8 @@
            }
            //* Load system.ini into the sys_ini table
            $system_ini = $this->db->quote(rf('tpl/system.ini.master'));
            $this->db->query("UPDATE sys_ini SET config = '$system_ini' WHERE sysini_id = 1");
            $system_ini = rf('tpl/system.ini.master');
            $this->db->query("UPDATE sys_ini SET config = ? WHERE sysini_id = 1", $system_ini);
        }
    }
@@ -210,15 +210,13 @@
        }
        // Delete ISPConfig user in the local database, in case that it exists
        $this->db->query("DELETE FROM mysql.user WHERE User = '".$conf['mysql']['ispconfig_user']."' AND Host = '".$from_host."';");
        $this->db->query("DELETE FROM mysql.db WHERE Db = '".$conf['mysql']['database']."' AND Host = '".$from_host."';");
        $this->db->query('FLUSH PRIVILEGES;');
        $this->db->query("DELETE FROM mysql.user WHERE User = ? AND Host = ?", $conf['mysql']['ispconfig_user'], $from_host);
        $this->db->query("DELETE FROM mysql.db WHERE Db = ? AND Host = ?", $conf['mysql']['database'], $from_host);
        $this->db->query('FLUSH PRIVILEGES');
        //* Create the ISPConfig database user in the local database
        $query = 'GRANT SELECT, INSERT, UPDATE, DELETE ON '.$conf['mysql']['database'].".* "
            ."TO '".$conf['mysql']['ispconfig_user']."'@'".$from_host."' "
            ."IDENTIFIED BY '".$conf['mysql']['ispconfig_password']."';";
        if(!$this->db->query($query)) {
        $query = 'GRANT SELECT, INSERT, UPDATE, DELETE ON ?? TO ?@? IDENTIFIED BY ?';
        if(!$this->db->query($query, $conf['mysql']['database'] . ".*", $conf['mysql']['ispconfig_user'], $from_host, $conf['mysql']['ispconfig_password'])) {
            $this->error('Unable to create database user: '.$conf['mysql']['ispconfig_user'].' Error: '.$this->db->errorMessage);
        }
@@ -309,14 +307,14 @@
        if($conf['mysql']['master_slave_setup'] == 'y') {
            //* Insert the server record in master DB
            $sql = "INSERT INTO `server` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (1, 1, 'riud', 'riud', 'r', '".$conf['hostname']."', '$mail_server_enabled', '$web_server_enabled', '$dns_server_enabled', '$file_server_enabled', '$db_server_enabled', '$vserver_server_enabled', '$server_ini_content', 0, 1, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);";
            $this->dbmaster->query($sql);
            $sql = "INSERT INTO `server` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (1, 1, 'riud', 'riud', 'r', ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, ?, ?, ?);";
            $this->dbmaster->query($sql, $conf['hostname'], $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $server_ini_content, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);
            $conf['server_id'] = $this->dbmaster->insertID();
            $conf['server_id'] = $conf['server_id'];
            //* Insert the same record in the local DB
            $sql = "INSERT INTO `server` (`server_id`, `sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES ('".$conf['server_id']."',1, 1, 'riud', 'riud', 'r', '".$conf['hostname']."', '$mail_server_enabled', '$web_server_enabled', '$dns_server_enabled', '$file_server_enabled', '$db_server_enabled', '$vserver_server_enabled', '$server_ini_content', 0, 1, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);";
            $this->db->query($sql);
            $sql = "INSERT INTO `server` (`server_id`, `sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (?,1, 1, 'riud', 'riud', 'r', ?, ?, ?, ?, ?, ?, ?, 0, 1, ?, ?, ?);";
            $this->db->query($sql, $conf['server_id'], $conf['hostname'], $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $server_ini_content, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);
            //* username for the ispconfig user
            $conf['mysql']['master_ispconfig_user'] = 'ispcsrv'.$conf['server_id'];
@@ -325,8 +323,8 @@
        } else {
            //* Insert the server, if its not a mster / slave setup
            $sql = "INSERT INTO `server` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (1, 1, 'riud', 'riud', 'r', '".$conf['hostname']."', '$mail_server_enabled', '$web_server_enabled', '$dns_server_enabled', '$file_server_enabled', '$db_server_enabled', '$vserver_server_enabled', '$server_ini_content', 0, 1, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);";
            $this->db->query($sql);
            $sql = "INSERT INTO `server` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_name`, `mail_server`, `web_server`, `dns_server`, `file_server`, `db_server`, `vserver_server`, `config`, `updated`, `active`, `dbversion`,`firewall_server`,`proxy_server`) VALUES (1, 1, 'riud', 'riud', 'r', ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, ?, ?, ?);";
            $this->db->query($sql, $conf['hostname'], $mail_server_enabled, $web_server_enabled, $dns_server_enabled, $file_server_enabled, $db_server_enabled, $vserver_server_enabled, $server_ini_content, $current_db_version, $proxy_server_enabled, $firewall_server_enabled);
            $conf['server_id'] = $this->db->insertID();
            $conf['server_id'] = $conf['server_id'];
        }
@@ -388,141 +386,141 @@
             * if not, the user already exists and we do not need the pwd
             */
                if ($value['pwd'] != ''){
                    $query = "CREATE USER '".$value['user']."'@'".$host."' IDENTIFIED BY '" . $value['pwd'] . "'";
                    $query = "CREATE USER ?@? IDENTIFIED BY ?";
                    if ($verbose){
                        echo "\n\n" . $query ."\n";
                    }
                    $this->dbmaster->query($query); // ignore the error
                    $this->dbmaster->query($query, $value['user'], $host, $value['pwd']); // ignore the error
                }
                /*
             *  Try to delete all rights of the user in case that it exists.
             *  In Case that it will not exist, do nothing (ignore the error!)
             */
                $query = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM '".$value['user']."'@'".$host."' ";
                $query = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM ?@?";
                if ($verbose){
                    echo "\n\n" . $query ."\n";
                }
                $this->dbmaster->query($query); // ignore the error
                $this->dbmaster->query($query, $value['user'], $host); // ignore the error
                //* Create the ISPConfig database user in the remote database
                $query = "GRANT SELECT ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.server', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, INSERT ON ".$value['db'].".`sys_log` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, INSERT ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.sys_log', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, UPDATE(`status`, `error`) ON ".$value['db'].".`sys_datalog` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, UPDATE(`status`, `error`) ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.sys_datalog', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, UPDATE(`status`) ON ".$value['db'].".`software_update_inst` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, UPDATE(`status`) ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.software_update_inst', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, UPDATE(`updated`) ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, UPDATE(`updated`) ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.server', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, UPDATE (`ssl_request`, `ssl_cert`, `ssl_action`, `ssl_key`) ON ".$value['db'].".`web_domain` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, UPDATE (`ssl_request`, `ssl_cert`, `ssl_action`, `ssl_key`) ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.web_domain', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT ON ".$value['db'].".`sys_group` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.sys_group', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, UPDATE (`action_state`, `response`) ON ".$value['db'].".`sys_remoteaction` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, UPDATE (`action_state`, `response`) ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.sys_remoteaction', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, INSERT , DELETE ON ".$value['db'].".`monitor_data` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, INSERT , DELETE ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.monitor_data', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`mail_traffic` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, INSERT, UPDATE ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.mail_traffic', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`web_traffic` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, INSERT, UPDATE ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.web_traffic', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, UPDATE, DELETE ON ".$value['db'].".`aps_instances` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, UPDATE, DELETE ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.aps_instances', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                
                $query = "GRANT SELECT, DELETE ON ".$value['db'].".`aps_instances_settings` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, DELETE ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.aps_instances_settings', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, INSERT, DELETE ON ".$value['db'].".`web_backup` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, INSERT, DELETE ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.web_backup', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
                $query = "GRANT SELECT, INSERT, DELETE ON ".$value['db'].".`mail_backup` TO '".$value['user']."'@'".$host."' ";
                $query = "GRANT SELECT, INSERT, DELETE ON ?? TO ?@?";
                if ($verbose){
                    echo $query ."\n";
                }
                if(!$this->dbmaster->query($query)) {
                if(!$this->dbmaster->query($query, $value['db'] . '.mail_backup', $value['user'], $host)) {
                    $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage);
                }
            }
@@ -530,7 +528,7 @@
            /*
         * It is all done. Relod the rights...
         */
            $this->dbmaster->query('FLUSH PRIVILEGES;');
            $this->dbmaster->query('FLUSH PRIVILEGES');
        }
    }
@@ -732,7 +730,7 @@
        if(!is_user($cf['vmail_username'])) caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
        //* These postconf commands will be executed on installation and update
        $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM `" . $this->db->quote($conf["mysql"]["database"]) . "`.`server` WHERE server_id = ".$conf['server_id']);
        $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . '.server', $conf['server_id']);
        $server_ini_array = ini_to_array(stripslashes($server_ini_rec['config']));
        unset($server_ini_rec);
@@ -974,7 +972,7 @@
        
        // check if virtual_transport must be changed
        if ($this->is_update) {
            $tmp = $this->db->queryOneRecord("SELECT * FROM ".$conf["mysql"]["database"].".server WHERE server_id = ".$conf['server_id']);
            $tmp = $this->db->queryOneRecord("SELECT * FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . ".server", $conf['server_id']);
            $ini_array = ini_to_array(stripslashes($tmp['config']));
            // ini_array needs not to be checked, because already done in update.php -> updateDbAndIni()
            
@@ -1250,18 +1248,18 @@
        global $conf;
        //* Create the database
        if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['powerdns']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) {
        if(!$this->db->query('CREATE DATABASE IF NOT EXISTS ?? DEFAULT CHARACTER SET ?', $conf['powerdns']['database'], $conf['mysql']['charset'])) {
            $this->error('Unable to create MySQL database: '.$conf['powerdns']['database'].'.');
        }
        //* Create the ISPConfig database user in the local database
        $query = "GRANT ALL ON `".$conf['powerdns']['database']."` . * TO '".$conf['mysql']['ispconfig_user']."'@'localhost';";
        if(!$this->db->query($query)) {
        $query = "GRANT ALL ON ?? TO ?@'localhost'";
        if(!$this->db->query($query, $conf['powerdns']['database'] . '.*', $conf['mysql']['ispconfig_user'])) {
            $this->error('Unable to create user for powerdns database Error: '.$this->db->errorMessage);
        }
        //* Reload database privelages
        $this->db->query('FLUSH PRIVILEGES;');
        $this->db->query('FLUSH PRIVILEGES');
        //* load the powerdns databse dump
        if($conf['mysql']['admin_password'] == '') {
@@ -1324,7 +1322,7 @@
        if(!@is_dir('/etc/metronome/status')) mkdir('/etc/metronome/status', 0755, true);
        unlink('/etc/metronome/metronome.cfg.lua');
        $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
        $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ?", $conf["server_id"]);
        $server_name = $row["server_name"];
        $tpl = new tpl('metronome_conf_main.master');
@@ -1483,7 +1481,7 @@
        $tpl = new tpl('apache_ispconfig.conf.master');
        $tpl->setVar('apache_version',getapacheversion());
        
        $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
        $records = $this->db->queryAllRecords("SELECT * FROM ?? WHERE server_id = ? AND virtualhost = 'y'", $conf['mysql']['master_database'] . '.server_ip', $conf['server_id']);
        $ip_addresses = array();
        
        if(is_array($records) && count($records) > 0) {
@@ -1566,36 +1564,6 @@
        //* add a sshusers group
        $command = 'groupadd sshusers';
        if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command");
        /*
        $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
        $ip_address = gethostbyname($row["server_name"]);
        $server_name = $row["server_name"];
        //setup proxy.conf
        $configfile = 'proxy.conf';
        if(is_file($conf["nginx"]["config_dir"].'/'.$configfile)) copy($conf["nginx"]["config_dir"].'/'.$configfile,$conf["nginx"]["config_dir"].'/'.$configfile.'~');
        if(is_file($conf["nginx"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/'.$configfile.'~');
        $content = rf("tpl/nginx_".$configfile.".master");
        wf($conf["nginx"]["config_dir"].'/'.$configfile,$content);
        exec('chmod 600 '.$conf["nginx"]["config_dir"].'/'.$configfile);
        exec('chown root:root '.$conf["nginx"]["config_dir"].'/'.$configfile);
        //setup conf.d/cache.conf
        $configfile = 'cache.conf';
        if(is_file($conf["nginx"]["config_dir"].'/conf.d/'.$configfile)) copy($conf["nginx"]["config_dir"].'/conf.d/'.$configfile,$conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~');
        if(is_file($conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~')) exec('chmod 400 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile.'~');
        $content = rf("tpl/nginx_".$configfile.".master");
        wf($conf["nginx"]["config_dir"].'/conf.d/'.$configfile,$content);
        exec('chmod 600 '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
        exec('chown root:root '.$conf["nginx"]["config_dir"].'/conf.d/'.$configfile);
        //setup cache directories
        mkdir('/var/cache/nginx/cache');
        exec('chown www-data:www-data /var/cache/nginx/cache');
        mkdir('/var/cache/nginx/temp');
        exec('chown www-data:www-data /var/cache/nginx/temp');
        */
    }
    public function configure_fail2ban() {
@@ -1605,7 +1573,7 @@
    public function configure_squid()
    {
        global $conf;
        $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$conf["server_id"]."");
        $row = $this->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ?", $conf["server_id"]);
        $ip_address = gethostbyname($row["server_name"]);
        $server_name = $row["server_name"];
@@ -1652,7 +1620,7 @@
        $tcp_public_services = '';
        $udp_public_services = '';
        $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id']));
        $row = $this->db->queryOneRecord('SELECT * FROM ?? WHERE server_id = ?', $conf["mysql"]["database"] . '.firewall', $conf['server_id']);
        if(trim($row['tcp_port']) != '' || trim($row['udp_port']) != '') {
            $tcp_public_services = trim(str_replace(',', ' ', $row['tcp_port']));
@@ -1664,7 +1632,7 @@
        if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) {
            $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']);
            if($row['tcp_port'] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ',".intval($conf['apache']['vhost_port'])."' WHERE server_id = ".intval($conf['server_id']));
            if($row['tcp_port'] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ? WHERE server_id = ?", ',' . intval($conf['apache']['vhost_port']), $conf['server_id']);
        }
        $content = str_replace('{TCP_PUBLIC_SERVICES}', $tcp_public_services, $content);
@@ -2091,13 +2059,11 @@
        $firewall_server_enabled = ($conf['services']['firewall'])?1:0;
        $xmpp_server_enabled = ($conf['services']['xmpp'])?1:0;
        $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled', proxy_server = '$proxy_server_enabled', firewall_server = '$firewall_server_enabled', xmpp_server = '.$xmpp_server_enabled.' WHERE server_id = ".intval($conf['server_id']);
        $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled', proxy_server = '$proxy_server_enabled', firewall_server = '$firewall_server_enabled', xmpp_server = '.$xmpp_server_enabled.' WHERE server_id = ?";
        $this->db->query($sql, $conf['server_id']);
        if($conf['mysql']['master_slave_setup'] == 'y') {
            $this->dbmaster->query($sql);
            $this->db->query($sql);
        } else {
            $this->db->query($sql);
            $this->dbmaster->query($sql, $conf['server_id']);
        }
install/lib/mysql.lib.php
@@ -1,7 +1,6 @@
<?php
/*
Copyright (c) 2007, Till Brehm, projektfarm Gmbh
   Copyright (c) 2005, Till Brehm, projektfarm Gmbh
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
@@ -28,163 +27,469 @@
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
class db
class db extends mysqli
{
    var $dbHost = "";    // hostname of the MySQL server
    var $dbName = "";    // logical database name on that server
    var $dbUser = "";    // database authorized user
    var $dbPass = "";    // user's password
    var $dbCharset = "";      // what charset comes and goes to mysql: utf8 / latin1
    var $linkId = false;    // last result of mysql_connect()
    var $queryId = 0;    // last result of mysql_query()
    var $record = array();   // last record fetched
    var $autoCommit = 1;      // Autocommit Transactions
    var $currentRow;    // current row number
    var $errorNumber = 0;   // last error number
    var $errorMessage = "";   // last error message
    var $errorLocation = "";  // last error location
    var $show_error_messages = false;
    /**#@+
     * @access private
     */
    private $_iQueryId;
    private $_iConnId;
    private $dbHost = '';  // hostname of the MySQL server
    private $dbName = '';  // logical database name on that server
    private $dbUser = '';  // database authorized user
    private $dbPass = '';  // user's password
    private $dbCharset = 'utf8';// Database charset
    private $dbNewLink = false; // Return a new linkID when connect is called again
    private $dbClientFlags = 0; // MySQL Client falgs
    /**#@-*/
    public $show_error_messages = false; // false in server, true in interface
    /* old things - unused now ////
    private $linkId = 0;  // last result of mysqli_connect()
    private $queryId = 0;  // last result of mysqli_query()
    private $record = array(); // last record fetched
    private $autoCommit = 1;    // Autocommit Transactions
    private $currentRow;  // current row number
    public $errorNumber = 0; // last error number
    public $errorMessage = ''; // last error message
    private $errorLocation = '';// last error location
    private $isConnected = false; // needed to know if we have a valid mysqli object from the constructor
    ////
    */
    // constructor
    function db()
    {
    public function __construct($host = NULL , $user = NULL, $pass = NULL, $database = NULL) {
        global $conf;
        $this->dbHost = $conf["mysql"]["host"];
        //$this->dbName = $conf["mysql"]["database"];
        $this->dbName = '';
        $this->dbUser = $conf["mysql"]["admin_user"];
        $this->dbPass = $conf["mysql"]["admin_password"];
        $this->dbCharset = $conf["mysql"]["charset"];
        //$this->connect();
        $this->dbNewLink = false;
        $this->dbClientFlags = null;
        $this->_iConnId = mysqli_connect($this->dbHost, $this->dbUser, $this->dbPass);
        $try = 0;
        while((!is_object($this->_iConnId) || mysqli_connect_error()) && $try < 5) {
            if($try > 0) sleep(1);
            $try++;
            $this->_iConnId = mysqli_connect($this->dbHost, $this->dbUser, $this->dbPass);
    }
    // error handler
    function updateError($location)
    {
        $this->errorNumber = mysqli_errno($this->linkId);
        $this->errorMessage = mysqli_error($this->linkId);
        $this->errorLocation = $location;
        if($this->errorNumber && $this->show_error_messages)
        {
            echo '<br /><b>'.$this->errorLocation.'</b><br />'.$this->errorMessage;
            flush();
        }
    }
    function connect()
    {
        if(!$this->linkId)
        {
            $this->linkId = mysqli_connect($this->dbHost, $this->dbUser, $this->dbPass);
            if(!$this->linkId)
            {
                $this->updateError('DB::connect()<br />mysqli_connect');
        if(!is_object($this->_iConnId) || mysqli_connect_error()) {
            $this->_iConnId = null;
            $this->_sqlerror('Zugriff auf Datenbankserver fehlgeschlagen! / Database server not accessible!');
                return false;
            }
            $this->queryId = @mysqli_query($this->linkId, 'SET NAMES '.$this->dbCharset);
        if(!((bool)mysqli_query( $this->_iConnId, 'USE `' . $this->dbName . '`'))) {
            $this->close();
            $this->_sqlerror('Datenbank nicht gefunden / Database not found');
            return false;
        }
        $this->_setCharset();
    }
    public function __destruct() {
        if($this->_iConnId) mysqli_close($this->_iConnId);
    }
    public function close() {
        if($this->_iConnId) mysqli_close($this->_iConnId);
        $this->_iConnId = null;
    }
    /* This allows our private variables to be "read" out side of the class */
    public function __get($var) {
        return isset($this->$var) ? $this->$var : 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 $sKey => $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);
                    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_string($sValue) && (strcmp($sValue, '#NULL#') == 0)) {
                        $sTxt = 'NULL';
                    } elseif(is_array($sValue)) {
                        $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() {
        mysqli_query($this->_iConnId, 'SET NAMES '.$this->dbCharset);
        mysqli_query($this->_iConnId, "SET character_set_results = '".$this->dbCharset."', character_set_client = '".$this->dbCharset."', character_set_connection = '".$this->dbCharset."', character_set_database = '".$this->dbCharset."', character_set_server = '".$this->dbCharset."'");
    }
    private function _query($sQuery = '') {
        global $app;
        //if($this->isConnected == false) return false;
        if ($sQuery == '') {
            $this->_sqlerror('Keine Anfrage angegeben / No query given');
            return false;
        }
        $try = 0;
        do {
            $try++;
            $ok = mysqli_ping($this->_iConnId);
            if(!$ok) {
                if(!mysqli_connect($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName)) {
                    if($this->errorNumber == '111') {
                        // server is not available
                        if($try > 9) {
                            if(isset($app) && isset($app->forceErrorExit)) {
                                $app->forceErrorExit('Database connection failure!');
                            }
                            // if we reach this, the app object is missing or has no exit method, so we continue as normal
                        }
                        sleep(30); // additional seconds, please!
                    }
                    if($try > 9) {
                        $this->_sqlerror('DB::query -> reconnect');
                        return false;
                    } else {
                        sleep(($try > 7 ? 5 : 1));
                    }
                } else {
                    $this->_setCharset();
                    $ok = true;
                }
            }
        } while($ok == false);
        $aArgs = func_get_args();
        $sQuery = call_user_func_array(array(&$this, '_build_query_string'), $aArgs);
        $this->_iQueryId = mysqli_query($this->_iConnId, $sQuery);
        if (!$this->_iQueryId) {
            $this->_sqlerror('Falsche Anfrage / Wrong Query', false, 'SQL-Query = ' . $sQuery);
            return false;
        }
        return is_bool($this->_iQueryId) ? $this->_iQueryId : new db_result($this->_iQueryId, $this->_iConnId);
    }
    /**#@-*/
    /**
     * 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 db_result the result object of the query
     */
    public function query($sQuery = '') {
        $aArgs = func_get_args();
        return call_user_func_array(array(&$this, '_query'), $aArgs);
    }
    /**
     * 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 queryOneRecord($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 call_user_func_array(array(&$this, 'queryOneRecord'), func_get_args());
    }
    public function query_one($sQuery = '') {
        return call_user_func_array(array(&$this, 'queryOneRecord'), func_get_args());
    }
    /**
     * Execute a query and return all rows
     *
     * Executes a query and returns all result rows in an array
     * <strong>Use this with extreme care!!!</strong> 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 queryAllRecords($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;
    }
    public function queryAll($sQuery = '') {
        return call_user_func_array(array(&$this, 'queryAllRecords'), func_get_args());
    }
    public function query_all($sQuery = '') {
        return call_user_func_array(array(&$this, 'queryAllRecords'), func_get_args());
    }
    /**
     * Execute a query and return all rows as simple array
     *
     * Executes a query and returns all result rows in an array with elements
     * <strong>Only first column is returned</strong> 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 queryAllArray($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 query_all_array($sQuery = '') {
        return call_user_func_array(array(&$this, 'queryAllArray'), func_get_args());
    }
    /**
     * 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->_iConnId, '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->_iConnId)) return 0;
        $iRows = mysqli_affected_rows($this->_iConnId);
        if(!$iRows) $iRows = 0;
        return $iRows;
    }
    /**
     * check if a utf8 string is valid
     *
     * @access public
     * @param string  $string the string to check
     * @return bool true if it is valid utf8, false otherwise
     */
    private 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;
    } // end of check_utf8
    /**
     * 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) {
        global $app;
        if(!is_string($sString) && !is_numeric($sString)) {
            $app->log('NON-String given in escape function! (' . gettype($sString) . ')', LOGLEVEL_INFO);
            //$sAddMsg = getDebugBacktrace();
            $app->log($sAddMsg, LOGLEVEL_DEBUG);
            $sString = '';
    }
    function query($queryString)
    {
        if(!$this->connect())
        {
            return false;
        $cur_encoding = mb_detect_encoding($sString);
        if($cur_encoding != "UTF-8") {
            if($cur_encoding != 'ASCII') {
                $app->log('String ' . substr($sString, 0, 25) . '... is ' . $cur_encoding . '.', LOGLEVEL_INFO);
                if($cur_encoding) $sString = mb_convert_encoding($sString, 'UTF-8', $cur_encoding);
                else $sString = mb_convert_encoding($sString, 'UTF-8');
        }
        if($this->dbName != '') {
            if(!mysqli_select_db($this->linkId, $this->dbName))
            {
                $this->updateError('DB::connect()<br />mysqli_select_db');
                return false;
            }
        }
        $this->queryId = @mysqli_query($this->linkId, $queryString);
        $this->updateError('DB::query('.$queryString.')<br />mysqli_query');
        if(!$this->queryId)
        {
            return false;
        }
        $this->currentRow = 0;
        return $this->queryId;
        } elseif(!$this->check_utf8($sString)) {
            $sString = utf8_encode($sString);
    }
    // returns all records in an array
    function queryAllRecords($queryString)
    {
        if(!$this->query($queryString))
        {
            return false;
        }
        $ret = array();
        while($line = $this->nextRecord())
        {
            $ret[] = $line;
        }
        return $ret;
        if($this->_iConnId) return mysqli_real_escape_string($this->_iConnId, $sString);
        else return addslashes($sString);
    }
    // returns one record in an array
    function queryOneRecord($queryString)
    {
        if(!$this->query($queryString) || $this->numRows() == 0)
        {
            return false;
    /**
     *
     *
     * @access private
     */
    private function _sqlerror($sErrormsg = 'Unbekannter Fehler', $sAddMsg = '') {
        global $app, $conf;
        $mysql_error = (is_object($this->_iConnId) ? mysqli_error($this->_iConnId) : mysqli_connect_error());
        $mysql_errno = (is_object($this->_iConnId) ? mysqli_errno($this->_iConnId) : mysqli_connect_errno());
        //$sAddMsg .= getDebugBacktrace();
        if($this->show_error_messages && $conf['demo_mode'] === false) {
            echo $sErrormsg . $sAddMsg;
        } else if(is_object($app) && method_exists($app, 'log')) {
                $app->log($sErrormsg . $sAddMsg . ' -> ' . $mysql_errno . ' (' . $mysql_error . ')', LOGLEVEL_WARN);
        }
        return $this->nextRecord();
    }
    // returns the next record in an array
    function nextRecord()
    {
        $this->record = mysqli_fetch_assoc($this->queryId);
        $this->updateError('DB::nextRecord()<br />mysqli_fetch_array');
        if(!$this->record || !is_array($this->record))
        {
            return false;
        }
        $this->currentRow++;
        return $this->record;
    }
    // returns number of rows returned by the last select query
    function numRows()
    {
        return mysqli_num_rows($this->queryId);
    }
    function affectedRows()
    {
        return mysqli_affected_rows($this->linkId);
    public function affectedRows() {
        return $this->affected();
    }
    // returns mySQL insert id
    function insertID()
    {
        return mysqli_insert_id($this->linkId);
    public function insertID() {
        return $this->insert_id();
    }
    // Check der variablen
    // deprecated, now use quote
    function check($formfield)
    {
        return $this->quote($formfield);
    //* Function to quote strings
    public function quote($formfield) {
        return $this->escape($formfield);
    }
    // Check der variablen
    function quote($formfield)
    {
        return mysqli_real_escape_string($this->linkId, $formfield);
    }
    // Check der variablen
    function unquote($formfield)
    {
    //* Function to unquotae strings
    public function unquote($formfield) {
        return stripslashes($formfield);
    }
    function toLower($record) {
    public function toLower($record) {
        if(is_array($record)) {
            foreach($record as $key => $val) {
                $key = strtolower($key);
@@ -194,7 +499,7 @@
        return $out;
    }
    /* TODO: rewrite SQL */
    function insert($tablename, $form, $debug = 0)
    {
        if(is_array($form)){
@@ -214,6 +519,7 @@
        }
    }
    /* TODO: rewrite SQL */
    function update($tablename, $form, $bedingung, $debug = 0)
    {
@@ -230,23 +536,6 @@
        }
    }
    function closeConn() {
    }
    function freeResult() {
    }
    function delete() {
    }
    function Transaction($action) {
        //action = begin, commit oder rollback
    }
    /*
   $columns = array(action =>   add | alter | drop
@@ -261,42 +550,31 @@
   */
    function createTable($table_name, $columns) {
        $index = "";
        $sql = "CREATE TABLE $table_name (";
    /* TODO: rewrite SQL */
    public function createTable($table_name, $columns) {
        $index = '';
        $sql = "CREATE TABLE ?? (";
        foreach($columns as $col){
            $sql .= $col["name"]." ".$this->mapType($col["type"], $col["typeValue"])." ";
            $sql .= $col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
            if($col["defaultValue"] != "") {
                if($col["defaultValue"] == "NULL" or $col["defaultValue"] == "NOT NULL") {
                    $sql .= "DEFAULT ".$col["defaultValue"]." ";
            if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' ";
            if($col['notNull'] == true) {
                $sql .= 'NOT NULL ';
                } else {
                    $sql .= "DEFAULT '".$col["defaultValue"]."' ";
                $sql .= 'NULL ';
                }
            } elseif($col["defaultValue"] != false) {
                $sql .= "DEFAULT '' ";
            }
            if($col["defaultValue"] != "NULL" && $col["defaultValue"] != "NOT NULL") {
                if($col["notNull"] == true) {
                    $sql .= "NOT NULL ";
                } else {
                    $sql .= "NULL ";
                }
            }
            if($col["autoInc"] == true) $sql .= "auto_increment ";
            $sql.= ",";
            if($col['autoInc'] == true) $sql .= 'auto_increment ';
            $sql.= ',';
            // key Definitionen
            if($col["option"] == "primary") $index .= "PRIMARY KEY (".$col["name"]."),";
            if($col["option"] == "index") $index .= "INDEX (".$col["name"]."),";
            if($col["option"] == "unique") $index .= "UNIQUE (".$col["name"]."),";
            if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),';
            if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),';
            if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),';
        }
        $sql .= $index;
        $sql = substr($sql, 0, -1);
        $sql .= ")";
        $this->query($sql);
        $sql .= ')';
        /* TODO: secure parameters */
        $this->query($sql, $table_name);
        return true;
    }
@@ -313,68 +591,52 @@
   */
    function alterTable($table_name, $columns) {
        $index = "";
        $sql = "ALTER TABLE $table_name ";
    /* TODO: rewrite SQL */
    public function alterTable($table_name, $columns) {
        $index = '';
        $sql = "ALTER TABLE ?? ";
        foreach($columns as $col){
            if($col["action"] == 'add') {
                $sql .= "ADD ".$col["name"]." ".$this->mapType($col["type"], $col["typeValue"])." ";
            } elseif ($col["action"] == 'alter') {
                $sql .= "CHANGE ".$col["name"]." ".$col["name_new"]." ".$this->mapType($col["type"], $col["typeValue"])." ";
            } elseif ($col["action"] == 'drop') {
                $sql .= "DROP ".$col["name"]." ";
            if($col['action'] == 'add') {
                $sql .= 'ADD '.$col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
            } elseif ($col['action'] == 'alter') {
                $sql .= 'CHANGE '.$col['name'].' '.$col['name_new'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
            } elseif ($col['action'] == 'drop') {
                $sql .= 'DROP '.$col['name'].' ';
            }
            if($col["action"] != 'drop') {
                if($col["defaultValue"] != "") $sql .= "DEFAULT '".$col["defaultValue"]."' ";
                if($col["notNull"] == true) {
                    $sql .= "NOT NULL ";
            if($col['action'] != 'drop') {
                if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' ";
                if($col['notNull'] == true) {
                    $sql .= 'NOT NULL ';
                } else {
                    $sql .= "NULL ";
                    $sql .= 'NULL ';
                }
                if($col["autoInc"] == true) $sql .= "auto_increment ";
                $sql.= ",";
                // key Definitionen
                if($col["option"] == "primary") $index .= "PRIMARY KEY (".$col["name"]."),";
                if($col["option"] == "index") $index .= "INDEX (".$col["name"]."),";
                if($col["option"] == "unique") $index .= "UNIQUE (".$col["name"]."),";
                if($col['autoInc'] == true) $sql .= 'auto_increment ';
                $sql.= ',';
                // Index definitions
                if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),';
                if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),';
                if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),';
            }
        }
        $sql .= $index;
        $sql = substr($sql, 0, -1);
        /* TODO: secure parameters */
        //die($sql);
        $this->query($sql);
        $this->query($sql, $table_name);
        return true;
    }
    function dropTable($table_name) {
    public function dropTable($table_name) {
        $this->check($table_name);
        $sql = "DROP TABLE '". $table_name."'";
        return $this->query($sql);
        $sql = "DROP TABLE ??";
        return $this->query($sql, $table_name);
    }
    // gibt Array mit Tabellennamen zur�ck
    function getTables($database_name = '') {
        if($database_name == ''){
            $database_name = $this->dbName;
        }
        $tables = $this->queryAllRecords("SHOW TABLES FROM `$database_name`");
        $tb_names = array();
        if(is_array($tables) && !empty($tables)){
            for($i = 0; $i < sizeof($tables); $i++){
                $tb_names[$i] = $tables[$i]['Tables_in_'.$database_name];
            }
        }
        /*
        $result = mysqli_query("SHOW TABLES FROM `$database_name`");
        $tb_names = array();
        for ($i = 0; $i < mysqli_num_rows($result); $i++) {
            $tb_names[$i] = mysql_tablename($result, $i);
        }
        */
    public function getTables($database_name = '') {
        if(!is_object($this->_iConnId)) return false;
        if($database_name == '') $database_name = $this->dbName;
        $tb_names = $this->queryAllArray("SHOW TABLES FROM ??", $database_name);
        return $tb_names;
    }
@@ -392,56 +654,56 @@
   */
    /* TODO: rewrite SQL */
    function tableInfo($table_name) {
        global $go_api, $go_info;
        // Tabellenfelder einlesen
        if($rows = $go_api->db->queryAllRecords("SHOW FIELDS FROM ".$table_name)){
        if($rows = $go_api->db->queryAllRecords('SHOW FIELDS FROM ??', $table_name)){
            foreach($rows as $row) {
                $name = $row[0];
                $default = $row[4];
                $key = $row[3];
                $extra = $row[5];
                $isnull = $row[2];
                $type = $row[1];
                $name = $row['Field'];
                $default = $row['Default'];
                $key = $row['Key'];
                $extra = $row['Extra'];
                $isnull = $row['Null'];
                $type = $row['Type'];
                $column = array();
                $column["name"] = $name;
                //$column["type"] = $type;
                $column["defaultValue"] = $default;
                if(stristr($key, "PRI")) $column["option"] = "primary";
                if(stristr($isnull, "YES")) {
                    $column["notNull"] = false;
                $column['name'] = $name;
                //$column['type'] = $type;
                $column['defaultValue'] = $default;
                if(stristr($key, 'PRI')) $column['option'] = 'primary';
                if(stristr($isnull, 'YES')) {
                    $column['notNull'] = false;
                } else {
                    $column["notNull"] = true;
                    $column['notNull'] = true;
                }
                if($extra == 'auto_increment') $column["autoInc"] = true;
                if($extra == 'auto_increment') $column['autoInc'] = true;
                // Type in Metatype umsetzen
                if(stristr($type, "int(")) $metaType = 'int32';
                if(stristr($type, "bigint")) $metaType = 'int64';
                if(stristr($type, "char")) {
                if(stristr($type, 'int(')) $metaType = 'int32';
                if(stristr($type, 'bigint')) $metaType = 'int64';
                if(stristr($type, 'char')) {
                    $metaType = 'char';
                    $tmp_typeValue = explode('(', $type);
                    $column["typeValue"] = substr($tmp_typeValue[1], 0, -1);
                    $column['typeValue'] = substr($tmp_typeValue[1], 0, -1);
                }
                if(stristr($type, "varchar")) {
                if(stristr($type, 'varchar')) {
                    $metaType = 'varchar';
                    $tmp_typeValue = explode('(', $type);
                    $column["typeValue"] = substr($tmp_typeValue[1], 0, -1);
                    $column['typeValue'] = substr($tmp_typeValue[1], 0, -1);
                }
                if(stristr($type, "text")) $metaType = 'text';
                if(stristr($type, "double")) $metaType = 'double';
                if(stristr($type, "blob")) $metaType = 'blob';
                if(stristr($type, 'text')) $metaType = 'text';
                if(stristr($type, 'double')) $metaType = 'double';
                if(stristr($type, 'blob')) $metaType = 'blob';
                $column["type"] = $metaType;
                $column['type'] = $metaType;
                $columns[] = $column;
            }
@@ -452,7 +714,7 @@
    }
    function mapType($metaType, $typeValue) {
    public function mapType($metaType, $typeValue) {
        global $go_api;
        $metaType = strtolower($metaType);
        switch ($metaType) {
@@ -472,7 +734,7 @@
            return 'char';
            break;
        case 'varchar':
            if($typeValue < 1) die("Datenbank Fehler: F�r diesen Datentyp ist eine L�ngenangabe notwendig.");
            if($typeValue < 1) die('Database failure: Lenght required for these data types.');
            return 'varchar('.$typeValue.')';
            break;
        case 'text':
@@ -486,4 +748,238 @@
}
/**
 * database query result class
 *
 * @package pxFramework
 *
 */
class db_result {
    /**
     *
     *
     * @access private
     */
    private $_iResId = null;
    private $_iConnection = null;
    /**
     *
     *
     * @access private
     */
    public function db_result($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;
    }
}
/**
 * database query result class
 *
 * emulates a db result set out of an array so you can use array results and db results the same way
 *
 * @package pxFramework
 * @see db_result
 *
 *
 */
class fakedb_result {
    /**
     *
     *
     * @access private
     */
    private $aResultData = array();
    /**
     *
     *
     * @access private
     */
    private $aLimitedData = array();
    /**
     *
     *
     * @access private
     */
    public function fakedb_result($aData) {
        $this->aResultData = $aData;
        $this->aLimitedData = $aData;
        reset($this->aLimitedData);
    }
    /**
     * get count of result rows
     *
     * Returns the amount of rows in the result set
     *
     * @access public
     * @return int amount of rows
     */
    // Gibt die Anzahl Zeilen zurück
    public function rows() {
        return count($this->aLimitedData);
    }
    /**
     * Frees the result set
     *
     * @access public
     */
    // Gibt ein Ergebnisset frei
    public function free() {
        $this->aResultData = array();
        $this->aLimitedData = array();
        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
     */
    // Gibt eine Ergebniszeile zurück
    public function get() {
        $aItem = null;
        if(!is_array($this->aLimitedData)) return $aItem;
        if(list($vKey, $aItem) = each($this->aLimitedData)) {
            if(!$aItem) $aItem = null;
        }
        return $aItem;
    }
    /**
     * Get a result row (array with numeric index)
     *
     * @access public
     * @return array result row
     */
    public function getAsRow() {
        return $this->get();
    }
    /**
     * Limit the result (like a LIMIT x,y in a SQL query)
     *
     * @access public
     * @param int     $iStart offset to start read
     * @param int     iLength amount of datasets to read
     */
    public function limit_result($iStart, $iLength) {
        $this->aLimitedData = array_slice($this->aResultData, $iStart, $iLength, true);
    }
}
?>
install/lib/update.lib.php
@@ -124,7 +124,7 @@
    global $inst, $conf;
    //* Update $conf array with values from the server.ini that shall be preserved
    $tmp = $inst->db->queryOneRecord("SELECT * FROM ".$conf["mysql"]["database"].".server WHERE server_id = ".$conf['server_id']);
    $tmp = $inst->db->queryOneRecord("SELECT * FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . '.server', $conf['server_id']);
    $ini_array = ini_to_array(stripslashes($tmp['config']));
    $current_db_version = (isset($tmp['dbversion']))?intval($tmp['dbversion']):0;
@@ -218,8 +218,8 @@
        }
        //* update the database version in server table
        $inst->db->query("UPDATE ".$conf["mysql"]["database"].".server SET dbversion = '".$current_db_version."' WHERE server_id = ".$conf['server_id']);
        if($inst->db->dbHost != $inst->dbmaster->dbHost) $inst->dbmaster->query("UPDATE ".$conf["mysql"]["master_database"].".server SET dbversion = '".$current_db_version."' WHERE server_id = ".$conf['server_id']);
        $inst->db->query("UPDATE ?? SET dbversion = ? WHERE server_id = ?", $conf["mysql"]["database"] . ".server", $current_db_version, $conf['server_id']);
        if($inst->db->dbHost != $inst->dbmaster->dbHost) $inst->dbmaster->query("UPDATE ?? SET dbversion = ? WHERE server_id = ?", $conf["mysql"]["master_database"] . ".server", $current_db_version, $conf['server_id']);
        //* If ISPConfig Version < 3.0.3, we will do a full db update
@@ -228,7 +228,7 @@
        swriteln($inst->lng('Starting full database update.'));
        //** Delete the old database
        if( !$inst->db->query('DROP DATABASE IF EXISTS '.$conf['mysql']['database']) ) {
        if( !$inst->db->query('DROP DATABASE IF EXISTS ??', $conf['mysql']['database']) ) {
            $inst->error('Unable to drop MySQL database: '.$conf['mysql']['database'].'.');
        }
@@ -239,7 +239,7 @@
        $db_tables = $inst->db->getTables();
        foreach($db_tables as $table) {
            $inst->db->query("TRUNCATE $table");
            $inst->db->query("TRUNCATE ??", $table);
        }
        //** load old data back into database
@@ -262,15 +262,15 @@
        }
        //* update the database version in server table
        $inst->db->query("UPDATE ".$conf["mysql"]["database"].".server SET dbversion = '".$current_db_version."' WHERE server_id = ".$conf['server_id']);
        if($inst->db->dbHost != $inst->dbmaster->dbHost) $inst->dbmaster->query("UPDATE ".$conf["mysql"]["master_database"].".server SET dbversion = '".$current_db_version."' WHERE server_id = ".$conf['server_id']);
        $inst->db->query("UPDATE ?? SET dbversion = ? WHERE server_id = ?", $conf["mysql"]["database"] . ".server", $current_db_version, $conf['server_id']);
        if($inst->db->dbHost != $inst->dbmaster->dbHost) $inst->dbmaster->query("UPDATE ?? SET dbversion = ? WHERE server_id = ?", $conf["mysql"]["master_database"] . ".server", $current_db_version, $conf['server_id']);
        if ($conf['powerdns']['installed']) {
            swriteln($inst->lng('Starting full PowerDNS database update.'));
            //** Delete the old PowerDNS database
            if( !$inst->db->query('DROP DATABASE IF EXISTS '.$conf['powerdns']['database']) ) {
            if( !$inst->db->query('DROP DATABASE IF EXISTS ??', $conf['powerdns']['database']) ) {
                $inst->error('Unable to drop MySQL database: '.$conf['powerdns']['database'].'.');
            }
@@ -288,7 +288,7 @@
    //** Update server ini
    $tmp_server_rec = $inst->db->queryOneRecord("SELECT config FROM ".$conf["mysql"]["database"].".server WHERE server_id = ".$conf['server_id']);
    $tmp_server_rec = $inst->db->queryOneRecord("SELECT config FROM ?? WHERE server_id = ?", $conf["mysql"]["database"] . ".server", $conf['server_id']);
    $old_ini_array = ini_to_array(stripslashes($tmp_server_rec['config']));
    unset($tmp_server_rec);
    $tpl_ini_array = ini_to_array(rf('tpl/server.ini.master'));
@@ -344,12 +344,12 @@
    }
    $new_ini = array_to_ini($tpl_ini_array);
    $sql = "UPDATE ".$conf["mysql"]["database"].".server SET config = '".mysql_real_escape_string($new_ini)."' WHERE server_id = ".$conf['server_id'];
    $inst->db->query($sql);
    $sql = "UPDATE ?? SET config = ? WHERE server_id = ?";
    $inst->db->query($sql, $conf["mysql"]["database"] . ".server", $new_ini, $conf['server_id']);
    if($inst->db->dbHost != $inst->dbmaster->dbHost) {
        $sql = "UPDATE ".$conf["mysql"]["master_database"].".server SET config = '".mysql_real_escape_string($new_ini)."' WHERE server_id = ".$conf['server_id'];
        $inst->dbmaster->query($sql);
        $sql = "UPDATE ?? SET config = ? WHERE server_id = ?";
        $inst->dbmaster->query($sql, $conf["mysql"]["master_database"].".server", $new_ini, $conf['server_id']);
    }
    unset($old_ini_array);
    unset($tpl_ini_array);
@@ -357,7 +357,7 @@
    //** Update system ini
    $tmp_server_rec = $inst->db->queryOneRecord("SELECT config FROM ".$conf["mysql"]["database"].".sys_ini WHERE sysini_id = 1");
    $tmp_server_rec = $inst->db->queryOneRecord("SELECT config FROM ?? WHERE sysini_id = 1", $conf["mysql"]["database"] . ".sys_ini");
    $old_ini_array = ini_to_array(stripslashes($tmp_server_rec['config']));
    unset($tmp_server_rec);
    $tpl_ini_array = ini_to_array(rf('tpl/system.ini.master'));
@@ -372,11 +372,11 @@
    }
    $new_ini = array_to_ini($tpl_ini_array);
    $tmp = $inst->db->queryOneRecord('SELECT count(sysini_id) as number FROM '.$conf["mysql"]["database"].'.sys_ini WHERE 1');
    $tmp = $inst->db->queryOneRecord('SELECT count(sysini_id) as number FROM ?? WHERE 1', $conf["mysql"]["database"] . '.sys_ini');
    if($tmp['number'] == 0) {
        $inst->db->query("INSERT INTO ".$conf["mysql"]["database"].".sys_ini (sysini_id, config) VALUES (1,'".mysql_real_escape_string($new_ini)."')");
        $inst->db->query("INSERT INTO ?? (sysini_id, config) VALUES (1,?)", $conf["mysql"]["database"] . ".sys_ini", $new_ini);
    } else {
        $inst->db->query("UPDATE ".$conf["mysql"]["database"].".sys_ini SET config = '".mysql_real_escape_string($new_ini)."' WHERE sysini_id = 1");
        $inst->db->query("UPDATE ?? SET config = ? WHERE sysini_id = 1", $conf["mysql"]["database"] . ".sys_ini", $new_ini);
    }
    unset($old_ini_array);
    unset($tpl_ini_array);
interface/lib/classes/aps_crawler.inc.php
@@ -608,7 +608,7 @@
                foreach($incomplete_pkgs as $incomplete_pkg){
                    $pkg_url = @file_get_contents($this->interface_pkg_dir.'/'.$incomplete_pkg['path'].'/PKG_URL');
                    if($pkg_url != ''){
                        $app->db->datalogUpdate('aps_packages', "package_url = '".$app->db->quote($pkg_url)."'", 'id', $incomplete_pkg['id']);
                        $app->db->datalogUpdate('aps_packages', array("package_url" => $pkg_url), 'id', $incomplete_pkg['id']);
                    }
                }
            }
interface/lib/classes/aps_guicontroller.inc.php
@@ -268,7 +268,7 @@
        if (empty($settings['main_database_name'])) {
            //* Find a free db name for the app
            for($n = 1; $n <= 1000; $n++) {
                $mysql_db_name = $app->db->quote(($dbname_prefix != '' ? $dbname_prefix.'aps'.$n : uniqid('aps')));
                $mysql_db_name = ($dbname_prefix != '' ? $dbname_prefix.'aps'.$n : uniqid('aps'));
                $tmp = $app->db->queryOneRecord("SELECT count(database_id) as number FROM web_database WHERE database_name = ?", $mysql_db_name);
                if($tmp['number'] == 0) break;
            }
@@ -277,7 +277,7 @@
        if (empty($settings['main_database_login'])) {
            //* Find a free db username for the app
            for($n = 1; $n <= 1000; $n++) {
                $mysql_db_user = $app->db->quote(($dbuser_prefix != '' ? $dbuser_prefix.'aps'.$n : uniqid('aps')));
                $mysql_db_user = ($dbuser_prefix != '' ? $dbuser_prefix.'aps'.$n : uniqid('aps'));
                $tmp = $app->db->queryOneRecord("SELECT count(database_user_id) as number FROM web_database_user WHERE database_user = ?", $mysql_db_user);
                if($tmp['number'] == 0) break;
            }
@@ -287,8 +287,16 @@
        //* Create the mysql database user if not existing
        $tmp = $app->db->queryOneRecord("SELECT database_user_id FROM web_database_user WHERE database_user = ?", $settings['main_database_login']);
        if(!$tmp) {
            $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `database_user`, `database_user_prefix`, `database_password`)
                                          VALUES( ".$app->functions->intval($websrv['sys_userid']).", ".$app->functions->intval($websrv['sys_groupid']).", 'riud', '".$app->functions->intval($websrv['sys_perm_group'])."', '', 0, '".$settings['main_database_login']."', '".$app->db->quote($dbuser_prefix) . "', PASSWORD('".$settings['main_database_password']."'))";
            $insert_data = array("sys_userid" => $websrv['sys_userid'],
                                 "sys_groupid" => $websrv['sys_groupid'],
                                 "sys_perm_user" => 'riud',
                                 "sys_perm_group" => $websrv['sys_perm_group'],
                                 "sys_perm_other" => '',
                                 "server_id" => 0,
                                 "database_user" => $settings['main_database_login'],
                                 "database_user_prefix" => $dbuser_prefix,
                                 "database_password" => "PASSWORD('" . $settings['main_database_password'] . "')"
                                 );
            $mysql_db_user_id = $app->db->datalogInsert('web_database_user', $insert_data, 'database_user_id');
        }
        else $mysql_db_user_id = $tmp['database_user_id'];
@@ -296,8 +304,25 @@
        //* Create the mysql database if not existing
        $tmp = $app->db->queryOneRecord("SELECT count(database_id) as number FROM web_database WHERE database_name = ?", $settings['main_database_name']);
        if($tmp['number'] == 0) {
            $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `parent_domain_id`, `type`, `database_name`, `database_name_prefix`, `database_user_id`, `database_ro_user_id`, `database_charset`, `remote_access`, `remote_ips`, `backup_copies`, `active`, `backup_interval`)
                                          VALUES( ".$app->functions->intval($websrv['sys_userid']).", ".$app->functions->intval($websrv['sys_groupid']).", 'riud', '".$app->functions->intval($websrv['sys_perm_group'])."', '', $mysql_db_server_id, ".$app->functions->intval($websrv['domain_id']).", 'mysql', '".$settings['main_database_name']."', '" . $app->db->quote($dbname_prefix) . "', '$mysql_db_user_id', 0, '', '$mysql_db_remote_access', '$mysql_db_remote_ips', ".$app->functions->intval($websrv['backup_copies']).", 'y', '".$app->functions->intval($websrv['backup_interval'])."')";
            $insert_data = array("sys_userid" => $websrv['sys_userid'],
                                 "sys_groupid" => $websrv['sys_groupid'],
                                 "sys_perm_user" => 'riud',
                                 "sys_perm_group" => $websrv['sys_perm_group'],
                                 "sys_perm_other" => '',
                                 "server_id" => $mysql_db_server_id,
                                 "parent_domain_id" => $websrv['domain_id'],
                                 "type" => 'mysql',
                                 "database_name" => $settings['main_database_name'],
                                 "database_name_prefix" => $dbname_prefix,
                                 "database_user_id" => $mysql_db_user_id,
                                 "database_ro_user_id" => 0,
                                 "database_charset" => '',
                                 "remote_access" => $mysql_db_remote_access,
                                 "remote_ips" => $mysql_db_remote_ips,
                                 "backup_copies" => $websrv['backup_copies'],
                                 "active" => 'y',
                                 "backup_interval" => $websrv['backup_interval']
                                 );
            $app->db->datalogInsert('web_database', $insert_data, 'database_id');
        }
        
interface/lib/classes/db_mysql.inc.php
@@ -626,20 +626,26 @@
        if(is_array($insert_data)) {
            $key_str = '';
            $val_str = '';
            $params = array($tablename);
            $v_params = array();
            foreach($insert_data as $key => $val) {
                $key_str .= "`".$key ."`,";
                $val_str .= "'".$this->escape($val)."',";
                $key_str .= '??,'
                $params[] = $key;
                $val_str .= '?,';
                $v_params[] = $val;
            }
            $key_str = substr($key_str, 0, -1);
            $val_str = substr($val_str, 0, -1);
            $insert_data_str = '('.$key_str.') VALUES ('.$val_str.')';
            $this->query("INSERT INTO ?? $insert_data_str", true, $params + $v_params);
        } else {
            /* TODO: deprecate this method! */
            $insert_data_str = $insert_data;
            $this->query("INSERT INTO ?? $insert_data_str", $tablename);
        }
        /* TODO: reduce risk of insert_data_str! */
        $old_rec = array();
        $this->query("INSERT INTO ?? $insert_data_str", $tablename);
        $index_value = $this->insertID();
        $new_rec = $this->queryOneRecord("SELECT * FROM ?? WHERE ? = ?", $tablename, $index_field, $index_value);
        $this->datalogSave($tablename, 'INSERT', $index_field, $index_value, $old_rec, $new_rec);
@@ -658,17 +664,23 @@
        $old_rec = $this->queryOneRecord("SELECT * FROM ?? WHERE ?? = ?", $tablename, $index_field, $index_value);
        if(is_array($update_data)) {
            $params = array($tablename);
            $update_data_str = '';
            foreach($update_data as $key => $val) {
                $update_data_str .= "`".$key ."` = '".$this->escape($val)."',";
                $update_data_str .= '?? = ?,';
                $params[] = $key;
                $params[] = $val;
            }
            $params[] = $index_field;
            $params[] = $index_value;
            $update_data_str = substr($update_data_str, 0, -1);
            $this->query("UPDATE ?? SET $update_data_str WHERE ?? = ?", true, $params);
        } else {
            /* TODO: deprecate this method! */
            $update_data_str = $update_data;
        }
        /* TODO: reduce risk of update_data_str */
        $this->query("UPDATE ?? SET $update_data_str WHERE ?? = ?", $tablename, $index_field, $index_value);
        }
        $new_rec = $this->queryOneRecord("SELECT * FROM ?? WHERE ?? = ?", $tablename, $index_field, $index_value);
        $this->datalogSave($tablename, 'UPDATE', $index_field, $index_value, $old_rec, $new_rec, $force_update);
interface/lib/classes/listform.inc.php
@@ -246,6 +246,7 @@
        return $this->pagingValues[$key];
    }
    /* TODO: maybe rewrite sql */
    public function getPagingSQL($sql_where = '1')
    {
        global $app, $conf;
@@ -283,7 +284,7 @@
        if($this->searchChanged == 1) $_SESSION['search'][$list_name]['page'] = 0;
        $sql_von = $app->functions->intval($_SESSION['search'][$list_name]['page'] * $records_per_page);
        $record_count = $app->db->queryOneRecord("SELECT count(*) AS anzahl FROM $table".($app->listform->listDef['additional_tables'] != ''? ','.$app->listform->listDef['additional_tables'] : '')." WHERE $sql_where");
        $record_count = $app->db->queryOneRecord("SELECT count(*) AS anzahl FROM ??".($app->listform->listDef['additional_tables'] != ''? ','.$app->listform->listDef['additional_tables'] : '')." WHERE $sql_where", $table);
        $pages = $app->functions->intval(($record_count['anzahl'] - 1) / $records_per_page);
@@ -483,6 +484,7 @@
        return $record;
    }
    /* TODO: check double quoting of SQL */
    public function encode($record)
    {
        global $app;
interface/lib/classes/listform_actions.inc.php
@@ -190,6 +190,7 @@
        return $rec;
    }
    /* TODO: maybe rewrite SQL */
    public function getQueryString($no_limit = false) {
        global $app;
        $sql_where = '';
interface/lib/classes/plugin_dbhistory.inc.php
@@ -47,12 +47,13 @@
        $db_table_idx = $app->tform->formDef["db_table_idx"];
        $primary_id = $this->form->id;
        if($_SESSION["s"]["user"]["typ"] == 'admin') {
            $sql = "SELECT action, tstamp, user, data FROM sys_datalog WHERE dbtable = '".$db_table."' AND dbidx = '".$db_table_idx.":".$primary_id."'";
            $sql = "SELECT action, tstamp, user, data FROM sys_datalog WHERE dbtable = ? AND dbidx = ?";
            $records = $app->db->queryAllRecords($sql, $db_table, $db_table_idx.":".$primary_id);
        } else {
            $sql = "SELECT action, tstamp, user, data FROM sys_datalog WHERE user = '".$_SESSION["s"]["user"]["username"]."' dbtable = '".$db_table."' AND dbidx = '".$db_table_idx.":".$primary_id."'";
            $sql = "SELECT action, tstamp, user, data FROM sys_datalog WHERE user = ? AND dbtable = ? AND dbidx = ?";
            $records = $app->db->queryAllRecords($sql, $_SESSION["s"]["user"]["username"], $db_table, $db_table_idx.":".$primary_id);
        }
        $records = $app->db->queryAllRecords($sql);
        if(is_array($records)) {
            $content .= '<table>';
            foreach($records as $rec) {
interface/lib/classes/remote.d/client.inc.php
@@ -468,7 +468,6 @@
            throw new SoapFault('permission_denied', 'You do not have the permissions to access this function.');
            return false;
        }
        $username = $app->db->quote($username);
        $rec = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE username = ?", $username);
        if (isset($rec)) {
            return $rec;
@@ -519,7 +518,6 @@
        $client_id = $app->functions->intval($client_id);
        $client = $app->db->queryOneRecord("SELECT client_id FROM client WHERE client_id = ?", $client_id);
        if($client['client_id'] > 0) {
            $new_password = $app->db->quote($new_password);
            $sql = "UPDATE client SET password = md5(?)     WHERE client_id = ?";
            $app->db->query($sql, $new_password, $client_id);
            $sql = "UPDATE sys_user SET passwort = md5(?)     WHERE client_id = ?";
interface/lib/classes/remote.d/mail.inc.php
@@ -1061,7 +1061,6 @@
            return false;
        }
        if (!empty($domain)) {
            $domain       = $app->db->quote($domain);
            $sql            = "SELECT * FROM mail_domain WHERE domain = ?";
            $result         = $app->db->queryAllRecords($sql, $domain);
            return          $result;
interface/lib/classes/remote.d/sites.inc.php
@@ -103,6 +103,7 @@
        return $app->remoting_lib->getDataRecord($primary_id);
    }
    /* TODO: secure queries! */
    //* Add a record
    public function sites_database_add($session_id, $client_id, $params)
    {
interface/lib/classes/remoting.inc.php
@@ -93,9 +93,6 @@
        $sql = "DELETE FROM remote_session WHERE tstamp < UNIX_TIMSTAMP()";
        $app->db->query($sql);
        $username = $app->db->quote($username);
        $password = $app->db->quote($password);
        if($client_login == true) {
            $sql = "SELECT * FROM sys_user WHERE USERNAME = ?";
            $user = $app->db->queryOneRecord($sql, $username);
@@ -175,8 +172,6 @@
            return false;
        }
        $session_id = $app->db->quote($session_id);
        $sql = "DELETE FROM remote_session WHERE remote_session = ?";
        if($app->db->query($sql, $session_id) != false) {
            return true;
@@ -201,7 +196,7 @@
        $sql = $app->remoting_lib->getSQL($params, 'INSERT', 0);
        //* Check if no system user with that username exists
        $username = $app->db->quote($params["username"]);
        $username = $params["username"];
        $tmp = $app->db->queryOneRecord("SELECT count(userid) as number FROM sys_user WHERE username = ?", $username);
        if($tmp['number'] > 0) $app->remoting_lib->errorMessage .= "Duplicate username<br />";
@@ -470,8 +465,6 @@
            throw new SoapFault('session_id_empty', 'The SessionID is empty.');
            return false;
        }
        $session_id = $app->db->quote($session_id);
        $sql = "SELECT * FROM remote_session WHERE remote_session = ? AND tstamp >= UNIX_TIMSTAMP()";
        $session = $app->db->queryOneRecord($sql, $session_id);
interface/lib/classes/remoting_lib.inc.php
@@ -262,12 +262,12 @@
    function ispconfig_sysuser_add($params, $insert_id){
        global $conf, $app, $sql1;
        $username = $app->db->quote($params["username"]);
        $password = $app->db->quote($params["password"]);
        $username = $params["username"];
        $password = $params["password"];
        if(!isset($params['modules'])) {
            $modules = $conf['interface_modules_enabled'];
        } else {
            $modules = $app->db->quote($params['modules']);
            $modules = $params['modules'];
        }
        if(isset($params['limit_client']) && $params['limit_client'] > 0) {
            $modules .= ',client';
@@ -276,18 +276,18 @@
        if(!isset($params['startmodule'])) {
            $startmodule = 'dashboard';
        } else {
            $startmodule = $app->db->quote($params["startmodule"]);
            $startmodule = $params["startmodule"];
            if(!preg_match('/'.$startmodule.'/', $modules)) {
                $_modules = explode(',', $modules);
                $startmodule=$_modules[0];
            }
        }
        $usertheme = $app->db->quote($params["usertheme"]);
        $usertheme = $params["usertheme"];
        $type = 'user';
        $active = 1;
        $insert_id = $app->functions->intval($insert_id);
        $language = $app->db->quote($params["language"]);
        $groupid = $app->db->datalogInsert('sys_group', "(name,description,client_id) VALUES ('$username','','$insert_id')", 'groupid');
        $language = $params["language"];
        $groupid = $app->db->datalogInsert('sys_group', array("name" => $username, "description" => "", "client_id" => $insert_id), 'groupid');
        $groups = $groupid;
        if(!isset($params['_ispconfig_pw_crypted']) || $params['_ispconfig_pw_crypted'] != 1) $password = $app->auth->crypt_password(stripslashes($password));
        $sql1 = "INSERT INTO sys_user (username,passwort,modules,startmodule,app_theme,typ,active,language,groups,default_group,client_id)
@@ -297,8 +297,8 @@
    function ispconfig_sysuser_update($params, $client_id){
        global $app;
        $username = $app->db->quote($params["username"]);
        $clear_password = $app->db->quote($params["password"]);
        $username = $params["username"];
        $clear_password = $params["password"];
        $client_id = $app->functions->intval($client_id);
        if(!isset($params['_ispconfig_pw_crypted']) || $params['_ispconfig_pw_crypted'] != 1) $password = $app->auth->crypt_password(stripslashes($clear_password));
        else $password = $clear_password;
interface/lib/classes/searchform.inc.php
@@ -177,7 +177,7 @@
        if($this->searchChanged == 1)   $_SESSION['search'][$list_name]['page'] = 0;
        $sql_von = $_SESSION['search'][$list_name]['page'] * $records_per_page;
        $record_count = $app->db->queryOneRecord("SELECT count(*) AS anzahl FROM $table WHERE $sql_where");
        $record_count = $app->db->queryOneRecord("SELECT count(*) AS anzahl FROM ?? WHERE $sql_where", $table);
        $pages = $app->functions->intval(($record_count['anzahl'] - 1) / $records_per_page);
        $vars['list_file']      = $this->listDef['file'];
@@ -247,7 +247,7 @@
        $list_name = $this->listDef['name'];
        $settings = $_SESSION['search'][$list_name];
        unset($settings['page']);
        $data = $app->db->quote(serialize($settings));
        $data = serialize($settings);
        $userid = $_SESSION['s']['user']['userid'];
        $groupid = $_SESSION['s']['user']['default_group'];
@@ -260,9 +260,8 @@
        $sql = 'INSERT INTO `searchform` ( '
            .'`sys_userid` , `sys_groupid` , `sys_perm_user` , `sys_perm_group` , `sys_perm_other` , `module` , `searchform` , `title` , `data` '
            .')VALUES ('
            ."'$userid', '$groupid', '$sys_perm_user', '$sys_perm_group', '$sys_perm_other', '$module', '$searchform', '$title', '$data')";
        $app->db->query($sql);
            .')VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)';
        $app->db->query($sql, $userid, $groupid, $sys_perm_user, $sys_perm_group, $sys_perm_other, $module, $searchform, $title, $data);
    }
    public function decode($record)
@@ -303,6 +302,7 @@
        return $record;
    }
    /* TODO: check for double quoting mysql value */
    public function encode($record)
    {
        global $app;
interface/lib/classes/sites_database_plugin.inc.php
@@ -44,7 +44,7 @@
            //* The Database user shall be owned by the same group then the website
            $sys_groupid = $app->functions->intval($web['sys_groupid']);
            $backup_interval = $app->db->quote($web['backup_interval']);
            $backup_interval = $web['backup_interval'];
            $backup_copies = $app->functions->intval($web['backup_copies']);
            $sql = "UPDATE web_database SET sys_groupid = ?, backup_interval = ?, backup_copies = ? WHERE database_id = ?";
interface/lib/classes/tform.inc.php
@@ -79,8 +79,8 @@
                $escape = '`';
            }
            $sql = "SELECT ".$this->formDef['db_table_idx']." FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$record_id." AND ".$this->getAuthSQL($perm);
            if($record = $app->db->queryOneRecord($sql)) {
            $sql = "SELECT ?? FROM ?? WHERE ?? = ? AND ".$this->getAuthSQL($perm);
            if($record = $app->db->queryOneRecord($sql, $this->formDef['db_table_idx'], $this->formDef['db_table'], $this->formDef['db_table_idx'], $record_id)) {
                return true;
            } else {
                return false;
@@ -133,8 +133,8 @@
            $escape = '`';
        }
        $sql = "SELECT sys_userid FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id;
        $record = $app->db->queryOneRecord($sql);
        $sql = "SELECT sys_userid FROM ?? WHERE ?? = ?";
        $record = $app->db->queryOneRecord($sql, $this->formDef['db_table'], $this->formDef['db_table_idx'], $primary_id);
        // return true if the readonly flag of the form is set and the current loggedin user is not the owner of the record.
        if(isset($this->formDef['tabs'][$tab]['readonly']) && $this->formDef['tabs'][$tab]['readonly'] == true && $record['sys_userid'] != $_SESSION["s"]["user"]["userid"]) {
@@ -161,18 +161,17 @@
        global $app;
        $check_passed = true;
        $limit_name = $app->db->quote($limit_name);
        if($limit_name == '') $app->error('Limit name missing in function checkClientLimit.');
        // Get the limits of the client that is currently logged in
        $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
        $client = $app->db->queryOneRecord("SELECT $limit_name as number, parent_client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ?", $client_group_id);
        $client = $app->db->queryOneRecord("SELECT ?? as number, parent_client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ?", $limit_name, $client_group_id);
        // Check if the user may add another item
        if($client["number"] >= 0) {
            $sql = "SELECT count(".$this->formDef['db_table_idx'].") as number FROM ".$this->formDef['db_table']." WHERE ".$this->getAuthSQL('u');
            $sql = "SELECT count(??) as number FROM ?? WHERE ".$this->getAuthSQL('u');
            if($sql_where != '') $sql .= ' and '.$sql_where;
            $tmp = $app->db->queryOneRecord($sql);
            $tmp = $app->db->queryOneRecord($sql, $this->formDef['db_table_idx'], $this->formDef['db_table']);
            if($tmp["number"] >= $client["number"]) $check_passed = false;
        }
@@ -183,7 +182,6 @@
        global $app;
        $check_passed = true;
        $limit_name = $app->db->quote($limit_name);
        if($limit_name == '') $app->error('Limit name missing in function checkClientLimit.');
        // Get the limits of the client that is currently logged in
@@ -194,19 +192,19 @@
        if($client['parent_client_id'] != 0) {
            //* first we need to know the groups of this reseller
            $tmp = $app->db->queryOneRecord("SELECT userid, groups FROM sys_user WHERE client_id = ".$client['parent_client_id']);
            $tmp = $app->db->queryOneRecord("SELECT userid, groups FROM sys_user WHERE client_id = ?", $client['parent_client_id']);
            $reseller_groups = $tmp["groups"];
            $reseller_userid = $tmp["userid"];
            // Get the limits of the reseller of the logged in client
            $client_group_id = $_SESSION["s"]["user"]["default_group"];
            $reseller = $app->db->queryOneRecord("SELECT $limit_name as number FROM client WHERE client_id = ".$client['parent_client_id']);
            $reseller = $app->db->queryOneRecord("SELECT $limit_name as number FROM client WHERE client_id = ?", $client['parent_client_id']);
            // Check if the user may add another item
            if($reseller["number"] >= 0) {
                $sql = "SELECT count(".$this->formDef['db_table_idx'].") as number FROM ".$this->formDef['db_table']." WHERE (sys_groupid IN (".$reseller_groups.") or sys_userid = ".$reseller_userid.")";
                $sql = "SELECT count(??) as number FROM ?? WHERE (sys_groupid IN ? or sys_userid = ?)";
                if($sql_where != '') $sql .= ' and '.$sql_where;
                $tmp = $app->db->queryOneRecord($sql);
                $tmp = $app->db->queryOneRecord($sql, $this->formDef['db_table_idx'], $this->formDef['db_table'], explode(',', $reseller_groups), $reseller_userid);
                if($tmp["number"] >= $reseller["number"]) $check_passed = false;
            }
        }
interface/lib/classes/tform_base.inc.php
@@ -365,13 +365,13 @@
                if($client['parent_client_id'] != 0) {
                    //* first we need to know the groups of this reseller
                    $tmp = $app->db->queryOneRecord("SELECT userid, groups FROM sys_user WHERE client_id = ".$client['parent_client_id']);
                    $tmp = $app->db->queryOneRecord("SELECT userid, groups FROM sys_user WHERE client_id = ?", $client['parent_client_id']);
                    $reseller_groups = $tmp["groups"];
                    $reseller_userid = $tmp["userid"];
                    // Get the limits of the reseller of the logged in client
                    $client_group_id = $_SESSION["s"]["user"]["default_group"];
                    $reseller = $app->db->queryOneRecord("SELECT ".$limit_parts[1]." as lm FROM client WHERE client_id = ".$client['parent_client_id']);
                    $reseller = $app->db->queryOneRecord("SELECT ".$limit_parts[1]." as lm FROM client WHERE client_id = ?", $client['parent_client_id']);
                    $allowed = explode(',', $reseller['lm']);
                } else {
                    return $values;
@@ -853,7 +853,7 @@
                if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n';
                if($validator['allowempty'] == 'n' || ($validator['allowempty'] == 'y' && $field_value != '')){
                    if($this->action == 'NEW') {
                        $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."'");
                        $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ?? WHERE ?? = ?", $this->formDef['db_table'], $field_name, $field_value);
                        if($num_rec["number"] > 0) {
                            $errmsg = $validator['errmsg'];
                            if(isset($this->wordbook[$errmsg])) {
@@ -863,7 +863,7 @@
                            }
                        }
                    } else {
                        $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."' AND ".$this->formDef['db_table_idx']." != ".$this->primary_id);
                        $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ?? WHERE ?? = ? AND ?? != ?", $this->formDef['db_table'], $field_name, $field_value, $this->formDef['db_table_idx'], $this->primary_id);
                        if($num_rec["number"] > 0) {
                            $errmsg = $validator['errmsg'];
                            if(isset($this->wordbook[$errmsg])) {
@@ -1139,7 +1139,7 @@
                                $record[$key] = $app->auth->crypt_password(stripslashes($record[$key]));
                                $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
                            } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') {
                                $tmp = $app->db->queryOneRecord("SELECT PASSWORD('".$app->db->quote(stripslashes($record[$key]))."') as `crypted`");
                                $tmp = $app->db->queryOneRecord("SELECT PASSWORD(?) as `crypted`", stripslashes($record[$key]));
                                $record[$key] = $tmp['crypted'];
                                $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
                            } else {
@@ -1167,7 +1167,7 @@
                                $record[$key] = $app->auth->crypt_password(stripslashes($record[$key]));
                                $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
                            } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') {
                                $tmp = $app->db->queryOneRecord("SELECT PASSWORD('".$app->db->quote(stripslashes($record[$key]))."') as `crypted`");
                                $tmp = $app->db->queryOneRecord("SELECT PASSWORD(?) as `crypted`", stripslashes($record[$key]));
                                $record[$key] = $tmp['crypted'];
                                $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
                            } else {
@@ -1359,8 +1359,8 @@
    function getDataRecord($primary_id) {
        global $app;
        $escape = '`';
        $sql = "SELECT * FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id." AND ".$this->getAuthSQL('r', $this->formDef['db_table']);
        return $app->db->queryOneRecord($sql);
        $sql = "SELECT * FROM ?? WHERE ?? = ? AND ".$this->getAuthSQL('r', $this->formDef['db_table']);
        return $app->db->queryOneRecord($sql, $this->formDef['db_table'], $this->formDef['db_table_idx'], $primary_id);
    }
interface/lib/classes/tools_sites.inc.php
@@ -144,6 +144,7 @@
        return $res;
    }
    /* TODO: rewrite SQL */
    function getDomainModuleDomains($not_used_in_table = null, $selected_domain = null) {
        global $app;
@@ -168,6 +169,7 @@
        return $app->db->queryAllRecords($sql, $not_used_in_table, $selected_domain);
    }
    /* TODO: rewrite SQL */
    function checkDomainModuleDomain($domain_id) {
        global $app;
@@ -181,6 +183,7 @@
        return $domain['domain'];
    }
    /* TODO: rewrite SQL */
    function getClientIdForDomain($domain_id) {
        global $app;
interface/lib/plugins/mail_user_filter_plugin.inc.php
@@ -86,8 +86,7 @@
            $out = $new_rule . $out;
        }
        $out = $app->db->quote($out);
        $app->db->datalogUpdate('mail_user', "custom_mailfilter = '$out'", 'mailuser_id', $page_form->dataRecord["mailuser_id"]);
        $app->db->datalogUpdate('mail_user', array("custom_mailfilter" => $out), 'mailuser_id', $page_form->dataRecord["mailuser_id"]);
    }
@@ -111,8 +110,7 @@
            }
        }
        $out = $app->db->quote($out);
        $app->db->datalogUpdate('mail_user', "custom_mailfilter = '$out'", 'mailuser_id', $page_form->dataRecord["mailuser_id"]);
        $app->db->datalogUpdate('mail_user', array("custom_mailfilter" => $out), 'mailuser_id', $page_form->dataRecord["mailuser_id"]);
    }
interface/lib/plugins/sites_web_vhost_domain_plugin.inc.php
@@ -227,15 +227,15 @@
                if(empty($web_rec['php_open_basedir']) ||
                    (!empty($page_form->dataRecord["domain"]) && !empty($page_form->oldDataRecord["domain"]) && $page_form->dataRecord["domain"] != $page_form->oldDataRecord["domain"])) {
                    $php_open_basedir = $web_rec['php_open_basedir'];
                    $php_open_basedir = $app->db->quote(str_replace($page_form->oldDataRecord['domain'], $web_rec['domain'], $php_open_basedir));
                    $php_open_basedir = str_replace($page_form->oldDataRecord['domain'], $web_rec['domain'], $php_open_basedir);
                    $sql = "UPDATE web_domain SET php_open_basedir = ? WHERE domain_id = ?";
                    $app->db->query($sql, $php_open_basedir, $page_form->id);
                }
                if(empty($web_rec['php_open_basedir']) ||
                    (isset($page_form->dataRecord["client_group_id"]) && $page_form->dataRecord["client_group_id"] != $page_form->oldDataRecord["sys_groupid"])) {
                    $document_root = $app->db->quote(str_replace("[client_id]", $client_id, $document_root));
                    $document_root = str_replace("[client_id]", $client_id, $document_root);
                    $php_open_basedir = str_replace("[website_path]", $document_root, $web_config["php_open_basedir"]);
                    $php_open_basedir = $app->db->quote(str_replace("[website_domain]", $web_rec['domain'], $php_open_basedir));
                    $php_open_basedir = str_replace("[website_domain]", $web_rec['domain'], $php_open_basedir);
                    $sql = "UPDATE web_domain SET php_open_basedir = ? WHERE domain_id = ?";
                    $app->db->query($sql, $php_open_basedir, $page_form->id);
                }
@@ -243,11 +243,11 @@
                //* Change database backup options when web backup options have been changed
                if(isset($page_form->dataRecord['backup_interval']) && ($page_form->dataRecord['backup_interval'] != $page_form->oldDataRecord['backup_interval'] || $page_form->dataRecord['backup_copies'] != $page_form->oldDataRecord['backup_copies'])) {
                    //* Update all databases
                    $backup_interval = $app->db->quote($page_form->dataRecord['backup_interval']);
                    $backup_interval = $page_form->dataRecord['backup_interval'];
                    $backup_copies = $app->functions->intval($page_form->dataRecord['backup_copies']);
                    $records = $app->db->queryAllRecords("SELECT database_id FROM web_database WHERE parent_domain_id = ".$page_form->id);
                    foreach($records as $rec) {
                        $app->db->datalogUpdate('web_database', "backup_interval = '$backup_interval', backup_copies = '$backup_copies'", 'database_id', $rec['database_id']);
                        $app->db->datalogUpdate('web_database', array("backup_interval" => $backup_interval, "backup_copies" => $backup_copies), 'database_id', $rec['database_id']);
                    }
                    unset($records);
                    unset($rec);
interface/lib/plugins/vm_openvz_plugin.inc.php
@@ -214,9 +214,9 @@
        $full_hostname = str_replace('{VEID}', $vm['veid'], $vm['hostname']);
        $hostname_parts = explode('.', $full_hostname);
        $hostname = $app->db->quote($hostname_parts[0]);
        $hostname = $hostname_parts[0];
        unset($hostname_parts[0]);
        $zone = $app->db->quote((implode('.', $hostname_parts)));
        $zone = implode('.', $hostname_parts);
        unset($hostname_parts);
        // Find the dns zone
@@ -224,7 +224,7 @@
        $rr_rec = $app->db->queryOneRecord("SELECT * FROM dns_rr WHERE zone = ? AND name = ?", $zone_rec['id'], $hostname);
        if($zone_rec['id'] > 0) {
            $ip_address = $app->db->quote($vm['ip_address']);
            $ip_address = $vm['ip_address'];
            $sys_userid = $app->functions->intval($zone_rec['sys_userid']);
            $sys_groupid = $app->functions->intval($zone_rec['sys_groupid']);
            $server_id = $app->functions->intval($zone_rec['server_id']);
interface/web/admin/server_config_edit.php
@@ -96,7 +96,7 @@
            $server_config_array[$section] = $app->tform->encode($this->dataRecord, $section);
            $server_config_str = $app->ini_parser->get_ini_string($server_config_array);
            $app->db->datalogUpdate('server', "config = '".$app->db->quote($server_config_str)."'", 'server_id', $server_id);
            $app->db->datalogUpdate('server', array("config" => $server_config_str), 'server_id', $server_id);
        }
    }
interface/web/admin/software_package_install.php
@@ -38,9 +38,9 @@
//* This is only allowed for administrators
if(!$app->auth->is_admin()) die('only allowed for administrators.');
$package_name = $app->db->quote($_REQUEST['package']);
$package_name = $_REQUEST['package'];
$install_server_id = $app->functions->intval($_REQUEST['server_id']);
$install_key = $app->db->quote(trim($_REQUEST['install_key']));
$install_key = trim($_REQUEST['install_key']);
$package = $app->db->queryOneRecord("SELECT * FROM software_package WHERE package_name = ?", $package_name);
@@ -105,7 +105,7 @@
        if(!isset($package_config_array['remote_api'])) {
            $remote_user = 'ispapp'.$package['package_id'];
            $remote_password = md5(mt_rand());
            $remote_functions = $app->db->quote($package['package_remote_functions']);
            $remote_functions = $package['package_remote_functions'];
            $package_config_array['remote_api'] = array(
                'remote_hostname' => $_SERVER['HTTP_HOST'],
@@ -116,7 +116,7 @@
            $package_config_str = $app->ini_parser->get_ini_string($package_config_array);
            $package['package_config'] = $package_config_str;
            $remote_password_md5 = md5($remote_password);
            $app->db->datalogUpdate('software_package', "package_config = '".$app->db->quote($package_config_str)."'", 'package_id', $package['package_id']);
            $app->db->datalogUpdate('software_package', array("package_config" => $package_config_str), 'package_id', $package['package_id']);
            $sql = "INSERT INTO `remote_user` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `remote_username`, `remote_password`, `remote_functions`) VALUES
                    (1, 1, 'riud', 'riud', '', ?, ?, ?)";
interface/web/admin/software_package_list.php
@@ -48,23 +48,40 @@
        $packages = $client->get_packages($repo['repo_username'], $repo['repo_password']);
        if(is_array($packages)) {
            foreach($packages as $p) {
                $package_name = $app->db->quote($p['name']);
                $package_name = $p['name'];
                $tmp = $app->db->queryOneRecord("SELECT package_id FROM software_package WHERE package_name = ?", $package_name);
                $package_title = $app->db->quote($p['title']);
                $package_description = $app->db->quote($p['description']);
                $package_title = $p['title'];
                $package_description = $p['description'];
                $software_repo_id = $app->functions->intval($repo['software_repo_id']);
                $package_type = $app->db->quote($p['type']);
                $package_installable = $app->db->quote($p['installable']);
                $package_requires_db = $app->db->quote($p['requires_db']);
                $package_remote_functions = $app->db->quote($p['remote_functions']);
                $package_type = $p['type'];
                $package_installable = $p['installable'];
                $package_requires_db = $p['requires_db'];
                $package_remote_functions = $p['remote_functions'];
                if(empty($tmp['package_id'])) {
                    $insert_data = "(software_repo_id, package_name, package_title, package_description,package_type,package_installable,package_requires_db,package_remote_functions) VALUES ($software_repo_id, '$package_name', '$package_title', '$package_description','$package_type','$package_installable','$package_requires_db','$package_remote_functions')";
                    $insert_data = array(
                        "software_repo_id" => $software_repo_id,
                        "package_name" => $package_name,
                        "package_title" => $package_title,
                        "package_description" => $package_description,
                        "package_type" => $package_type,
                        "package_installable" => $package_installable,
                        "package_requires_db" => $package_requires_db,
                        "package_remote_functions" => $package_remote_functions
                        );
                    $app->db->datalogInsert('software_package', $insert_data, 'package_id');
                    $packages_added++;
                } else {
                    $update_data = "software_repo_id = $software_repo_id, package_title = '$package_title', package_description = '$package_description', package_type = '$package_type', package_installable = '$package_installable', package_requires_db = '$package_requires_db', package_remote_functions = '$package_remote_functions'";
                    $update_data = array(
                        "software_repo_id" => $software_repo_id,
                        "package_title" => $package_title,
                        "package_description" => $package_description,
                        "package_type" => $package_type,
                        "package_installable" => $package_installable,
                        "package_requires_db" => $package_requires_db,
                        "package_remote_functions" => $package_remote_functions
                        );
                    //echo $update_data;
                    $app->db->datalogUpdate('software_package', $update_data, 'package_id', $tmp['package_id']);
                }
@@ -99,8 +116,19 @@
                        $sql = "SELECT * FROM software_update WHERE package_name = ? and v1 = ? and v2 = ? and v3 = ? and v4 = ?";
                        $tmp = $app->db->queryOneRecord($sql, $package_name, $v1, $v2, $v3, $v4);
                        if(!isset($tmp['software_update_id'])) {
                            $insert_data = "(software_repo_id, package_name, update_url, update_md5, update_dependencies, update_title, v1, v2, v3, v4, type)
                            VALUES ($software_repo_id, '$package_name', '$update_url', '$update_md5', '$update_dependencies', '$update_title', '$v1', '$v2', '$v3', '$v4', '$type')";
                            $insert_data = array(
                                "software_repo_id" => $software_repo_id,
                                "package_name" => $package_name,
                                "update_url" => $update_url,
                                "update_md5" => $update_md5,
                                "update_dependencies" => $update_dependencies,
                                "update_title" => $update_title,
                                "v1" => $v1,
                                "v2" => $v2,
                                "v3" => $v3,
                                "v4" => $v4,
                                "type" => $type
                            );
                            $app->db->datalogInsert('software_update', $insert_data, 'software_update_id');
                        }
interface/web/admin/software_update_list.php
@@ -72,13 +72,13 @@
                        $v3 = $app->functions->intval($version_array[2]);
                        $v4 = $app->functions->intval($version_array[3]);
                        $package_name = $app->db->quote($u['package_name']);
                        $package_name = $u['package_name'];
                        $software_repo_id = $app->functions->intval($repo['software_repo_id']);
                        $update_url = $app->db->quote($u['url']);
                        $update_md5 = $app->db->quote($u['md5']);
                        $update_dependencies = (isset($u['dependencies']))?$app->db->quote($u['dependencies']):'';
                        $update_title = $app->db->quote($u['title']);
                        $type = $app->db->quote($u['type']);
                        $update_url = $u['url'];
                        $update_md5 = $u['md5'];
                        $update_dependencies = (isset($u['dependencies']))?$u['dependencies']:'';
                        $update_title = $u['title'];
                        $type = $u['type'];
                        // Check that we do not have this update in the database yet
                        $sql = "SELECT * FROM software_update WHERE package_name = ? and v1 = ? and v2 = ? and v3 = ? and v4 = ?";
interface/web/admin/system_config_edit.php
@@ -165,7 +165,7 @@
        $server_config_array[$section] = $new_config;
        $server_config_str = $app->ini_parser->get_ini_string($server_config_array);
        if($conf['demo_mode'] != true) $app->db->datalogUpdate('sys_ini', "config = '".$app->db->quote($server_config_str)."'", 'sysini_id', 1);
        if($conf['demo_mode'] != true) $app->db->datalogUpdate('sys_ini', array("config" => $server_config_str), 'sysini_id', 1);
        /*
         * If we should use the domain-module, we have to insert all existing domains into the table
interface/web/admin/users_edit.php
@@ -98,8 +98,8 @@
        $client = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE userid = ?", $this->id);
        $client_id = $app->functions->intval($client['client_id']);
        $username = $app->db->quote($this->dataRecord["username"]);
        $old_username = $app->db->quote($this->oldDataRecord['username']);
        $username = $this->dataRecord["username"];
        $old_username = $this->oldDataRecord['username'];
        // username changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord['username']) && $this->dataRecord['username'] != '' && $this->oldDataRecord['username'] != $this->dataRecord['username']) {
@@ -112,7 +112,7 @@
        // password changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord["passwort"]) && $this->dataRecord["passwort"] != '') {
            $password = $app->db->quote($this->dataRecord["passwort"]);
            $password = $this->dataRecord["passwort"];
            $salt="$1$";
            $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
            for ($n=0;$n<8;$n++) {
@@ -126,7 +126,7 @@
        // language changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord['language']) && $this->dataRecord['language'] != '' && $this->oldDataRecord['language'] != $this->dataRecord['language']) {
            $language = $app->db->quote($this->dataRecord["language"]);
            $language = $this->dataRecord["language"];
            $sql = "UPDATE client SET language = ? WHERE client_id = ? AND username = ?";
            $app->db->query($sql, $language, $client_id, $username);
        }
interface/web/client/client_edit.php
@@ -103,7 +103,7 @@
        }
        if($this->id != 0) {
            $this->oldTemplatesAssigned = $app->db->queryAllRecords('SELECT * FROM `client_template_assigned` WHERE `client_id` = ' . $this->id);
            $this->oldTemplatesAssigned = $app->db->queryAllRecords('SELECT * FROM `client_template_assigned` WHERE `client_id` = ?', $this->id);
            if(!is_array($this->oldTemplatesAssigned) || count($this->oldTemplatesAssigned) < 1) {
                // check previous type of storing templates
                $tpls = explode('/', $this->oldDataRecord['template_additional']);
@@ -140,7 +140,7 @@
        $app->tpl->setVar('tpl_add_select', $option);
        // check for new-style records
        $result = $app->db->queryAllRecords('SELECT assigned_template_id, client_template_id FROM client_template_assigned WHERE client_id = ' . $this->id);
        $result = $app->db->queryAllRecords('SELECT assigned_template_id, client_template_id FROM client_template_assigned WHERE client_id = ?', $this->id);
        if($result && count($result) > 0) {
            // new style
            $items = array();
@@ -166,8 +166,8 @@
            unset($tmprec);
        } else {
            // old style
            $sql = "SELECT template_additional FROM client WHERE client_id = " . $this->id;
            $result = $app->db->queryOneRecord($sql);
            $sql = "SELECT template_additional FROM client WHERE client_id = ?";
            $result = $app->db->queryOneRecord($sql, $this->id);
            $tplAdd = explode("/", $result['template_additional']);
            $text = '';
            foreach($tplAdd as $item){
@@ -196,31 +196,18 @@
                    $customer_no = $app->functions->intval($system_config['misc']['customer_no_start']+$system_config['misc']['customer_no_counter']);
                    $customer_no_string = str_replace('[CUSTOMER_NO]',$customer_no,$system_config['misc']['customer_no_template']);
                    $app->tpl->setVar('customer_no',$customer_no_string);
                    //* save new counter value
                    /*
                    $system_config['misc']['customer_no_counter']++;
                    $system_config_str = $app->ini_parser->get_ini_string($system_config);
                    $app->db->datalogUpdate('sys_ini', "config = '".$app->db->quote($system_config_str)."'", 'sysini_id', 1);
                    */
                }
            } else {
                //* Logged in user must be a reseller
                //* get the record of the reseller
                $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
                $reseller = $app->db->queryOneRecord("SELECT client.client_id, client.customer_no_template, client.customer_no_counter, client.customer_no_start FROM sys_group,client WHERE client.client_id = sys_group.client_id and sys_group.groupid = ".$client_group_id);
                $reseller = $app->db->queryOneRecord("SELECT client.client_id, client.customer_no_template, client.customer_no_counter, client.customer_no_start FROM sys_group,client WHERE client.client_id = sys_group.client_id and sys_group.groupid = ?", $client_group_id);
                
                if($reseller['customer_no_template'] != '') {
                    //* Set customer no default
                    $customer_no = $app->functions->intval($reseller['customer_no_start']+$reseller['customer_no_counter']);
                    $customer_no_string = str_replace('[CUSTOMER_NO]',$customer_no,$reseller['customer_no_template']);
                    $app->tpl->setVar('customer_no',$customer_no_string);
                    //* save new counter value
                    /*
                    $customer_no_counter = $app->functions->intval($reseller['customer_no_counter']+1);
                    $app->db->query("UPDATE client SET customer_no_counter = $customer_no_counter WHERE client_id = ".$app->functions->intval($reseller['client_id']));
                    */
                }
            }
        }
@@ -257,39 +244,39 @@
        $groupid = $app->db->datalogInsert('sys_group', "(name,description,client_id) VALUES ('".$app->db->quote($this->dataRecord["username"])."','',".$this->id.")", 'groupid');
        $groups = $groupid;
        $username = $app->db->quote($this->dataRecord["username"]);
        $password = $app->db->quote($this->dataRecord["password"]);
        $username = $this->dataRecord["username"];
        $password = $this->dataRecord["password"];
        $modules = $conf['interface_modules_enabled'];
        if(isset($this->dataRecord["limit_client"]) && $this->dataRecord["limit_client"] > 0) $modules .= ',client';
        $startmodule = (stristr($modules, 'dashboard'))?'dashboard':'client';
        $usertheme = $app->db->quote($this->dataRecord["usertheme"]);
        $usertheme = $this->dataRecord["usertheme"];
        $type = 'user';
        $active = 1;
        $language = $app->db->quote($this->dataRecord["language"]);
        $language = $this->dataRecord["language"];
        $password = $app->auth->crypt_password($password);
        // Create the controlpaneluser for the client
        //Generate ssh-rsa-keys
        exec('ssh-keygen -t rsa -C '.$username.'-rsa-key-'.time().' -f /tmp/id_rsa -N ""');
        $app->db->query("UPDATE client SET created_at = ".time().", id_rsa = '".$app->db->quote(@file_get_contents('/tmp/id_rsa'))."', ssh_rsa = '".$app->db->quote(@file_get_contents('/tmp/id_rsa.pub'))."' WHERE client_id = ".$this->id);
        $app->db->query("UPDATE client SET created_at = UNIX_TIMESTAMP(), id_rsa = ?, ssh_rsa = ? WHERE client_id = ?", @file_get_contents('/tmp/id_rsa'), @file_get_contents('/tmp/id_rsa.pub'), $this->id);
        exec('rm -f /tmp/id_rsa /tmp/id_rsa.pub');
        // Create the controlpaneluser for the client
        $sql = "INSERT INTO sys_user (username,passwort,modules,startmodule,app_theme,typ,active,language,groups,default_group,client_id)
        VALUES ('$username','$password','$modules','$startmodule','$usertheme','$type','$active','$language',$groups,$groupid,".$this->id.")";
        $app->db->query($sql);
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $app->db->query($sql, $username, $password, $modules, $startmodule, $usertheme, $type, $active, $language, $groups, $groupid, $this->id);
        //* If the user who inserted the client is a reseller (not admin), we will have to add this new client group
        //* to his groups, so he can administrate the records of this client.
        if($_SESSION['s']['user']['typ'] == 'user') {
            $app->auth->add_group_to_user($_SESSION['s']['user']['userid'], $groupid);
            $app->db->query("UPDATE client SET parent_client_id = ".$app->functions->intval($_SESSION['s']['user']['client_id'])." WHERE client_id = ".$this->id);
            $app->db->query("UPDATE client SET parent_client_id = ? WHERE client_id = ?", $_SESSION['s']['user']['client_id'], $this->id);
        } else {
            if($this->dataRecord['parent_client_id'] > 0) {
                //* get userid of the reseller and add it to the group of the client
                $tmp = $app->db->queryOneRecord("SELECT sys_user.userid FROM sys_user,sys_group WHERE sys_user.default_group = sys_group.groupid AND sys_group.client_id = ".$app->functions->intval($this->dataRecord['parent_client_id']));
                $tmp = $app->db->queryOneRecord("SELECT sys_user.userid FROM sys_user,sys_group WHERE sys_user.default_group = sys_group.groupid AND sys_group.client_id = ?", $this->dataRecord['parent_client_id']);
                $app->auth->add_group_to_user($tmp['userid'], $groupid);
                $app->db->query("UPDATE client SET parent_client_id = ".$app->functions->intval($this->dataRecord['parent_client_id'])." WHERE client_id = ".$this->id);
                $app->db->query("UPDATE client SET parent_client_id = ? WHERE client_id = ?", $this->dataRecord['parent_client_id'], $this->id);
                unset($tmp);
            }
        }
@@ -319,8 +306,8 @@
            $default_dnsserver = $app->functions->intval($tmp['server_id']);
        }
        $sql = "UPDATE client SET mail_servers = $default_mailserver, web_servers = $default_webserver, dns_servers = $default_dnsserver, default_slave_dnsserver = $default_dnsserver, db_servers = $default_dbserver WHERE client_id = ".$this->id;
        $app->db->query($sql);
        $sql = "UPDATE client SET mail_servers = ?, web_servers = ?, dns_servers = ?, default_slave_dnsserver = ?, db_servers = ? WHERE client_id = ?";
        $app->db->query($sql, $default_mailserver, $default_webserver, $default_dnsserver, $default_dnsserver, $default_dbserver, $this->id);
        if(isset($this->dataRecord['template_master'])) {
            $app->uses('client_templates');
@@ -344,20 +331,20 @@
                //* Logged in user must be a reseller
                //* get the record of the reseller
                $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
                $reseller = $app->db->queryOneRecord("SELECT client.client_id, client.customer_no_template, client.customer_no_counter, client.customer_no_start FROM sys_group,client WHERE client.client_id = sys_group.client_id and sys_group.groupid = ".$client_group_id);
                $reseller = $app->db->queryOneRecord("SELECT client.client_id, client.customer_no_template, client.customer_no_counter, client.customer_no_start FROM sys_group,client WHERE client.client_id = sys_group.client_id and sys_group.groupid = ?", $client_group_id);
                
                if($reseller['customer_no_template'] != '') {
                    //* save new counter value
                    $customer_no_counter = $app->functions->intval($reseller['customer_no_counter']+1);
                    $app->db->query("UPDATE client SET customer_no_counter = $customer_no_counter WHERE client_id = ".$app->functions->intval($reseller['client_id']));
                    $app->db->query("UPDATE client SET customer_no_counter = ? WHERE client_id = ?", $customer_no_counter, $reseller['client_id']);
                }
            }
        }
        
        //* Send welcome email
        $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
        $sql = "SELECT * FROM client_message_template WHERE template_type = 'welcome' AND sys_groupid = ".$client_group_id;
        $email_template = $app->db->queryOneRecord($sql);
        $sql = "SELECT * FROM client_message_template WHERE template_type = 'welcome' AND sys_groupid = ?";
        $email_template = $app->db->queryOneRecord($sql, $client_group_id);
        $client = $app->tform->getDataRecord($this->id);
        if(is_array($email_template) && $client['email'] != '') {
@@ -387,7 +374,7 @@
                $from = $system_config['admin_mail'];
            } else {
                $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
                $reseller = $app->db->queryOneRecord("SELECT client.email FROM sys_group,client WHERE client.client_id = sys_group.client_id and sys_group.groupid = ".$client_group_id);
                $reseller = $app->db->queryOneRecord("SELECT client.email FROM sys_group,client WHERE client.client_id = sys_group.client_id and sys_group.groupid = ?", $client_group_id);
                $from = $reseller["email"];
            }
@@ -408,19 +395,19 @@
        global $app, $conf;
        // username changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord['username']) && $this->dataRecord['username'] != '' && $this->oldDataRecord['username'] != $this->dataRecord['username']) {
            $username = $app->db->quote($this->dataRecord["username"]);
            $username = $this->dataRecord["username"];
            $client_id = $this->id;
            $sql = "UPDATE sys_user SET username = '$username' WHERE client_id = $client_id";
            $app->db->query($sql);
            $sql = "UPDATE sys_user SET username = ? WHERE client_id = ?";
            $app->db->query($sql, $username, $client_id);
            $tmp = $app->db->queryOneRecord("SELECT * FROM sys_group WHERE client_id = $client_id");
            $app->db->datalogUpdate("sys_group", "name = '$username'", 'groupid', $tmp['groupid']);
            $tmp = $app->db->queryOneRecord("SELECT * FROM sys_group WHERE client_id = ?", $client_id);
            $app->db->datalogUpdate("sys_group", array("name" => $username), 'groupid', $tmp['groupid']);
            unset($tmp);
        }
        // password changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord["password"]) && $this->dataRecord["password"] != '') {
            $password = $app->db->quote($this->dataRecord["password"]);
            $password = $this->dataRecord["password"];
            $salt="$1$";
            $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
            for ($n=0;$n<8;$n++) {
@@ -429,8 +416,8 @@
            $salt.="$";
            $password = crypt(stripslashes($password), $salt);
            $client_id = $this->id;
            $sql = "UPDATE sys_user SET passwort = '$password' WHERE client_id = $client_id";
            $app->db->query($sql);
            $sql = "UPDATE sys_user SET passwort = ? WHERE client_id = ?";
            $app->db->query($sql, $password, $client_id);
        }
        if(!isset($this->dataRecord['locked'])) $this->dataRecord['locked'] = 'n';
@@ -439,7 +426,7 @@
            // get tmp_data of client
            $client_data = $app->db->queryOneRecord('SELECT `tmp_data` FROM `client` WHERE `client_id` = ' . $this->id);
            $client_data = $app->db->queryOneRecord('SELECT `tmp_data` FROM `client` WHERE `client_id` = ?', $this->id);
            if($client_data['tmp_data'] == '') $tmp_data = array();
            else $tmp_data = unserialize($client_data['tmp_data']);
@@ -463,8 +450,8 @@
                'web_folder_user' => 'web_folder_user_id'
            );
            $udata = $app->db->queryOneRecord('SELECT `userid` FROM `sys_user` WHERE `client_id` = ' . $this->id);
            $gdata = $app->db->queryOneRecord('SELECT `groupid` FROM `sys_group` WHERE `client_id` = ' . $this->id);
            $udata = $app->db->queryOneRecord('SELECT `userid` FROM `sys_user` WHERE `client_id` = ?', $this->id);
            $gdata = $app->db->queryOneRecord('SELECT `groupid` FROM `sys_group` WHERE `client_id` = ?', $this->id);
            $sys_groupid = $gdata['groupid'];
            $sys_userid = $udata['userid'];
@@ -486,7 +473,7 @@
                    if(!isset($prev_active[$current])) $prev_active[$current] = array();
                    if(!isset($prev_sysuser[$current])) $prev_sysuser[$current] = array();
                    $entries = $app->db->queryAllRecords('SELECT `' . $keycolumn . '` as `id`, `sys_userid`, `' . $active_col . '` FROM `' . $current . '` WHERE `sys_groupid` = ' . $sys_groupid);
                    $entries = $app->db->queryAllRecords('SELECT ?? as `id`, `sys_userid`, ?? FROM ?? WHERE `sys_groupid` = ?', $keycolumn, $active_col, $current, $sys_groupid);
                    foreach($entries as $item) {
                        if($item[$active_col] != 'y' && $reverse == false) $prev_active[$current][$item['id']][$active_col] = 'n';
@@ -500,7 +487,7 @@
                $tmp_data['prev_active'] = $prev_active;
                $tmp_data['prev_sys_userid'] = $prev_sysuser;
                $app->db->query("UPDATE `client` SET `tmp_data` = '" . $app->db->quote(serialize($tmp_data)) . "' WHERE `client_id` = " . $this->id);
                $app->db->query("UPDATE `client` SET `tmp_data` = ? WHERE `client_id` = ?", serialize($tmp_data), $this->id);
                unset($prev_active);
                unset($prev_sysuser);
            } elseif($this->dataRecord['locked'] == 'n') {
@@ -515,7 +502,7 @@
                        $reverse = true;
                    }
                    
                    $entries = $app->db->queryAllRecords('SELECT `' . $keycolumn . '` as `id` FROM `' . $current . '` WHERE `sys_groupid` = ' . $sys_groupid);
                    $entries = $app->db->queryAllRecords('SELECT ?? as `id` FROM ?? WHERE `sys_groupid` = ?', $keycolumn, $current, $sys_groupid);
                    foreach($entries as $item) {
                        $set_active = ($reverse == true ? 'n' : 'y');
                        $set_inactive = ($reverse == true ? 'y' : 'n');
@@ -533,7 +520,7 @@
                    }
                }
                if(array_key_exists('prev_active', $tmp_data)) unset($tmp_data['prev_active']);
                $app->db->query("UPDATE `client` SET `tmp_data` = '" . $app->db->quote(serialize($tmp_data)) . "' WHERE `client_id` = " . $this->id);
                $app->db->query("UPDATE `client` SET `tmp_data` = ? WHERE `client_id` = ?", serialize($tmp_data), $this->id);
            }
            unset($tmp_data);
            unset($entries);
@@ -543,43 +530,42 @@
        if(!isset($this->dataRecord['canceled'])) $this->dataRecord['canceled'] = 'n';
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && $this->dataRecord["canceled"] != $this->oldDataRecord['canceled']) {
            if($this->dataRecord['canceled'] == 'y') {
                $sql = "UPDATE sys_user SET active = '0' WHERE client_id = " . $this->id;
                $app->db->query($sql);
                $sql = "UPDATE sys_user SET active = '0' WHERE client_id = ?";
                $app->db->query($sql, $this->id);
            } elseif($this->dataRecord['canceled'] == 'n') {
                $sql = "UPDATE sys_user SET active = '1' WHERE client_id = " . $this->id;
                $app->db->query($sql);
                $sql = "UPDATE sys_user SET active = '1' WHERE client_id = ?";
                $app->db->query($sql, $this->id);
            }
        }
        // language changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord['language']) && $this->dataRecord['language'] != '' && $this->oldDataRecord['language'] != $this->dataRecord['language']) {
            $language = $app->db->quote($this->dataRecord["language"]);
            $language = $this->dataRecord["language"];
            $client_id = $this->id;
            $sql = "UPDATE sys_user SET language = '$language' WHERE client_id = $client_id";
            $app->db->query($sql);
            $sql = "UPDATE sys_user SET language = ? WHERE client_id = ?";
            $app->db->query($sql, $language, $client_id);
        }
        //* reseller status changed
        if(isset($this->dataRecord["limit_client"]) && $this->dataRecord["limit_client"] != $this->oldDataRecord["limit_client"]) {
            $modules = $conf['interface_modules_enabled'];
            if($this->dataRecord["limit_client"] > 0) $modules .= ',client';
            $modules = $app->db->quote($modules);
            $client_id = $this->id;
            $sql = "UPDATE sys_user SET modules = '$modules' WHERE client_id = $client_id";
            $app->db->query($sql);
            $sql = "UPDATE sys_user SET modules = ? WHERE client_id = ?";
            $app->db->query($sql, $modules, $client_id);
        }
        
        //* Client has been moved to another reseller
        if($_SESSION['s']['user']['typ'] == 'admin' && isset($this->dataRecord['parent_client_id']) && $this->dataRecord['parent_client_id'] != $this->oldDataRecord['parent_client_id']) {
            //* Get groupid of the client
            $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".intval($this->id));
            $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $this->id);
            $groupid = $tmp['groupid'];
            unset($tmp);
            
            //* Remove sys_user of old reseller from client group
            if($this->oldDataRecord['parent_client_id'] > 0) {
                //* get userid of the old reseller remove it from the group of the client
                $tmp = $app->db->queryOneRecord("SELECT sys_user.userid FROM sys_user,sys_group WHERE sys_user.default_group = sys_group.groupid AND sys_group.client_id = ".$app->functions->intval($this->oldDataRecord['parent_client_id']));
                $tmp = $app->db->queryOneRecord("SELECT sys_user.userid FROM sys_user,sys_group WHERE sys_user.default_group = sys_group.groupid AND sys_group.client_id = ?", $this->oldDataRecord['parent_client_id']);
                $app->auth->remove_group_from_user($tmp['userid'], $groupid);
                unset($tmp);
            }
@@ -587,13 +573,13 @@
            //* Add sys_user of new reseller to client group
            if($this->dataRecord['parent_client_id'] > 0) {
                //* get userid of the reseller and add it to the group of the client
                $tmp = $app->db->queryOneRecord("SELECT sys_user.userid, sys_user.default_group FROM sys_user,sys_group WHERE sys_user.default_group = sys_group.groupid AND sys_group.client_id = ".$app->functions->intval($this->dataRecord['parent_client_id']));
                $tmp = $app->db->queryOneRecord("SELECT sys_user.userid, sys_user.default_group FROM sys_user,sys_group WHERE sys_user.default_group = sys_group.groupid AND sys_group.client_id = ?", $this->dataRecord['parent_client_id']);
                $app->auth->add_group_to_user($tmp['userid'], $groupid);
                $app->db->query("UPDATE client SET sys_userid = ".$app->functions->intval($tmp['userid']).", sys_groupid = ".$app->functions->intval($tmp['default_group']).", parent_client_id = ".$app->functions->intval($this->dataRecord['parent_client_id'])." WHERE client_id = ".$this->id);
                $app->db->query("UPDATE client SET sys_userid = ?, sys_groupid = ?, parent_client_id = ? WHERE client_id = ?", $tmp['userid'], $tmp['default_group'], $this->dataRecord['parent_client_id'], $this->id);
                unset($tmp);
            } else {
                //* Client is not assigned to a reseller anymore, so we assign it to the admin
                $app->db->query("UPDATE client SET sys_userid = 1, sys_groupid = 1, parent_client_id = 0 WHERE client_id = ".$this->id);
                $app->db->query("UPDATE client SET sys_userid = 1, sys_groupid = 1, parent_client_id = 0 WHERE client_id = ?", $this->id);
            }
        }
interface/web/client/client_message.php
@@ -120,8 +120,8 @@
    if($_SESSION["s"]["user"]["typ"] != 'admin'){
        $client_id = $app->functions->intval($_SESSION['s']['user']['client_id']);
        if($client_id > 0){
            $sql = "SELECT email FROM client WHERE client_id = ".$client_id;
            $client = $app->db->queryOneRecord($sql);
            $sql = "SELECT email FROM client WHERE client_id = ?";
            $client = $app->db->queryOneRecord($sql, $client_id);
            if($client['email'] != '') $app->tpl->setVar('sender', $client['email']);
        }
    }
interface/web/client/reseller_edit.php
@@ -96,7 +96,7 @@
        }
        
        if($this->id != 0) {
            $this->oldTemplatesAssigned = $app->db->queryAllRecords('SELECT * FROM `client_template_assigned` WHERE `client_id` = ' . $this->id);
            $this->oldTemplatesAssigned = $app->db->queryAllRecords('SELECT * FROM `client_template_assigned` WHERE `client_id` = ?', $this->id);
            if(!is_array($this->oldTemplatesAssigned) || count($this->oldTemplatesAssigned) < 1) {
                // check previous type of storing templates
                $tpls = explode('/', $this->oldDataRecord['template_additional']);
@@ -134,7 +134,7 @@
        $app->tpl->setVar('tpl_add_select', $option);
        // check for new-style records
        $result = $app->db->queryAllRecords('SELECT assigned_template_id, client_template_id FROM client_template_assigned WHERE client_id = ' . $this->id);
        $result = $app->db->queryAllRecords('SELECT assigned_template_id, client_template_id FROM client_template_assigned WHERE client_id = ?', $this->id);
        if($result && count($result) > 0) {
            // new style
            $items = array();
@@ -160,8 +160,8 @@
            unset($tmprec);
        } else {
            // old style
            $sql = "SELECT template_additional FROM client WHERE client_id = " . $this->id;
            $result = $app->db->queryOneRecord($sql);
            $sql = "SELECT template_additional FROM client WHERE client_id = ?";
            $result = $app->db->queryOneRecord($sql, $this->id);
            $tplAdd = explode("/", $result['template_additional']);
            $text = '';
            foreach($tplAdd as $item){
@@ -186,13 +186,6 @@
                $customer_no = $app->functions->intval($system_config['misc']['customer_no_start']+$system_config['misc']['customer_no_counter']);
                $customer_no_string = str_replace('[CUSTOMER_NO]',$customer_no,$system_config['misc']['customer_no_template']);
                $app->tpl->setVar('customer_no',$customer_no_string);
                //* save new counter value
                /*
                $system_config['misc']['customer_no_counter']++;
                $system_config_str = $app->ini_parser->get_ini_string($system_config);
                $app->db->datalogUpdate('sys_ini', "config = '".$app->db->quote($system_config_str)."'", 'sysini_id', 1);
                */
            }
        }
        
@@ -210,14 +203,14 @@
        $groupid = $app->db->datalogInsert('sys_group', "(name,description,client_id) VALUES ('".$app->db->quote($this->dataRecord["username"])."','',".$this->id.")", 'groupid');
        $groups = $groupid;
        $username = $app->db->quote($this->dataRecord["username"]);
        $password = $app->db->quote($this->dataRecord["password"]);
        $modules = $app->db->quote($conf['interface_modules_enabled'] . ',client');
        $username = $this->dataRecord["username"];
        $password = $this->dataRecord["password"];
        $modules = $conf['interface_modules_enabled'] . ',client';
        $startmodule = (stristr($modules, 'dashboard'))?'dashboard':'client';
        $usertheme = $app->db->quote($this->dataRecord["usertheme"]);
        $usertheme = $this->dataRecord["usertheme"];
        $type = 'user';
        $active = 1;
        $language = $app->db->quote($this->dataRecord["language"]);
        $language = $this->dataRecord["language"];
        $salt="$1$";
        $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
@@ -229,11 +222,11 @@
        // Create the controlpaneluser for the reseller
        $sql = "INSERT INTO sys_user (username,passwort,modules,startmodule,app_theme,typ,active,language,groups,default_group,client_id)
        VALUES ('$username','$password','$modules','$startmodule','$usertheme','$type','$active','$language',$groups,$groupid,".$this->id.")";
        $app->db->query($sql);
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $app->db->query($sql, $username, $password, $modules, $startmodule, $usertheme, $type, $active, $language, $groups, $groupid, $this->id);
        //* set the number of clients to 1
        $app->db->query("UPDATE client SET limit_client = 1 WHERE client_id = ".$this->id);
        $app->db->query("UPDATE client SET limit_client = 1 WHERE client_id = ?", $this->id);
        //* Set the default servers
        $tmp = $app->db->queryOneRecord('SELECT server_id FROM server WHERE mail_server = 1 LIMIT 0,1');
@@ -245,8 +238,8 @@
        $tmp = $app->db->queryOneRecord('SELECT server_id FROM server WHERE db_server = 1 LIMIT 0,1');
        $default_dbserver = $app->functions->intval($tmp['server_id']);
        $sql = "UPDATE client SET default_mailserver = $default_mailserver, default_webserver = $default_webserver, default_dnsserver = $default_dnsserver, default_slave_dnsserver = $default_dnsserver, default_dbserver = $default_dbserver WHERE client_id = ".$this->id;
        $app->db->query($sql);
        $sql = "UPDATE client SET default_mailserver = ?, default_webserver = ?, default_dnsserver = ?, default_slave_dnsserver = ?, default_dbserver = ? WHERE client_id = ?";
        $app->db->query($sql, $default_mailserver, $default_webserver, $default_dnsserver, $default_dnsserver, $default_dbserver, $this->id);
        
        if(isset($this->dataRecord['template_master'])) {
            $app->uses('client_templates');
@@ -262,15 +255,15 @@
                //* save new counter value
                $system_config['misc']['customer_no_counter']++;
                $system_config_str = $app->ini_parser->get_ini_string($system_config);
                $app->db->datalogUpdate('sys_ini', "config = '".$app->db->quote($system_config_str)."'", 'sysini_id', 1);
                $app->db->datalogUpdate('sys_ini', array("config" => $system_config_str), 'sysini_id', 1);
                
            }
        }
        
        //* Send welcome email
        $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
        $sql = "SELECT * FROM client_message_template WHERE template_type = 'welcome' AND sys_groupid = ".$client_group_id;
        $email_template = $app->db->queryOneRecord($sql);
        $sql = "SELECT * FROM client_message_template WHERE template_type = 'welcome' AND sys_groupid = ?";
        $email_template = $app->db->queryOneRecord($sql, $client_group_id);
        $client = $app->tform->getDataRecord($this->id);
        if(is_array($email_template) && $client['email'] != '') {
@@ -300,7 +293,7 @@
                $from = $system_config['admin_mail'];
            } else {
                $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
                $reseller = $app->db->queryOneRecord("SELECT client.email FROM sys_group,client WHERE client.client_id = sys_group.client_id and sys_group.groupid = ".$client_group_id);
                $reseller = $app->db->queryOneRecord("SELECT client.email FROM sys_group,client WHERE client.client_id = sys_group.client_id and sys_group.groupid = ?", $client_group_id);
                $from = $reseller["email"];
            }
@@ -321,19 +314,19 @@
        // username changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord['username']) && $this->dataRecord['username'] != '' && $this->oldDataRecord['username'] != $this->dataRecord['username']) {
            $username = $app->db->quote($this->dataRecord["username"]);
            $username = $this->dataRecord["username"];
            $client_id = $this->id;
            $sql = "UPDATE sys_user SET username = '$username' WHERE client_id = $client_id";
            $app->db->query($sql);
            $sql = "UPDATE sys_user SET username = ? WHERE client_id = ?";
            $app->db->query($sql, $username, $client_id);
            $tmp = $app->db->queryOneRecord("SELECT * FROM sys_group WHERE client_id = $client_id");
            $app->db->datalogUpdate("sys_group", "name = '$username'", 'groupid', $tmp['groupid']);
            $tmp = $app->db->queryOneRecord("SELECT * FROM sys_group WHERE client_id = ?", $client_id);
            $app->db->datalogUpdate("sys_group", array("name" => $username), 'groupid', $tmp['groupid']);
            unset($tmp);
        }
        // password changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord["password"]) && $this->dataRecord["password"] != '') {
            $password = $app->db->quote($this->dataRecord["password"]);
            $password = $this->dataRecord["password"];
            $client_id = $this->id;
            $salt="$1$";
            $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
@@ -342,32 +335,32 @@
            }
            $salt.="$";
            $password = crypt(stripslashes($password), $salt);
            $sql = "UPDATE sys_user SET passwort = '$password' WHERE client_id = $client_id";
            $app->db->query($sql);
            $sql = "UPDATE sys_user SET passwort = ? WHERE client_id = ?";
            $app->db->query($sql, $password, $client_id);
        }
        // language changed
        if(isset($conf['demo_mode']) && $conf['demo_mode'] != true && isset($this->dataRecord['language']) && $this->dataRecord['language'] != '' && $this->oldDataRecord['language'] != $this->dataRecord['language']) {
            $language = $app->db->quote($this->dataRecord["language"]);
            $language = $this->dataRecord["language"];
            $client_id = $this->id;
            $sql = "UPDATE sys_user SET language = '$language' WHERE client_id = $client_id";
            $app->db->query($sql);
            $sql = "UPDATE sys_user SET language = ? WHERE client_id = ?";
            $app->db->query($sql, $language, $client_id);
        }
        // ensure that a reseller is not converted to a client in demo mode when client_id <= 2
        if(isset($conf['demo_mode']) && $conf['demo_mode'] == true && $this->id <= 2) {
            if(isset($this->dataRecord["limit_client"]) && $this->dataRecord["limit_client"] != -1) {
                $app->db->query('UPDATE client set limit_client = -1 WHERE client_id = '.$this->id);
                $app->db->query('UPDATE client set limit_client = -1 WHERE client_id = ?', $this->id);
            }
        }
        // reseller status changed
        if(isset($this->dataRecord["limit_client"]) && $this->dataRecord["limit_client"] != $this->oldDataRecord["limit_client"]) {
            $modules = $app->db->quote($conf['interface_modules_enabled'] . ',client');
            $modules = $app->db->quote($modules);
            $modules = $conf['interface_modules_enabled'] . ',client';
            $modules = $modules;
            $client_id = $this->id;
            $sql = "UPDATE sys_user SET modules = '$modules' WHERE client_id = $client_id";
            $app->db->query($sql);
            $sql = "UPDATE sys_user SET modules = ? WHERE client_id = ?";
            $app->db->query($sql, $modules, $client_id);
        }
        
        if(isset($this->dataRecord['template_master'])) {
interface/web/dashboard/ajax_get_json.php
@@ -76,28 +76,6 @@
    $result[] = _search('sites', 'shell_user');
    // databases
    /*
        $result_databases = array('cheader' => array(), 'cdata' => array());
        if(in_array('sites', $modules)){
            $sql = "SELECT * FROM web_database WHERE database_name LIKE '%".$q."%' OR database_user LIKE '%".$q."%' OR remote_ips LIKE '%".$q."%'".$authsql." ORDER BY database_name";
            $results = $app->db->queryAllRecords($sql);
            if(is_array($results) && !empty($results)){
                $result_databases['cheader'] = array('title' => 'Databases',
                                                        'total' => count($results),
                                                        'limit' => count($results)
                                                    );
                foreach($results as $result){
                    $description = 'Database User: '.$result['database_user'].' - Remote IPs: '.$result['remote_ips'];
                    $result_databases['cdata'][] = array('title' => $result['database_name'],
                                                'description' => $description,
                                                'onclick' => 'ISPConfig.capp(\'sites\',\'sites/database_edit.php?id='.$result['database_id'].'\');',
                                                'fill_text' => strtolower($result['database_name'])
                                                );
                }
            }
        }
        */
    $result[] = _search('sites', 'database');
    // database users
@@ -205,8 +183,8 @@
        $order_clause = '';
        if($order_by != '') $order_clause = ' ORDER BY '.$order_by;
        $sql = "SELECT * FROM ".$db_table." WHERE ".$where_clause.$authsql.$order_clause." LIMIT 0,10";
        $results = $app->db->queryAllRecords($sql);
        $sql = "SELECT * FROM ?? WHERE ".$where_clause.$authsql.$order_clause." LIMIT 0,10";
        $results = $app->db->queryAllRecords($sql, $db_table);
        if(is_array($results) && !empty($results)){
            $lng_file = '../'.$module.'/lib/lang/'.$_SESSION['s']['language'].'_'.$section.'.lng';
interface/web/login/index.php
@@ -73,9 +73,9 @@
            if(!preg_match("/^.{1,64}$/i", $_POST['passwort'])) $error = $app->lng('pw_error_length');
            //** iporting variables
            $ip    = $app->db->quote(ip2long($_SERVER['REMOTE_ADDR']));
            $username = $app->db->quote($_POST['username']);
            $passwort = $app->db->quote($_POST['passwort']);
            $ip    = ip2long($_SERVER['REMOTE_ADDR']);
            $username = $_POST['username'];
            $passwort = $_POST['passwort'];
            $loginAs  = false;
            $time = time();
interface/web/login/password_reset.php
@@ -51,8 +51,8 @@
    if(!preg_match("/^[\w\.\-\_]{1,64}$/", $_POST['username'])) die($app->lng('user_regex_error'));
    if(!preg_match("/^\w+[\w.-]*\w+@\w+[\w.-]*\w+\.[a-z]{2,10}$/i", $_POST['email'])) die($app->lng('email_error'));
    $username = $app->db->quote($_POST['username']);
    $email = $app->db->quote($_POST['email']);
    $username = $_POST['username'];
    $email = $_POST['email'];
    $client = $app->db->queryOneRecord("SELECT client.*, sys_user.lost_password_function FROM client,sys_user WHERE client.username = ? AND client.email = ? AND client.client_id = sys_user.client_id", $username, $email);
@@ -62,9 +62,8 @@
        if($client['client_id'] > 0) {
            $new_password = $app->auth->get_random_password();
            $new_password_encrypted = $app->auth->crypt_password($new_password);
            $new_password_encrypted = $app->db->quote($new_password_encrypted);
            $username = $app->db->quote($client['username']);
            $username = $client['username'];
            $app->db->query("UPDATE sys_user SET passwort = ? WHERE username = ?", $new_password_encrypted, $username);
            $app->db->query("UPDATE client SET password = ? WHERE username = ?", $new_password_encrypted, $username);
            $app->tpl->setVar("message", $wb['pw_reset']);
interface/web/mail/mail_alias_edit.php
@@ -95,12 +95,12 @@
        global $app, $conf;
        // Check if Domain belongs to user
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"]));
        if($domain["domain"] != $app->functions->idn_encode($_POST["email_domain"])) $app->tform->errorMessage .= $app->tform->wordbook["no_domain_perm"];
        //* Check if destination email belongs to user
        if(isset($_POST["destination"])) {
            $email = $app->db->queryOneRecord("SELECT email FROM mail_user WHERE email = '".$app->db->quote($app->functions->idn_encode($_POST["destination"]))."' AND ".$app->tform->getAuthSQL('r'));
            $email = $app->db->queryOneRecord("SELECT email FROM mail_user WHERE email = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["destination"]));
            if($email["email"] != $app->functions->idn_encode($_POST["destination"])) $app->tform->errorMessage .= $app->tform->lng("no_destination_perm");
        }
@@ -112,7 +112,7 @@
            // Check if the user may add another mailbox.
            if($this->id == 0 && $client["limit_mailalias"] >= 0) {
                $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE sys_groupid = $client_group_id AND type = 'alias'");
                $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE sys_groupid = ? AND type = 'alias'", $client_group_id);
                if($tmp["number"] >= $client["limit_mailalias"]) {
                    $app->tform->errorMessage .= $app->tform->wordbook["limit_mailalias_txt"]."<br>";
                }
@@ -130,15 +130,15 @@
        unset($this->dataRecord["email_domain"]);
        //* Check if there is no active mailbox with this address
        $tmp = $app->db->queryOneRecord("SELECT count(mailuser_id) as number FROM mail_user WHERE postfix = 'y' AND email = '".$app->db->quote($this->dataRecord["source"])."'");
        $tmp = $app->db->queryOneRecord("SELECT count(mailuser_id) as number FROM mail_user WHERE postfix = 'y' AND email = ?", $this->dataRecord["source"]);
        if($tmp['number'] > 0) $app->tform->errorMessage .= $app->tform->lng("duplicate_mailbox_txt")."<br>";
        unset($tmp);
        //* Check if email alias exists
        if($this->id > 0) {
            $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE source = '".$app->db->quote($this->dataRecord["source"])."' AND destination = '".$app->db->quote($this->dataRecord["destination"])."' AND forwarding_id != ".$this->id);
            $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE source = ? AND destination = ? AND forwarding_id != ?", $this->dataRecord["source"], $this->dataRecord["destination"], $this->id);
        } else {
            $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE source = '".$app->db->quote($this->dataRecord["source"])."' AND destination = '".$app->db->quote($this->dataRecord["destination"])."'");
            $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE source = ? AND destination = ?", $this->dataRecord["source"], $this->dataRecord["destination"]);
        }
        if($tmp['number'] > 0) $app->tform->errorMessage .= $app->tform->lng("duplicate_email_alias_txt")."<br>";
        unset($tmp);
@@ -149,8 +149,8 @@
    function onAfterInsert() {
        global $app;
        $domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
        $app->db->query("update mail_forwarding SET sys_groupid = ".$app->functions->intval($domain['sys_groupid'])." WHERE forwarding_id = ".$this->id);
        $domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"])));
        $app->db->query("update mail_forwarding SET sys_groupid = ? WHERE forwarding_id = ?", $domain['sys_groupid'], $this->id);
    }
interface/web/mail/mail_aliasdomain_edit.php
@@ -97,11 +97,11 @@
        global $app, $conf;
        // Check if source Domain belongs to user
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["source"]))."' AND ".$app->tform->getAuthSQL('r'));
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["source"]));
        if($domain["domain"] != $app->functions->idn_encode($_POST["source"])) $app->tform->errorMessage .= $app->tform->wordbook["no_domain_perm"];
        // Check if the destination domain belongs to the user
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["destination"]))."' AND ".$app->tform->getAuthSQL('r'));
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["destination"]));
        if($domain["domain"] != $app->functions->idn_encode($_POST["destination"])) $app->tform->errorMessage .= $app->tform->wordbook["no_domain_perm"];
        // Check the client limits, if user is not the admin
@@ -116,6 +116,7 @@
        if($this->dataRecord["source"] == $this->dataRecord["destination"]) $app->tform->errorMessage .= $app->tform->wordbook["source_destination_identical_txt"];
        /* TODO: check if this quoting is correkt! */
        // compose the source and destination field
        $this->dataRecord["source"] = "@".$app->db->quote($this->dataRecord["source"]);
        $this->dataRecord["destination"] = "@".$app->db->quote($this->dataRecord["destination"]);
@@ -128,8 +129,8 @@
    function onAfterInsert() {
        global $app;
        $domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["destination"]))."' AND ".$app->tform->getAuthSQL('r'));
        $app->db->query("update mail_forwarding SET sys_groupid = ".$app->functions->intval($domain['sys_groupid'])." WHERE forwarding_id = ".$this->id);
        $domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["destination"]));
        $app->db->query("update mail_forwarding SET sys_groupid = ? WHERE forwarding_id = ?", $domain['sys_groupid'], $this->id);
    }
interface/web/mail/mail_content_filter_edit.php
@@ -58,7 +58,7 @@
        //* Check if the server has been changed
        // We do this only for the admin or reseller users, as normal clients can not change the server ID anyway
        if($_SESSION["s"]["user"]["typ"] == 'admin' || $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
            $rec = $app->db->queryOneRecord("SELECT server_id from mail_content_filter WHERE content_filter_id = ".$this->id);
            $rec = $app->db->queryOneRecord("SELECT server_id from mail_content_filter WHERE content_filter_id = ?", $this->id);
            if($rec['server_id'] != $this->dataRecord["server_id"]) {
                //* Add a error message and switch back to old server
                $app->tform->errorMessage .= $app->lng('The Server can not be changed.');
interface/web/mail/mail_domain_catchall_edit.php
@@ -94,7 +94,7 @@
        global $app, $conf;
        // Check if Domain belongs to user
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"]));
        if($domain["domain"] != $app->functions->idn_encode($_POST["email_domain"])) $app->tform->errorMessage .= $app->tform->wordbook["no_domain_perm"];
        // Check the client limits, if user is not the admin
@@ -105,7 +105,7 @@
            // Check if the user may add another catchall
            if($this->id == 0 && $client["limit_mailcatchall"] >= 0) {
                $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE sys_groupid = $client_group_id AND type = 'catchall'");
                $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE sys_groupid = ? AND type = 'catchall'", $client_group_id);
                if($tmp["number"] >= $client["limit_mailcatchall"]) {
                    $app->tform->errorMessage .= $app->tform->wordbook["limit_mailcatchall_txt"]."<br>";
                }
@@ -127,8 +127,8 @@
    function onAfterInsert() {
        global $app;
        $domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
        $app->db->query("update mail_forwarding SET sys_groupid = ".$app->functions->intval($domain['sys_groupid'])." WHERE forwarding_id = ".$this->id);
        $domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"])));
        $app->db->query("update mail_forwarding SET sys_groupid = ? WHERE forwarding_id = ?", $domain['sys_groupid'], $this->id);
    }
interface/web/mail/mail_domain_del.php
@@ -60,31 +60,31 @@
        // we will delete all depending records.
        // Delete all forwardings where the source or destination belongs to this domain
        $records = $app->db->queryAllRecords("SELECT forwarding_id as id FROM mail_forwarding WHERE source like '%@".$app->db->quote($domain)."' OR (destination like '%@".$app->db->quote($domain)."' AND type != 'forward')");
        $records = $app->db->queryAllRecords("SELECT forwarding_id as id FROM mail_forwarding WHERE source like ? OR (destination like ? AND type != 'forward')", '%@' . $domain, '%@' . $domain);
        foreach($records as $rec) {
            $app->db->datalogDelete('mail_forwarding', 'forwarding_id', $rec['id']);
        }
        // Delete all fetchmail accounts where destination belongs to this domain
        $records = $app->db->queryAllRecords("SELECT mailget_id as id FROM mail_get WHERE destination like '%@".$app->db->quote($domain)."'");
        $records = $app->db->queryAllRecords("SELECT mailget_id as id FROM mail_get WHERE destination like ?", '%@' . $domain);
        foreach($records as $rec) {
            $app->db->datalogDelete('mail_get', 'mailget_id', $rec['id']);
        }
        // Delete all mailboxes where destination belongs to this domain
        $records = $app->db->queryAllRecords("SELECT mailuser_id as id FROM mail_user WHERE email like '%@".$app->db->quote($domain)."'");
        $records = $app->db->queryAllRecords("SELECT mailuser_id as id FROM mail_user WHERE email like ?", '%@' . $domain);
        foreach($records as $rec) {
            $app->db->datalogDelete('mail_user', 'mailuser_id', $rec['id']);
        }
        // Delete all spamfilters that belong to this domain
        $records = $app->db->queryAllRecords("SELECT id FROM spamfilter_users WHERE email = '%@".$app->db->quote($domain)."'");
        $records = $app->db->queryAllRecords("SELECT id FROM spamfilter_users WHERE email = ?", '%@' . $domain);
        foreach($records as $rec) {
            $app->db->datalogDelete('spamfilter_users', 'id', $rec['id']);
        }
        // Delete all mailinglists that belong to this domain
        $records = $app->db->queryAllRecords("SELECT mailinglist_id FROM mail_mailinglist WHERE domain = '".$app->db->quote($domain)."'");
        $records = $app->db->queryAllRecords("SELECT mailinglist_id FROM mail_mailinglist WHERE domain = ?", $domain);
        foreach($records as $rec) {
            $app->db->datalogDelete('mail_mailinglist', 'mailinglist_id', $rec['id']);
        }
interface/web/mail/mail_domain_edit.php
@@ -95,18 +95,18 @@
            // Get the limits of the client
            $client_group_id = $_SESSION["s"]["user"]["default_group"];
            $client = $app->db->queryOneRecord("SELECT client.client_id, client.contact_name, client.default_mailserver, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname, sys_group.name FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id order by client.contact_name");
            $client = $app->db->queryOneRecord("SELECT client.client_id, client.contact_name, client.default_mailserver, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname, sys_group.name FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ? order by client.contact_name", $client_group_id);
            // Set the mailserver to the default server of the client
            $tmp = $app->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = $client[default_mailserver]");
            $tmp = $app->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ?", $client['default_mailserver']);
            $app->tpl->setVar("server_id", "<option value='$client[default_mailserver]'>$tmp[server_name]</option>");
            unset($tmp);
            if ($settings['use_domain_module'] != 'y') {
                // Fill the client select field
                $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ".$app->functions->intval($client['client_id'])." ORDER BY client.company_name, client.contact_name, sys_group.name";
                $clients = $app->db->queryAllRecords($sql);
                $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($client['client_id']));
                $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ? ORDER BY client.company_name, client.contact_name, sys_group.name";
                $clients = $app->db->queryAllRecords($sql, $client['client_id']);
                $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
                $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contactname'].'</option>';
                //$tmp_data_record = $app->tform->getDataRecord($this->id);
                if(is_array($clients)) {
@@ -133,8 +133,8 @@
                $app->tpl->setVar('server_id_value', $client_mail['mail_servers_ids'][0]);
            }
            $sql = "SELECT server_id, server_name FROM server WHERE server_id IN (" . $client_mail['mail_servers'] . ");";
            $mail_servers = $app->db->queryAllRecords($sql);
            $sql = "SELECT server_id, server_name FROM server WHERE server_id IN ?";
            $mail_servers = $app->db->queryAllRecords($sql, $client_mail['mail_servers_ids']);
            $options_mail_servers = "";
@@ -183,7 +183,7 @@
        // Get the spamfilter policys for the user
        $tmp_user = $app->db->queryOneRecord("SELECT policy_id FROM spamfilter_users WHERE email = '@".$app->db->quote($this->dataRecord["domain"])."'");
        $tmp_user = $app->db->queryOneRecord("SELECT policy_id FROM spamfilter_users WHERE email = ?", '@' . $this->dataRecord["domain"]);
        $sql = "SELECT id, policy_name FROM spamfilter_policy WHERE ".$app->tform->getAuthSQL('r')." ORDER BY policy_name";
        $policys = $app->db->queryAllRecords($sql);
        $policy_select = "<option value='0'>".$app->tform->wordbook["no_policy"]."</option>";
@@ -245,7 +245,7 @@
            // When the record is updated
            if($this->id > 0) {
                // restore the server ID if the user is not admin and record is edited
                $tmp = $app->db->queryOneRecord("SELECT server_id FROM mail_domain WHERE domain_id = ".$app->functions->intval($this->id));
                $tmp = $app->db->queryOneRecord("SELECT server_id FROM mail_domain WHERE domain_id = ?", $this->id);
                $this->dataRecord["server_id"] = $tmp["server_id"];
                unset($tmp);
                // When the record is inserted
@@ -282,12 +282,12 @@
        // Spamfilter policy
        $policy_id = $app->functions->intval($this->dataRecord["policy"]);
        if($policy_id > 0) {
            $tmp_user = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = '@".$app->db->quote($this->dataRecord["domain"])."'");
            $tmp_user = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = ?", '@' . $this->dataRecord["domain"]);
            if($tmp_user["id"] > 0) {
                // There is already a record that we will update
                $app->db->datalogUpdate('spamfilter_users', "policy_id = $policy_id", 'id', $tmp_user["id"]);
            } else {
                $tmp_domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain_id = ".$this->id);
                $tmp_domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain_id = ?", $this->id);
                // We create a new record
                $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `priority`, `policy_id`, `email`, `fullname`, `local`)
                        VALUES (".$_SESSION["s"]["user"]["userid"].", ".$app->functions->intval($tmp_domain["sys_groupid"]).", 'riud', 'riud', '', ".$app->functions->intval($this->dataRecord["server_id"]).", 5, ".$app->functions->intval($policy_id).", '@".$app->db->quote($this->dataRecord["domain"])."', '@".$app->db->quote($this->dataRecord["domain"])."', 'Y')";
@@ -310,7 +310,7 @@
        //* Check if the server has been changed
        // We do this only for the admin or reseller users, as normal clients can not change the server ID anyway
        if($_SESSION["s"]["user"]["typ"] == 'admin' || $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
            $rec = $app->db->queryOneRecord("SELECT server_id, domain from mail_domain WHERE domain_id = ".$this->id);
            $rec = $app->db->queryOneRecord("SELECT server_id, domain from mail_domain WHERE domain_id = ?", $this->id);
            if($rec['server_id'] != $this->dataRecord["server_id"]) {
                //* Add a error message and switch back to old server
                $app->tform->errorMessage .= $app->lng('The Server can not be changed.');
@@ -320,7 +320,7 @@
            //* If the user is neither admin nor reseller
        } else {
            //* We do not allow users to change a domain which has been created by the admin
            $rec = $app->db->queryOneRecord("SELECT domain from mail_domain WHERE domain_id = ".$this->id);
            $rec = $app->db->queryOneRecord("SELECT domain from mail_domain WHERE domain_id = ?", $this->id);
            if($rec['domain'] != $this->dataRecord["domain"] && $app->tform->checkPerm($this->id, 'u')) {
                //* Add a error message and switch back to old server
                $app->tform->errorMessage .= $app->lng('The Domain can not be changed. Please ask your Administrator if you want to change the domain name.');
@@ -336,13 +336,13 @@
        // Spamfilter policy
        $policy_id = $app->functions->intval($this->dataRecord["policy"]);
        $tmp_user = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = '@".$app->db->quote($this->dataRecord["domain"])."'");
        $tmp_user = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = ?", '@' . $this->dataRecord["domain"]);
        if($policy_id > 0) {
            if($tmp_user["id"] > 0) {
                // There is already a record that we will update
                $app->db->datalogUpdate('spamfilter_users', "policy_id = $policy_id", 'id', $tmp_user["id"]);
            } else {
                $tmp_domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain_id = ".$this->id);
                $tmp_domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain_id = ?", $this->id);
                // We create a new record
                $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `priority`, `policy_id`, `email`, `fullname`, `local`)
                        VALUES (".$_SESSION["s"]["user"]["userid"].", ".$app->functions->intval($tmp_domain["sys_groupid"]).", 'riud', 'riud', '', ".$app->functions->intval($this->dataRecord["server_id"]).", 5, ".$app->functions->intval($policy_id).", '@".$app->db->quote($this->dataRecord["domain"])."', '@".$app->db->quote($this->dataRecord["domain"])."', 'Y')";
@@ -361,9 +361,9 @@
            $mail_config = $app->getconf->get_server_config($this->dataRecord["server_id"], 'mail');
            //* Update the mailboxes
            $mailusers = $app->db->queryAllRecords("SELECT * FROM mail_user WHERE email like '%@".$app->db->quote($this->oldDataRecord['domain'])."'");
            $mailusers = $app->db->queryAllRecords("SELECT * FROM mail_user WHERE email like ?", '%@' . $this->oldDataRecord['domain']);
            $sys_groupid = $app->functions->intval((isset($this->dataRecord['client_group_id']))?$this->dataRecord['client_group_id']:$this->oldDataRecord['sys_groupid']);
            $tmp = $app->db->queryOneRecord("SELECT userid FROM sys_user WHERE default_group = $client_group_id");
            $tmp = $app->db->queryOneRecord("SELECT userid FROM sys_user WHERE default_group = ?", $client_group_id);
            $client_user_id = $app->functions->intval(($tmp['userid'] > 0)?$tmp['userid']:1);
            if(is_array($mailusers)) {
                foreach($mailusers as $rec) {
@@ -378,7 +378,7 @@
            }
            //* Update the aliases
            $forwardings = $app->db->queryAllRecords("SELECT * FROM mail_forwarding WHERE source like '%@".$app->db->quote($this->oldDataRecord['domain'])."' OR destination like '%@".$app->db->quote($this->oldDataRecord['domain'])."'");
            $forwardings = $app->db->queryAllRecords("SELECT * FROM mail_forwarding WHERE source like ? OR destination like ?", '%@' . $this->oldDataRecord['domain'], '%@' . $this->oldDataRecord['domain']);
            if(is_array($forwardings)) {
                foreach($forwardings as $rec) {
                    $destination = $app->db->quote(str_replace($this->oldDataRecord['domain'], $this->dataRecord['domain'], $rec['destination']));
@@ -388,10 +388,10 @@
            }
            //* Update the mailinglist
            $app->db->query("UPDATE mail_mailinglist SET sys_userid = $client_user_id, sys_groupid = $sys_groupid WHERE domain = '".$app->db->quote($this->oldDataRecord['domain'])."'");
            $app->db->query("UPDATE mail_mailinglist SET sys_userid = ?, sys_groupid = ? WHERE domain = ?", $client_user_id, $sys_groupid, $this->oldDataRecord['domain']);
            
            //* Update fetchmail accounts
            $fetchmail = $app->db->queryAllRecords("SELECT * FROM mail_get WHERE destination like '%@".$app->db->quote($this->oldDataRecord['domain'])."'");
            $fetchmail = $app->db->queryAllRecords("SELECT * FROM mail_get WHERE destination like ?", '%@' . $this->oldDataRecord['domain']);
            if(is_array($fetchmail)) {
                foreach($fetchmail as $rec) {
                    $destination = $app->db->quote(str_replace($this->oldDataRecord['domain'], $this->dataRecord['domain'], $rec['destination']));
@@ -400,7 +400,7 @@
            }
            
            //* Delete the old spamfilter record
            $tmp = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = '@".$app->db->quote($this->oldDataRecord["domain"])."'");
            $tmp = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = ?", '@' . $this->oldDataRecord["domain"]);
            $app->db->datalogDelete('spamfilter_users', 'id', $tmp["id"]);
            unset($tmp);
@@ -422,8 +422,8 @@
                }
            if (! $dkim_active) {
                // updated existing dmarc-record to policy 'none'
                $sql = "SELECT * from dns_rr WHERE name = ? AND data LIKE 'v=DMARC1%' AND ?";
                $rec = $app->db->queryOneRecord($sql, '_dmarc.'.$this->dataRecord['domain'].'.', $app->tform->getAuthSQL('r'));
                $sql = "SELECT * from dns_rr WHERE name = ? AND data LIKE 'v=DMARC1%' AND " . $app->tform->getAuthSQL('r');
                $rec = $app->db->queryOneRecord($sql, '_dmarc.'.$this->dataRecord['domain'].'.');
                if (is_array($rec))
                    if (strpos($rec['data'], 'p=none=') === false) {
                        $rec['data'] = str_replace(array('quarantine', 'reject'), 'none', $rec['data']);
@@ -441,15 +441,15 @@
        global $app, $conf;
        // purge old rr-record(s)
        $sql = "SELECT * FROM dns_rr WHERE name LIKE ? AND data LIKE 'v=DKIM1%' AND ? ORDER BY serial DESC";
        $rec = $app->db->queryAllRecords($sql, '%._domainkey.'.$dataRecord['domain'].'.', $app->tform->getAuthSQL('r'));
        $sql = "SELECT * FROM dns_rr WHERE name LIKE ? AND data LIKE 'v=DKIM1%' AND " . $app->tform->getAuthSQL('r') . " ORDER BY serial DESC";
        $rec = $app->db->queryAllRecords($sql, '%._domainkey.'.$dataRecord['domain'].'.');
        if (is_array($rec[1])) {
            for ($i=1; $i < count($rec); ++$i)
                $app->db->datalogDelete('dns_rr', 'id', $rec[$i]['id']);
        }
        // also delete a dsn-records with same selector 
        $sql = "SELECT * from dns_rr WHERE name ? AND data LIKE 'v=DKIM1%' AND ?";
        $rec = $app->db->queryAllRecords($sql, '.._domainkey.'.$dataRecord['dkim_selector'].'.', $dataRecord['domain'], $app->tform->getAuthSQL('r'));
        $sql = "SELECT * from dns_rr WHERE name ? AND data LIKE 'v=DKIM1%' AND " . $app->tform->getAuthSQL('r');
        $rec = $app->db->queryAllRecords($sql, '._domainkey.'.$dataRecord['dkim_selector'].'.', $dataRecord['domain']);
        if (is_array($rec))
            foreach ($rec as $del)
                $app->db->datalogDelete('dns_rr', 'id', $del['id']);
interface/web/mail/mail_forward_edit.php
@@ -93,7 +93,7 @@
        global $app, $conf;
        // Check if Domain belongs to user
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"]));
        if($domain["domain"] != $app->functions->idn_encode($_POST["email_domain"])) $app->tform->errorMessage .= $app->tform->wordbook["no_domain_perm"];
        // Check the client limits, if user is not the admin
@@ -104,7 +104,7 @@
            // Check if the user may add another mailbox.
            if($this->id == 0 && $client["limit_mailforward"] >= 0) {
                $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE sys_groupid = $client_group_id AND type = 'forward'");
                $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE sys_groupid = ? AND type = 'forward'", $client_group_id);
                if($tmp["number"] >= $client["limit_mailforward"]) {
                    $app->tform->errorMessage .= $app->tform->wordbook["limit_mailforward_txt"]."<br>";
                }
@@ -121,7 +121,7 @@
        unset($this->dataRecord["email_domain"]);
        //* Check if there is no active mailbox with this address
        $tmp = $app->db->queryOneRecord("SELECT count(mailuser_id) as number FROM mail_user WHERE postfix = 'y' AND email = '".$app->db->quote($this->dataRecord["source"])."'");
        $tmp = $app->db->queryOneRecord("SELECT count(mailuser_id) as number FROM mail_user WHERE postfix = 'y' AND email = ?", $this->dataRecord["source"]);
        if($tmp['number'] > 0) $app->tform->errorMessage .= $app->tform->lng("duplicate_mailbox_txt")."<br>";
        unset($tmp);
@@ -131,8 +131,8 @@
    function onAfterInsert() {
        global $app;
        $domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
        $app->db->query("update mail_forwarding SET sys_groupid = ".$app->functions->intval($domain['sys_groupid'])." WHERE forwarding_id = ".$this->id);
        $domain = $app->db->queryOneRecord("SELECT sys_groupid FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"])));
        $app->db->query("update mail_forwarding SET sys_groupid = ? WHERE forwarding_id = ?", $domain['sys_groupid'], $this->id);
    }
interface/web/mail/mail_mailinglist_edit.php
@@ -89,12 +89,12 @@
            // Get the limits of the client
            $client_group_id = $_SESSION["s"]["user"]["default_group"];
            $client = $app->db->queryOneRecord("SELECT client.client_id, client.contact_name, client.default_mailserver, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname, sys_group.name FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id order by contact_name");
            $client = $app->db->queryOneRecord("SELECT client.client_id, client.contact_name, client.default_mailserver, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname, sys_group.name FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ? order by contact_name", $client_group_id);
            // Fill the client select field
            $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ".intval($client['client_id'])." ORDER BY client.company_name, client.contact_name, sys_group.name";
            $clients = $app->db->queryAllRecords($sql);
            $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".intval($client['client_id']));
            $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ? ORDER BY client.company_name, client.contact_name, sys_group.name";
            $clients = $app->db->queryAllRecords($sql, $client['client_id']);
            $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
            $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contactname'].'</option>';
            $tmp_data_record = $app->tform->getDataRecord($this->id);
            if(is_array($clients)) {
@@ -142,24 +142,24 @@
            //* Check if Domain belongs to user
            if(isset($_POST["domain"])) {
                $domain = $app->db->queryOneRecord("SELECT domain FROM mail_domain WHERE domain = '".$app->db->quote($this->dataRecord["domain"])."' AND ".$app->tform->getAuthSQL('r'));
                $domain = $app->db->queryOneRecord("SELECT domain FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $this->dataRecord["domain"]);
                if($domain["domain"] != $this->dataRecord["domain"]) $app->tform->errorMessage .= $app->tform->lng("no_domain_perm");
            }
            // When the record is updated
            if($this->id == 0) {
                //Check if email is in use
                $check = $app->db->queryOneRecord("SELECT count(source) as number FROM mail_forwarding WHERE source = '".$app->db->quote($this->dataRecord["listname"])."@".$app->db->quote($this->dataRecord["domain"])."'");
                $check = $app->db->queryOneRecord("SELECT count(source) as number FROM mail_forwarding WHERE source = ?", $this->dataRecord["listname"]."@".$this->dataRecord["domain"]);
                if($check['number'] != 0) {
                    $app->error($app->tform->wordbook["email_in_use_txt"]);
                }
                $check = $app->db->queryOneRecord("SELECT count(email) as number FROM mail_user WHERE email = '".$app->db->quote($this->dataRecord["listname"])."@".$app->db->quote($this->dataRecord["domain"])."'");
                $check = $app->db->queryOneRecord("SELECT count(email) as number FROM mail_user WHERE email = ?", $this->dataRecord["listname"]."@".$this->dataRecord["domain"]);
                if($check['number'] != 0) {
                    $app->error($app->tform->wordbook["email_in_use_txt"]);
                }
                $check = $app->db->queryOneRecord("SELECT count(mailinglist_id) as number FROM mail_mailinglist WHERE listname = '".$app->db->quote($this->dataRecord["listname"])."' AND domain = '".$app->db->quote($this->dataRecord["domain"])."'");
                $check = $app->db->queryOneRecord("SELECT count(mailinglist_id) as number FROM mail_mailinglist WHERE listname = ? AND domain = ?", $this->dataRecord["listname"], $this->dataRecord["domain"]);
                if($check['number'] != 0) {
                    $app->error($app->tform->wordbook["email_in_use_txt"]);
                }
@@ -187,7 +187,7 @@
        global $app, $conf;
        // Set the server id of the mailinglist = server ID of mail domain.
        $domain = $app->db->queryOneRecord("SELECT server_id FROM mail_domain WHERE domain = '".$app->db->quote($this->dataRecord["domain"])."'");
        $domain = $app->db->queryOneRecord("SELECT server_id FROM mail_domain WHERE domain = ?", $this->dataRecord["domain"]);
        $this->dataRecord["server_id"] = $domain['server_id'];
    }
@@ -198,11 +198,11 @@
        // also make sure that the user can not delete domain created by a admin
        if($_SESSION["s"]["user"]["typ"] == 'admin' && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE mail_mailinglist SET sys_groupid = $client_group_id, sys_perm_group = 'ru' WHERE mailinglist_id = ".$this->id);
            $app->db->query("UPDATE mail_mailinglist SET sys_groupid = ?, sys_perm_group = 'ru' WHERE mailinglist_id = ?", $client_group_id, $this->id);
        }
        if($app->auth->has_clients($_SESSION['s']['user']['userid']) && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE mail_mailinglist SET sys_groupid = $client_group_id, sys_perm_group = 'riud' WHERE mailinglist_id = ".$this->id);
            $app->db->query("UPDATE mail_mailinglist SET sys_groupid = ?, sys_perm_group = 'riud' WHERE mailinglist_id = ?", $client_group_id, $this->id);
        }
    }
@@ -212,13 +212,13 @@
        //* Check if the server has been changed
        // We do this only for the admin or reseller users, as normal clients can not change the server ID anyway
        if($_SESSION["s"]["user"]["typ"] == 'admin' || $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
            $rec = $app->db->queryOneRecord("SELECT server_id, domain from mail_mailinglist WHERE mailinglist_id = ".$this->id);
            $rec = $app->db->queryOneRecord("SELECT server_id, domain from mail_mailinglist WHERE mailinglist_id = ?", $this->id);
            $this->dataRecord["server_id"] = $rec['server_id'];
            unset($rec);
            //* If the user is neither admin nor reseller
        } else {
            //* We do not allow users to change a domain which has been created by the admin
            $rec = $app->db->queryOneRecord("SELECT domain from mail_mailinglist WHERE mailinglist_id = ".$this->id);
            $rec = $app->db->queryOneRecord("SELECT domain from mail_mailinglist WHERE mailinglist_id = ?", $this->id);
            if($rec['domain'] != $this->dataRecord["domain"] && $app->tform->checkPerm($this->id, 'u')) {
                //* Add a error message and switch back to old server
                $app->tform->errorMessage .= $app->lng('The Domain can not be changed. Please ask your Administrator if you want to change the domain name.');
@@ -235,11 +235,11 @@
        // also make sure that the user can not delete domain created by a admin
        if($_SESSION["s"]["user"]["typ"] == 'admin' && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE mail_mailinglist SET sys_groupid = $client_group_id, sys_perm_group = 'ru' WHERE mailinglist_id = ".$this->id);
            $app->db->query("UPDATE mail_mailinglist SET sys_groupid = ?, sys_perm_group = 'ru' WHERE mailinglist_id = ?", $client_group_id, $this->id);
        }
        if($app->auth->has_clients($_SESSION['s']['user']['userid']) && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE mail_mailinglist SET sys_groupid = $client_group_id, sys_perm_group = 'riud' WHERE mailinglist_id = ".$this->id);
            $app->db->query("UPDATE mail_mailinglist SET sys_groupid = ?, sys_perm_group = 'riud' WHERE mailinglist_id = ?", $client_group_id, $this->id);
        }
    }
interface/web/mail/mail_spamfilter_edit.php
@@ -76,8 +76,8 @@
        }
        // Changing maildir to mailbox_id
        $sql = "SELECT mailbox_id FROM mail_box WHERE maildir = '".$app->db->quote($this->dataRecord["spam_redirect_maildir"])."' AND ".$app->tform->getAuthSQL('r');
        $mailbox = $app->db->queryOneRecord($sql);
        $sql = "SELECT mailbox_id FROM mail_box WHERE maildir = ? AND ".$app->tform->getAuthSQL('r');
        $mailbox = $app->db->queryOneRecord($sql, $this->dataRecord["spam_redirect_maildir"]);
        $this->dataRecord["spam_redirect_maildir"] = $mailbox["mailbox_id"];
        parent::onShowEnd();
@@ -87,7 +87,7 @@
        global $app, $conf;
        // Check if Domain belongs to user
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = '".$app->db->quote($_POST["email_domain"])."' AND ".$app->tform->getAuthSQL('r'));
        $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $_POST["email_domain"]);
        if($domain["domain"] != $_POST["email_domain"]) $app->tform->errorMessage .= $app->tform->wordbook["no_domain_perm"];
        // compose the email field
@@ -108,8 +108,8 @@
        $this->dataRecord["spam_delete_score_int"]   = $_POST["spam_delete_score_int"] * 100;
        // Changing mailbox_id to maildir
        $sql = "SELECT maildir FROM mail_box WHERE mailbox_id = '".$app->functions->intval($_POST["spam_redirect_maildir"])."' AND ".$app->tform->getAuthSQL('r');
        $mailbox = $app->db->queryOneRecord($sql);
        $sql = "SELECT maildir FROM mail_box WHERE mailbox_id = ? AND ".$app->tform->getAuthSQL('r');
        $mailbox = $app->db->queryOneRecord($sql, $_POST["spam_redirect_maildir"]);
        $this->dataRecord["spam_redirect_maildir"] = $mailbox["maildir"];
        parent::onSubmit();
interface/web/mail/mail_user_edit.php
@@ -92,7 +92,7 @@
        unset($domain_select);
        // Get the spamfilter policys for the user
        $tmp_user = $app->db->queryOneRecord("SELECT policy_id FROM spamfilter_users WHERE email = '".$app->db->quote($this->dataRecord["email"])."'");
        $tmp_user = $app->db->queryOneRecord("SELECT policy_id FROM spamfilter_users WHERE email = ?", $this->dataRecord["email"]);
        $sql = "SELECT id, policy_name FROM spamfilter_policy WHERE ".$app->tform->getAuthSQL('r') . " ORDER BY policy_name";
        $policys = $app->db->queryAllRecords($sql);
        $policy_select = "<option value='0'>".$app->tform->lng("no_policy")."</option>";
@@ -139,7 +139,7 @@
        //* Check if Domain belongs to user
        if(isset($_POST["email_domain"])) {
            $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
            $domain = $app->db->queryOneRecord("SELECT server_id, domain FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"]));
            if($domain["domain"] != $app->functions->idn_encode($_POST["email_domain"])) $app->tform->errorMessage .= $app->tform->lng("no_domain_perm");
        }
@@ -167,7 +167,7 @@
            // Check the quota and adjust
            if(isset($_POST["quota"]) && $client["limit_mailquota"] >= 0 && (($app->functions->intval($this->dataRecord["quota"]) * 1024 * 1024 != $this->oldDataRecord['quota']) || ($_POST["quota"] <= 0))) {
                $tmp = $app->db->queryOneRecord("SELECT sum(quota) as mailquota FROM mail_user WHERE mailuser_id != ".$app->functions->intval($this->id)." AND ".$app->tform->getAuthSQL('u'));
                $tmp = $app->db->queryOneRecord("SELECT sum(quota) as mailquota FROM mail_user WHERE mailuser_id != ? AND ".$app->tform->getAuthSQL('u'), $this->id);
                $mailquota = $tmp["mailquota"] / 1024 / 1024;
                $new_mailbox_quota = $app->functions->intval($this->dataRecord["quota"]);
                if(($mailquota + $new_mailbox_quota > $client["limit_mailquota"]) || ($new_mailbox_quota == 0 && $client["limit_mailquota"] != -1)) {
@@ -182,11 +182,11 @@
            if($client['parent_client_id'] > 0) {
                // Get the limits of the reseller
                $reseller = $app->db->queryOneRecord("SELECT limit_mailquota, limit_maildomain FROM client WHERE client_id = ".$client['parent_client_id']);
                $reseller = $app->db->queryOneRecord("SELECT limit_mailquota, limit_maildomain FROM client WHERE client_id = ?", $client['parent_client_id']);
                //* Check the website quota of the client
                if(isset($_POST["quota"]) && $reseller["limit_mailquota"] >= 0 && $app->functions->intval($this->dataRecord["quota"]) * 1024 * 1024 != $this->oldDataRecord['quota']) {
                    $tmp = $app->db->queryOneRecord("SELECT sum(quota) as mailquota FROM mail_user, sys_group, client WHERE mail_user.sys_groupid=sys_group.groupid AND sys_group.client_id=client.client_id AND ".$client['parent_client_id']." IN (client.parent_client_id, client.client_id) AND mailuser_id != ".$app->functions->intval($this->id));
                    $tmp = $app->db->queryOneRecord("SELECT sum(quota) as mailquota FROM mail_user, sys_group, client WHERE mail_user.sys_groupid=sys_group.groupid AND sys_group.client_id=client.client_id AND ? IN (client.parent_client_id, client.client_id) AND mailuser_id != ?", $client['parent_client_id'], $this->id);
                    $mailquota = $tmp["mailquota"] / 1024 / 1024;
                    $new_mailbox_quota = $app->functions->intval($this->dataRecord["quota"]);
@@ -231,7 +231,7 @@
            $this->dataRecord['gid'] = -1;
                
            //* Check if there is no alias or forward with this address
            $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE active = 'y' AND source = '".$app->db->quote($this->dataRecord["email"])."'");
            $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE active = 'y' AND source = ?", $this->dataRecord["email"]);
            if($tmp['number'] > 0) $app->tform->errorMessage .= $app->tform->lng("duplicate_alias_or_forward_txt")."<br>";
            unset($tmp);
@@ -257,13 +257,13 @@
        global $app, $conf;
        // Set the domain owner as mailbox owner
        $domain = $app->db->queryOneRecord("SELECT sys_groupid, server_id FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
        $app->db->query("UPDATE mail_user SET sys_groupid = ".$app->functions->intval($domain["sys_groupid"])." WHERE mailuser_id = ".$this->id);
        $domain = $app->db->queryOneRecord("SELECT sys_groupid, server_id FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"]));
        $app->db->query("UPDATE mail_user SET sys_groupid = ? WHERE mailuser_id = ?", $domain["sys_groupid"], $this->id);
        // Spamfilter policy
        $policy_id = $app->functions->intval($this->dataRecord["policy"]);
        if($policy_id > 0) {
            $tmp_user = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = '".$app->db->quote($this->dataRecord["email"])."'");
            $tmp_user = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = ?", $this->dataRecord["email"]);
            if($tmp_user["id"] > 0) {
                // There is already a record that we will update
                $app->db->datalogUpdate('spamfilter_users', "policy_id = $policy_id", 'id', $tmp_user["id"]);
@@ -283,8 +283,8 @@
            $disabledeliver = ($this->dataRecord["postfix"] == 'y')?'n':'y';
            $disablesmtp = ($this->dataRecord["disablesmtp"])?'y':'n';
            $sql = "UPDATE mail_user SET disableimap = '$disableimap', disablesieve = '$disableimap', disablepop3 = '$disablepop3', disablesmtp = '$disablesmtp', disabledeliver = '$disabledeliver', disablelda = '$disabledeliver', disabledoveadm = '$disableimap' WHERE mailuser_id = ".$this->id;
            $app->db->query($sql);
            $sql = "UPDATE mail_user SET disableimap = ?, disablesieve = ?, disablepop3 = ?, disablesmtp = ?, disabledeliver = ?, disablelda = ?, disabledoveadm = ? WHERE mailuser_id = ?";
            $app->db->query($sql, $disableimap, $disableimap, $disablepop3, $disablesmtp, $disabledeliver, $disabledeliver, $disableimap, $this->id);
        }
    }
@@ -293,12 +293,12 @@
        // Set the domain owner as mailbox owner
        if(isset($_POST["email_domain"])) {
            $domain = $app->db->queryOneRecord("SELECT sys_groupid, server_id FROM mail_domain WHERE domain = '".$app->db->quote($app->functions->idn_encode($_POST["email_domain"]))."' AND ".$app->tform->getAuthSQL('r'));
            $app->db->query("UPDATE mail_user SET sys_groupid = ".$app->functions->intval($domain["sys_groupid"])." WHERE mailuser_id = ".$this->id);
            $domain = $app->db->queryOneRecord("SELECT sys_groupid, server_id FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r'), $app->functions->idn_encode($_POST["email_domain"]));
            $app->db->query("UPDATE mail_user SET sys_groupid = ? WHERE mailuser_id = ?", $domain["sys_groupid"], $this->id);
            // Spamfilter policy
            $policy_id = $app->functions->intval($this->dataRecord["policy"]);
            $tmp_user = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = '".$app->db->quote($this->dataRecord["email"])."'");
            $tmp_user = $app->db->queryOneRecord("SELECT id FROM spamfilter_users WHERE email = ?", $this->dataRecord["email"]);
            if($policy_id > 0) {
                if($tmp_user["id"] > 0) {
                    // There is already a record that we will update
@@ -324,8 +324,8 @@
            $disabledeliver = ($this->dataRecord["postfix"] == 'y')?'n':'y';
            $disablesmtp = (isset($this->dataRecord["disablesmtp"]) && $this->dataRecord["disablesmtp"])?'y':'n';
            $sql = "UPDATE mail_user SET disableimap = '$disableimap', disablesieve = '$disableimap', `disablesieve-filter` = '$disableimap', disablepop3 = '$disablepop3', disablesmtp = '$disablesmtp', disabledeliver = '$disabledeliver', disablelda = '$disabledeliver', disabledoveadm = '$disableimap' WHERE mailuser_id = ".$this->id;
            $app->db->query($sql);
            $sql = "UPDATE mail_user SET disableimap = ?, disablesieve = ?, `disablesieve-filter` = ?, disablepop3 = ?, disablesmtp = ?, disabledeliver = ?, disablelda = ?, disabledoveadm = ? WHERE mailuser_id = ?";
            $app->db->query($sql, $disableimap, $disableimap, $disableimap, $disablepop3, $disablesmtp, $disabledeliver, $disabledeliver, $disableimap, $this->id);
        }
        //** If the email address has been changed, change it in all aliases too
@@ -333,7 +333,7 @@
            //if($this->oldDataRecord['email'] != $this->dataRecord['email']) {
            //* Update the aliases
            $forwardings = $app->db->queryAllRecords("SELECT * FROM mail_forwarding WHERE destination = '".$app->db->quote($this->oldDataRecord['email'])."'");
            $forwardings = $app->db->queryAllRecords("SELECT * FROM mail_forwarding WHERE destination = ?", $this->oldDataRecord['email']);
            if(is_array($forwardings)) {
                foreach($forwardings as $rec) {
                    $destination = $app->db->quote($this->dataRecord['email']);
interface/web/mail/mail_user_filter_edit.php
@@ -70,7 +70,7 @@
        global $app, $conf;
        // Get the parent mail_user record
        $mailuser = $app->db->queryOneRecord("SELECT * FROM mail_user WHERE mailuser_id = '".$app->functions->intval($_REQUEST["mailuser_id"])."' AND ".$app->tform->getAuthSQL('r'));
        $mailuser = $app->db->queryOneRecord("SELECT * FROM mail_user WHERE mailuser_id = ? AND ".$app->tform->getAuthSQL('r'). $_REQUEST["mailuser_id"]);
        // Check if Domain belongs to user
        if($mailuser["mailuser_id"] != $_POST["mailuser_id"]) $app->tform->errorMessage .= $app->tform->wordbook["no_mailuser_perm"];
interface/web/mail/mail_user_stats.php
@@ -34,28 +34,28 @@
        //* Set the statistics colums
        //** Traffic of the current month
        $tmp_date = date('Y-m');
        $tmp_rec = $app->db->queryOneRecord("SELECT traffic as t FROM mail_traffic WHERE mailuser_id = ".$app->functions->intval($rec['mailuser_id'])." AND month = '$tmp_date'");
        $tmp_rec = $app->db->queryOneRecord("SELECT traffic as t FROM mail_traffic WHERE mailuser_id = ? AND month = ?", $rec['mailuser_id'], $tmp_date);
//        $rec['this_month'] = number_format($app->functions->intval($tmp_rec['t'])/1024/1024, 0, '.', ' ');
        $rec['this_month'] = $app->functions->formatBytes($tmp_rec['t']);
        if ($rec['this_month'] == 'NAN') $rec['this_month'] = '0 KB';
        //** Traffic of the current year
        $tmp_date = date('Y');
        $tmp_rec = $app->db->queryOneRecord("SELECT sum(traffic) as t FROM mail_traffic WHERE mailuser_id = ".$app->functions->intval($rec['mailuser_id'])." AND month like '$tmp_date%'");
        $tmp_rec = $app->db->queryOneRecord("SELECT sum(traffic) as t FROM mail_traffic WHERE mailuser_id = ? AND month like ?", $rec['mailuser_id'], $tmp_date . '%');
//        $rec['this_year'] = number_format($app->functions->intval($tmp_rec['t'])/1024/1024, 0, '.', ' ');
        $rec['this_year'] = $app->functions->formatBytes($tmp_rec['t']);
        if ($rec['this_year'] == 'NAN') $rec['this_year'] = '0 KB';
        //** Traffic of the last month
        $tmp_date = date('Y-m', mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
        $tmp_rec = $app->db->queryOneRecord("SELECT traffic as t FROM mail_traffic WHERE mailuser_id = ".$app->functions->intval($rec['mailuser_id'])." AND month = '$tmp_date'");
        $tmp_rec = $app->db->queryOneRecord("SELECT traffic as t FROM mail_traffic WHERE mailuser_id = ? AND month = ?", $rec['mailuser_id'], $tmp_date);
//        $rec['last_month'] = number_format($app->functions->intval($tmp_rec['t'])/1024/1024, 0, '.', ' ');
        $rec['last_month'] = $app->functions->formatBytes($tmp_rec['t']);
        if ($rec['last_month'] == 'NAN') $rec['last_month'] = '0 KB';
        //** Traffic of the last year
        $tmp_date = date('Y', mktime(0, 0, 0, date("m"), date("d"), date("Y")-1));
        $tmp_rec = $app->db->queryOneRecord("SELECT sum(traffic) as t FROM mail_traffic WHERE mailuser_id = ".$app->functions->intval($rec['mailuser_id'])." AND month like '$tmp_date%'");
        $tmp_rec = $app->db->queryOneRecord("SELECT sum(traffic) as t FROM mail_traffic WHERE mailuser_id = ? AND month like ?", $rec['mailuser_id'], $tmp_date . '%');
//        $rec['last_year'] = number_format($app->functions->intval($tmp_rec['t'])/1024/1024, 0, '.', ' ');
        $rec['last_year'] = $app->functions->formatBytes($tmp_rec['t']);
        if ($rec['last_year'] == 'NAN') $rec['last_year'] = '0 KB';
interface/web/mail/mail_whitelist_edit.php
@@ -72,7 +72,7 @@
        //* Check if the server has been changed
        // We do this only for the admin or reseller users, as normal clients can not change the server ID anyway
        if($_SESSION["s"]["user"]["typ"] == 'admin' || $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
            $rec = $app->db->queryOneRecord("SELECT server_id from mail_access WHERE access_id = ".$this->id);
            $rec = $app->db->queryOneRecord("SELECT server_id from mail_access WHERE access_id = ?", $this->id);
            if($rec['server_id'] != $this->dataRecord["server_id"]) {
                //* Add a error message and switch back to old server
                $app->tform->errorMessage .= $app->lng('The Server can not be changed.');
interface/web/mail/spamfilter_config_edit.php
@@ -83,8 +83,8 @@
        $server_config_array[$section] = $app->tform->encode($this->dataRecord, $section);
        $server_config_str = $app->ini_parser->get_ini_string($server_config_array);
        $sql = "UPDATE server SET config = '".$app->db->quote($server_config_str)."' WHERE server_id = ".$app->functions->intval($server_id);
        $app->db->query($sql);
        $sql = "UPDATE server SET config = ? WHERE server_id = ?";
        $app->db->query($sql, $server_config_str, $server_id);
    }
}
interface/web/mail/spamfilter_whitelist_edit.php
@@ -65,24 +65,6 @@
        parent::onShowNew();
    }
    /*
    function onBeforeUpdate() {
        global $app, $conf;
        //* Check if the server has been changed
        // We do this only for the admin or reseller users, as normal clients can not change the server ID anyway
        if($_SESSION["s"]["user"]["typ"] == 'admin' || $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
            $rec = $app->db->queryOneRecord("SELECT server_id from spamfilter_wblist WHERE id = ".$this->id);
            if($rec['server_id'] != $this->dataRecord["server_id"]) {
                //* Add a error message and switch back to old server
                $app->tform->errorMessage .= $app->lng('The Server can not be changed.');
                $this->dataRecord["server_id"] = $rec['server_id'];
            }
            unset($rec);
        }
    }
    */
    function onSubmit() {
        global $app, $conf;
@@ -103,7 +85,7 @@
        } // end if user is not admin
        // Select and set the server_id so it matches the server_id of the spa,filter_users record
        $tmp = $app->db->queryOneRecord("SELECT server_id FROM spamfilter_users WHERE id = ".$app->functions->intval($this->dataRecord["rid"]));
        $tmp = $app->db->queryOneRecord("SELECT server_id FROM spamfilter_users WHERE id = ?", $this->dataRecord["rid"]);
        $this->dataRecord["server_id"] = $tmp["server_id"];
        unset($tmp);
interface/web/mail/user_quota_stats.php
@@ -19,8 +19,6 @@
$app->load('listform_actions');
// $tmp_rec = $app->db->queryOneRecord("SELECT data from monitor_data WHERE type = 'harddisk_quota' ORDER BY created DESC");
// $monitor_data = unserialize($app->db->unquote($tmp_rec['data']));
$tmp_rec =  $app->db->queryAllRecords("SELECT data from monitor_data WHERE type = 'email_quota' ORDER BY created DESC");
$monitor_data = array();
if(is_array($tmp_rec)) {
interface/web/mail/xmpp_domain_edit.php
@@ -123,13 +123,13 @@
            // Get the limits of the client
            $client_group_id = $_SESSION["s"]["user"]["default_group"];
            $client = $app->db->queryOneRecord("SELECT client.client_id, client.contact_name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname, sys_group.name FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id order by client.contact_name");
            $client = $app->db->queryOneRecord("SELECT client.client_id, client.contact_name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname, sys_group.name FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ? order by client.contact_name", $client_group_id);
            if ($settings['use_domain_module'] != 'y') {
                // Fill the client select field
                $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ".$app->functions->intval($client['client_id'])." ORDER BY client.company_name, client.contact_name, sys_group.name";
                $clients = $app->db->queryAllRecords($sql);
                $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($client['client_id']));
                $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ? ORDER BY client.company_name, client.contact_name, sys_group.name";
                $clients = $app->db->queryAllRecords($sql, $client['client_id']);
                $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
                $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contactname'].'</option>';
                //$tmp_data_record = $app->tform->getDataRecord($this->id);
                if(is_array($clients)) {
@@ -156,8 +156,8 @@
                $app->tpl->setVar('server_id_value', $client_xmpp['xmpp_servers_ids'][0]);
            }
            $sql = "SELECT server_id, server_name FROM server WHERE server_id IN (" . $client_xmpp['xmpp_servers'] . ");";
            $xmpp_servers = $app->db->queryAllRecords($sql);
            $sql = "SELECT server_id, server_name FROM server WHERE server_id IN ?";
            $xmpp_servers = $app->db->queryAllRecords($sql, $client_xmpp['xmpp_servers_ids']);
            $options_xmpp_servers = "";
@@ -243,7 +243,7 @@
            // When the record is updated
            if($this->id > 0) {
                // restore the server ID if the user is not admin and record is edited
                $tmp = $app->db->queryOneRecord("SELECT server_id FROM xmpp_domain WHERE domain_id = ".$app->functions->intval($this->id));
                $tmp = $app->db->queryOneRecord("SELECT server_id FROM xmpp_domain WHERE domain_id = ?", $this->id);
                $this->dataRecord["server_id"] = $tmp["server_id"];
                unset($tmp);
                // When the record is inserted
@@ -281,7 +281,7 @@
                case 1:
                    $this->dataRecord["management_method"] = 'maildomain';
                    // Check for corresponding mail domain
                    $tmp = $app->db->queryOneRecord("SELECT count(domain_id) AS number FROM mail_domain WHERE domain = '".$this->dataRecord["domain"]."' AND ".$app->tform->getAuthSQL('r')." ORDER BY domain");
                    $tmp = $app->db->queryOneRecord("SELECT count(domain_id) AS number FROM mail_domain WHERE domain = ? AND ".$app->tform->getAuthSQL('r')." ORDER BY domain", $this->dataRecord["domain"]);
                    if($tmp['number']==0){
                        $app->error($app->tform->wordbook["no_corresponding_maildomain_txt"]);
                        break;
@@ -318,11 +318,11 @@
        // also make sure that the user can not delete domain created by a admin
        if($_SESSION["s"]["user"]["typ"] == 'admin' && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE xmpp_domain SET sys_groupid = $client_group_id, sys_perm_group = 'ru' WHERE domain_id = ".$this->id);
            $app->db->query("UPDATE xmpp_domain SET sys_groupid = ?, sys_perm_group = 'ru' WHERE domain_id = ?", $client_group_id, $this->id);
        }
        if($app->auth->has_clients($_SESSION['s']['user']['userid']) && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE xmpp_domain SET sys_groupid = $client_group_id, sys_perm_group = 'riud' WHERE domain_id = ".$this->id);
            $app->db->query("UPDATE xmpp_domain SET sys_groupid = ?, sys_perm_group = 'riud' WHERE domain_id = ?", $client_group_id, $this->id);
        }
        //* make sure that the xmpp domain is lowercase
@@ -342,7 +342,7 @@
        if($this->_xmpp_type == 'server') {
            // Check if the domain has been changed
            $rec = $app->db->queryOneRecord("SELECT domain from xmpp_domain WHERE domain_id = ".$this->id);
            $rec = $app->db->queryOneRecord("SELECT domain from xmpp_domain WHERE domain_id = ?", $this->id);
            if($this->dataRecord['domain']!=$rec['domain'])
                $app->error($app->tform->wordbook["cant_change_domainname_txt"]);
@@ -350,7 +350,7 @@
            // We do this only for the admin or reseller users, as normal clients can not change the server ID anyway
            if($_SESSION["s"]["user"]["typ"] == 'admin' || $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
                if (isset($this->dataRecord["server_id"])) {
                    $rec = $app->db->queryOneRecord("SELECT server_id from xmpp_domain WHERE domain_id = ".$this->id);
                    $rec = $app->db->queryOneRecord("SELECT server_id from xmpp_domain WHERE domain_id = ?", $this->id);
                    if($rec['server_id'] != $this->dataRecord["server_id"]) {
                        //* Add a error message and switch back to old server
                        $app->tform->errorMessage .= $app->lng('The Server can not be changed.');
@@ -361,7 +361,7 @@
                //* If the user is neither admin nor reseller
            } else {
                //* We do not allow users to change a domain which has been created by the admin
                $rec = $app->db->queryOneRecord("SELECT sys_perm_group, domain from xmpp_domain WHERE domain_id = ".$this->id);
                $rec = $app->db->queryOneRecord("SELECT sys_perm_group, domain from xmpp_domain WHERE domain_id = ?", $this->id);
                if(isset($this->dataRecord["domain"]) && $rec['domain'] != $this->dataRecord["domain"] && $app->tform->checkPerm($this->id, 'u')) {
                    //* Add a error message and switch back to old server
                    $app->tform->errorMessage .= $app->lng('The Domain can not be changed. Please ask your Administrator if you want to change the domain name.');
@@ -411,7 +411,7 @@
    private function update_dns($dataRecord, $new_rr) {
        global $app, $conf;
        $rec = $app->db->queryOneRecord("SELECT use_pubsub, use_proxy, use_anon_host, use_vjud, use_muc_host from xmpp_domain WHERE domain_id = ".$this->id);
        $rec = $app->db->queryOneRecord("SELECT use_pubsub, use_proxy, use_anon_host, use_vjud, use_muc_host from xmpp_domain WHERE domain_id = ?", $this->id);
        $required_hosts = array('xmpp');
        if($rec['use_pubsub']=='y')
            $required_hosts[] = 'pubsub';
@@ -425,8 +425,8 @@
            $required_hosts[] = 'muc';
        // purge old rr-record
        $sql = "SELECT * FROM dns_rr WHERE zone = ? AND (name IN ? AND type = 'CNAME' OR name LIKE ? AND type = 'SRV')  AND ? ORDER BY serial DESC";
        $rec = $app->db->queryAllRecords($sql, $new_rr['zone'], array('xmpp', 'pubsub', 'proxy', 'anon', 'vjud', 'muc'), '_xmpp-%', $app->tform->getAuthSQL('r'));
        $sql = "SELECT * FROM dns_rr WHERE zone = ? AND (name IN ? AND type = 'CNAME' OR name LIKE ? AND type = 'SRV')  AND " . $app->tform->getAuthSQL('r') . " ORDER BY serial DESC";
        $rec = $app->db->queryAllRecords($sql, $new_rr['zone'], array('xmpp', 'pubsub', 'proxy', 'anon', 'vjud', 'muc'), '_xmpp-%');
        if (is_array($rec[1])) {
            for ($i=0; $i < count($rec); ++$i)
                $app->db->datalogDelete('dns_rr', 'id', $rec[$i]['id']);
interface/web/sites/ajax_get_ip.php
@@ -37,7 +37,7 @@
$server_id = $app->functions->intval($_GET["server_id"]);
$client_group_id = $app->functions->intval($_GET["client_group_id"]);
$ip_type = $app->db->quote($_GET['ip_type']);
$ip_type = $_GET['ip_type'];
if($_SESSION["s"]["user"]["typ"] == 'admin' or $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
interface/web/sites/ajax_get_json.php
@@ -56,8 +56,8 @@
if($type == 'getserverid'){
    $json = '{"serverid":"';
    $sql = "SELECT server_id FROM web_domain WHERE domain_id = $web_id AND ".$app->tform->getAuthSQL('r');
    $server = $app->db->queryOneRecord($sql);
    $sql = "SELECT server_id FROM web_domain WHERE domain_id = ?? AND ".$app->tform->getAuthSQL('r');
    $server = $app->db->queryOneRecord($sql, $web_id);
    $json .= $server['server_id'];
    unset($server);
    $json .= '"}';
@@ -77,7 +77,7 @@
        $sql_where = " AND (client_id = 0 OR client_id = ".$app->functions->intval($_SESSION["s"]["user"]["client_id"]) . ")";
        //* Reseller: If the logged in user is not admin and has sub clients (is a reseller)
    } elseif ($_SESSION["s"]["user"]["typ"] != 'admin' && $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
        $client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE groupid = $client_group_id");
        $client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE groupid = ?", $client_group_id);
        //$sql_where = " AND (client_id = 0 OR client_id = ".$_SESSION["s"]["user"]["client_id"];
        $sql_where = " AND (client_id = 0";
        if($app->functions->intval($client['client_id']) > 0) $sql_where .= " OR client_id = ".$app->functions->intval($client['client_id']);
@@ -85,7 +85,7 @@
        //* Admin: If the logged in user is admin
    } else {
        //$sql_where = '';
        $client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE groupid = $client_group_id");
        $client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE groupid = ?", $client_group_id);
        //$sql_where = " AND (client_id = 0 OR client_id = ".$_SESSION["s"]["user"]["client_id"];
        $sql_where = " AND (client_id = 0";
        if($app->functions->intval($client['client_id']) > 0) $sql_where .= " OR client_id = ".$app->functions->intval($client['client_id']);
@@ -93,10 +93,9 @@
    }
    if($php_type == 'php-fpm'){
        $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = $server_id".$sql_where);
    }
    if($php_type == 'fast-cgi'){
        $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = $server_id".$sql_where);
        $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ?".$sql_where, $server_id);
    } elseif($php_type == 'fast-cgi'){
        $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ?".$sql_where, $server_id);
    }
    $php_select = "";
    if(is_array($php_records) && !empty($php_records)) {
@@ -116,8 +115,8 @@
if($type == 'getphptype'){
    $json = '{"phptype":"';
    $sql = "SELECT php FROM web_domain WHERE domain_id = $web_id AND ".$app->tform->getAuthSQL('r');
    $php = $app->db->queryOneRecord($sql);
    $sql = "SELECT php FROM web_domain WHERE domain_id = ? AND ".$app->tform->getAuthSQL('r');
    $php = $app->db->queryOneRecord($sql, $web_id);
    $json .= $php['php'];
    unset($php);
    $json .= '"}';
@@ -125,8 +124,8 @@
if($type == 'getredirecttype'){
    $json = '{"redirecttype":"';
    $sql = "SELECT redirect_type FROM web_domain WHERE domain_id = $web_id AND ".$app->tform->getAuthSQL('r');
    $redirect = $app->db->queryOneRecord($sql);
    $sql = "SELECT redirect_type FROM web_domain WHERE domain_id = ? AND ".$app->tform->getAuthSQL('r');
    $redirect = $app->db->queryOneRecord($sql, $web_id);
    $json .= $redirect['redirect_type'];
    unset($redirect);
    $json .= '"}';
@@ -155,11 +154,11 @@
if($type == 'getdatabaseusers') {
    $json = '{}';
    $sql = "SELECT sys_groupid FROM web_domain WHERE domain_id = $web_id AND ".$app->tform->getAuthSQL('r');
    $group = $app->db->queryOneRecord($sql);
    $sql = "SELECT sys_groupid FROM web_domain WHERE domain_id = ? AND ".$app->tform->getAuthSQL('r');
    $group = $app->db->queryOneRecord($sql, $web_id);
    if($group) {
        $sql = "SELECT database_user_id, database_user FROM web_database_user WHERE sys_groupid = '" . $app->functions->intval($group['sys_groupid']) . "'";
        $records = $app->db->queryAllRecords($sql);
        $sql = "SELECT database_user_id, database_user FROM web_database_user WHERE sys_groupid = ?";
        $records = $app->db->queryAllRecords($sql, $group['sys_groupid']);
        $tmp_array = array();
        foreach($records as $record) {
@@ -202,9 +201,9 @@
}
if($type == 'getclientssldata'){
    $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", intval($web_id));
    $sys_group = $app->db->queryOneRecord("SELECT * FROM sys_group WHERE groupid = ?", intval($web['sys_groupid']));
    $client = $app->db->queryOneRecord("SELECT * FROM client WHERE client_id = ?", intval($sys_group['client_id']));
    $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $web_id);
    $sys_group = $app->db->queryOneRecord("SELECT * FROM sys_group WHERE groupid = ?", $web['sys_groupid']);
    $client = $app->db->queryOneRecord("SELECT * FROM client WHERE client_id = ?", $sys_group['client_id']);
    if(is_array($client) && !empty($client)){
        if($client['telephone'] == '' && $client['mobile'] != '') $client['telephone'] = $client['mobile'];
        
interface/web/sites/aps_install_package.php
@@ -62,7 +62,7 @@
$adminflag = ($_SESSION['s']['user']['typ'] == 'admin') ? true : false;
$gui = new ApsGUIController($app);
$pkg_id = (isset($_GET['id'])) ? $app->db->quote($_GET['id']) : '';
$pkg_id = (isset($_GET['id'])) ? $_GET['id'] : '';
// Check if a newer version is available for the current package
// Note: It's intended that here is no strict ID check (see below)
interface/web/sites/aps_installedpackages_list.php
@@ -51,7 +51,7 @@
$is_admin = ($_SESSION['s']['user']['typ'] == 'admin') ? true : false;
if(!$is_admin)
{
    $cid = $app->db->queryOneRecord('SELECT client_id FROM client WHERE username = "'.$app->db->quote($_SESSION['s']['user']['username']).'";');
    $cid = $app->db->queryOneRecord('SELECT client_id FROM client WHERE username = ?', $_SESSION['s']['user']['username']);
    //$client_ext = ' AND aps_instances.customer_id = '.$cid['client_id'];
    $client_ext = ' AND '.$app->tform->getAuthSQL('r', 'aps_instances');
}
interface/web/sites/aps_packagedetails_show.php
@@ -47,7 +47,7 @@
$app->tpl->setVar($wb);
$gui = new ApsGUIController($app);
$pkg_id = (isset($_GET['id'])) ? $app->db->quote($_GET['id']) : '';
$pkg_id = (isset($_GET['id'])) ? $_GET['id'] : '';
// Check if a newer version is available for the current package
// Note: It's intended that here is no strict ID check (see below)
interface/web/sites/database_user_edit.php
@@ -69,9 +69,9 @@
            $client = $app->db->queryOneRecord("SELECT client.company_name, client.contact_name, client.client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ?", $client_group_id);
            // Fill the client select field
            $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ".$app->functions->intval($client['client_id'])." ORDER BY client.company_name, client.contact_name, sys_group.name";
            $records = $app->db->queryAllRecords($sql);
            $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($client['client_id']));
            $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ? ORDER BY client.company_name, client.contact_name, sys_group.name";
            $records = $app->db->queryAllRecords($sql, $client['client_id']);
            $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
            $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contact_name'].'</option>';
            //$tmp_data_record = $app->tform->getDataRecord($this->id);
            if(is_array($records)) {
@@ -128,7 +128,7 @@
        $global_config = $app->getconf->get_global_config('sites');
        $dbuser_prefix = $app->tools_sites->replacePrefix($global_config['dbuser_prefix'], $this->dataRecord);
        $this->oldDataRecord = $app->db->queryOneRecord("SELECT * FROM web_database_user WHERE database_user_id = '".$this->id."'");
        $this->oldDataRecord = $app->db->queryOneRecord("SELECT * FROM web_database_user WHERE database_user_id = ?", $this->id);
        $dbuser_prefix = $app->tools_sites->getPrefix($this->oldDataRecord['database_user_prefix'], $dbuser_prefix);
        $this->dataRecord['database_user_prefix'] = $dbuser_prefix;
@@ -200,11 +200,11 @@
        if($_SESSION["s"]["user"]["typ"] == 'admin' && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE web_database_user SET sys_groupid = $client_group_id, sys_perm_group = 'riud' WHERE database_user_id = ".$this->id);
            $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_group_id, $this->id);
        }
        if($app->auth->has_clients($_SESSION['s']['user']['userid']) && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE web_database_user SET sys_groupid = $client_group_id, sys_perm_group = 'riud' WHERE database_user_id = ".$this->id);
            $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_group_id, $this->id);
        }
    }
@@ -213,24 +213,12 @@
        if($_SESSION["s"]["user"]["typ"] == 'admin' && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE web_database_user SET sys_groupid = $client_group_id, sys_perm_group = 'riud' WHERE database_user_id = ".$this->id);
            $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_group_id, $this->id);
        }
        if($app->auth->has_clients($_SESSION['s']['user']['userid']) && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE web_database_user SET sys_groupid = $client_group_id, sys_perm_group = 'riud' WHERE database_user_id = ".$this->id);
            $app->db->query("UPDATE web_database_user SET sys_groupid = ?, sys_perm_group = 'riud' WHERE database_user_id = ?", $client_group_id, $this->id);
        }
        /*$password = $app->db->queryOneRecord("SELECT database_password FROM web_database_user WHERE database_user_id = ".$this->id);
        $records = $app->db->queryAllRecords("SELECT DISTINCT server_id FROM web_database WHERE database_user_id = '".$app->functions->intval($this->id)."' UNION SELECT DISTINCT server_id FROM web_database WHERE database_ro_user_id = '".$app->functions->intval($this->id)."'");
        foreach($records as $rec) {
            $new_rec = $this->dataRecord;
            $new_rec['server_id'] = $rec['server_id'];
            // Make sure to store the password in encrypted form in sys_datalog
            $new_rec['database_password'] = $password['database_password'];
            $app->db->datalogSave('web_database_user', 'UPDATE', 'database_user_id', $this->id, $this->oldDataRecord, $new_rec);
        }
        unset($new_rec);*/
    }
}
interface/web/sites/ftp_user_edit.php
@@ -96,11 +96,11 @@
        // Get the record of the parent domain
        if(isset($this->dataRecord["parent_domain_id"])) {
            $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ".$app->functions->intval(@$this->dataRecord["parent_domain_id"]) . " AND ".$app->tform->getAuthSQL('r'));
            $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ? AND ".$app->tform->getAuthSQL('r'), @$this->dataRecord["parent_domain_id"]);
            if(!$parent_domain || $parent_domain['domain_id'] != @$this->dataRecord['parent_domain_id']) $app->tform->errorMessage .= $app->tform->lng("no_domain_perm");
        } else {
            $tmp = $app->tform->getDataRecord($this->id);
            $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ".$app->functions->intval($tmp["parent_domain_id"]) . " AND ".$app->tform->getAuthSQL('r'));
            $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ? AND ".$app->tform->getAuthSQL('r'), $tmp["parent_domain_id"]);
            if(!$parent_domain) $app->tform->errorMessage .= $app->tform->lng("no_domain_perm");
            unset($tmp);
        }
@@ -137,11 +137,11 @@
    function onAfterInsert() {
        global $app, $conf;
        $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".$app->functions->intval($this->dataRecord["parent_domain_id"]));
        $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
        $server_id = $app->functions->intval($web["server_id"]);
        $dir = $app->db->quote($web["document_root"]);
        $uid = $app->db->quote($web["system_user"]);
        $gid = $app->db->quote($web["system_group"]);
        $dir = $web["document_root"];
        $uid = $web["system_user"];
        $gid = $web["system_group"];
        
        // Check system user and group
        if($app->functions->is_allowed_user($uid) == false || $app->functions->is_allowed_group($gid) == false) {
@@ -151,8 +151,8 @@
        // The FTP user shall be owned by the same group then the website
        $sys_groupid = $app->functions->intval($web['sys_groupid']);
        $sql = "UPDATE ftp_user SET server_id = $server_id, dir = '$dir', uid = '$uid', gid = '$gid', sys_groupid = '$sys_groupid' WHERE ftp_user_id = ".$this->id;
        $app->db->query($sql);
        $sql = "UPDATE ftp_user SET server_id = ?, dir = ?, uid = ?, gid = ?, sys_groupid = ? WHERE ftp_user_id = ?";
        $app->db->query($sql, $server_id, $dir, $uid, $gid, $sys_groupid, $this->id);
    }
    function onBeforeUpdate() {
@@ -181,17 +181,17 @@
        //* When the site of the FTP user has been changed
        if(isset($this->dataRecord['parent_domain_id']) && $this->oldDataRecord['parent_domain_id'] != $this->dataRecord['parent_domain_id']) {
            $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".$app->functions->intval($this->dataRecord["parent_domain_id"]));
            $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
            $server_id = $app->functions->intval($web["server_id"]);
            $dir = $app->db->quote($web["document_root"]);
            $uid = $app->db->quote($web["system_user"]);
            $gid = $app->db->quote($web["system_group"]);
            $dir = $web["document_root"];
            $uid = $web["system_user"];
            $gid = $web["system_group"];
            // The FTP user shall be owned by the same group then the website
            $sys_groupid = $app->functions->intval($web['sys_groupid']);
            $sql = "UPDATE ftp_user SET server_id = $server_id, dir = '$dir', uid = '$uid', gid = '$gid', sys_groupid = '$sys_groupid' WHERE ftp_user_id = ".$this->id;
            $app->db->query($sql);
            $sql = "UPDATE ftp_user SET server_id = ?, dir = ?, uid = ?, gid = ?, sys_groupid = ? WHERE ftp_user_id = ?";
            $app->db->query($sql, $server_id, $dir, $uid, $gid, $sys_groupid, $this->id);
        }
        //* 2. check to ensure that the FTP user path is not changed to a path outside of the docroot by a normal user
@@ -201,11 +201,11 @@
            //* This check should normally never be triggered
            //* Set the path to a safe path (web doc root).
            if($error_message != '') {
                $ftp_data = $app->db->queryOneRecord("SELECT parent_domain_id FROM ftp_user WHERE ftp_user_id = '".$app->db->quote($app->tform->primary_id)."'");
                $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".$app->functions->intval($ftp_data["parent_domain_id"]));
                $dir = $app->db->quote($web["document_root"]);
                $sql = "UPDATE ftp_user SET dir = '$dir' WHERE ftp_user_id = ".$this->id;
                $app->db->query($sql);
                $ftp_data = $app->db->queryOneRecord("SELECT parent_domain_id FROM ftp_user WHERE ftp_user_id = ?", $app->tform->primary_id);
                $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $ftp_data["parent_domain_id"]);
                $dir = $web["document_root"];
                $sql = "UPDATE ftp_user SET dir = ? WHERE ftp_user_id = ?";
                $app->db->query($sql, $dir, $this->id);
                $app->log("Error in FTP path settings of FTP user ".$this->dataRecord['username'], 1);
            }
interface/web/sites/shell_user_edit.php
@@ -164,9 +164,9 @@
        $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
        $server_id = $app->functions->intval($web["server_id"]);
        $dir = $app->db->quote($web["document_root"]);
        $uid = $app->db->quote($web["system_user"]);
        $gid = $app->db->quote($web["system_group"]);
        $dir = $web["document_root"];
        $uid = $web["system_user"];
        $gid = $web["system_group"];
        
        // Check system user and group
        if($app->functions->is_allowed_user($uid) == false || $app->functions->is_allowed_group($gid) == false) {
interface/web/sites/user_quota_stats.php
@@ -19,8 +19,6 @@
$app->load('listform_actions');
// $tmp_rec = $app->db->queryOneRecord("SELECT data from monitor_data WHERE type = 'harddisk_quota' ORDER BY created DESC");
// $monitor_data = unserialize($app->db->unquote($tmp_rec['data']));
$tmp_rec =  $app->db->queryAllRecords("SELECT data from monitor_data WHERE type = 'harddisk_quota' ORDER BY created DESC");
$monitor_data = array();
if(is_array($tmp_rec)) {
@@ -43,7 +41,7 @@
        $rec['bgcolor'] = $this->DataRowColor;
        $username = $rec['system_user'];
        $server = $app->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ".$rec['server_id']);
        $server = $app->db->queryOneRecord("SELECT server_name FROM server WHERE server_id = ?", $rec['server_id']);
        $rec['domain'] = $rec['domain'].($server['server_name'] != '' ? ' ('.$server['server_name'].')' : '');
        
        $rec['used'] = $monitor_data['user'][$username]['used'];
interface/web/sites/web_folder_edit.php
@@ -55,7 +55,7 @@
        global $app, $conf;
        // Get the record of the parent domain
        $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ".$app->functions->intval(@$this->dataRecord["parent_domain_id"]) . " AND ".$app->tform->getAuthSQL('r'));
        $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ? AND ".$app->tform->getAuthSQL('r'), @$this->dataRecord["parent_domain_id"]);
        if(!$parent_domain || $parent_domain['domain_id'] != @$this->dataRecord['parent_domain_id']) $app->tform->errorMessage .= $app->tform->lng("no_domain_perm");
        // Set a few fixed values
@@ -63,9 +63,9 @@
        
        // make sure this folder isn't protected already
        if($this->id > 0){
            $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE parent_domain_id = ".$this->dataRecord['parent_domain_id']." AND path = '".$this->dataRecord['path']."' AND web_folder_id != ".$this->id);
            $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE parent_domain_id = ? AND path = ? AND web_folder_id != ?", $this->dataRecord['parent_domain_id'], $this->dataRecord['path'], $this->id);
        } else {
            $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE parent_domain_id = ".$this->dataRecord['parent_domain_id']." AND path = '".$this->dataRecord['path']."'");
            $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE parent_domain_id = ? AND path = ?", $this->dataRecord['parent_domain_id'], $this->dataRecord['path']);
        }
        if(is_array($folder) && !empty($folder)) $app->tform->errorMessage .= $app->tform->lng('error_folder_already_protected_txt');
@@ -75,13 +75,13 @@
    function onAfterInsert() {
        global $app, $conf;
        $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".$app->functions->intval($this->dataRecord["parent_domain_id"]));
        $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
        // The web folder entry shall be owned by the same group as the website
        $sys_groupid = $app->functions->intval($web['sys_groupid']);
        $sql = "UPDATE web_folder SET sys_groupid = '$sys_groupid' WHERE web_folder_id = ".$this->id;
        $app->db->query($sql);
        $sql = "UPDATE web_folder SET sys_groupid = ? WHERE web_folder_id = ?";
        $app->db->query($sql, $sys_groupid, $this->id);
    }
    
    function onAfterUpdate() {
@@ -89,13 +89,13 @@
        //* When the site of the web folder has been changed
        if(isset($this->dataRecord['parent_domain_id']) && $this->oldDataRecord['parent_domain_id'] != $this->dataRecord['parent_domain_id']) {
            $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".$app->functions->intval($this->dataRecord["parent_domain_id"]));
            $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
            // The web folder entry shall be owned by the same group as the website
            $sys_groupid = $app->functions->intval($web['sys_groupid']);
            $sql = "UPDATE web_folder SET sys_groupid = '$sys_groupid' WHERE web_folder_id = ".$this->id;
            $app->db->query($sql);
            $sql = "UPDATE web_folder SET sys_groupid = ? WHERE web_folder_id = ?";
            $app->db->query($sql, $sys_groupid, $this->id);
        }
    }
interface/web/sites/web_folder_user_edit.php
@@ -55,7 +55,7 @@
        global $app, $conf;
        // Get the record of the parent domain
        $folder = $app->db->queryOneRecord("select * FROM web_folder WHERE web_folder_id = ".$app->functions->intval(@$this->dataRecord["web_folder_id"]) . " AND ".$app->tform->getAuthSQL('r'));
        $folder = $app->db->queryOneRecord("select * FROM web_folder WHERE web_folder_id = ? AND ".$app->tform->getAuthSQL('r'), @$this->dataRecord["web_folder_id"]);
        if(!$folder || $folder['web_folder_id'] != @$this->dataRecord['web_folder_id']) $app->tform->errorMessage .= $app->tform->lng("no_folder_perm");
        // Set a few fixed values
@@ -63,9 +63,9 @@
        
        // make sure this folder/user combination does not exist already
        if($this->id > 0){
            $user = $app->db->queryOneRecord("SELECT * FROM web_folder_user WHERE web_folder_id = ".$this->dataRecord['web_folder_id']." AND username = '".$this->dataRecord['username']."' AND web_folder_user_id != ".$this->id);
            $user = $app->db->queryOneRecord("SELECT * FROM web_folder_user WHERE web_folder_id = ? AND username = ? AND web_folder_user_id != ?", $this->dataRecord['web_folder_id'], $this->dataRecord['username'], $this->id);
        } else {
            $user = $app->db->queryOneRecord("SELECT * FROM web_folder_user WHERE web_folder_id = ".$this->dataRecord['web_folder_id']." AND username = '".$this->dataRecord['username']."'");
            $user = $app->db->queryOneRecord("SELECT * FROM web_folder_user WHERE web_folder_id = ? AND username = ?", $this->dataRecord['web_folder_id'], $this->dataRecord['username']);
        }
        if(is_array($user) && !empty($user)) $app->tform->errorMessage .= $app->tform->lng('error_user_exists_already_txt');
@@ -75,12 +75,12 @@
    function onAfterInsert() {
        global $app, $conf;
        $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE web_folder_id = ".$app->functions->intval($this->dataRecord["web_folder_id"]));
        $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE web_folder_id = ?", $this->dataRecord["web_folder_id"]);
        // The web folder user entry shall be owned by the same group as the web folder
        $sys_groupid = $app->functions->intval($folder['sys_groupid']);
        $sql = "UPDATE web_folder_user SET sys_groupid = '$sys_groupid' WHERE web_folder_user_id = ".$this->id;
        $sql = "UPDATE web_folder_user SET sys_groupid = ? WHERE web_folder_user_id = ?", $sys_groupid, $this->id;
        $app->db->query($sql);
    }
    
@@ -89,13 +89,13 @@
        //* When the web folder has been changed
        if(isset($this->dataRecord['web_folder_id']) && $this->oldDataRecord['web_folder_id'] != $this->dataRecord['web_folder_id']) {
            $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE web_folder_id = ".$app->functions->intval($this->dataRecord["web_folder_id"]));
            $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE web_folder_id = ?", $this->dataRecord["web_folder_id"]);
            // The web folder user entry shall be owned by the same group as the web folder
            $sys_groupid = $app->functions->intval($folder['sys_groupid']);
            $sql = "UPDATE web_folder_user SET sys_groupid = '$sys_groupid' WHERE web_folder_user_id = ".$this->id;
            $app->db->query($sql);
            $sql = "UPDATE web_folder_user SET sys_groupid = ? WHERE web_folder_user_id = ?";
            $app->db->query($sql, $sys_groupid, $this->id);
        }
    }
interface/web/sites/web_vhost_domain_del.php
@@ -72,45 +72,45 @@
            if($app->tform->checkPerm($this->id, 'd') == false) $app->error($app->lng('error_no_delete_permission'));
            //* Delete all records that belong to this web.
            $records = $app->db->queryAllRecords("SELECT domain_id FROM web_domain WHERE parent_domain_id = '".$app->functions->intval($this->id)."' AND type != 'vhost'");
            $records = $app->db->queryAllRecords("SELECT domain_id FROM web_domain WHERE parent_domain_id = ? AND type != 'vhost'", $this->id);
            foreach($records as $rec) {
                $app->db->datalogDelete('web_domain', 'domain_id', $rec['domain_id']);
            }
            //* Delete all records that belong to this web.
            $records = $app->db->queryAllRecords("SELECT ftp_user_id FROM ftp_user WHERE parent_domain_id = '".$app->functions->intval($this->id)."'");
            $records = $app->db->queryAllRecords("SELECT ftp_user_id FROM ftp_user WHERE parent_domain_id = ?", $this->id);
            foreach($records as $rec) {
                $app->db->datalogDelete('ftp_user', 'ftp_user_id', $rec['ftp_user_id']);
            }
            //* Delete all records that belong to this web.
            $records = $app->db->queryAllRecords("SELECT shell_user_id FROM shell_user WHERE parent_domain_id = '".$app->functions->intval($this->id)."'");
            $records = $app->db->queryAllRecords("SELECT shell_user_id FROM shell_user WHERE parent_domain_id = ?", $this->id);
            foreach($records as $rec) {
                $app->db->datalogDelete('shell_user', 'shell_user_id', $rec['shell_user_id']);
            }
            //* Delete all records that belong to this web.
            $records = $app->db->queryAllRecords("SELECT id FROM cron WHERE parent_domain_id = '".$app->functions->intval($this->id)."'");
            $records = $app->db->queryAllRecords("SELECT id FROM cron WHERE parent_domain_id = ?", $this->id);
            foreach($records as $rec) {
                $app->db->datalogDelete('cron', 'id', $rec['id']);
            }
            //* Delete all records that belong to this web
            $records = $app->db->queryAllRecords("SELECT webdav_user_id FROM webdav_user WHERE parent_domain_id = '".$app->functions->intval($this->id)."'");
            $records = $app->db->queryAllRecords("SELECT webdav_user_id FROM webdav_user WHERE parent_domain_id = ?", $this->id);
            foreach($records as $rec) {
                $app->db->datalogDelete('webdav_user', 'webdav_user_id', $rec['webdav_user_id']);
            }
            //* Delete all records that belong to this web
            $records = $app->db->queryAllRecords("SELECT backup_id FROM web_backup WHERE parent_domain_id = '".$app->functions->intval($this->id)."'");
            $records = $app->db->queryAllRecords("SELECT backup_id FROM web_backup WHERE parent_domain_id = ?", $this->id);
            foreach($records as $rec) {
                $app->db->datalogDelete('web_backup', 'backup_id', $rec['backup_id']);
            }
            //* Delete all records that belog to this web.
            $web_domain = $app->db->queryOneRecord("SELECT domain FROM web_domain WHERE domain_id = ".$app->functions->intval($this->id));
            $web_domain = $app->db->queryOneRecord("SELECT domain FROM web_domain WHERE domain_id = ?", $this->id);
            if($web_domain['domain'] != ''){
                $aps_instances = $app->db->queryAllRecords("SELECT instance_id FROM aps_instances_settings WHERE name = 'main_domain' AND value = '".$app->db->quote($web_domain['domain'])."'");
                $aps_instances = $app->db->queryAllRecords("SELECT instance_id FROM aps_instances_settings WHERE name = 'main_domain' AND value = ?", $web_domain['domain']);
                if(is_array($aps_instances) && !empty($aps_instances)){
                    foreach($aps_instances as $aps_instance){
                        if($aps_instance['instance_id'] > 0){
@@ -123,10 +123,10 @@
        }
        //* Delete all web folders
        $records = $app->db->queryAllRecords("SELECT web_folder_id FROM web_folder WHERE parent_domain_id = '".$app->functions->intval($this->id)."'");
        $records = $app->db->queryAllRecords("SELECT web_folder_id FROM web_folder WHERE parent_domain_id = ?", $this->id);
        foreach($records as $rec) {
            //* Delete all web folder users
            $records2 = $app->db->queryAllRecords("SELECT web_folder_user_id FROM web_folder_user WHERE web_folder_id = '".$app->functions->intval($rec['web_folder_id'])."'");
            $records2 = $app->db->queryAllRecords("SELECT web_folder_user_id FROM web_folder_user WHERE web_folder_id = ?", $rec['web_folder_id']);
            foreach($records2 as $rec2) {
                $app->db->datalogDelete('web_folder_user', 'web_folder_user_id', $rec2['web_folder_user_id']);
            }
interface/web/sites/web_vhost_domain_edit.php
@@ -167,8 +167,8 @@
                $web_config[$web_server_id] = $app->getconf->get_server_config($web_server_id, 'web');
            }
            $sql = "SELECT server_id, server_name FROM server WHERE server_id IN (" . $client['web_servers'] . ");";
            $web_servers = $app->db->queryAllRecords($sql);
            $sql = "SELECT server_id, server_name FROM server WHERE server_id IN ?";
            $web_servers = $app->db->queryAllRecords($sql, $client['web_servers_ids']);
            $options_web_servers = "";
@@ -181,7 +181,7 @@
            if($this->id > 0) {
                if(!isset($this->dataRecord["server_id"])){
                    $tmp = $app->db->queryOneRecord("SELECT server_id FROM web_domain WHERE domain_id = ".$app->functions->intval($this->id));
                    $tmp = $app->db->queryOneRecord("SELECT server_id FROM web_domain WHERE domain_id = ?", $this->id);
                    $this->dataRecord["server_id"] = $tmp["server_id"];
                    unset($tmp);
                }
@@ -200,8 +200,8 @@
            }
            
            //* Fill the IPv4 select field with the IP addresses that are allowed for this client
            $sql = "SELECT ip_address FROM server_ip WHERE server_id IN (" . $client['web_servers'] . ") AND ip_type = 'IPv4' AND (client_id = 0 OR client_id=".$_SESSION['s']['user']['client_id'].")";
            $ips = $app->db->queryAllRecords($sql);
            $sql = "SELECT ip_address FROM server_ip WHERE server_id IN ? AND ip_type = 'IPv4' AND (client_id = 0 OR client_id=".$_SESSION['s']['user']['client_id'].")";
            $ips = $app->db->queryAllRecords($sql, explode(',', $client['web_servers']));
            $ip_select = ($web_config[$server_id]['enable_ip_wildcard'] == 'y')?"<option value='*'>*</option>":"";
            //if(!in_array($this->dataRecord["ip_address"], $ips)) $ip_select .= "<option value='".$this->dataRecord["ip_address"]."' SELECTED>".$this->dataRecord["ip_address"]."</option>\r\n";
            //$ip_select = "";
@@ -216,8 +216,8 @@
            unset($ips);
            //* Fill the IPv6 select field with the IP addresses that are allowed for this client
            $sql = "SELECT ip_address FROM server_ip WHERE server_id IN (" . $client['web_servers'] . ") AND ip_type = 'IPv6' AND (client_id = 0 OR client_id=".$_SESSION['s']['user']['client_id'].")";
            $ips = $app->db->queryAllRecords($sql);
            $sql = "SELECT ip_address FROM server_ip WHERE server_id IN ? AND ip_type = 'IPv6' AND (client_id = 0 OR client_id=?)";
            $ips = $app->db->queryAllRecords($sql, explode(',', $client['web_servers']), $_SESSION['s']['user']['client_id']);
            $ip_select = "<option value=''></option>";
            //$ip_select = "";
            if(is_array($ips)) {
@@ -237,17 +237,17 @@
            if($this->_vhostdomain_type == 'domain') {
                if($this->dataRecord['php'] == 'php-fpm'){
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ".($this->id > 0 ? $app->functions->intval($this->dataRecord['server_id']) : $app->functions->intval($client['default_webserver']))." AND (client_id = 0 OR client_id=".$app->functions->intval($_SESSION['s']['user']['client_id']).")");
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ? AND (client_id = 0 OR client_id=?)", ($this->id > 0 ? $this->dataRecord['server_id'] : $client['default_webserver']), $_SESSION['s']['user']['client_id']);
                }
                if($this->dataRecord['php'] == 'fast-cgi'){
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ".($this->id > 0 ? $app->functions->intval($this->dataRecord['server_id']) : $app->functions->intval($client['default_webserver']))." AND (client_id = 0 OR client_id=".$app->functions->intval($_SESSION['s']['user']['client_id']).")");
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ? AND (client_id = 0 OR client_id=?)", ($this->id > 0 ? $this->dataRecord['server_id'] : $client['default_webserver']), $_SESSION['s']['user']['client_id']);
                }
            } else {
                if($this->dataRecord['php'] == 'php-fpm'){
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ".$app->functions->intval($parent_domain['server_id'])." AND (client_id = 0 OR client_id=".$app->functions->intval($_SESSION['s']['user']['client_id']).")");
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ? AND (client_id = 0 OR client_id=?)", $parent_domain['server_id'], $_SESSION['s']['user']['client_id']);
                }
                if($this->dataRecord['php'] == 'fast-cgi'){
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ".$app->functions->intval($parent_domain['server_id'])." AND (client_id = 0 OR client_id=".$app->functions->intval($_SESSION['s']['user']['client_id']).")");
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ? AND (client_id = 0 OR client_id=?)", $parent_domain['server_id'], $_SESSION['s']['user']['client_id']);
                }
            }
            $php_select = "<option value=''>Default</option>";
@@ -292,8 +292,8 @@
                $web_config[$web_server_id] = $app->getconf->get_server_config($web_server_id, 'web');
            }
            $sql = "SELECT server_id, server_name FROM server WHERE server_id IN (" . $client['web_servers'] . ");";
            $web_servers = $app->db->queryAllRecords($sql);
            $sql = "SELECT server_id, server_name FROM server WHERE server_id IN ?";
            $web_servers = $app->db->queryAllRecords($sql, $client['web_servers_ids']);
            $options_web_servers = "";
@@ -306,9 +306,9 @@
            if ($settings['use_domain_module'] != 'y') {
                // Fill the client select field
                $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ".$client['client_id']." ORDER BY client.company_name, client.contact_name, sys_group.name";
                $records = $app->db->queryAllRecords($sql);
                $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($client['client_id']));
                $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ? ORDER BY client.company_name, client.contact_name, sys_group.name";
                $records = $app->db->queryAllRecords($sql, $client['client_id']);
                $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
                $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contactname'].'</option>';
                //$tmp_data_record = $app->tform->getDataRecord($this->id);
                if(is_array($records)) {
@@ -333,8 +333,8 @@
            }
            
            //* Fill the IPv4 select field with the IP addresses that are allowed for this client
            $sql = "SELECT ip_address FROM server_ip WHERE server_id IN (" . $client['web_servers'] . ") AND ip_type = 'IPv4' AND (client_id = 0 OR client_id=".$_SESSION['s']['user']['client_id'].")";
            $ips = $app->db->queryAllRecords($sql);
            $sql = "SELECT ip_address FROM server_ip WHERE server_id IN ? AND ip_type = 'IPv4' AND (client_id = 0 OR client_id=?)";
            $ips = $app->db->queryAllRecords($sql, explode(',', $client['web_servers']), $_SESSION['s']['user']['client_id']);
            $ip_select = ($web_config[$server_id]['enable_ip_wildcard'] == 'y')?"<option value='*'>*</option>":"";
            //if(!in_array($this->dataRecord["ip_address"], $ips)) $ip_select .= "<option value='".$this->dataRecord["ip_address"]."' SELECTED>".$this->dataRecord["ip_address"]."</option>\r\n";
            //$ip_select = "";
@@ -349,8 +349,8 @@
            unset($ips);
            //* Fill the IPv6 select field with the IP addresses that are allowed for this client
            $sql = "SELECT ip_address FROM server_ip WHERE server_id IN (" . $client['web_servers'] . ") AND ip_type = 'IPv6' AND (client_id = 0 OR client_id=".$_SESSION['s']['user']['client_id'].")";
            $ips = $app->db->queryAllRecords($sql);
            $sql = "SELECT ip_address FROM server_ip WHERE server_id IN ? AND ip_type = 'IPv6' AND (client_id = 0 OR client_id=?)";
            $ips = $app->db->queryAllRecords($sql, $client['web_servers'], $_SESSION['s']['user']['client_id']);
            $ip_select = "<option value=''></option>";
            //$ip_select = "";
            if(is_array($ips)) {
@@ -367,22 +367,21 @@
            $server_type = 'apache';
            if(!empty($web_config[$server_id]['server_type'])) $server_type = $web_config[$server_id]['server_type'];
            if($server_type == 'nginx' && $this->dataRecord['php'] == 'fast-cgi') $this->dataRecord['php'] = 'php-fpm';
            $selected_client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE groupid = ".$app->functions->intval($selected_client_group_id));
            //$sql_where = " AND (client_id = 0 OR client_id=".$_SESSION['s']['user']['client_id']." OR client_id = ".intval($selected_client['client_id']).")";
            $sql_where = " AND (client_id = 0 OR client_id = ".intval($selected_client['client_id']).")";
            $selected_client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE groupid = ?", $selected_client_group_id);
            $sql_where = " AND (client_id = 0 OR client_id = ?)";
            if($this->_vhostdomain_type == 'domain') {
                if($this->dataRecord['php'] == 'php-fpm'){
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ".($this->id > 0 ? $app->functions->intval($this->dataRecord['server_id']) : $app->functions->intval($client['default_webserver'])).$sql_where);
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ?".$sql_where, ($this->id > 0 ? $this->dataRecord['server_id'] : $client['default_webserver']), $selected_client['client_id']);
                }
                if($this->dataRecord['php'] == 'fast-cgi') {
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ".($this->id > 0 ? $app->functions->intval($this->dataRecord['server_id']) : $app->functions->intval($client['default_webserver'])).$sql_where);
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ?".$sql_where, ($this->id > 0 ? $this->dataRecord['server_id'] : $client['default_webserver']), $selected_client['client_id']);
                }
            } else {
                if($this->dataRecord['php'] == 'php-fpm'){
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ".$app->functions->intval($parent_domain['server_id'])." AND (client_id = 0 OR client_id=".$app->functions->intval($_SESSION['s']['user']['client_id']).")");
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ? AND (client_id = 0 OR client_id=?)", $parent_domain['server_id'], $_SESSION['s']['user']['client_id']);
                }
                if($this->dataRecord['php'] == 'fast-cgi') {
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ".$app->functions->intval($parent_domain['server_id'])." AND (client_id = 0 OR client_id=".$app->functions->intval($_SESSION['s']['user']['client_id']).")");
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ? AND (client_id = 0 OR client_id=?)", $parent_domain['server_id'], $_SESSION['s']['user']['client_id']);
                }
            }
            $php_select = "<option value=''>Default</option>";
@@ -460,7 +459,7 @@
                // The user is admin, so we fill in all IP addresses of the server
                if($this->id > 0) {
                    if(!isset($this->dataRecord["server_id"])){
                        $tmp = $app->db->queryOneRecord("SELECT server_id FROM web_domain WHERE domain_id = ".$app->functions->intval($this->id));
                        $tmp = $app->db->queryOneRecord("SELECT server_id FROM web_domain WHERE domain_id = ?", $this->id);
                        $this->dataRecord["server_id"] = $tmp["server_id"];
                        unset($tmp);
                    }
@@ -483,8 +482,8 @@
            }
            //* Fill the IPv4 select field
            $sql = "SELECT ip_address FROM server_ip WHERE ip_type = 'IPv4' AND server_id = ".$app->functions->intval($server_id);
            $ips = $app->db->queryAllRecords($sql);
            $sql = "SELECT ip_address FROM server_ip WHERE ip_type = 'IPv4' AND server_id = ?";
            $ips = $app->db->queryAllRecords($sql, $server_id);
            $ip_select = ($web_config['enable_ip_wildcard'] == 'y')?"<option value='*'>*</option>":"";
            //$ip_select = "";
            if(is_array($ips)) {
@@ -498,8 +497,8 @@
            unset($ips);
            //* Fill the IPv6 select field
            $sql = "SELECT ip_address FROM server_ip WHERE ip_type = 'IPv6' AND server_id = ".$app->functions->intval($server_id);
            $ips = $app->db->queryAllRecords($sql);
            $sql = "SELECT ip_address FROM server_ip WHERE ip_type = 'IPv6' AND server_id = ?";
            $ips = $app->db->queryAllRecords($sql, $server_id);
            $ip_select = "<option value=''></option>";
            //$ip_select = "";
            if(is_array($ips)) {
@@ -535,22 +534,21 @@
            $server_type = 'apache';
            if(!empty($web_config['server_type'])) $server_type = $web_config['server_type'];
            if($server_type == 'nginx' && $this->dataRecord['php'] == 'fast-cgi') $this->dataRecord['php'] = 'php-fpm';
            $selected_client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE groupid = ".$app->functions->intval($selected_client_group_id));
            //$sql_where = " AND (client_id = 0 OR client_id=".$_SESSION['s']['user']['client_id']." OR client_id = ".intval($selected_client['client_id']).")";
            $sql_where = " AND (client_id = 0 OR client_id = ".$app->functions->intval($selected_client['client_id']).")";
            $selected_client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE groupid = ?", $selected_client_group_id);
            $sql_where = " AND (client_id = 0 OR client_id = ?)";
            if($this->_vhostdomain_type == 'domain') {
                if($this->dataRecord['php'] == 'php-fpm'){
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = $server_id".$sql_where);
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ?".$sql_where, $server_id, $selected_client['client_id']);
                }
                if($this->dataRecord['php'] == 'fast-cgi') {
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ".$app->functions->intval($server_id).$sql_where);
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ?".$sql_where, $server_id, $selected_client['client_id']);
                }
            } else {
                if($this->dataRecord['php'] == 'php-fpm'){
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = " . $app->functions->intval($parent_domain['server_id']));
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ?", $parent_domain['server_id']);
                }
                if($this->dataRecord['php'] == 'fast-cgi') {
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = " . $app->functions->intval($parent_domain['server_id']));
                    $php_records = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fastcgi_binary != '' AND php_fastcgi_ini_dir != '' AND server_id = ?", $parent_domain['server_id']);
                }
            }
            $php_select = "<option value=''>Default</option>";
@@ -618,7 +616,7 @@
        $ssl_domain_select = '';
        $ssl_domains = array();
        $tmpd = $app->db->queryAllRecords("SELECT domain, type FROM web_domain WHERE domain_id = ".$this->id." OR parent_domain_id = ".$this->id);
        $tmpd = $app->db->queryAllRecords("SELECT domain, type FROM web_domain WHERE domain_id = ? OR parent_domain_id = ?", $this->id, $this->id);
        foreach($tmpd as $tmp) {
            if($tmp['type'] == 'subdomain' || $tmp['type'] == 'vhostsubdomain') {
                $ssl_domains[] = $tmp["domain"];
@@ -692,7 +690,7 @@
        // check for configuration errors in sys_datalog
        if($this->id > 0) {
            $datalog = $app->db->queryOneRecord("SELECT sys_datalog.error, sys_log.tstamp FROM sys_datalog, sys_log WHERE sys_datalog.dbtable = 'web_domain' AND sys_datalog.dbidx = 'domain_id:".$app->functions->intval($this->id)."' AND sys_datalog.datalog_id = sys_log.datalog_id AND sys_log.message = CONCAT('Processed datalog_id ',sys_log.datalog_id) ORDER BY sys_datalog.tstamp DESC");
            $datalog = $app->db->queryOneRecord("SELECT sys_datalog.error, sys_log.tstamp FROM sys_datalog, sys_log WHERE sys_datalog.dbtable = 'web_domain' AND sys_datalog.dbidx = ? AND sys_datalog.datalog_id = sys_log.datalog_id AND sys_log.message = CONCAT('Processed datalog_id ',sys_log.datalog_id) ORDER BY sys_datalog.tstamp DESC", 'domain_id:' . $this->id);
            if(is_array($datalog) && !empty($datalog)){
                if(trim($datalog['error']) != ''){
                    $app->tpl->setVar("config_error_msg", nl2br(htmlentities($datalog['error'])));
@@ -733,12 +731,12 @@
        } else {
            // Get the record of the parent domain
            if(!@$this->dataRecord["parent_domain_id"] && $this->id) {
                $tmp = $app->db->queryOneRecord("SELECT parent_domain_id FROM web_domain WHERE domain_id = ".$app->functions->intval($this->id));
                $tmp = $app->db->queryOneRecord("SELECT parent_domain_id FROM web_domain WHERE domain_id = ?", $this->id);
                if($tmp) $this->dataRecord["parent_domain_id"] = $tmp['parent_domain_id'];
                unset($tmp);
            }
            $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ".$app->functions->intval(@$this->dataRecord["parent_domain_id"]) . " AND ".$app->tform->getAuthSQL('r'));
            $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ? AND ".$app->tform->getAuthSQL('r'), @$this->dataRecord["parent_domain_id"]);
            if(!$parent_domain || $parent_domain['domain_id'] != @$this->dataRecord['parent_domain_id']) $app->tform->errorMessage .= $app->tform->lng("no_domain_perm");
            if($this->_vhostdomain_type == 'subdomain') {
@@ -800,14 +798,6 @@
                // vhostaliasdomains do not have a quota of their own
                $this->dataRecord["hd_quota"] = 0;
                // check for duplicate folder usage
                /*
                $check = $app->db->queryOneRecord("SELECT COUNT(*) as `cnt` FROM `web_domain` WHERE `type` = 'vhostalias' AND `parent_domain_id` = '" . $app->functions->intval($this->dataRecord['parent_domain_id']) . "' AND `web_folder` = '" . $app->db->quote($this->dataRecord['web_folder']) . "' AND `domain_id` != '" . $app->functions->intval($this->id) . "'");
                if($check && $check['cnt'] > 0) {
                    $app->tform->errorMessage .= $app->tform->lng("web_folder_unique_txt")."<br>";
                }
                */
            }
        }
@@ -832,7 +822,7 @@
            // only generate quota and traffic warnings if value has changed
            if($this->id > 0) {
                $old_web_values = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".$app->functions->intval($this->id));
                $old_web_values = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->id);
            } else {
                $old_web_values = array();
            }
@@ -840,7 +830,7 @@
            if($this->_vhostdomain_type == 'domain') {
                //* Check the website quota of the client
                if(isset($_POST["hd_quota"]) && $client["limit_web_quota"] >= 0 && $_POST["hd_quota"] != $old_web_values["hd_quota"]) {
                    $tmp = $app->db->queryOneRecord("SELECT sum(hd_quota) as webquota FROM web_domain WHERE domain_id != ".$app->functions->intval($this->id)." AND type = 'vhost' AND ".$app->tform->getAuthSQL('u'));
                    $tmp = $app->db->queryOneRecord("SELECT sum(hd_quota) as webquota FROM web_domain WHERE domain_id != ? AND type = 'vhost' AND ".$app->tform->getAuthSQL('u'), $this->id);
                    $webquota = $tmp["webquota"];
                    $new_web_quota = $app->functions->intval($this->dataRecord["hd_quota"]);
                    if(($webquota + $new_web_quota > $client["limit_web_quota"]) || ($new_web_quota < 0 && $client["limit_web_quota"] >= 0)) {
@@ -857,7 +847,7 @@
            //* Check the traffic quota of the client
            if(isset($_POST["traffic_quota"]) && $client["limit_traffic_quota"] > 0 && $_POST["traffic_quota"] != $old_web_values["traffic_quota"]) {
                $tmp = $app->db->queryOneRecord("SELECT sum(traffic_quota) as trafficquota FROM web_domain WHERE domain_id != ".$app->functions->intval($this->id)." AND ".$app->tform->getAuthSQL('u'));
                $tmp = $app->db->queryOneRecord("SELECT sum(traffic_quota) as trafficquota FROM web_domain WHERE domain_id != ? AND ".$app->tform->getAuthSQL('u'), $this->id);
                $trafficquota = $tmp["trafficquota"];
                $new_traffic_quota = $app->functions->intval($this->dataRecord["traffic_quota"]);
                if(($trafficquota + $new_traffic_quota > $client["limit_traffic_quota"]) || ($new_traffic_quota < 0 && $client["limit_traffic_quota"] >= 0)) {
@@ -873,12 +863,12 @@
            if($client['parent_client_id'] > 0) {
                // Get the limits of the reseller
                $reseller = $app->db->queryOneRecord("SELECT limit_traffic_quota, limit_web_domain, limit_web_aliasdomain, limit_web_subdomain, web_servers, limit_web_quota FROM client WHERE client_id = ".$client['parent_client_id']);
                $reseller = $app->db->queryOneRecord("SELECT limit_traffic_quota, limit_web_domain, limit_web_aliasdomain, limit_web_subdomain, web_servers, limit_web_quota FROM client WHERE client_id = ?", $client['parent_client_id']);
                if($this->_vhostdomain_type == 'domain') {
                    //* Check the website quota of the client
                    if(isset($_POST["hd_quota"]) && $reseller["limit_web_quota"] >= 0 && $_POST["hd_quota"] != $old_web_values["hd_quota"]) {
                        $tmp = $app->db->queryOneRecord("SELECT sum(hd_quota) as webquota FROM web_domain, sys_group, client WHERE web_domain.sys_groupid=sys_group.groupid AND sys_group.client_id=client.client_id AND ".$client['parent_client_id']." IN (client.parent_client_id, client.client_id) AND domain_id != ".$app->functions->intval($this->id)." AND type = 'vhost'");
                        $tmp = $app->db->queryOneRecord("SELECT sum(hd_quota) as webquota FROM web_domain, sys_group, client WHERE web_domain.sys_groupid=sys_group.groupid AND sys_group.client_id=client.client_id AND ? IN (client.parent_client_id, client.client_id) AND domain_id != ? AND type = 'vhost'", $client['parent_client_id'], $this->id);
                        $webquota = $tmp["webquota"];
                        $new_web_quota = $app->functions->intval($this->dataRecord["hd_quota"]);
@@ -896,7 +886,7 @@
                //* Check the traffic quota of the client
                if(isset($_POST["traffic_quota"]) && $reseller["limit_traffic_quota"] > 0 && $_POST["traffic_quota"] != $old_web_values["traffic_quota"]) {
                    $tmp = $app->db->queryOneRecord("SELECT sum(traffic_quota) as trafficquota FROM web_domain, sys_group, client WHERE web_domain.sys_groupid=sys_group.groupid AND sys_group.client_id=client.client_id AND ".$client['parent_client_id']." IN (client.parent_client_id, client.client_id) AND domain_id != ".$app->functions->intval($this->id)." AND type = 'vhost'");
                    $tmp = $app->db->queryOneRecord("SELECT sum(traffic_quota) as trafficquota FROM web_domain, sys_group, client WHERE web_domain.sys_groupid=sys_group.groupid AND sys_group.client_id=client.client_id AND ? IN (client.parent_client_id, client.client_id) AND domain_id != ? AND type = 'vhost'", $client['parent_client_id'], $this->id);
                    $trafficquota = $tmp["trafficquota"];
                    $new_traffic_quota = $app->functions->intval($this->dataRecord["traffic_quota"]);
                    if(($trafficquota + $new_traffic_quota > $reseller["limit_traffic_quota"]) || ($new_traffic_quota < 0 && $reseller["limit_traffic_quota"] >= 0)) {
@@ -914,7 +904,7 @@
            // When the record is updated
            if($this->id > 0) {
                // restore the server ID if the user is not admin and record is edited
                $tmp = $app->db->queryOneRecord("SELECT server_id, `system_user`, `system_group`, `web_folder`, `cgi`, `ssi`, `perl`, `ruby`, `python`, `suexec`, `errordocs`, `subdomain`, `ssl` FROM web_domain WHERE domain_id = ".$app->functions->intval($this->id));
                $tmp = $app->db->queryOneRecord("SELECT server_id, `system_user`, `system_group`, `web_folder`, `cgi`, `ssi`, `perl`, `ruby`, `python`, `suexec`, `errordocs`, `subdomain`, `ssl` FROM web_domain WHERE domain_id = ?", $this->id);
                $this->dataRecord["server_id"] = $tmp["server_id"];
                $this->dataRecord['web_folder'] = $tmp['web_folder']; // cannot be changed!
                $this->dataRecord['system_user'] = $tmp['system_user'];
@@ -943,17 +933,17 @@
                // Check if the user may add another web_domain
                if($this->_vhostdomain_type == 'domain' && $client["limit_web_domain"] >= 0) {
                    $tmp = $app->db->queryOneRecord("SELECT count(domain_id) as number FROM web_domain WHERE sys_groupid = $client_group_id and type = 'vhost'");
                    $tmp = $app->db->queryOneRecord("SELECT count(domain_id) as number FROM web_domain WHERE sys_groupid = ? and type = 'vhost'", $client_group_id);
                    if($tmp["number"] >= $client["limit_web_domain"]) {
                        $app->error($app->tform->wordbook["limit_web_domain_txt"]);
                    }
                } elseif($this->_vhostdomain_type == 'aliasdomain' && $client["limit_web_aliasdomain"] >= 0) {
                    $tmp = $app->db->queryOneRecord("SELECT count(domain_id) as number FROM web_domain WHERE sys_groupid = $client_group_id and (type = 'alias' OR type = 'vhostalias')");
                    $tmp = $app->db->queryOneRecord("SELECT count(domain_id) as number FROM web_domain WHERE sys_groupid = ? and (type = 'alias' OR type = 'vhostalias')", $client_group_id);
                    if($tmp["number"] >= $client["limit_web_aliasdomain"]) {
                        $app->error($app->tform->wordbook["limit_web_aliasdomain_txt"]);
                    }
                } elseif($this->_vhostdomain_type == 'subdomain' && $client["limit_web_subdomain"] >= 0) {
                    $tmp = $app->db->queryOneRecord("SELECT count(domain_id) as number FROM web_domain WHERE sys_groupid = $client_group_id and (type = 'subdomain' OR type = 'vhostsubdomain')");
                    $tmp = $app->db->queryOneRecord("SELECT count(domain_id) as number FROM web_domain WHERE sys_groupid = ? and (type = 'subdomain' OR type = 'vhostsubdomain')", $client_group_id);
                    if($tmp["number"] >= $client["limit_web_subdomain"]) {
                        $app->error($app->tform->wordbook["limit_web_subdomain_txt"]);
                    }
@@ -980,8 +970,8 @@
        $web_config = $app->getconf->get_server_config($app->functions->intval(isset($this->dataRecord["server_id"]) ? $this->dataRecord["server_id"] : $server_id), 'web');
        //* Check for duplicate ssl certs per IP if SNI is disabled
        if(isset($this->dataRecord['ssl']) && $this->dataRecord['ssl'] == 'y' && $web_config['enable_sni'] != 'y') {
            $sql = "SELECT count(domain_id) as number FROM web_domain WHERE `ssl` = 'y' AND ip_address = '".$app->db->quote($this->dataRecord['ip_address'])."' and domain_id != ".$this->id;
            $tmp = $app->db->queryOneRecord($sql);
            $sql = "SELECT count(domain_id) as number FROM web_domain WHERE `ssl` = 'y' AND ip_address = ? and domain_id != ?";
            $tmp = $app->db->queryOneRecord($sql, $this->dataRecord['ip_address'], $this->id);
            if($tmp['number'] > 0) $app->tform->errorMessage .= $app->tform->lng("error_no_sni_txt");
        }
@@ -1096,11 +1086,11 @@
        // also make sure that the user can not delete domain created by a admin
        if($_SESSION["s"]["user"]["typ"] == 'admin' && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE web_domain SET sys_groupid = $client_group_id, sys_perm_group = 'ru' WHERE domain_id = ".$this->id);
            $app->db->query("UPDATE web_domain SET sys_groupid = ?, sys_perm_group = 'ru' WHERE domain_id = ?", $client_group_id, $this->id);
        }
        if($app->auth->has_clients($_SESSION['s']['user']['userid']) && isset($this->dataRecord["client_group_id"])) {
            $client_group_id = $app->functions->intval($this->dataRecord["client_group_id"]);
            $app->db->query("UPDATE web_domain SET sys_groupid = $client_group_id, sys_perm_group = 'riud' WHERE domain_id = ".$this->id);
            $app->db->query("UPDATE web_domain SET sys_groupid = ?, sys_perm_group = 'riud' WHERE domain_id = ?", $client_group_id, $this->id);
        }
        // Get configuration for the web system
@@ -1118,47 +1108,48 @@
            // get the ID of the client
            if($_SESSION["s"]["user"]["typ"] != 'admin' && !$app->auth->has_clients($_SESSION['s']['user']['userid'])) {
                $client_group_id = $app->functions->intval($_SESSION["s"]["user"]["default_group"]);
                $client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE sys_group.groupid = $client_group_id");
                $client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE sys_group.groupid = ?", $client_group_id);
                $client_id = $app->functions->intval($client["client_id"]);
            } else {
                //$client_id = $app->functions->intval($this->dataRecord["client_group_id"]);
                $client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE sys_group.groupid = ".$app->functions->intval($this->dataRecord["client_group_id"]));
                $client = $app->db->queryOneRecord("SELECT client_id FROM sys_group WHERE sys_group.groupid = ?", $this->dataRecord["client_group_id"]);
                $client_id = $app->functions->intval($client["client_id"]);
            }
            // Set the values for document_root, system_user and system_group
            $system_user = $app->db->quote('web'.$this->id);
            $system_group = $app->db->quote('client'.$client_id);
            $system_user = 'web'.$this->id;
            $system_group = 'client'.$client_id;
            $document_root = str_replace("[client_id]", $client_id, $document_root);
            $document_root = str_replace("[client_idhash_1]", $this->id_hash($client_id, 1), $document_root);
            $document_root = str_replace("[client_idhash_2]", $this->id_hash($client_id, 2), $document_root);
            $document_root = str_replace("[client_idhash_3]", $this->id_hash($client_id, 3), $document_root);
            $document_root = str_replace("[client_idhash_4]", $this->id_hash($client_id, 4), $document_root);
            $document_root = $app->db->quote($document_root);
            $document_root = $document_root;
            $php_open_basedir = str_replace("[website_path]", $document_root, $web_config["php_open_basedir"]);
            $php_open_basedir = $app->db->quote(str_replace("[website_domain]", $web_rec['domain'], $php_open_basedir));
            $htaccess_allow_override = $app->db->quote($web_config["htaccess_allow_override"]);
            $php_open_basedir = str_replace("[website_domain]", $web_rec['domain'], $php_open_basedir);
            $htaccess_allow_override = $web_config["htaccess_allow_override"];
            $added_date = date($app->lng('conf_format_dateshort'));
            $added_by = $app->db->quote($_SESSION['s']['user']['username']);
            $added_by = $_SESSION['s']['user']['username'];
            $sql = "UPDATE web_domain SET system_user = '$system_user', system_group = '$system_group', document_root = '$document_root', allow_override = '$htaccess_allow_override', php_open_basedir = '$php_open_basedir', added_date = '$added_date', added_by = '$added_by'  WHERE domain_id = ".$this->id;
            $sql = "UPDATE web_domain SET system_user = ?, system_group = ?, document_root = ?, allow_override = ?, php_open_basedir = ?, added_date = ?, added_by = ?  WHERE domain_id = ?";
            $app->db->query($sql, $system_user, $system_group, $document_root, $htaccess_allow_override, $php_open_basedir, $added_date, $added_by, $this->id);
        } else  {
            // Set the values for document_root, system_user and system_group
            $system_user = $app->db->quote($this->parent_domain_record['system_user']);
            $system_group = $app->db->quote($this->parent_domain_record['system_group']);
            $document_root = $app->db->quote($this->parent_domain_record['document_root']);
            $system_user = $this->parent_domain_record['system_user'];
            $system_group = $this->parent_domain_record['system_group'];
            $document_root = $this->parent_domain_record['document_root'];
            $php_open_basedir = str_replace("[website_path]/web", $document_root.'/'.$web_rec['web_folder'], $web_config["php_open_basedir"]);
            $php_open_basedir = str_replace("[website_domain]/web", $web_rec['domain'].'/'.$web_rec['web_folder'], $php_open_basedir);
            $php_open_basedir = str_replace("[website_path]", $document_root, $php_open_basedir);
            $php_open_basedir = $app->db->quote(str_replace("[website_domain]", $web_rec['domain'], $php_open_basedir));
            $htaccess_allow_override = $app->db->quote($this->parent_domain_record['allow_override']);
            $php_open_basedir = str_replace("[website_domain]", $web_rec['domain'], $php_open_basedir);
            $htaccess_allow_override = $this->parent_domain_record['allow_override'];
            $added_date = date($app->lng('conf_format_dateshort'));
            $added_by = $app->db->quote($_SESSION['s']['user']['username']);
            $added_by = $_SESSION['s']['user']['username'];
            $sql = "UPDATE web_domain SET sys_groupid = ".$app->functions->intval($this->parent_domain_record['sys_groupid']).",system_user = '$system_user', system_group = '$system_group', document_root = '$document_root', allow_override = '$htaccess_allow_override', php_open_basedir = '$php_open_basedir', added_date = '$added_date', added_by = '$added_by' WHERE domain_id = ".$this->id;
            $sql = "UPDATE web_domain SET sys_groupid = ?, system_user = ?, system_group = ?, document_root = ?, allow_override = ?, php_open_basedir = ?, added_date = ?, added_by = ?  WHERE domain_id = ?";
            $app->db->query($sql, $this->parent_domain_record['sys_groupid'], $system_user, $system_group, $document_root, $htaccess_allow_override, $php_open_basedir, $added_date, $added_by, $this->id);
        }
        $app->db->query($sql);
    }
    function onBeforeUpdate () {
@@ -1169,7 +1160,7 @@
            // We do this only for the admin or reseller users, as normal clients can not change the server ID anyway
            if($_SESSION["s"]["user"]["typ"] == 'admin' || $app->auth->has_clients($_SESSION['s']['user']['userid'])) {
                if (isset($this->dataRecord["server_id"])) {
                    $rec = $app->db->queryOneRecord("SELECT server_id from web_domain WHERE domain_id = ".$this->id);
                    $rec = $app->db->queryOneRecord("SELECT server_id from web_domain WHERE domain_id = ?", $this->id);
                    if($rec['server_id'] != $this->dataRecord["server_id"]) {
                        //* Add a error message and switch back to old server
                        $app->tform->errorMessage .= $app->lng('The Server can not be changed.');
@@ -1180,7 +1171,7 @@
                //* If the user is neither admin nor reseller
            } else {
                //* We do not allow users to change a domain which has been created by the admin
                $rec = $app->db->queryOneRecord("SELECT sys_perm_group, domain, ip_address, ipv6_address from web_domain WHERE domain_id = ".$this->id);
                $rec = $app->db->queryOneRecord("SELECT sys_perm_group, domain, ip_address, ipv6_address from web_domain WHERE domain_id = ?", $this->id);
                if(isset($this->dataRecord["domain"]) && $rec['domain'] != $this->dataRecord["domain"] && $app->tform->checkPerm($this->id, 'u')) {
                    //* Add a error message and switch back to old server
                    $app->tform->errorMessage .= $app->lng('The Domain can not be changed. Please ask your Administrator if you want to change the domain name.');
interface/web/sites/webdav_user_edit.php
@@ -102,7 +102,7 @@
        global $app, $conf;
        /* Get the record of the parent domain */
        $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ".$app->functions->intval(@$this->dataRecord["parent_domain_id"]) . " AND ".$app->tform->getAuthSQL('r'));
        $parent_domain = $app->db->queryOneRecord("select * FROM web_domain WHERE domain_id = ? AND ".$app->tform->getAuthSQL('r'), @$this->dataRecord["parent_domain_id"]);
        if(!$parent_domain || $parent_domain['domain_id'] != @$this->dataRecord['parent_domain_id']) $app->tform->errorMessage .= $app->tform->lng("no_domain_perm");
        /*
@@ -145,7 +145,7 @@
    function onAfterInsert() {
        global $app, $conf;
        $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".$app->functions->intval($this->dataRecord["parent_domain_id"]));
        $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
        $server_id = $app->functions->intval($web["server_id"]);
        // The webdav user shall be owned by the same group then the website
@@ -157,8 +157,8 @@
        $hash = md5($this->dataRecord["username"] . ':' . $this->dataRecord["dir"] . ':' . $this->dataRecord["password"]);
        $this->dataRecord["password"] = $hash;
        
        $sql = "UPDATE webdav_user SET server_id = ".$server_id.", sys_groupid = '".$sys_groupid."', password = '".$this->dataRecord["password"]."' WHERE webdav_user_id = ".$this->id;
        $app->db->query($sql);
        $sql = "UPDATE webdav_user SET server_id = ?, sys_groupid = ?, password = ? WHERE webdav_user_id = ?";
        $app->db->query($sql, $server_id, $sys_groupid, $this->dataRecord["password"], $this->id);
        
    }
@@ -169,7 +169,7 @@
         * we can not change the username and the dir, so get the "old" - data from the db
         * and set it
        */
        $data = $app->db->queryOneRecord("SELECT * FROM webdav_user WHERE webdav_user_id = ".$app->functions->intval($this->id));
        $data = $app->db->queryOneRecord("SELECT * FROM webdav_user WHERE webdav_user_id = ?", $this->id);
        $this->dataRecord["username"] = $data['username'];
        $this->dataRecord["dir"]      = $data['dir'];
        $this->dataRecord['username_prefix'] = $data['username_prefix'];
@@ -183,14 +183,14 @@
        //* When the site of the webdav user has been changed
        if(isset($this->dataRecord['parent_domain_id']) && $this->oldDataRecord['parent_domain_id'] != $this->dataRecord['parent_domain_id']) {
            $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".$app->functions->intval($this->dataRecord["parent_domain_id"]));
            $web = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $this->dataRecord["parent_domain_id"]);
            $server_id = $app->functions->intval($web["server_id"]);
            // The webdav user shall be owned by the same group then the website
            $sys_groupid = $app->functions->intval($web['sys_groupid']);
            $sql = "UPDATE webdav_user SET server_id = $server_id, sys_groupid = '$sys_groupid' WHERE webdav_user_id = ".$this->id;
            $app->db->query($sql);
            $sql = "UPDATE webdav_user SET server_id = ?, sys_groupid = ? WHERE webdav_user_id = ?";
            $app->db->query($sql, $server_id, $sys_groupid, $this->id);
        }
        
        /*
@@ -200,7 +200,7 @@
        if ((isset($this->dataRecord["password"])) && ($this->dataRecord["password"] != '') && ($this->dataRecord["password"] != $this->dataRecord['passwordOld'])) {
            $hash = md5($this->dataRecord["username"] . ':' . $this->dataRecord["dir"] . ':' . $this->dataRecord["password"]);
            $this->dataRecord["password"] = $hash;
            $app->db->query("UPDATE webdav_user SET password = '".$this->dataRecord["password"]."' WHERE webdav_user_id = ".$this->id);
            $app->db->query("UPDATE webdav_user SET password = ? WHERE webdav_user_id = ?", $this->dataRecord["password"], $this->id);
        }
        
    }
interface/web/tools/import_ispconfig.php
@@ -143,7 +143,7 @@
    //* Get the user and groupid for the new records
    $sys_groupid = $app->functions->intval($_POST['client_group_id']);
    $tmp = $app->db->queryOneRecord("SELECT userid FROM sys_user WHERE default_group = $sys_groupid");
    $tmp = $app->db->queryOneRecord("SELECT userid FROM sys_user WHERE default_group = ?", $sys_groupid);
    $sys_userid = $app->functions->intval($tmp['userid']);
    unset($tmp);
    if($sys_groupid == 0) $error .= 'Inavlid groupid<br />';
@@ -159,7 +159,7 @@
    $mail_domain_rec = $client->mail_domain_get($remote_session_id, array('domain' => $mail_domain));
    if(is_array($mail_domain_rec)) {
        $mail_domain_rec = $mail_domain_rec[0];
        $tmp = $app->db->queryOneRecord("SELECT count(domain_id) as number FROM mail_domain WHERE domain = '".$app->db->quote($mail_domain)."'");
        $tmp = $app->db->queryOneRecord("SELECT count(domain_id) as number FROM mail_domain WHERE domain = ?", $mail_domain);
        if($tmp['number'] > 0) $error .= 'Domain '.$mail_domain.' exists already in local database.<br />';
        unset($tmp);
@@ -182,7 +182,7 @@
            $mail_users = $client->mail_user_get($remote_session_id, array('email' => '%@'.$mail_domain));
            if(is_array($mail_users)) {
                foreach($mail_users as $mail_user) {
                    $tmp = $app->db->queryOneRecord("SELECT count(mailuser_id) as number FROM mail_user WHERE email = '".$app->db->quote($mail_user['email'])."'");
                    $tmp = $app->db->queryOneRecord("SELECT count(mailuser_id) as number FROM mail_user WHERE email = ?", $mail_user['email']);
                    if($tmp['number'] == 0) {
                        //* Prepare record
@@ -229,7 +229,7 @@
            $mail_aliases = $client->mail_alias_get($remote_session_id, array('type' => 'alias', 'destination' => '%@'.$mail_domain));
            if(is_array($mail_aliases)) {
                foreach($mail_aliases as $mail_alias) {
                    $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE `type` = 'alias' AND source = '".$app->db->quote($mail_alias['source'])."' AND destination = '".$app->db->quote($mail_alias['destination'])."'");
                    $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE `type` = 'alias' AND source = ? AND destination = ?", $mail_alias['source'], $mail_alias['destination']);
                    if($tmp['number'] == 0) {
                        $mail_alias['sys_userid'] = $sys_userid;
                        $mail_alias['sys_groupid'] = $sys_groupid;
@@ -250,7 +250,7 @@
            $mail_aliases = $client->mail_alias_get($remote_session_id, array('type' => 'aliasdomain', 'destination' => '@'.$mail_domain));
            if(is_array($mail_aliases)) {
                foreach($mail_aliases as $mail_alias) {
                    $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE `type` = 'aliasdomain' AND source = '".$app->db->quote($mail_alias['source'])."' AND destination = '".$app->db->quote($mail_alias['destination'])."'");
                    $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE `type` = 'aliasdomain' AND source = ? AND destination = ?", $mail_alias['source'], $mail_alias['destination']);
                    if($tmp['number'] == 0) {
                        $mail_alias['sys_userid'] = $sys_userid;
                        $mail_alias['sys_groupid'] = $sys_groupid;
@@ -271,7 +271,7 @@
            $mail_forwards = $client->mail_forward_get($remote_session_id, array('type' => 'forward', 'source' => '%@'.$mail_domain));
            if(is_array($mail_forwards)) {
                foreach($mail_forwards as $mail_forward) {
                    $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE `type` = 'forward' AND source = '".$app->db->quote($mail_forward['source'])."' AND destination = '".$app->db->quote($mail_forward['destination'])."'");
                    $tmp = $app->db->queryOneRecord("SELECT count(forwarding_id) as number FROM mail_forwarding WHERE `type` = 'forward' AND source = ? AND destination = ?", $mail_forward['source'], $mail_forward['destination']);
                    if($tmp['number'] == 0) {
                        $mail_forward['sys_userid'] = $sys_userid;
                        $mail_forward['sys_groupid'] = $sys_groupid;
@@ -292,7 +292,7 @@
            $mail_spamfilters = $client->mail_spamfilter_user_get($remote_session_id, array('email' => '%@'.$mail_domain));
            if(is_array($mail_spamfilters)) {
                foreach($mail_spamfilters as $mail_spamfilter) {
                    $tmp = $app->db->queryOneRecord("SELECT count(id) as number FROM spamfilter_users WHERE email = '".$app->db->quote($mail_spamfilter['email'])."'");
                    $tmp = $app->db->queryOneRecord("SELECT count(id) as number FROM spamfilter_users WHERE email = ?", $mail_spamfilter['email']);
                    if($tmp['number'] == 0) {
                        $mail_spamfilter['sys_userid'] = $sys_userid;
                        $mail_spamfilter['sys_groupid'] = $sys_groupid;
interface/web/tools/import_vpopmail.php
@@ -121,14 +121,14 @@
                $groupid = $app->db->datalogInsert('sys_group', "(name,description,client_id) VALUES ('".$app->db->quote($pw_domain)."','',".$client_id.")", 'groupid');
                $groups = $groupid;
                $username = $app->db->quote($pw_domain);
                $username = $pw_domain;
                $password = $pw_crypt_password;
                $modules = $conf['interface_modules_enabled'];
                $startmodule = 'dashboard';
                $usertheme = $app->db->quote('default');
                $usertheme = 'default';
                $type = 'user';
                $active = 1;
                $language = $app->db->quote($conf["language"]);
                $language = $conf["language"];
                //$password = $app->auth->crypt_password($password);
                // Create the controlpaneluser for the client
interface/web/vm/openvz_action.php
@@ -17,7 +17,7 @@
if($vm_id == 0) die('Invalid VM ID');
$vm = $app->db->queryOneRecord("SELECT server_id, veid FROM openvz_vm WHERE vm_id = $vm_id");
$vm = $app->db->queryOneRecord("SELECT server_id, veid FROM openvz_vm WHERE vm_id = ?", $vm_id);
$veid = $app->functions->intval($vm['veid']);
$server_id = $app->functions->intval($vm['server_id']);
@@ -47,15 +47,8 @@
    //* Start the virtual machine
    $sql =  "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " .
        "VALUES (".
        (int)$server_id . ", ".
        time() . ", ".
        "'openvz_start_vm', ".
        $veid.", ".
        "'pending', ".
        "''".
        ")";
    $app->db->query($sql);
        "VALUES (?, UNIX_TIMESTAMP(), 'openvz_start_vm', ?, 'pending', '')";
    $app->db->query($sql, $server_id, $veid);
    $app->tpl->setVar('msg', $wb['start_exec_txt']);
    $options['start_option_enabled'] = 'checked="checked"';
@@ -64,15 +57,8 @@
    //* Stop the virtual machine
    $sql =  "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " .
        "VALUES (".
        (int)$server_id . ", ".
        time() . ", ".
        "'openvz_stop_vm', ".
        $veid.", ".
        "'pending', ".
        "''".
        ")";
    $app->db->query($sql);
        "VALUES (?, UNIX_TIMESTAMP(), 'openvz_stop_vm', ?, 'pending', '')";
    $app->db->query($sql, $server_id, $veid);
    $app->tpl->setVar('msg', $wb['stop_exec_txt']);
    $options['stop_option_enabled'] = 'checked="checked"';
@@ -81,15 +67,8 @@
    //* Restart the virtual machine
    $sql =  "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " .
        "VALUES (".
        (int)$server_id . ", ".
        time() . ", ".
        "'openvz_restart_vm', ".
        $veid.", ".
        "'pending', ".
        "''".
        ")";
    $app->db->query($sql);
        "VALUES (?, UNIX_TIMESTAMP(), 'openvz_restart_vm', ?, 'pending', '')";
    $app->db->query($sql, $server_id, $veid);
    $app->tpl->setVar('msg', $wb['restart_exec_txt']);
    $options['restart_option_enabled'] = 'checked="checked"';
@@ -104,30 +83,22 @@
    }
    //* Quote name
    $ostemplate_name = $app->db->quote($ostemplate_name);
    //* Check for duplicates
    $tmp = $app->db->queryOneRecord("SELECT count(ostemplate_id) as number FROM openvz_ostemplate WHERE template_file = '$ostemplate_name'");
    $tmp = $app->db->queryOneRecord("SELECT count(ostemplate_id) as number FROM openvz_ostemplate WHERE template_file = ?", $ostemplate_name);
    if($tmp['number'] > 0) $error_msg .= $wb['ostemplate_name_unique_error'].'<br />';
    unset($tmp);
    if($error_msg == '') {
        //* Create ostemplate action
        $sql =  "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " .
            "VALUES (".
            (int)$server_id . ", ".
            time() . ", ".
            "'openvz_create_ostpl', ".
            "'".$veid.":".$ostemplate_name."', ".
            "'pending', ".
            "''".
            ")";
        $app->db->query($sql);
            "VALUES (?, UNIX_TIMESTAMP(), 'openvz_create_ostpl', ?, 'pending', '')";
        $app->db->query($sql, $server_id, $veid.":".$ostemplate_name);
        //* Create a record in the openvz_ostemplate table
        $sql = "INSERT INTO `openvz_ostemplate` (`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `template_name`, `template_file`, `server_id`, `allservers`, `active`, `description`)
        VALUES(1, 1, 'riud', 'riud', '', '$ostemplate_name', '$ostemplate_name', $server_id, 'n', 'y', '')";
        $app->db->query($sql);
        VALUES(1, 1, 'riud', 'riud', '', ?, ?, ?, 'n', 'y', '')";
        $app->db->query($sql, $ostemplate_name, $ostemplate_name, $server_id);
        $app->tpl->setVar('msg', $wb['ostemplate_exec_txt']);
        $options['ostemplate_option_enabled'] = 'checked="checked"';
interface/web/vm/openvz_template_edit.php
@@ -54,10 +54,7 @@
    function onAfterInsert() {
        global $app, $conf;
        $guar_ram = $app->functions->intval($this->dataRecord['ram']*256);
        $burst_ram = $app->functions->intval($this->dataRecord['ram_burst']*256);
        $sql = "UPDATE openvz_template SET shmpages = '$guar_ram:$guar_ram',vmguarpages = '$guar_ram:$guar_ram', oomguarpages = '$guar_ram:$guar_ram',privvmpages = '$burst_ram:$burst_ram' WHERE template_id = $this->id";
        $app->db->query($sql);
        $this->onAfterUpdate();
    }
    function onAfterUpdate() {
@@ -65,8 +62,8 @@
        $guar_ram = $app->functions->intval($this->dataRecord['ram']*256);
        $burst_ram = $app->functions->intval($this->dataRecord['ram_burst']*256);
        $sql = "UPDATE openvz_template SET shmpages = '$guar_ram:$guar_ram',vmguarpages = '$guar_ram:$guar_ram', oomguarpages = '$guar_ram:$guar_ram',privvmpages = '$burst_ram:$burst_ram' WHERE template_id = $this->id";
        $app->db->query($sql);
        $sql = "UPDATE openvz_template SET shmpages = ?,vmguarpages = ?, oomguarpages = ?,privvmpages = ? WHERE template_id = ?";
        $app->db->query($sql, $guar_ram . ':' . $guar_ram, $guar_ram . ':' . $guar_ram, $guar_ram . ':' . $guar_ram, $burst_ram . ':' . $burst_ram, $this->id);
    }
}
interface/web/vm/openvz_vm_edit.php
@@ -80,9 +80,9 @@
            if($client['limit_openvz_vm_template_id'] == 0) {
                $sql = 'SELECT template_id,template_name FROM openvz_template WHERE 1 ORDER BY template_name';
            } else {
                $sql = 'SELECT template_id,template_name FROM openvz_template WHERE template_id = '.$app->functions->intval($client['limit_openvz_vm_template_id']).' ORDER BY template_name';
                $sql = 'SELECT template_id,template_name FROM openvz_template WHERE template_id = ? ORDER BY template_name';
            }
            $records = $app->db->queryAllRecords($sql);
            $records = $app->db->queryAllRecords($sql, $client['limit_openvz_vm_template_id']);
            if(is_array($records)) {
                foreach( $records as $rec) {
                    $selected = @($rec["template_id"] == $this->dataRecord["template_id"])?'SELECTED':'';
@@ -100,9 +100,9 @@
            //* Fill the client select field
            $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ".$app->functions->intval($client['client_id'])." ORDER BY client.company_name, client.contact_name, sys_group.name";
            $records = $app->db->queryAllRecords($sql);
            $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($client['client_id']));
            $sql = "SELECT sys_group.groupid, sys_group.name, CONCAT(IF(client.company_name != '', CONCAT(client.company_name, ' :: '), ''), client.contact_name, ' (', client.username, IF(client.customer_no != '', CONCAT(', ', client.customer_no), ''), ')') as contactname FROM sys_group, client WHERE sys_group.client_id = client.client_id AND client.parent_client_id = ? ORDER BY client.company_name, client.contact_name, sys_group.name";
            $records = $app->db->queryAllRecords($sql, $client['client_id']);
            $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ?", $client['client_id']);
            $client_select = '<option value="'.$tmp['groupid'].'">'.$client['contactname'].'</option>';
            //$tmp_data_record = $app->tform->getDataRecord($this->id);
            if(is_array($records)) {
@@ -117,9 +117,9 @@
            if($client['limit_openvz_vm_template_id'] == 0) {
                $sql = 'SELECT template_id,template_name FROM openvz_template WHERE 1 ORDER BY template_name';
            } else {
                $sql = 'SELECT template_id,template_name FROM openvz_template WHERE template_id = '.$app->functions->intval($client['limit_openvz_vm_template_id']).' ORDER BY template_name';
                $sql = 'SELECT template_id,template_name FROM openvz_template WHERE template_id = ? ORDER BY template_name';
            }
            $records = $app->db->queryAllRecords($sql);
            $records = $app->db->queryAllRecords($sql, $client['limit_openvz_vm_template_id']);
            if(is_array($records)) {
                foreach( $records as $rec) {
                    $selected = @($rec["template_id"] == $this->dataRecord["template_id"])?'SELECTED':'';
@@ -166,8 +166,8 @@
            $tmp = $app->db->queryOneRecord('SELECT server_id FROM server WHERE vserver_server = 1 AND mirror_server_id = 0 ORDER BY server_name LIMIT 0,1');
            $vm_server_id = $app->functions->intval($tmp['server_id']);
        }
        $sql = "SELECT ip_address FROM openvz_ip WHERE reserved = 'n' AND (vm_id = 0 or vm_id = '".$this->id."') AND server_id = ".$app->functions->intval($vm_server_id)." ORDER BY ip_address";
        $ips = $app->db->queryAllRecords($sql);
        $sql = "SELECT ip_address FROM openvz_ip WHERE reserved = 'n' AND (vm_id = 0 or vm_id = ?) AND server_id = ? ORDER BY ip_address";
        $ips = $app->db->queryAllRecords($sql, $this->id, $vm_server_id);
        $ip_select = "";
        if(is_array($ips)) {
            foreach( $ips as $ip) {
server/lib/app.inc.php
@@ -151,7 +151,7 @@
            if(isset($this->dbmaster)) {
                $server_id = $conf['server_id'];
                $loglevel = $priority;
                $message = $this->dbmaster->quote($msg);
                $message = $msg;
                $datalog_id = (isset($this->modules->current_datalog_id) && $this->modules->current_datalog_id > 0)?$this->modules->current_datalog_id:0;
                if($datalog_id > 0) {
                    $tmp_rec = $this->dbmaster->queryOneRecord("SELECT count(syslog_id) as number FROM sys_log WHERE datalog_id = ? AND loglevel = ?", $datalog_id, LOGLEVEL_ERROR);
server/lib/classes/cron.d/500-backup.inc.php
@@ -130,8 +130,6 @@
                                    chmod($web_backup_dir.'/'.$web_backup_file, 0750);
                                    //* Insert web backup record in database
                                    //$insert_data = "(server_id,parent_domain_id,backup_type,backup_mode,tstamp,filename) VALUES (".$conf['server_id'].",".$web_id.",'web','".$backup_mode."',".time().",'".$app->db->quote($web_backup_file)."')";
                                    //$app->dbmaster->datalogInsert('web_backup', $insert_data, 'backup_id');
                                    $filesize = filesize($web_backup_dir.'/'.$web_backup_file);
                                    $sql = "INSERT INTO web_backup (server_id, parent_domain_id, backup_type, backup_mode, tstamp, filename, filesize) VALUES (?, ?, ?, ?, ?, ?, ?)";
                                    $app->db->query($sql, $conf['server_id'], $web_id, 'web', $backup_mode, time(), $web_backup_file, $filesize);
@@ -160,10 +158,6 @@
                            for ($n = $backup_copies; $n <= 10; $n++) {
                                if(isset($files[$n]) && is_file($web_backup_dir.'/'.$files[$n])) {
                                    unlink($web_backup_dir.'/'.$files[$n]);
                                    //$sql = "SELECT backup_id FROM web_backup WHERE server_id = ".$conf['server_id']." AND parent_domain_id = $web_id AND filename = '".$app->db->quote($files[$n])."'";
                                    //$tmp = $app->dbmaster->queryOneRecord($sql);
                                    //$app->dbmaster->datalogDelete('web_backup', 'backup_id', $tmp['backup_id']);
                                    //$sql = "DELETE FROM web_backup WHERE backup_id = ".intval($tmp['backup_id']);
                                    $sql = "DELETE FROM web_backup WHERE server_id = ? AND parent_domain_id = ? AND filename = ?";
                                    $app->db->query($sql, $conf['server_id'], $web_id, $files[$n]);
                                    if($app->db->dbHost != $app->dbmaster->dbHost) $app->dbmaster->query($sql, $conf['server_id'],  $web_id, $files[$n]);
@@ -247,8 +241,6 @@
                                    chgrp($db_backup_dir.'/'.$db_backup_file.'.gz', filegroup($db_backup_dir));
                                    //* Insert web backup record in database
                                    //$insert_data = "(server_id,parent_domain_id,backup_type,backup_mode,tstamp,filename) VALUES (".$conf['server_id'].",$web_id,'mysql','sqlgz',".time().",'".$app->db->quote($db_backup_file).".gz')";
                                    //$app->dbmaster->datalogInsert('web_backup', $insert_data, 'backup_id');
                                    $filesize = filesize($db_backup_dir.'/'.$db_backup_file.'.gz');
                                    $sql = "INSERT INTO web_backup (server_id, parent_domain_id, backup_type, backup_mode, tstamp, filename, filesize) VALUES (?, ?, ?, ?, ?, ?, ?)";
                                    $app->db->query($sql, $conf['server_id'], $web_id, 'mysql', 'sqlgz', time(), $db_backup_file.'.gz', $filesize);
@@ -281,9 +273,6 @@
                                for ($n = $backup_copies; $n <= 10; $n++) {
                                    if(isset($filelist[$n]) && is_file($db_backup_dir.'/'.$filelist[$n])) {
                                        unlink($db_backup_dir.'/'.$filelist[$n]);
                                        //$sql = "SELECT backup_id FROM web_backup WHERE server_id = ".$conf['server_id']." AND parent_domain_id = $web_id AND filename = '".$app->db->quote($filelist[$n])."'";
                                        //$tmp = $app->dbmaster->queryOneRecord($sql);
                                        //$sql = "DELETE FROM web_backup WHERE backup_id = ".intval($tmp['backup_id']);
                                        $sql = "DELETE FROM web_backup WHERE server_id = ? AND parent_domain_id = ? AND filename = ?";
                                        $app->db->query($sql, $conf['server_id'], $web_id, $filelist[$n]);
                                        if($app->db->dbHost != $app->dbmaster->dbHost) $app->dbmaster->query($sql, $conf['server_id'], $web_id, $filelist[$n]);
server/lib/classes/db_mysql.inc.php
@@ -615,20 +615,26 @@
        if(is_array($insert_data)) {
            $key_str = '';
            $val_str = '';
            $params = array($tablename);
            $v_params = array();
            foreach($insert_data as $key => $val) {
                $key_str .= "`".$key ."`,";
                $val_str .= "'".$this->escape($val)."',";
                $key_str .= '??,'
                $params[] = $key;
                $val_str .= '?,';
                $v_params[] = $val;
            }
            $key_str = substr($key_str, 0, -1);
            $val_str = substr($val_str, 0, -1);
            $insert_data_str = '('.$key_str.') VALUES ('.$val_str.')';
            $this->query("INSERT INTO ?? $insert_data_str", true, $params + $v_params);
        } else {
            /* TODO: deprecate this method! */
            $insert_data_str = $insert_data;
            $this->query("INSERT INTO ?? $insert_data_str", $tablename);
        }
        /* TODO: reduce risk of insert_data_str! */
        $old_rec = array();
        $this->query("INSERT INTO ?? $insert_data_str", $tablename);
        $index_value = $this->insertID();
        $new_rec = $this->queryOneRecord("SELECT * FROM ?? WHERE ? = ?", $tablename, $index_field, $index_value);
        $this->datalogSave($tablename, 'INSERT', $index_field, $index_value, $old_rec, $new_rec);
@@ -643,17 +649,23 @@
        $old_rec = $this->queryOneRecord("SELECT * FROM ?? WHERE ?? = ?", $tablename, $index_field, $index_value);
        if(is_array($update_data)) {
            $params = array($tablename);
            $update_data_str = '';
            foreach($update_data as $key => $val) {
                $update_data_str .= "`".$key ."` = '".$this->escape($val)."',";
                $update_data_str .= '?? = ?,';
                $params[] = $key;
                $params[] = $val;
            }
            $params[] = $index_field;
            $params[] = $index_value;
            $update_data_str = substr($update_data_str, 0, -1);
            $this->query("UPDATE ?? SET $update_data_str WHERE ?? = ?", true, $params);
        } else {
            /* TODO: deprecate this method! */
            $update_data_str = $update_data;
        }
        /* TODO: reduce risk of update_data_str */
        $this->query("UPDATE ?? SET $update_data_str WHERE ?? = ?", $tablename, $index_field, $index_value);
        }
        $new_rec = $this->queryOneRecord("SELECT * FROM ?? WHERE ?? = ?", $tablename, $index_field, $index_value);
        $this->datalogSave($tablename, 'UPDATE', $index_field, $index_value, $old_rec, $new_rec, $force_update);
@@ -676,7 +688,7 @@
    public function datalogError($errormsg) {
        global $app;
        if(isset($app->modules->current_datalog_id) && $app->modules->current_datalog_id > 0) $this->query("UPDATE sys_datalog set error = '".$this->quote($errormsg)."' WHERE datalog_id = ".$app->modules->current_datalog_id);
        if(isset($app->modules->current_datalog_id) && $app->modules->current_datalog_id > 0) $this->query("UPDATE sys_datalog set error = ? WHERE datalog_id = ?", $errormsg, $app->modules->current_datalog_id);
        return true;
    }
server/plugins-available/apache2_plugin.inc.php
@@ -108,23 +108,27 @@
         * php_version -> php ini path that changed (additional php versions)
         */
        $param = '';
        $qrystr = "SELECT * FROM web_domain WHERE custom_php_ini != ''";
        if($data['mode'] == 'mod') {
            $qrystr .= " AND php = 'mod'";
        } elseif($data['mode'] == 'fast-cgi') {
            $qrystr .= " AND php = 'fast-cgi'";
            if($data['php_version']) {
                $qrystr .= " AND fastcgi_php_version LIKE '%:" . $app->db->quote($data['php_version']) . "'";
                $qrystr .= " AND fastcgi_php_version LIKE ?";
                $param = '%:' . $data['php_version'];
            }
        } elseif($data['mode'] == 'php-fpm') {
            $qrystr .= " AND php = 'php-fpm'";
            if($data['php_version']) {
                $qrystr .= " AND fastcgi_php_version LIKE '%:" . $app->db->quote($data['php_version']) . ":%'";
                $qrystr .= " AND fastcgi_php_version LIKE ?";
                $param = '%:' . $data['php_version'] . ':%';
            }
        } elseif($data['mode'] == 'hhvm') {
            $qrystr .= " AND php = 'hhvm'";
            if($data['php_version']) {
                $qrystr .= " AND fastcgi_php_version LIKE '%:" . $app->db->quote($data['php_version']) . ":%'";
                $qrystr .= " AND fastcgi_php_version LIKE ?";
                $param = '%:' . $data['php_version'] . ':%';
            }
        } else {
            $qrystr .= " AND php != 'mod' AND php != 'fast-cgi'";
@@ -132,7 +136,7 @@
        //** Get all the webs
        $web_domains = $app->db->queryAllRecords($qrystr);
        $web_domains = $app->db->queryAllRecords($qrystr, $param);
        foreach($web_domains as $web_data) {
            $custom_php_ini_dir = $web_config['website_basedir'].'/conf/'.$web_data['system_user'];
            $web_folder = 'web';
@@ -303,15 +307,15 @@
            $app->system->chmod($key_file2, 0400);
            @$app->system->unlink($config_file);
            @$app->system->unlink($rand_file);
            $ssl_request = $app->db->quote($app->system->file_get_contents($csr_file));
            $ssl_cert = $app->db->quote($app->system->file_get_contents($crt_file));
            $ssl_key2 = $app->db->quote($app->system->file_get_contents($key_file2));
            $ssl_request = $app->system->file_get_contents($csr_file);
            $ssl_cert = $app->system->file_get_contents($crt_file);
            $ssl_key2 = $app->system->file_get_contents($key_file2);
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE web_domain SET ssl_request = '$ssl_request', ssl_cert = '$ssl_cert', ssl_key = '$ssl_key2' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_request = ?, ssl_cert = ?, ssl_key = ? WHERE domain = ?", $ssl_request, $ssl_cert, $ssl_key2, $data['new']['domain']);
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE web_domain SET ssl_request = '$ssl_request', ssl_cert = '$ssl_cert', ssl_key = '$ssl_key2' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_request = ?, ssl_cert = ?, ssl_key = ? WHERE domain = ?", $ssl_request, $ssl_cert, $ssl_key2, $data['new']['domain']);
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
        }
        //* Save a SSL certificate to disk
@@ -355,18 +359,18 @@
                $app->system->file_put_contents($key_file2, $data["new"]["ssl_key"]);
                $app->system->chmod($key_file2, 0400);
            } else {
                $ssl_key2 = $app->db->quote($app->system->file_get_contents($key_file2));
                $ssl_key2 = $app->system->file_get_contents($key_file2);
                /* Update the DB of the (local) Server */
                $app->db->query("UPDATE web_domain SET ssl_key = '$ssl_key2' WHERE domain = '".$data['new']['domain']."'");
                $app->db->query("UPDATE web_domain SET ssl_key = ? WHERE domain = ?", $ssl_key2, $data['new']['domain']);
                /* Update also the master-DB of the Server-Farm */
                $app->dbmaster->query("UPDATE web_domain SET ssl_key = '$ssl_key2' WHERE domain = '".$data['new']['domain']."'");
                $app->dbmaster->query("UPDATE web_domain SET ssl_key = ? WHERE domain = ?", $ssl_key2, $data['new']['domain']);
            }
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            $app->log('Saving SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }
@@ -386,11 +390,11 @@
            $app->system->unlink($crt_file);
            $app->system->unlink($bundle_file);
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE web_domain SET ssl_request = '', ssl_cert = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_request = '', ssl_cert = '' WHERE domain = ?", $data['new']['domain']);
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE web_domain SET ssl_request = '', ssl_cert = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_request = '', ssl_cert = '' WHERE domain = ?", $data['new']['domain']);
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            $app->log('Deleting SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }
@@ -420,7 +424,7 @@
            // If the parent_domain_id has been changed, we will have to update the old site as well.
            if($this->action == 'update' && $data['new']['parent_domain_id'] != $data['old']['parent_domain_id']) {
                $tmp = $app->db->queryOneRecord('SELECT * FROM web_domain WHERE domain_id = '.$old_parent_domain_id." AND active = 'y'");
                $tmp = $app->db->queryOneRecord('SELECT * FROM web_domain WHERE domain_id = ? AND active = ?', $old_parent_domain_id, 'y');
                $data['new'] = $tmp;
                $data['old'] = $tmp;
                $this->action = 'update';
@@ -428,7 +432,7 @@
            }
            // This is not a vhost, so we need to update the parent record instead.
            $tmp = $app->db->queryOneRecord('SELECT * FROM web_domain WHERE domain_id = '.$new_parent_domain_id." AND active = 'y'");
            $tmp = $app->db->queryOneRecord('SELECT * FROM web_domain WHERE domain_id = ? AND active = ', $new_parent_domain_id, 'y');
            $data['new'] = $tmp;
            $data['old'] = $tmp;
            $this->action = 'update';
@@ -466,7 +470,7 @@
        $old_log_folder = 'log';
        if($data['new']['type'] == 'vhostsubdomain' || $data['new']['type'] == 'vhostalias') {
            // new one
            $tmp = $app->db->queryOneRecord('SELECT `domain` FROM web_domain WHERE domain_id = '.intval($data['new']['parent_domain_id']));
            $tmp = $app->db->queryOneRecord('SELECT `domain` FROM web_domain WHERE domain_id = ?', $data['new']['parent_domain_id']);
            $subdomain_host = preg_replace('/^(.*)\.' . preg_quote($tmp['domain'], '/') . '$/', '$1', $data['new']['domain']);
            if($subdomain_host == '') $subdomain_host = 'web'.$data['new']['domain_id'];
            $web_folder = $data['new']['web_folder'];
@@ -475,7 +479,7 @@
            
            if(isset($data['old']['parent_domain_id'])) {
                // old one
                $tmp = $app->db->queryOneRecord('SELECT `domain` FROM web_domain WHERE domain_id = '.intval($data['old']['parent_domain_id']));
                $tmp = $app->db->queryOneRecord('SELECT `domain` FROM web_domain WHERE domain_id = ?', $data['old']['parent_domain_id']);
                $subdomain_host = preg_replace('/^(.*)\.' . preg_quote($tmp['domain'], '/') . '$/', '$1', $data['old']['domain']);
                if($subdomain_host == '') $subdomain_host = 'web'.$data['old']['domain_id'];
                $old_web_folder = $data['old']['web_folder'];
@@ -529,7 +533,7 @@
        if($this->action == 'update' && $data['new']['document_root'] != $data['old']['document_root']) {
            //* Get the old client ID
            $old_client = $app->dbmaster->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = '.intval($data['old']['sys_groupid']));
            $old_client = $app->dbmaster->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = ?', $data['old']['sys_groupid']);
            $old_client_id = intval($old_client['client_id']);
            unset($old_client);
@@ -671,7 +675,7 @@
        $app->system->web_folder_protection($data['new']['document_root'], true);
        // Get the client ID
        $client = $app->dbmaster->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = '.intval($data['new']['sys_groupid']));
        $client = $app->dbmaster->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = ?', $data['new']['sys_groupid']);
        $client_id = intval($client['client_id']);
        unset($client);
@@ -1031,7 +1035,7 @@
        // Custom Apache directives
        if(intval($data['new']['directive_snippets_id']) > 0){
            $snippet = $app->db->queryOneRecord("SELECT * FROM directive_snippets WHERE directive_snippets_id = ? AND type = 'apache' AND active = 'y' AND customer_viewable = 'y'", intval($data['new']['directive_snippets_id']));
            $snippet = $app->db->queryOneRecord("SELECT * FROM directive_snippets WHERE directive_snippets_id = ? AND type = 'apache' AND active = 'y' AND customer_viewable = 'y'", $data['new']['directive_snippets_id']);
            if(isset($snippet['snippet'])){
                $vhost_data['apache_directives'] = $snippet['snippet'];
            }
@@ -1137,7 +1141,7 @@
        $auto_alias = $web_config['website_autoalias'];
        if($auto_alias != '') {
            // get the client username
            $client = $app->db->queryOneRecord("SELECT `username` FROM `client` WHERE `client_id` = '" . intval($client_id) . "'");
            $client = $app->db->queryOneRecord("SELECT `username` FROM `client` WHERE `client_id` = ?", $client_id);
            $aa_search = array('[client_id]', '[website_id]', '[client_username]', '[website_domain]');
            $aa_replace = array($client_id, $data['new']['domain_id'], $client['username'], $data['new']['domain']);
            $auto_alias = str_replace($aa_search, $aa_replace, $auto_alias);
@@ -1148,7 +1152,7 @@
        }
        // get alias domains (co-domains and subdomains)
        $aliases = $app->db->queryAllRecords('SELECT * FROM web_domain WHERE parent_domain_id = '.$data['new']['domain_id']." AND active = 'y' AND (type != 'vhostsubdomain' AND type != 'vhostalias')");
        $aliases = $app->db->queryAllRecords("SELECT * FROM web_domain WHERE parent_domain_id = ? AND active = 'y' AND (type != 'vhostsubdomain' AND type != 'vhostalias')", $data['new']['domain_id']);
        $alias_seo_redirects = array();
        switch($data['new']['subdomain']) {
        case 'www':
@@ -1792,7 +1796,7 @@
        $log_folder = 'log';
        $web_folder = '';
        if($data['old']['type'] == 'vhostsubdomain' || $data['old']['type'] == 'vhostalias') {
            $tmp = $app->db->queryOneRecord('SELECT `domain`,`document_root` FROM web_domain WHERE domain_id = '.intval($data['old']['parent_domain_id']));
            $tmp = $app->db->queryOneRecord('SELECT `domain`,`document_root` FROM web_domain WHERE domain_id = ?', $data['old']['parent_domain_id']);
            if($tmp['domain'] != ''){
                $subdomain_host = preg_replace('/^(.*)\.' . preg_quote($tmp['domain'], '/') . '$/', '$1', $data['old']['domain']);
            } else {
@@ -1864,7 +1868,7 @@
        if($data['old']['type'] != 'vhost' && $data['old']['type'] != 'vhostsubdomain' && $data['old']['type'] != 'vhostalias' && $data['old']['parent_domain_id'] > 0) {
            //* This is a alias domain or subdomain, so we have to update the website instead
            $parent_domain_id = intval($data['old']['parent_domain_id']);
            $tmp = $app->db->queryOneRecord('SELECT * FROM web_domain WHERE domain_id = '.$parent_domain_id." AND active = 'y'");
            $tmp = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ? AND active = 'y'", $parent_domain_id);
            $data['new'] = $tmp;
            $data['old'] = $tmp;
            $this->action = 'update';
@@ -1918,7 +1922,7 @@
                        } else {
                            // read all vhost subdomains and alias with same parent domain
                            $used_paths = array();
                            $tmp = $app->db->queryAllRecords("SELECT `web_folder` FROM web_domain WHERE (type = 'vhostsubdomain' OR type = 'vhostalias') AND parent_domain_id = ".intval($data['old']['parent_domain_id'])." AND domain_id != ".intval($data['old']['domain_id']));
                            $tmp = $app->db->queryAllRecords("SELECT `web_folder` FROM web_domain WHERE (type = 'vhostsubdomain' OR type = 'vhostalias') AND parent_domain_id = ? AND domain_id != ?", $data['old']['parent_domain_id'], $data['old']['domain_id']);
                            foreach($tmp as $tmprec) {
                                // we normalize the folder entries because we need to compare them
                                $tmp_folder = preg_replace('/[\/]{2,}/', '/', $tmprec['web_folder']); // replace / occuring multiple times
@@ -2000,7 +2004,7 @@
                $app->log('Removing website: '.$docroot, LOGLEVEL_DEBUG);
                // Delete the symlinks for the sites
                $client = $app->db->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = '.intval($data['old']['sys_groupid']));
                $client = $app->db->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = ?', $data['old']['sys_groupid']);
                $client_id = intval($client['client_id']);
                unset($client);
                $tmp_symlinks_array = explode(':', $web_config['website_symlinks']);
@@ -2089,7 +2093,7 @@
        $tpl = new tpl();
        $tpl->newTemplate('apache_ispconfig.conf.master');
        $tpl->setVar('apache_version', $app->system->getapacheversion());
        $records = $app->db->queryAllRecords('SELECT * FROM server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'");
        $records = $app->db->queryAllRecords("SELECT * FROM server_ip WHERE server_id = ? AND virtualhost = 'y'", $conf['server_id']);
        $records_out= array();
        if(is_array($records)) {
@@ -2135,8 +2139,8 @@
            $folder_id = $data['new']['web_folder_id'];
        }
        $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE web_folder_id = ".intval($folder_id));
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".intval($folder['parent_domain_id']));
        $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE web_folder_id = ?", $folder_id);
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $folder['parent_domain_id']);
        if(!is_array($folder) or !is_array($website)) {
            $app->log('Not able to retrieve folder or website record.', LOGLEVEL_DEBUG);
@@ -2171,19 +2175,6 @@
            $app->system->chgrp($folder_path.'.htpasswd', $website['system_group']);
            $app->log('Created file '.$folder_path.'.htpasswd', LOGLEVEL_DEBUG);
        }
        /*
        $auth_users = $app->db->queryAllRecords("SELECT * FROM web_folder_user WHERE active = 'y' AND web_folder_id = ".intval($folder_id));
        $htpasswd_content = '';
        if(is_array($auth_users) && !empty($auth_users)){
            foreach($auth_users as $auth_user){
                $htpasswd_content .= $auth_user['username'].':'.$auth_user['password']."\n";
            }
        }
        $htpasswd_content = trim($htpasswd_content);
        @file_put_contents($folder_path.'.htpasswd', $htpasswd_content);
        $app->log('Changed .htpasswd file: '.$folder_path.'.htpasswd',LOGLEVEL_DEBUG);
        */
        if(($data['new']['username'] != $data['old']['username'] || $data['new']['active'] == 'n') && $data['old']['username'] != '') {
            $app->system->removeLine($folder_path.'.htpasswd', $data['old']['username'].':');
@@ -2235,7 +2226,7 @@
        $folder_id = $data['old']['web_folder_id'];
        $folder = $data['old'];
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".intval($folder['parent_domain_id']));
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $folder['parent_domain_id']);
        if(!is_array($folder) or !is_array($website)) {
            $app->log('Not able to retrieve folder or website record.', LOGLEVEL_DEBUG);
@@ -2290,7 +2281,7 @@
    function web_folder_update($event_name, $data) {
        global $app, $conf;
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".intval($data['new']['parent_domain_id']));
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $data['new']['parent_domain_id']);
        if(!is_array($website)) {
            $app->log('Not able to retrieve folder or website record.', LOGLEVEL_DEBUG);
@@ -2450,7 +2441,7 @@
            /*
             * Get additional informations
            */
            $sitedata = $app->db->queryOneRecord('SELECT document_root, domain, system_user, system_group FROM web_domain WHERE domain_id = ' . $data['new']['parent_domain_id']);
            $sitedata = $app->db->queryOneRecord('SELECT document_root, domain, system_user, system_group FROM web_domain WHERE domain_id = ?', $data['new']['parent_domain_id']);
            $documentRoot = $sitedata['document_root'];
            $domain = $sitedata['domain'];
            $user = $sitedata['system_user'];
@@ -2538,7 +2529,7 @@
            /*
             * Get additional informations
            */
            $sitedata = $app->db->queryOneRecord('SELECT document_root, domain FROM web_domain WHERE domain_id = ' . $data['old']['parent_domain_id']);
            $sitedata = $app->db->queryOneRecord('SELECT document_root, domain FROM web_domain WHERE domain_id = ?', $data['old']['parent_domain_id']);
            $documentRoot = $sitedata['document_root'];
            $domain = $sitedata['domain'];
@@ -2925,7 +2916,7 @@
                $app->services->restartService('php-fpm', 'reload:'.$conf['init_scripts'].'/'.$web_config['php_fpm_init_script']);
            }
        }
        $php_versions = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ".$conf["server_id"]);
        $php_versions = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ?", $conf["server_id"]);
        if(is_array($php_versions) && !empty($php_versions)){
            foreach($php_versions as $php_version){
                if(substr($php_version['php_fpm_pool_dir'], -1) != '/') $php_version['php_fpm_pool_dir'] .= '/';
@@ -2989,7 +2980,7 @@
                $app->services->restartService('php-fpm', 'reload:'.$conf['init_scripts'].'/'.$web_config['php_fpm_init_script']);
            }
        }
        $php_versions = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ".$data['old']['server_id']);
        $php_versions = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ?", $data['old']['server_id']);
        if(is_array($php_versions) && !empty($php_versions)){
            foreach($php_versions as $php_version){
                if(substr($php_version['php_fpm_pool_dir'], -1) != '/') $php_version['php_fpm_pool_dir'] .= '/';
server/plugins-available/bind_dlz_plugin.inc.php
@@ -129,8 +129,7 @@
        //$_db->dbName = 'named';
        $app->db->query("INSERT INTO named.records (zone, ttl, type, primary_ns, resp_contact, serial, refresh, retry, expire, minimum, ispconfig_id) VALUES ".
            "('$origin', $ttl, 'SOA', '{$data["new"]["ns"]}', '{$data["new"]["mbox"]}', '{$serial["serial"]}', '{$serial["refresh"]}'," .
            "'{$serial["retry"]}', '{$serial["expire"]}', '{$serial["minimum"]}', $ispconfig_id)");
            "(?, ?, 'SOA', ?, ?, ?, ?, ?, ?, ?, ?)", $origin, $ttl, $data["new"]["ns"], $data["new"]["mbox"], $serial["serial"], $serial["refresh"], $serial["retry"], $serial["expire"], $serial["minimum"], $ispconfig_id);
        //unset($_db);
    }
@@ -149,16 +148,14 @@
            {
                $origin = substr($data["new"]["origin"], 0, -1);
                $ispconfig_id = $data["new"]["id"];
                $serial = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ".$ispconfig_id);
                $serial = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ?", $ispconfig_id);
                $ttl = $data["new"]["ttl"];
                //$_db = clone $app->db;
                //$_db->dbName = 'named';
                $app->db->query("UPDATE named.records SET zone = '$origin', ttl = $ttl, primary_ns = '{$data["new"]["ns"]}', resp_contact = '{$data["new"]["mbox"]}', ".
                    "serial = '{$serial["serial"]}', refresh = '{$serial["refresh"]}', retry = '{$serial["retry"]}', expire = '{$serial["expire"]}', ".
                    "minimum = '{$serial["minimum"]}' WHERE ispconfig_id = ".$data["new"]["id"]." AND type = 'SOA'");
                $app->db->query("UPDATE named.records SET zone = ?, ttl = ?, primary_ns = ?, resp_contact = ?, serial = ?, refresh = ?, retry = ?, expire = ?, minimum = ? WHERE ispconfig_id = ? AND type = 'SOA'", $origin, $ttl, $data["new"]["ns"], $data["new"]["mbox"], $serial["serial"], $serial["refresh"], $serial["retry"], $serial["expire"], $serial["minimum"], $data["new"]["id"]);
                //unset($_db);
            }
            else
@@ -166,7 +163,7 @@
                $this->soa_insert($event_name, $data);
                $ispconfig_id = $data["new"]["id"];
                if ($records = $app->db->queryAllRecords("SELECT * FROM dns_rr WHERE zone = $ispconfig_id AND active = 'Y'"))
                if ($records = $app->db->queryAllRecords("SELECT * FROM dns_rr WHERE zone = ? AND active = 'Y'", $ispconfig_id))
                {
                    foreach($records as $record)
                    {
@@ -188,7 +185,7 @@
        //$_db = clone $app->db;
        //$_db->dbName = 'named';
        $app->db->query( "DELETE FROM named.dns_records WHERE zone = '".substr($data['old']['origin'], 0, -1)."'");
        $app->db->query( "DELETE FROM named.dns_records WHERE zone = ?", substr($data['old']['origin'], 0, -1));
        //unset($_db);
    }
@@ -197,7 +194,7 @@
        global $app, $conf;
        if($data["new"]["active"] != 'Y') return;
        $zone = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ".$data["new"]["zone"]);
        $zone = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ?", $data["new"]["zone"]);
        $origin = substr($zone["origin"], 0, -1);
        $ispconfig_id = $data["new"]["id"];
@@ -251,13 +248,13 @@
        if ($type == 'MX') {
            $app->db->query("INSERT INTO named.records (zone, ttl, type, host, mx_priority, data, ispconfig_id)".
                " VALUES ('$origin', $ttl, '$type', '$name', {$data["new"]["aux"]}, '$content', $ispconfig_id)");
                " VALUES (?, ?, ?, ?, ?, ?, ?)", $origin, $ttl, $type, $name, $data["new"]["aux"], $content, $ispconfig_id);
        } elseif ($type == 'SRV') {
            $app->db->query("INSERT INTO named.records (zone, ttl, type, data, ispconfig_id)".
                " VALUES ('$origin', $ttl, '$type', '{$data["new"]["aux"]} $content', $ispconfig_id)");
                " VALUES (?, ?, ?, ?, ?)", $origin, $ttl, $type, $data["new"]["aux"] . ' ' . $content, $ispconfig_id);
        } else {
            $app->db->query("INSERT INTO named.records (zone, ttl, type, host, data, ispconfig_id)".
                " VALUES ('$origin', $ttl, '$type', '$name', '$content', $ispconfig_id)");
                " VALUES (?, ?, ?, ?, ?, ?)", $origin, $ttl, $type, $name, $content, $ispconfig_id);
        }
        //unset($_db);
@@ -276,7 +273,7 @@
        {
            if ($data["old"]["active"] == 'Y')
            {
                $zone = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ".$data["new"]["zone"]);
                $zone = $app->db->queryOneRecord("SELECT * FROM dns_soa WHERE id = ?", $data["new"]["zone"]);
                $origin = substr($zone["origin"], 0, -1);
                $ispconfig_id = $data["new"]["id"];
@@ -328,14 +325,11 @@
                //$_db->dbName = 'named';
                if ($type == 'MX') {
                    $app->db->query("UPDATE named.records SET zone = '$origin', ttl = $ttl, type = '$type', host = '$name', mx_priority = $prio, ".
                        "data = '$content' WHERE ispconfig_id = $ispconfig_id AND type != 'SOA'");
                    $app->db->query("UPDATE named.records SET zone = ?, ttl = ?, type = ?, host = ?, mx_priority = ?, data = ? WHERE ispconfig_id = ? AND type != 'SOA'", $origin, $ttl, $type, $name, $prio, $content, $ispconfig_id);
                } elseif ($type == 'SRV') {
                    $app->db->query("UPDATE named.records SET zone = '$origin', ttl = $ttl, type = '$type', ".
                        "data = '$prio $content' WHERE ispconfig_id = $ispconfig_id AND type != 'SOA'");
                    $app->db->query("UPDATE named.records SET zone = ?, ttl = ?, type = ?, data = ? WHERE ispconfig_id = ? AND type != 'SOA'", $origin, $ttl, $type, $prio . ' ' . $content, $ispconfig_id);
                } else {
                    $app->db->query("UPDATE named.records SET zone = '$origin', ttl = $ttl, type = '$type', host = '$name', ".
                        "data = '$content' WHERE ispconfig_id = $ispconfig_id AND type != 'SOA'");
                    $app->db->query("UPDATE named.records SET zone = ?, ttl = ?, type = ?, host = ?, data = ? WHERE ispconfig_id = ? AND type != 'SOA'", $origin, $ttl, $type, $name, $content, $ispconfig_id);
                }
                //unset($_db);
@@ -351,7 +345,7 @@
        //$_db = clone $app->db;
        //$_db->dbName = 'named';
        $app->db->query( "DELETE FROM named.dns_records WHERE type != 'SOA' AND zone = '".substr($data['old']['origin'], 0, -1)."'");
        $app->db->query( "DELETE FROM named.dns_records WHERE type != 'SOA' AND zone = ?", substr($data['old']['origin'], 0, -1));
        //unset($_db);
    }
server/plugins-available/mongo_clientdb_plugin.inc.php
@@ -500,8 +500,8 @@
                return;
            }
            $db_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = '" . intval($data['new']['database_user_id']) . "'");
            $db_ro_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = '" . intval($data['new']['database_ro_user_id']) . "'");
            $db_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = ?", $data['new']['database_user_id']);
            $db_ro_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = ?", $data['new']['database_ro_user_id']);
            $user = $db_user['database_user'];
            $password = $db_user['database_password_mongo'];
@@ -573,8 +573,8 @@
                return;
            }
            $db_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = '" . intval($data['new']['database_user_id']) . "'");
            $db_ro_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = '" . intval($data['new']['database_ro_user_id']) . "'");
            $db_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = ?", $data['new']['database_user_id']);
            $db_ro_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = ?", $data['new']['database_ro_user_id']);
            $user = $db_user['database_user'];
            $password = $db_user['database_password_mongo'];
@@ -600,7 +600,7 @@
                } else {
                // selected user has changed -> drop old one
                if ($data['new']['database_user_id'] != $data['old']['database_user_id']) {
                    $old_db_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = '" . intval($data['old']['database_user_id']) . "'");
                    $old_db_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = ?", $data['old']['database_user_id']);
                    if ((bool) $old_db_user) {
                        if ($old_db_user['database_user'] == 'root') {
@@ -613,7 +613,7 @@
                // selected read-only user has changed -> drop old one
                if ($data['new']['database_ro_user_id'] != $data['old']['database_ro_user_id']) {
                    $old_db_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = '" . intval($data['old']['database_ro_user_id']) . "'");
                    $old_db_user = $app->db->queryOneRecord("SELECT `database_user`, `database_password_mongo` FROM `web_database_user` WHERE `database_user_id` = ?", $data['old']['database_ro_user_id']);
                    if ((bool) $old_db_user) {
                        if ($old_db_user['database_user'] == 'root') {
server/plugins-available/nginx_plugin.inc.php
@@ -208,15 +208,15 @@
            $app->system->chmod($key_file2, 0400);
            @$app->system->unlink($config_file);
            @$app->system->unlink($rand_file);
            $ssl_request = $app->db->quote($app->system->file_get_contents($csr_file));
            $ssl_cert = $app->db->quote($app->system->file_get_contents($crt_file));
            $ssl_key2 = $app->db->quote($app->system->file_get_contents($key_file2));
            $ssl_request = $app->system->file_get_contents($csr_file);
            $ssl_cert = $app->system->file_get_contents($crt_file);
            $ssl_key2 = $app->system->file_get_contents($key_file2);
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE web_domain SET ssl_request = '$ssl_request', ssl_cert = '$ssl_cert', ssl_key = '$ssl_key2' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_request = ?, ssl_cert = ?, ssl_key = ? WHERE domain = ?", $ssl_request, $ssl_cert, $ssl_key2, $data['new']['domain']);
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE web_domain SET ssl_request = '$ssl_request', ssl_cert = '$ssl_cert', ssl_key = '$ssl_key2' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_request = ?, ssl_cert = ?, ssl_key = ? WHERE domain = ?", $ssl_request, $ssl_cert, $ssl_key2, $data['new']['domain']);
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
        }
        //* Save a SSL certificate to disk
@@ -263,10 +263,10 @@
                unset($crt_file_contents);
            }
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            $app->log('Saving SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }
@@ -286,11 +286,11 @@
            $app->system->unlink($crt_file);
            //$app->system->unlink($bundle_file);
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE web_domain SET ssl_request = '', ssl_cert = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE web_domain SET ssl_request = '', ssl_cert = '' WHERE domain = ?", $data['new']['domain']);
            $app->db->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE web_domain SET ssl_request = '', ssl_cert = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE web_domain SET ssl_request = '', ssl_cert = '' WHERE domain = ?", $data['new']['domain']);
            $app->dbmaster->query("UPDATE web_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            $app->log('Deleting SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }
@@ -326,7 +326,7 @@
            // If the parent_domain_id has been changed, we will have to update the old site as well.
            if($this->action == 'update' && $data['new']['parent_domain_id'] != $data['old']['parent_domain_id']) {
                $tmp = $app->db->queryOneRecord('SELECT * FROM web_domain WHERE domain_id = '.$old_parent_domain_id." AND active = 'y'");
                $tmp = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ? AND active = 'y'", $old_parent_domain_id);
                $data['new'] = $tmp;
                $data['old'] = $tmp;
                $this->action = 'update';
@@ -334,7 +334,7 @@
            }
            // This is not a vhost, so we need to update the parent record instead.
            $tmp = $app->db->queryOneRecord('SELECT * FROM web_domain WHERE domain_id = '.$new_parent_domain_id." AND active = 'y'");
            $tmp = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ? AND active = 'y'", $new_parent_domain_id);
            $data['new'] = $tmp;
            $data['old'] = $tmp;
            $this->action = 'update';
@@ -374,7 +374,7 @@
        $old_log_folder = 'log';
        if($data['new']['type'] == 'vhostsubdomain' || $data['new']['type'] == 'vhostalias') {
            // new one
            $tmp = $app->db->queryOneRecord('SELECT `domain` FROM web_domain WHERE domain_id = '.intval($data['new']['parent_domain_id']));
            $tmp = $app->db->queryOneRecord('SELECT `domain` FROM web_domain WHERE domain_id = ?', $data['new']['parent_domain_id']);
            $subdomain_host = preg_replace('/^(.*)\.' . preg_quote($tmp['domain'], '/') . '$/', '$1', $data['new']['domain']);
            if($subdomain_host == '') $subdomain_host = 'web'.$data['new']['domain_id'];
            $web_folder = $data['new']['web_folder'];
@@ -383,7 +383,7 @@
            
            if(isset($data['old']['parent_domain_id'])) {
                // old one
                $tmp = $app->db->queryOneRecord('SELECT `domain` FROM web_domain WHERE domain_id = '.intval($data['old']['parent_domain_id']));
                $tmp = $app->db->queryOneRecord('SELECT `domain` FROM web_domain WHERE domain_id = ?', $data['old']['parent_domain_id']);
                $subdomain_host = preg_replace('/^(.*)\.' . preg_quote($tmp['domain'], '/') . '$/', '$1', $data['old']['domain']);
                if($subdomain_host == '') $subdomain_host = 'web'.$data['old']['domain_id'];
                $old_web_folder = $data['old']['web_folder'];
@@ -437,7 +437,7 @@
        if($this->action == 'update' && $data['new']['document_root'] != $data['old']['document_root']) {
            //* Get the old client ID
            $old_client = $app->dbmaster->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = '.intval($data['old']['sys_groupid']));
            $old_client = $app->dbmaster->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = ?', $data['old']['sys_groupid']);
            $old_client_id = intval($old_client['client_id']);
            unset($old_client);
@@ -576,7 +576,7 @@
        $app->system->web_folder_protection($data['new']['document_root'], true);
        // Get the client ID
        $client = $app->dbmaster->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = '.intval($data['new']['sys_groupid']));
        $client = $app->dbmaster->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = ?', $data['new']['sys_groupid']);
        $client_id = intval($client['client_id']);
        unset($client);
@@ -1090,7 +1090,7 @@
        // Custom nginx directives
        $final_nginx_directives = array();
        if(intval($data['new']['directive_snippets_id']) > 0){
            $snippet = $app->db->queryOneRecord("SELECT * FROM directive_snippets WHERE directive_snippets_id = ? AND type = 'nginx' AND active = 'y' AND customer_viewable = 'y'", intval($data['new']['directive_snippets_id']));
            $snippet = $app->db->queryOneRecord("SELECT * FROM directive_snippets WHERE directive_snippets_id = ? AND type = 'nginx' AND active = 'y' AND customer_viewable = 'y'", $data['new']['directive_snippets_id']);
            if(isset($snippet['snippet'])){
                $nginx_directives = $snippet['snippet'];
            } else {
@@ -1336,7 +1336,7 @@
        $auto_alias = $web_config['website_autoalias'];
        if($auto_alias != '') {
            // get the client username
            $client = $app->db->queryOneRecord("SELECT `username` FROM `client` WHERE `client_id` = '" . intval($client_id) . "'");
            $client = $app->db->queryOneRecord("SELECT `username` FROM `client` WHERE `client_id` = ?", $client_id);
            $aa_search = array('[client_id]', '[website_id]', '[client_username]', '[website_domain]');
            $aa_replace = array($client_id, $data['new']['domain_id'], $client['username'], $data['new']['domain']);
            $auto_alias = str_replace($aa_search, $aa_replace, $auto_alias);
@@ -1356,7 +1356,7 @@
        }
        // get alias domains (co-domains and subdomains)
        $aliases = $app->db->queryAllRecords('SELECT * FROM web_domain WHERE parent_domain_id = '.$data['new']['domain_id']." AND active = 'y' AND (type != 'vhostsubdomain' AND type != 'vhostalias')");
        $aliases = $app->db->queryAllRecords("SELECT * FROM web_domain WHERE parent_domain_id = ? AND active = 'y' AND (type != 'vhostsubdomain' AND type != 'vhostalias')", $data['new']['domain_id']);
        $alias_seo_redirects = array();
        if(is_array($aliases)) {
            foreach($aliases as $alias) {
@@ -1805,7 +1805,7 @@
        $log_folder = 'log';
        $web_folder = '';
        if($data['old']['type'] == 'vhostsubdomain' || $data['old']['type'] == 'vhostalias') {
            $tmp = $app->db->queryOneRecord('SELECT `domain`,`document_root` FROM web_domain WHERE domain_id = '.intval($data['old']['parent_domain_id']));
            $tmp = $app->db->queryOneRecord('SELECT `domain`,`document_root` FROM web_domain WHERE domain_id = ?', $data['old']['parent_domain_id']);
            if($tmp['domain'] != ''){
                $subdomain_host = preg_replace('/^(.*)\.' . preg_quote($tmp['domain'], '/') . '$/', '$1', $data['old']['domain']);
            } else {
@@ -1877,7 +1877,7 @@
        if($data['old']['type'] != 'vhost' && $data['old']['type'] != 'vhostsubdomain' && $data['old']['type'] != 'vhostalias' && $data['old']['parent_domain_id'] > 0) {
            //* This is a alias domain or subdomain, so we have to update the website instead
            $parent_domain_id = intval($data['old']['parent_domain_id']);
            $tmp = $app->db->queryOneRecord('SELECT * FROM web_domain WHERE domain_id = '.$parent_domain_id." AND active = 'y'");
            $tmp = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ? AND active = 'y'", $parent_domain_id);
            $data['new'] = $tmp;
            $data['old'] = $tmp;
            $this->action = 'update';
@@ -1931,7 +1931,7 @@
                        } else {
                            // read all vhost subdomains with same parent domain
                            $used_paths = array();
                            $tmp = $app->db->queryAllRecords("SELECT `web_folder` FROM web_domain WHERE (type = 'vhostsubdomain' OR type = 'vhostalias') AND parent_domain_id = ".intval($data['old']['parent_domain_id'])." AND domain_id != ".intval($data['old']['domain_id']));
                            $tmp = $app->db->queryAllRecords("SELECT `web_folder` FROM web_domain WHERE (type = 'vhostsubdomain' OR type = 'vhostalias') AND parent_domain_id = ? AND domain_id != ?", $data['old']['parent_domain_id'], $data['old']['domain_id']);
                            foreach($tmp as $tmprec) {
                                // we normalize the folder entries because we need to compare them
                                $tmp_folder = preg_replace('/[\/]{2,}/', '/', $tmprec['web_folder']); // replace / occuring multiple times
@@ -2014,7 +2014,7 @@
                $app->log('Removing website: '.$docroot, LOGLEVEL_DEBUG);
                // Delete the symlinks for the sites
                $client = $app->db->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = '.intval($data['old']['sys_groupid']));
                $client = $app->db->queryOneRecord('SELECT client_id FROM sys_group WHERE sys_group.groupid = ?', $data['old']['sys_groupid']);
                $client_id = intval($client['client_id']);
                unset($client);
                $tmp_symlinks_array = explode(':', $web_config['website_symlinks']);
@@ -2102,8 +2102,8 @@
            $folder_id = $data['new']['web_folder_id'];
        }
        $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE web_folder_id = ".intval($folder_id));
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".intval($folder['parent_domain_id']));
        $folder = $app->db->queryOneRecord("SELECT * FROM web_folder WHERE web_folder_id = ?", $folder_id);
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $folder['parent_domain_id']);
        if(!is_array($folder) or !is_array($website)) {
            $app->log('Not able to retrieve folder or website record.', LOGLEVEL_DEBUG);
@@ -2139,19 +2139,6 @@
            $app->log('Created file '.$folder_path.'.htpasswd', LOGLEVEL_DEBUG);
        }
        /*
        $auth_users = $app->db->queryAllRecords("SELECT * FROM web_folder_user WHERE active = 'y' AND web_folder_id = ".intval($folder_id));
        $htpasswd_content = '';
        if(is_array($auth_users) && !empty($auth_users)){
            foreach($auth_users as $auth_user){
                $htpasswd_content .= $auth_user['username'].':'.$auth_user['password']."\n";
            }
        }
        $htpasswd_content = trim($htpasswd_content);
        @file_put_contents($folder_path.'.htpasswd', $htpasswd_content);
        $app->log('Changed .htpasswd file: '.$folder_path.'.htpasswd',LOGLEVEL_DEBUG);
        */
        if(($data['new']['username'] != $data['old']['username'] || $data['new']['active'] == 'n') && $data['old']['username'] != '') {
            $app->system->removeLine($folder_path.'.htpasswd', $data['old']['username'].':');
            $app->log('Removed user: '.$data['old']['username'], LOGLEVEL_DEBUG);
@@ -2180,7 +2167,7 @@
        $folder_id = $data['old']['web_folder_id'];
        $folder = $data['old'];
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".intval($folder['parent_domain_id']));
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $folder['parent_domain_id']);
        if(!is_array($folder) or !is_array($website)) {
            $app->log('Not able to retrieve folder or website record.', LOGLEVEL_DEBUG);
@@ -2217,7 +2204,7 @@
    function web_folder_update($event_name, $data) {
        global $app, $conf;
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ".intval($data['new']['parent_domain_id']));
        $website = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain_id = ?", $data['new']['parent_domain_id']);
        if(!is_array($website)) {
            $app->log('Not able to retrieve folder or website record.', LOGLEVEL_DEBUG);
@@ -2286,7 +2273,7 @@
        //$app->load('tpl');
        //$tpl = new tpl();
        //$tpl->newTemplate('nginx_http_authentication.auth.master');
        $website_auth_locations = $app->db->queryAllRecords("SELECT * FROM web_folder WHERE active = 'y' AND parent_domain_id = ".intval($website['domain_id']));
        $website_auth_locations = $app->db->queryAllRecords("SELECT * FROM web_folder WHERE active = 'y' AND parent_domain_id = ?", $website['domain_id']);
        $basic_auth_locations = array();
        if(is_array($website_auth_locations) && !empty($website_auth_locations)){
            foreach($website_auth_locations as $website_auth_location){
@@ -2526,7 +2513,7 @@
                $app->services->restartService('php-fpm', 'reload:'.$conf['init_scripts'].'/'.$web_config['php_fpm_init_script']);
            }
        }
        $php_versions = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ".$conf["server_id"]);
        $php_versions = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ?", $conf["server_id"]);
        if(is_array($php_versions) && !empty($php_versions)){
            foreach($php_versions as $php_version){
                if(substr($php_version['php_fpm_pool_dir'], -1) != '/') $php_version['php_fpm_pool_dir'] .= '/';
@@ -2584,7 +2571,7 @@
                $app->services->restartService('php-fpm', 'reload:'.$conf['init_scripts'].'/'.$web_config['php_fpm_init_script']);
            }
        }
        $php_versions = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ".$data['old']['server_id']);
        $php_versions = $app->db->queryAllRecords("SELECT * FROM server_php WHERE php_fpm_init_script != '' AND php_fpm_ini_dir != '' AND php_fpm_pool_dir != '' AND server_id = ?", $data['old']['server_id']);
        if(is_array($php_versions) && !empty($php_versions)){
            foreach($php_versions as $php_version){
                if(substr($php_version['php_fpm_pool_dir'], -1) != '/') $php_version['php_fpm_pool_dir'] .= '/';
server/plugins-available/xmpp_plugin.inc.php
@@ -315,17 +315,17 @@
            exec("(cd /etc/metronome/certs && make $domain.csr)");
            exec("(cd /etc/metronome/certs && make $domain.cert)");
            $ssl_key = $app->db->quote($app->system->file_get_contents($key_file));
            $ssl_key = $app->system->file_get_contents($key_file);
            $app->system->chmod($key_file, 0400);
            $app->system->chown($key_file, 'metronome');
            $ssl_request = $app->db->quote($app->system->file_get_contents($csr_file));
            $ssl_cert = $app->db->quote($app->system->file_get_contents($crt_file));
            $ssl_request = $app->system->file_get_contents($csr_file);
            $ssl_cert = $app->system->file_get_contents($crt_file);
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE xmpp_domain SET ssl_request = '$ssl_request', ssl_cert = '$ssl_cert', ssl_key = '$ssl_key' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE xmpp_domain SET ssl_request = ?, ssl_cert = ?, ssl_key = ? WHERE domain = ?", $ssl_request, $ssl_cert, $ssl_key, $data['new']['domain']);
            $app->db->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_request = '$ssl_request', ssl_cert = '$ssl_cert', ssl_key = '$ssl_key' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_request = ?, ssl_cert = ?, ssl_key = ? WHERE domain = ?", $ssl_request, $ssl_cert, $ssl_key, $data['new']['domain']);
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            $app->log('Creating XMPP SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }
@@ -355,18 +355,18 @@
                $app->system->chmod($key_file, 0400);
                $app->system->chown($key_file, 'metronome');
            } else {
                $ssl_key = $app->db->quote($app->system->file_get_contents($key_file));
                $ssl_key = $app->system->file_get_contents($key_file);
                /* Update the DB of the (local) Server */
                $app->db->query("UPDATE xmpp_domain SET ssl_key = '$ssl_key' WHERE domain = '".$data['new']['domain']."'");
                $app->db->query("UPDATE xmpp_domain SET ssl_key = ? WHERE domain = ?", $ssl_key, $data['new']['domain']);
                /* Update also the master-DB of the Server-Farm */
                $app->dbmaster->query("UPDATE xmpp_domain SET ssl_key = '$ssl_key' WHERE domain = '".$data['new']['domain']."'");
                $app->dbmaster->query("UPDATE xmpp_domain SET ssl_key = '$ssl_key' WHERE domain = ?", $data['new']['domain']);
            }
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            $app->log('Saving XMPP SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }
@@ -382,11 +382,11 @@
            $app->system->unlink($key_file.'.bak');
            $app->system->unlink($cnf_file.'.bak');
            /* Update the DB of the (local) Server */
            $app->db->query("UPDATE xmpp_domain SET ssl_request = '', ssl_cert = '', ssl_key = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->db->query("UPDATE xmpp_domain SET ssl_request = '', ssl_cert = '', ssl_key = '' WHERE domain = ?", $data['new']['domain']);
            $app->db->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            /* Update also the master-DB of the Server-Farm */
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_request = '', ssl_cert = '', ssl_key = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = '".$data['new']['domain']."'");
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_request = '', ssl_cert = '', ssl_key = '' WHERE domain = ?", $data['new']['domain']);
            $app->dbmaster->query("UPDATE xmpp_domain SET ssl_action = '' WHERE domain = ?", $data['new']['domain']);
            $app->log('Deleting SSL Cert for: '.$domain, LOGLEVEL_DEBUG);
        }