try migrating to pdo

pull/231/head
David Goodwin 6 years ago
parent eb61141d2f
commit ea33d9951a

@ -268,11 +268,13 @@ function check_domain($domain) {
*/ */
function get_password_expiration_value($domain) { function get_password_expiration_value($domain) {
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$domain = escape_string($domain); $query = "SELECT password_expiry FROM $table_domain WHERE domain= :domain";
$query = "SELECT password_expiry FROM $table_domain WHERE domain='$domain'";
$result = db_query($query); $result = db_prepared_fetch_one($query, array('domain' => $domain));
$password_expiration_value = db_assoc($result['result']); if(is_array($result) && isset($result['password_expiry'])) {
return $password_expiration_value['password_expiry']; return $result['password_expiry'];
}
return null;
} }
/** /**
@ -531,12 +533,10 @@ function create_page_browser($idxfield, $querypart) {
# get number of rows # get number of rows
$query = "SELECT count(*) as counter FROM (SELECT $idxfield $querypart) AS tmp"; $query = "SELECT count(*) as counter FROM (SELECT $idxfield $querypart) AS tmp";
$result = db_query($query); $result = db_prepared_fetch_one($query);
if ($result['rows'] > 0) { if ($result && isset($result['counter'])) {
$row = db_assoc($result['result']); $count_results = $result['counter'] -1; # we start counting at 0, not 1
$count_results = $row['counter'] -1; # we start counting at 0, not 1
} }
# echo "<p>rows: " . ($count_results +1) . " --- $query";
if ($count_results < $page_size) { if ($count_results < $page_size) {
return array(); # only one page - no pagebrowser required return array(); # only one page - no pagebrowser required
@ -583,16 +583,17 @@ function create_page_browser($idxfield, $querypart) {
# afterwards: DROP SEQUENCE foo # afterwards: DROP SEQUENCE foo
$result = db_query($query); $result = db_query($query);
if ($result['rows'] > 0) { $result = db_prepared_fetch_all($query);
while ($row = db_assoc($result['result'])) { foreach($result as $k => $row) {
if ($row2 = db_assoc($result['result'])) { if(isset($result[$k + 1])) {
$row2 = $result[$k + 1];
$label = substr($row['label'], 0, $label_len) . '-' . substr($row2['label'], 0, $label_len); $label = substr($row['label'], 0, $label_len) . '-' . substr($row2['label'], 0, $label_len);
$pagebrowser[] = $label;
} else { # only one row remaining
$label = substr($row['label'], 0, $label_len);
$pagebrowser[] = $label;
} }
else {
$label = substr($row['label'], 0, $label_len);
} }
$pagebrowser[] = $label;
} }
if (db_pgsql()) { if (db_pgsql()) {
@ -625,15 +626,17 @@ function divide_quota($quota) {
*/ */
function check_owner($username, $domain) { function check_owner($username, $domain) {
$table_domain_admins = table_by_key('domain_admins'); $table_domain_admins = table_by_key('domain_admins');
$E_username = escape_string($username);
$E_domain = escape_string($domain);
$result = db_query("SELECT 1 FROM $table_domain_admins WHERE username='$E_username' AND (domain='$E_domain' OR domain='ALL') AND active='1'");
if ($result['rows'] == 1 || $result['rows'] == 2) { # "ALL" + specific domain permissions is possible $result = db_prepared_fetch_all(
"SELECT 1 FROM $table_domain_admins WHERE username= ? AND (domain = ? OR domain = 'ALL') AND active = ?" ,
array($username, $domain, db_get_boolean(true))
);
if(sizeof($result) == 1 || sizeof($result) == 2) { # "ALL" + specific domain permissions is possible
# TODO: if superadmin, check if given domain exists in the database # TODO: if superadmin, check if given domain exists in the database
return true; return true;
} else { } else {
if ($result['rows'] > 2) { # more than 2 results means something really strange happened... if (sizeof($result) > 2) { # more than 2 results means something really strange happened...
flash_error("Permission check returned multiple results. Please go to 'edit admin' for your username and press the save " flash_error("Permission check returned multiple results. Please go to 'edit admin' for your username and press the save "
. "button once to fix the database. If this doesn't help, open a bugreport."); . "button once to fix the database. If this doesn't help, open a bugreport.");
} }
@ -649,6 +652,7 @@ function check_owner($username, $domain) {
* @return array of domain names. * @return array of domain names.
*/ */
function list_domains_for_admin($username) { function list_domains_for_admin($username) {
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$table_domain_admins = table_by_key('domain_admins'); $table_domain_admins = table_by_key('domain_admins');
@ -659,29 +663,39 @@ function list_domains_for_admin($username) {
$query = "SELECT $table_domain.domain FROM $table_domain "; $query = "SELECT $table_domain.domain FROM $table_domain ";
$condition[] = "$table_domain.domain != 'ALL'"; $condition[] = "$table_domain.domain != 'ALL'";
$result = db_query("SELECT username FROM $table_domain_admins WHERE username='$E_username' AND domain='ALL'"); $pvalues = array();
if ($result['rows'] < 1) { # not a superadmin
$result = db_prepared_fetch_one("SELECT username FROM $table_domain_admins WHERE username= :username AND domain='ALL'", array('username' => $username));
if (empty($result)) { # not a superadmin
$pvalues['username'] = $username;
$pvalues['active'] = db_get_boolean(true);
$pvalues['backupmx'] = db_get_boolean(false);
$query .= " LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain "; $query .= " LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain ";
$condition[] = "$table_domain_admins.username='$E_username' "; $condition[] = "$table_domain_admins.username = :username ";
$condition[] = "$table_domain.active='" . db_get_boolean(true) . "'"; # TODO: does it really make sense to exclude inactive... $condition[] = "$table_domain.active = :active "; # TODO: does it really make sense to exclude inactive...
$condition[] = "$table_domain.backupmx='" . db_get_boolean(false) . "'"; # TODO: ... and backupmx domains for non-superadmins? $condition[] = "$table_domain.backupmx = :backupmx" ; # TODO: ... and backupmx domains for non-superadmins?
} }
$query .= " WHERE " . join(' AND ', $condition); $query .= " WHERE " . join(' AND ', $condition);
$query .= " ORDER BY $table_domain.domain"; $query .= " ORDER BY $table_domain.domain";
$list = array(); $result = db_prepared_fetch_all($query, $pvalues);
$result = db_query($query);
if ($result['rows'] > 0) { return array_column($result, 'domain');
$i = 0;
while ($row = db_assoc($result['result'])) {
$list[$i] = $row['domain'];
$i++;
} }
if(!function_exists('array_column')) {
function array_column(array $array, $column) {
$retval = array();
foreach($array as $row) {
$retval[] = $row[$column];
}
return $retval;
} }
return $list;
} }
/** /**
* List all available domains. * List all available domains.
@ -692,16 +706,12 @@ function list_domains() {
$list = array(); $list = array();
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$result = db_query("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain"); $result = db_prepared_fetch_all("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain");
if ($result['rows'] > 0) {
$i = 0; $i = 0;
while ($row = db_assoc($result['result'])) { foreach($result as $row) {
if (is_array($row)) {
$list[$i] = $row['domain']; $list[$i] = $row['domain'];
$i++; $i++;
} }
}
}
return $list; return $list;
} }
@ -929,14 +939,13 @@ function _pacrypt_mysql_encrypt($pw, $pw_db) {
// this is apparently useful for pam_mysql etc. // this is apparently useful for pam_mysql etc.
$pw = escape_string($pw); $pw = escape_string($pw);
if ($pw_db!="") { if ($pw_db!="") {
$salt=escape_string(substr($pw_db, 0, 2)); $values = array('pw' => $pw_db, 'salt' => substr($pw_db, 0, 2));
$res=db_query("SELECT ENCRYPT('".$pw."','".$salt."');"); $res = db_prepared_fetch_one("SELECT ENCRYPT(:pw,:salt) as result", $values);
} else { } else {
$res=db_query("SELECT ENCRYPT('".$pw."');"); $res= db_prepared_fetch_one("SELECT ENCRYPT(:pw) as result", array('pw' => $pw));
} }
$l = db_row($res["result"]);
$password = $l[0]; return $res['result'];
return $password;
} }
function _pacrypt_authlib($pw, $pw_db) { function _pacrypt_authlib($pw, $pw_db) {
@ -1460,7 +1469,7 @@ EOF;
* array($link, $error_text); * array($link, $error_text);
* *
* @param bool $ignore_errors * @param bool $ignore_errors
* @return resource|mysqli|SQLite3 connection to db * @return PDO
*/ */
function db_connect() { function db_connect() {
list($link, $_) = db_connect_with_errors(); list($link, $_) = db_connect_with_errors();
@ -1485,70 +1494,42 @@ function db_connect_with_errors() {
} }
$link = 0; $link = 0;
if ($CONF['database_type'] == "mysql") { $options = [
if (function_exists("mysql_connect")) { PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
$link = @mysql_connect($CONF['database_host'], $CONF['database_user'], $CONF['database_password']) or $error_text .= ("<p />DEBUG INFORMATION:<br />Connect: " . mysql_error() . "$DEBUG_TEXT"); ];
if ($link) { $username_password = true;
@mysql_query("SET CHARACTER SET utf8", $link);
@mysql_query("SET COLLATION_CONNECTION='utf8_general_ci'", $link); if (db_mysql()) {
@mysql_select_db($CONF['database_name'], $link) or $error_text .= ("<p />DEBUG INFORMATION:<br />MySQL Select Database: " . mysql_error() . "$DEBUG_TEXT"); $dsn = "mysql:host={$CONF['database_host']};dbname={$CONF['database_name']};charset=UTF8";
} if (Config::bool('database_use_ssl')) {
} else { $options[PDO::MYSQL_ATTR_SSL_CA] = Config::read_string('database_ssl_ca');
$error_text .= "<p>DEBUG INFORMATION:<br />MySQL 3.x / 4.0 functions not available! (php5-mysql installed?)<br />database_type = 'mysql' in config.inc.php, are you using a different database? $DEBUG_TEXT"; $options[PDO::MYSQL_ATTR_SSL_CAPATH] = Config::read_string('database_ssl_ca_path');
} $options[PDO::MYSQL_ATTR_SSL_CERT] = Config::read_string('database_ssl_cert');
} elseif ($CONF['database_type'] == "mysqli") { $options[PDO::MYSQL_ATTR_SSL_CIPHER] = Config::read_string('database_ssl_cipher');
$is_connected = false; }
if ($CONF['database_use_ssl']) { $queries[] = 'SET CHARACTER SET utf8';
if (function_exists("mysqli_real_connect")) { $queries[] = "SET COLLATION_CONNECTION='utf8_general_ci'";
$link = mysqli_init(); }
$link->ssl_set($CONF['database_ssl_key'], $CONF['database_ssl_cert'], $CONF['database_ssl_ca'], $CONF['database_ssl_ca_path'], $CONF['database_ssl_cipher']); elseif (db_sqlite()) {
$connected = mysqli_real_connect($link, $CONF['database_host'], $CONF['database_user'], $CONF['database_password'], $CONF['database_name'], $CONF['database_port']); $dsn = "sqlite:{$CONF['database_name']}";
$is_connected = $connected; $username_password = false;
} else {
$error_text .= "<p>DEBUG INFORMATION:<br />MySQLi 5 functions not available! (php5-mysqli installed?)<br />database_type = 'mysqli' in config.inc.php, are you using a different database? $DEBUG_TEXT";
}
} else {
if (function_exists("mysqli_connect")) {
$link = @mysqli_connect($CONF['database_host'], $CONF['database_user'], $CONF['database_password'], $CONF['database_name'], $CONF['database_port'], $CONF['database_socket']) or $error_text .= ("<p />DEBUG INFORMATION:<br />Connect: " . mysqli_connect_error() . "$DEBUG_TEXT");
$is_connected = $link;
} else {
$error_text .= "<p>DEBUG INFORMATION:<br />MySQL 4.1 functions not available! (php5-mysqli installed?)<br />database_type = 'mysqli' in config.inc.php, are you using a different database? $DEBUG_TEXT";
}
}
if ($is_connected && $link instanceof mysqli) {
@mysqli_query($link, "SET CHARACTER SET utf8");
@mysqli_query($link, "SET COLLATION_CONNECTION='utf8_general_ci'");
}
} elseif (db_sqlite()) {
if (class_exists("SQLite3")) {
if ($CONF['database_name'] == '' || !is_dir(dirname($CONF['database_name'])) || !is_writable(dirname($CONF['database_name']))) {
$error_text .= ("<p>DEBUG INFORMATION<br />Connect: given database path does not exist, is not writable, or \$CONF['database_name'] is empty.");
} else {
$link = new SQLite3($CONF['database_name']) or $error_text .= ("<p />DEBUG INFORMATION<br />Connect: failed to connect to database. $DEBUG_TEXT");
if ($link instanceof SQLite3) {
$link->createFunction('base64_decode', 'base64_decode');
}
}
} else {
$error_text .= "<p>DEBUG INFORMATION:<br />SQLite functions not available! (php5-sqlite installed?)<br />database_type = 'sqlite' in config.inc.php, are you using a different database? $DEBUG_TEXT";
}
} elseif (db_pgsql()) { } elseif (db_pgsql()) {
if (function_exists("pg_pconnect")) {
if (!isset($CONF['database_port'])) { if (!isset($CONF['database_port'])) {
$CONF['database_port'] = '5432'; $CONF['database_port'] = '5432';
} }
$connect_string = "host=" . $CONF['database_host'] . " port=" . $CONF['database_port'] . " dbname=" . $CONF['database_name'] . " user=" . $CONF['database_user'] . " password=" . $CONF['database_password']; $dsn = "pgsql:host={$CONF['database_host']};port={$CONF['database_port']};dbname={$CONF['database_name']};charset=UTF8";
$link = @pg_pconnect($connect_string) or $error_text .= ("<p>DEBUG INFORMATION:<br />Connect: failed to connect to database. $DEBUG_TEXT");
if ($link) {
pg_set_client_encoding($link, 'UNICODE');
}
} else {
$error_text .= "<p>DEBUG INFORMATION:<br />PostgreSQL functions not available! (php5-pgsql installed?)<br />database_type = 'pgsql' in config.inc.php, are you using a different database? $DEBUG_TEXT";
}
} else { } else {
$error_text = "<p>DEBUG INFORMATION:<br />Invalid \$CONF['database_type']! Please fix your config.inc.php! $DEBUG_TEXT"; $error_text = "<p>DEBUG INFORMATION:<br />Invalid \$CONF['database_type']! Please fix your config.inc.php! $DEBUG_TEXT";
} }
if($username_password) {
$link = new PDO($dsn, Config::read_string('database_user'), Config::read_string('database_pass'), $options);
}
else {
$link = new PDO($dsn, null, null, $options);
}
return array($link, $error_text); return array($link, $error_text);
} }
@ -1650,147 +1631,97 @@ function db_sqlite() {
} }
/** /**
* @param string $query SQL to execute * @param string $sql
* @param int $ignore_errors (default 0 aka do not ignore errors) * @param array $values
* @return array ['result' => resource, 'rows' => int ,'error' => string] * @return array
*/ */
function db_query($query, $ignore_errors = 0) { function db_prepared_fetch_all($sql, array $values = array()) {
global $CONF; $r = db_prepared_query($sql, $values);
global $DEBUG_TEXT; return $r['result']->fetchAll(PDO::FETCH_ASSOC);
$result = "";
$number_rows = "";
$link = db_connect();
$error_text = "";
if ($ignore_errors) {
$DEBUG_TEXT = "";
} }
if ($CONF['database_type'] == "mysql" && is_resource($link)) { /**
$result = @mysql_query($query, $link) or $error_text = "Invalid query: " . mysql_error($link); * @param string $sql
} * @param array $values
if ($CONF['database_type'] == "mysqli" && $link instanceof mysqli) { * @return array
$result = @mysqli_query($link, $query) or $error_text = "Invalid query: " . mysqli_error($link); */
} function db_prepared_fetch_one($sql, array $values = array()) {
if (db_sqlite() && $link instanceof SQLite3) { $r = db_prepared_query($sql, $values);
$result = @$link->query($query) or $error_text = "Invalid query: " . $link->lastErrorMsg(); return $r['result']->fetch(PDO::FETCH_ASSOC);
} }
if (db_pgsql() && is_resource($link)) {
/* @var resource $link */
$result = @pg_query($link, $query) or $error_text = "Invalid query: " . pg_last_error(); function db_prepared_insert($sql, array $values = array()) {
$link = db_connect();
$error_text = '';
try {
$stmt = $link->prepare($sql);
$stmt->execute($values);
} }
if ($error_text != "" && $ignore_errors == 0) { catch(PDOException $e) {
$error_text = "Invalid query: " . $e->getMessage() . " caused by " . $sql ;
error_log($error_text); error_log($error_text);
error_log("caused by query: $query");
die("<p>DEBUG INFORMATION:<br />$error_text <p>Check your error_log for the failed query. $DEBUG_TEXT");
}
if ($error_text == "") {
if (db_sqlite() && $result instanceof SQLite3Result && $link instanceof SQLite3) {
/* @var SQLite3Result $result */
/* @var SQLite3 $link */
if ($result->numColumns()) {
// Query returned something
$num_rows = 0;
while (@$result->fetchArray(SQLITE3_ASSOC)) {
$num_rows++;
}
$result->reset();
$number_rows = $num_rows;
} else {
// Query was UPDATE, DELETE or INSERT
$number_rows = $link->changes();
}
} elseif (preg_match("/^SELECT/i", trim($query))) {
/* @var resource $result */
// if $query was a SELECT statement check the number of rows with [database_type]_num_rows ().
if ($CONF['database_type'] == "mysql" && is_resource($result)) {
$number_rows = mysql_num_rows($result);
} }
if ($CONF['database_type'] == "mysqli" && $result instanceof mysqli_result) { return $stmt->rowCount();
$number_rows = mysqli_num_rows($result);
} }
if (db_pgsql() && is_resource($result)) {
$number_rows = pg_num_rows($result); /**
} * @param string $sql
} else { * @param array $values
/* @var resource $result */ * @param bool $ignore_errors - set to true to ignore errors.
// if $query was something else, UPDATE, DELETE or INSERT check the number of rows with * @return array e.g. ['result' => PDOStatement, 'error' => string ]
// [database_type]_affected_rows (). */
if ($CONF['database_type'] == "mysql" && is_resource($link)) { function db_prepared_query($sql, array $values = array(), $ignore_errors = false) {
$number_rows = mysql_affected_rows($link);
} $link = db_connect();
if ($CONF['database_type'] == "mysqli" && $link instanceof mysqli) { $error_text = '';
$number_rows = mysqli_affected_rows($link);
} try {
if (db_pgsql() && is_resource($result)) { $stmt = $link->prepare($sql);
$number_rows = pg_affected_rows($result); $stmt->execute($values);
} }
catch(PDOException $e) {
$error_text = "Invalid query: " . $e->getMessage() . " caused by " . $sql ;
error_log($error_text);
if(!$ignore_errors) {
die("DEBUG INFORMATION: " . $e->getMessage() . "<br/> Check your error_log for the failed query");
} }
} }
$return = array(
"result" => $result, return array(
"rows" => $number_rows, "result" => $stmt,
"error" => $error_text "error" => $error_text,
); );
return $return;
} }
/**
* @param string $query SQL to execute
* @param int $ignore_errors (default 0 aka do not ignore errors)
* @return array ['result' => resource, 'rows' => int ,'error' => string]
*/
function db_query($query, $ignore_errors = 0)
{
return db_prepared_query($query, array(), $ignore_errors == 0);
}
// db_row // db_row
// Action: Returns a row from a table // Action: Returns a row from a table
// Call: db_row (int result) // Call: db_row (int result)
/**
* Returns numerically indexed array.
*
* @param resource|mysqli_result|SQLite3Result $result
* @return array
*/
function db_row($result) {
global $CONF;
$row = "";
if ($CONF['database_type'] == "mysql" && is_resource($result)) {
$row = mysql_fetch_row($result);
}
if ($CONF['database_type'] == "mysqli" && $result instanceof mysqli_result) {
$row = mysqli_fetch_row($result);
}
if (db_sqlite() && $result instanceof SQLite3Result) {
$row = $result->fetchArray(SQLITE3_NUM);
}
if (db_pgsql() && is_resource($result)) {
$row = pg_fetch_row($result);
}
if (!is_array($row)) {
return array();
}
return $row;
}
/** /**
* Get an associative array from a DB query resource. * Get an associative array from a DB query resource.
* *
* @param mixed $result - either resource or SQLite3Result depending on DB type chosen. * @param PDOStatement $result
* @return array * @return array
*/ */
function db_assoc($result) { function db_assoc(PDOStatement $result) {
global $CONF;
$row = []; $row = $result->fetch(PDO::FETCH_ASSOC);
if ($CONF['database_type'] == "mysql" && is_resource($result)) {
$row = mysql_fetch_assoc($result);
}
if ($CONF['database_type'] == "mysqli" && $result instanceof mysqli_result) {
$row = mysqli_fetch_assoc($result);
}
if (db_sqlite() && $result instanceof SQLite3Result) {
$row = $result->fetchArray(SQLITE3_ASSOC);
}
if (db_pgsql() && is_resource($result)) {
$row = pg_fetch_assoc($result);
}
if (!is_array($row)) { if (!is_array($row)) {
$row = []; $row = [];
} }
@ -1812,17 +1743,14 @@ function db_assoc($result) {
function db_delete($table, $where, $delete, $additionalwhere='') { function db_delete($table, $where, $delete, $additionalwhere='') {
$table = table_by_key($table); $table = table_by_key($table);
$query = "DELETE FROM $table WHERE $where ='" . escape_string($delete) . "' " . $additionalwhere; $query = "DELETE FROM $table WHERE $where = ? $additionalwhere";
$result = db_query($query);
return db_prepared_insert($query, [$delete]);
if ($result['rows'] >= 1) {
return $result['rows'];
} else {
return 0;
}
} }
/** /**
* db_insert * db_insert
* Action: Inserts a row from a specified table * Action: Inserts a row from a specified table
@ -1836,10 +1764,6 @@ function db_delete($table, $where, $delete, $additionalwhere='') {
function db_insert($table, array $values, $timestamp = array('created', 'modified')) { function db_insert($table, array $values, $timestamp = array('created', 'modified')) {
$table = table_by_key($table); $table = table_by_key($table);
foreach (array_keys($values) as $key) {
$values[$key] = "'" . escape_string($values[$key]) . "'";
}
foreach ($timestamp as $key) { foreach ($timestamp as $key) {
if (db_sqlite()) { if (db_sqlite()) {
$values[$key] = "datetime('now')"; $values[$key] = "datetime('now')";
@ -1866,9 +1790,27 @@ function db_insert($table, array $values, $timestamp = array('created', 'modifie
} }
} }
$sql_values = "(" . implode(",", array_keys($values)) .") VALUES (". implode(",", $values).")";
$result = db_query("INSERT INTO $table $sql_values"); $value_string = '';
return $result['rows']; $comma = '';
$prepared_statment_values = $values;
foreach($values as $field => $value) {
if(in_array($field, $timestamp)) {
$value_string .= $comma . $value; // see above.
unset($prepared_statment_values[$field]);
}
else {
$value_string .= $comma . ":{$field}";
}
$comma = ',';
}
return db_prepared_insert(
"INSERT INTO $table (" . implode(",", array_keys($values)) .") VALUES ($value_string)",
$prepared_statment_values);
} }
@ -1884,57 +1826,48 @@ function db_insert($table, array $values, $timestamp = array('created', 'modifie
* @return int - number of updated rows * @return int - number of updated rows
*/ */
function db_update($table, $where_col, $where_value, $values, $timestamp = array('modified')) { function db_update($table, $where_col, $where_value, $values, $timestamp = array('modified')) {
$where = $where_col . " = '" . escape_string($where_value) . "'";
return db_update_q($table, $where, $values, $timestamp);
}
/**
* db_update_q
* Action: Updates a specified table
* Call: db_update_q (string table, string where, array values [, array timestamp])
* @param string $table - table name
* @param string $where - WHERE condition (as SQL)
* @param array $values - key/value map of data to insert into the table.
* @param array $timestamp (optional) - array of fields to set to now() - default: array('modified')
* @return int - number of updated rows
*/
function db_update_q($table, $where, $values, $timestamp = array('modified')) {
global $CONF;
$table_key = table_by_key($table); $table_key = table_by_key($table);
$sql_values = array(); $sql_values = array();
foreach ($values as $key => $value) { $sql = "UPDATE $table_key SET ";
$sql_values[$key] = $key . "='" . escape_string($value) . "'";
}
foreach ($timestamp as $key) { $set = array();
foreach ($values as $key => $value) {
if(in_array($key, $timestamp)) {
if(db_sqlite()) { if(db_sqlite()) {
$sql_values[$key] = escape_string($key) . "=datetime('now')"; $set[] = " $key = datetime('now') ";
} else { }
$sql_values[$key] = escape_string($key) . "=now()"; else {
$set[] = " $key = now() ";
} }
} }
else {
$set[] = " $key = :$key ";
$pvalues[$key] = $value;
}
}
/* @todo this needs refactoring/moving out from here */ /* @todo this needs refactoring/moving out from here */
if (Config::bool('password_expiration')) { if (Config::bool('password_expiration')) {
if ($table == 'mailbox' && preg_match('/@/', $where)) { if ($table == 'mailbox' && preg_match('/@/', $where_value)) {
$where_type = explode('=', $where); $email = $where_value;
$email = ($where_type[1]);
$domain_dirty = explode('@',$email)[1]; $domain_dirty = explode('@',$email)[1];
$domain = substr($domain_dirty, 0, -1); $domain = substr($domain_dirty, 0, -1);
$password_expiration_value = get_password_expiration_value($domain); $password_expiration_value = get_password_expiration_value($domain);
$key = 'password_expiry'; $key = 'password_expiry';
$sql_values[$key] = $key . " = now() + interval " . $password_expiration_value . " day"; $set[] = " $key = now() + interval {$password_expiration_value} day";
} }
} }
$sql="UPDATE $table_key SET " . implode(",", $sql_values) . " WHERE $where"; $pvalues['where'] = $where_value;
$result = db_query($sql);
if (array_key_exists('rows', $result)) {
return $result['rows']; $sql="UPDATE $table_key SET " . implode(",", $set) . " WHERE $where_col = :where";
}
return 0; return db_prepared_insert($sql, $pvalues);
} }
@ -2105,16 +2038,12 @@ function check_db_version($error_out = true) {
$table = table_by_key('config'); $table = table_by_key('config');
$sql = "SELECT value FROM $table WHERE name = 'version'"; $sql = "SELECT value FROM $table WHERE name = 'version'";
$r = db_query($sql); $row = db_prepared_fetch_one($sql);
$dbversion = 0;
if ($r['rows'] == 1) {
$row = db_assoc($r['result']);
if (isset($row['value'])) { if (isset($row['value'])) {
$dbversion = (int) $row['value']; $dbversion = (int) $row['value'];
} }
} else { else {
db_query("INSERT INTO $table (name, value) VALUES ('version', '0')", 0); db_query("INSERT INTO $table (name, value) VALUES ('version', '0')", 0);
} }
@ -2141,13 +2070,11 @@ function gen_show_status($show_alias) {
$table_alias = table_by_key('alias'); $table_alias = table_by_key('alias');
$stat_string = ""; $stat_string = "";
$show_alias = escape_string($show_alias);
$stat_goto = ""; $stat_goto = "";
$stat_result = db_query("SELECT goto FROM $table_alias WHERE address='$show_alias'"); $stat_result = db_prepared_fetch_all("SELECT goto FROM $table_alias WHERE address=?", [$show_alias]);
if ($stat_result['rows'] > 0) {
$row = db_row($stat_result['result']); if (sizeof($stat_result) > 0) {
$stat_goto = $row[0]; $stat_goto = $stat_result[0]['goto'];
} }
$delimiter_regex = null; $delimiter_regex = null;
@ -2175,11 +2102,21 @@ function gen_show_status($show_alias) {
list($local_part, $stat_domain) = explode('@', $g); list($local_part, $stat_domain) = explode('@', $g);
$v = array();
$stat_delimiter = ""; $stat_delimiter = "";
$sql = "SELECT address FROM $table_alias WHERE address = ? OR address = ?";
$v[] = $g;
$v[] = '@' . $stat_domain;
if (!empty($CONF['recipient_delimiter']) && isset($delimiter_regex)) { if (!empty($CONF['recipient_delimiter']) && isset($delimiter_regex)) {
$stat_delimiter = "OR address = '" . escape_string(preg_replace($delimiter_regex, "@", $g)) . "'"; $v[] = preg_replace($delimiter_regex, "@", $g);
$sql .= " OR address = ? ";
} }
$stat_result = db_query("SELECT address FROM $table_alias WHERE address = '" . escape_string($g) . "' OR address = '@" . escape_string($stat_domain) . "' $stat_delimiter");
$stat_result = db_prepared_query($sql, $v);
if (array_key_exists('rows', $stat_result) && $stat_result['rows'] == 0) { if (array_key_exists('rows', $stat_result) && $stat_result['rows'] == 0) {
$stat_ok = 0; $stat_ok = 0;
} }
@ -2198,7 +2135,7 @@ function gen_show_status($show_alias) {
// Vacation CHECK // Vacation CHECK
if ( $CONF['show_vacation'] == 'YES' ) { if ( $CONF['show_vacation'] == 'YES' ) {
$stat_result = db_query("SELECT * FROM ". $CONF['database_tables']['vacation'] ." WHERE email = '" . $show_alias . "' AND active = '" . db_get_boolean(true) . "'") ; $stat_result = db_prepared_query("SELECT * FROM ". $CONF['database_tables']['vacation'] ." WHERE email = ? AND active = ? ", array($show_alias, db_get_boolean(true) )) ;
if ($stat_result['rows'] == 1) { if ($stat_result['rows'] == 1) {
$stat_string .= "<span style='background-color:" . $CONF['show_vacation_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;"; $stat_string .= "<span style='background-color:" . $CONF['show_vacation_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
} else { } else {
@ -2208,7 +2145,10 @@ function gen_show_status($show_alias) {
// Disabled CHECK // Disabled CHECK
if ( $CONF['show_disabled'] == 'YES' ) { if ( $CONF['show_disabled'] == 'YES' ) {
$stat_result = db_query("SELECT * FROM ". $CONF['database_tables']['mailbox'] ." WHERE username = '" . $show_alias . "' AND active = '" . db_get_boolean(false) . "'"); $stat_result = db_prepared_query(
"SELECT * FROM ". $CONF['database_tables']['mailbox'] ." WHERE username = ? AND active = ?",
array($show_alias, db_get_boolean(false))
);
if ($stat_result['rows'] == 1) { if ($stat_result['rows'] == 1) {
$stat_string .= "<span style='background-color:" . $CONF['show_disabled_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;"; $stat_string .= "<span style='background-color:" . $CONF['show_disabled_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";
} else { } else {
@ -2223,7 +2163,7 @@ function gen_show_status($show_alias) {
$now = "datetime('now')"; $now = "datetime('now')";
} }
$stat_result = db_query("SELECT * FROM ". $CONF['database_tables']['mailbox'] ." WHERE username = '" . $show_alias . "' AND password_expiry <= $now AND active = '" . db_get_boolean(true) . "'"); $stat_result = db_prepared_query("SELECT * FROM ". $CONF['database_tables']['mailbox'] ." WHERE username = ? AND password_expiry <= ? AND active = ?", array( $show_alias , $now , db_get_boolean(true) ));
if ($stat_result['rows'] == 1) { if ($stat_result['rows'] == 1) {
$stat_string .= "<span style='background-color:" . $CONF['show_expired_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;"; $stat_string .= "<span style='background-color:" . $CONF['show_expired_color'] . "'>" . $CONF['show_status_text'] . "</span>&nbsp;";

@ -479,11 +479,11 @@ class MailboxHandler extends PFAHandler {
return false; return false;
} else { } else {
$table_mailbox = table_by_key('mailbox'); $table_mailbox = table_by_key('mailbox');
$query = "SELECT SUM(quota) FROM $table_mailbox WHERE domain = '" . escape_string($domain) . "'"; $query = "SELECT SUM(quota) as sum FROM $table_mailbox WHERE domain = ? AND username != ?";
$query .= " AND username != '" . escape_string($this->id) . "'";
$result = db_query($query); $rows = db_prepared_fetch_all($query, array($domain, $this->id));
$row = db_row($result['result']);
$cur_quota_total = divide_quota($row[0]); # convert to MB $cur_quota_total = divide_quota($rows[0]['sum']); # convert to MB
if (($quota + $cur_quota_total) > $limit['quota']) { if (($quota + $cur_quota_total) > $limit['quota']) {
$rval = false; $rval = false;
} else { } else {

@ -725,16 +725,12 @@ abstract class PFAHandler {
$query .= " LIMIT $limit OFFSET $offset "; $query .= " LIMIT $limit OFFSET $offset ";
} }
$result = db_query($query);
$db_result = array(); $db_result = array();
if ($result['rows'] != 0) {
while ($row = db_assoc($result['result'])) { $result = db_prepared_fetch_all($query);
if (is_array($row)) { foreach($result as $row) {
$db_result[$row[$this->id_field]] = $row; $db_result[$row[$this->id_field]] = $row;
} }
}
}
$db_result = $this->read_from_db_postprocess($db_result); $db_result = $this->read_from_db_postprocess($db_result);
return $db_result; return $db_result;
@ -818,18 +814,17 @@ abstract class PFAHandler {
* @return boolean true on successful login (i.e. password matches etc) * @return boolean true on successful login (i.e. password matches etc)
*/ */
public function login($username, $password) { public function login($username, $password) {
$username = escape_string($username);
$table = table_by_key($this->db_table); $table = table_by_key($this->db_table);
$active = db_get_boolean(true); $active = db_get_boolean(true);
$query = "SELECT password FROM $table WHERE " . $this->id_field . "='$username' AND active='$active'"; $query = "SELECT password FROM $table WHERE {$this->id_field} = :username AND active = :active";
$values = array('username' => $username, 'active' => $active);
$result = db_prepared_fetch_all($query,$values);
if (sizeof($result) == 1) {
$row = $result[0];
$result = db_query($query);
if ($result['rows'] == 1) {
$row = db_assoc($result['result']);
if (!is_array($row)) {
return false;
}
$crypt_password = pacrypt($password, $row['password']); $crypt_password = pacrypt($password, $row['password']);
if ($row['password'] == $crypt_password) { if ($row['password'] == $crypt_password) {
@ -866,19 +861,17 @@ abstract class PFAHandler {
* @return boolean true on success (i.e. code matches etc) * @return boolean true on success (i.e. code matches etc)
*/ */
public function checkPasswordRecoveryCode($username, $token) { public function checkPasswordRecoveryCode($username, $token) {
$username = escape_string($username);
$table = table_by_key($this->db_table); $table = table_by_key($this->db_table);
$active = db_get_boolean(true); $active = db_get_boolean(true);
$query = "SELECT token FROM $table WHERE " . $this->id_field . "='$username' AND token <> '' AND active='$active' AND NOW() < token_validity";
$result = db_query($query); $query = "SELECT token FROM $table WHERE {$this->id_field} = :username AND token <> '' AND active = :active AND NOW() < token_validity";
if ($result['rows'] == 1) { $values = array('username' => $username, 'active' => $active);
$row = db_assoc($result['result']);
$result = db_prepared_fetch_all($query, $values);
if(sizeof($result) == 1) {
$row = $result[0];
if (!is_array($row)) {
return false;
}
$crypt_token = pacrypt($token, $row['token']); $crypt_token = pacrypt($token, $row['token']);
if ($row['token'] == $crypt_token) { if ($row['token'] == $crypt_token) {

@ -186,16 +186,16 @@ class VacationHandler extends PFAHandler {
* will return false if no existing data * will return false if no existing data
*/ */
public function get_details() { public function get_details() {
$table_vacation = table_by_key('vacation'); $table_vacation = table_by_key('vacation');
$E_username = escape_string($this->username);
$sql = "SELECT * FROM $table_vacation WHERE email = '$E_username'"; $sql = "SELECT * FROM $table_vacation WHERE email = :username";
$result = db_query($sql); $result = db_prepared_fetch_all($sql, array('username' => $this->username));
if ($result['rows'] != 1) { if(sizeof($result) != 1) {
return false; return false;
} }
$row = db_assoc($result['result']); $row = $result[0];
if (!is_array($row)) { if (!is_array($row)) {
return false; return false;

@ -65,8 +65,11 @@ if ($_SERVER['REQUEST_METHOD'] == "GET") {
umask(077); umask(077);
$path = (ini_get('upload_tmp_dir') != '') ? ini_get('upload_tmp_dir') : '/tmp'; $path = (ini_get('upload_tmp_dir') != '') ? ini_get('upload_tmp_dir') : '/tmp';
date_default_timezone_set(@date_default_timezone_get()); # Suppress date.timezone warnings date_default_timezone_set(@date_default_timezone_get()); # Suppress date.timezone warnings
$filename = "postfixadmin-" . date("Ymd") . "-" . getmypid() . ".sql";
$backup = $path . DIRECTORY_SEPARATOR . $filename; // Should use mktemp() or similar.
$backup = tempnam($path, 'postfixadmin-' . date('Ymd'));
$filename = basename($backup) . '.sql';
$header = "#\n# Postfix Admin $version\n# Date: " . date("D M j G:i:s T Y") . "\n#\n"; $header = "#\n# Postfix Admin $version\n# Date: " . date("D M j G:i:s T Y") . "\n#\n";
@ -94,18 +97,19 @@ if ($_SERVER['REQUEST_METHOD'] == "GET") {
); );
for ($i = 0 ; $i < sizeof($tables) ; ++$i) { for ($i = 0 ; $i < sizeof($tables) ; ++$i) {
$result = db_query("SHOW CREATE TABLE " . table_by_key($tables[$i])); $result = db_prepared_fetch_all("SHOW CREATE TABLE " . table_by_key($tables[$i]));
if ($result['rows'] > 0) { foreach($result as $row) {
while ($row = db_row($result['result'])) { fwrite($fh, array_pop($row));
fwrite($fh, "{$row[1]};\n\n");
}
} }
} }
for ($i = 0 ; $i < sizeof($tables) ; ++$i) { for ($i = 0 ; $i < sizeof($tables) ; ++$i) {
$result = db_query("SELECT * FROM " . table_by_key($tables[$i])); // may be a large resultset?
if ($result['rows'] > 0) { $pdo = db_connect();
while ($row = db_assoc($result['result'])) { $stmt = $pdo->prepare('SELECT * FROM ' . table_by_key($tables[$i]));
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$fields = array_keys($row); $fields = array_keys($row);
$values = array_values($row); $values = array_values($row);
$values = array_map(function ($str) { $values = array_map(function ($str) {
@ -116,16 +120,16 @@ if ($_SERVER['REQUEST_METHOD'] == "GET") {
$fields = ""; $fields = "";
$values = ""; $values = "";
} }
}
} }
} }
header("Content-Type: text/plain"); header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"$filename\""); header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Transfer-Encoding: binary"); header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize("$backup")); header("Content-Length: " . filesize($backup));
header("Content-Description: Postfix Admin"); header("Content-Description: Postfix Admin");
$download_backup = fopen("$backup", "r"); $download_backup = fopen($backup, "r");
unlink("$backup"); unlink($backup);
fpassthru($download_backup); fpassthru($download_backup);
} }
/* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */ /* vim: set expandtab softtabstop=3 tabstop=3 shiftwidth=3: */

@ -63,14 +63,8 @@ if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (intval(safepost('mailboxes_only')) == 0) { if (intval(safepost('mailboxes_only')) == 0) {
$q .= " UNION SELECT goto FROM $table_alias WHERE active='" . db_get_boolean(true) . "' AND ".db_in_clause("domain", $wanted_domains)."AND goto NOT IN ($q)"; $q .= " UNION SELECT goto FROM $table_alias WHERE active='" . db_get_boolean(true) . "' AND ".db_in_clause("domain", $wanted_domains)."AND goto NOT IN ($q)";
} }
$result = db_query($q); $result = db_prepared_fetch_all($q);
if ($result['rows'] > 0) { $recipients = array_column($result, 'username');
while ($row = db_assoc($result['result'])) {
if (is_array($row)) {
$recipients[] = $row['username'];
}
}
}
$recipients = array_unique($recipients); $recipients = array_unique($recipients);

@ -220,18 +220,16 @@ if (Config::bool('used_quotas') && (! Config::bool('new_quota_table'))) {
$mailbox_pagebrowser_query = "$sql_from\n$sql_join\n$sql_where\n$sql_order" ; $mailbox_pagebrowser_query = "$sql_from\n$sql_join\n$sql_where\n$sql_order" ;
$query = "$sql_select\n$mailbox_pagebrowser_query\n$sql_limit"; $query = "$sql_select\n$mailbox_pagebrowser_query\n$sql_limit";
$result = db_query($query); $result = db_prepared_fetch_all($query);
$tMailbox = array(); $tMailbox = array();
if ($result['rows'] > 0) {
$delimiter = preg_quote($CONF['recipient_delimiter'], "/"); $delimiter = preg_quote($CONF['recipient_delimiter'], "/");
$goto_single_rec_del = ""; $goto_single_rec_del = "";
while ($row = db_assoc($result['result'])) { foreach($result as $row) {
if (!is_array($row)) {
continue;
}
if ($display_mailbox_aliases) { if ($display_mailbox_aliases) {
$goto_split = explode(",", $row['goto']); $goto_split = explode(",", $row['goto']);
$row['goto_mailbox'] = 0; $row['goto_mailbox'] = 0;
@ -266,7 +264,7 @@ if ($result['rows'] > 0) {
} }
$tMailbox[] = $row; $tMailbox[] = $row;
} }
}
$alias_data['msg']['can_create'] = false; $alias_data['msg']['can_create'] = false;
$tCanAddMailbox = false; $tCanAddMailbox = false;

@ -41,6 +41,7 @@ $f_mysql_connect = function_exists("mysql_connect");
$f_mysqli_connect = function_exists("mysqli_connect"); $f_mysqli_connect = function_exists("mysqli_connect");
$f_pg_connect = function_exists("pg_connect"); $f_pg_connect = function_exists("pg_connect");
$f_sqlite_open = class_exists("SQLite3"); $f_sqlite_open = class_exists("SQLite3");
$f_pdo = class_exists('PDO');
$f_session_start = function_exists("session_start"); $f_session_start = function_exists("session_start");
$f_preg_match = function_exists("preg_match"); $f_preg_match = function_exists("preg_match");
$f_mb_encode_mimeheader = function_exists("mb_encode_mimeheader"); $f_mb_encode_mimeheader = function_exists("mb_encode_mimeheader");
@ -302,8 +303,8 @@ if ($error != 0) {
if ($error == 0 && $pw_check_result == 'pass_OK') { if ($error == 0 && $pw_check_result == 'pass_OK') {
// XXX need to ensure domains table includes an 'ALL' entry. // XXX need to ensure domains table includes an 'ALL' entry.
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$r = db_query("SELECT * FROM $table_domain WHERE domain = 'ALL'"); $rows = db_prepared_fetch_all("SELECT * FROM $table_domain WHERE domain = 'ALL'");
if ($r['rows'] == 0) { if(empty($rows)) {
db_insert('domain', array('domain' => 'ALL', 'description' => '', 'transport' => '')); // all other fields should default through the schema. db_insert('domain', array('domain' => 'ALL', 'description' => '', 'transport' => '')); // all other fields should default through the schema.
} }

@ -13,18 +13,15 @@ if (!isset($CONF) || !is_array($CONF)) {
/** /**
* Use this to check whether an object (Table, index etc) exists within a * Use this to check whether an object (table, index etc) exists within a
* PostgreSQL database. * PostgreSQL database.
* @param string the object name * @param string the object name
* @return boolean true if it exists * @return boolean true if it exists
*/ */
function _pgsql_object_exists($name) { function _pgsql_object_exists($name) {
$sql = "select relname from pg_class where relname = '$name'"; $sql = "select relname from pg_class where relname = '$name'";
$r = db_query($sql); $r = db_prepared_fetch_one($sql);
if ($r['rows'] == 1) { return !empty($r);
return true;
}
return false;
} }
/** /**
@ -51,30 +48,24 @@ function _pgsql_field_exists($table, $field) {
AND pg_catalog.pg_table_is_visible(c.oid) AND pg_catalog.pg_table_is_visible(c.oid)
) )
AND a.attname = '$field' "; AND a.attname = '$field' ";
$r = db_query($sql); $r = db_prepared_fetch_all($sql);
$row = db_row($r['result']);
if ($row) { return !empty($r);
return true;
}
return false;
} }
function _mysql_field_exists($table, $field) { function _mysql_field_exists($table, $field) {
# $table = table_by_key($table); # _mysql_field_exists is always called with the expanded table name - don't expand it twice # $table = table_by_key($table); # _mysql_field_exists is always called with the expanded table name - don't expand it twice
$sql = "SHOW COLUMNS FROM $table LIKE '$field'"; $sql = "SHOW COLUMNS FROM $table LIKE ?";
$r = db_query($sql); $r = db_prepared_fetch_all($sql, array( $field));
$row = db_row($r['result']);
if ($row) { return !empty($r);
return true;
}
return false;
} }
function _sqlite_field_exists($table, $field) { function _sqlite_field_exists($table, $field) {
$sql = "PRAGMA table_info($table)"; $sql = "PRAGMA table_info($table)";
$r = db_query($sql); $r = db_prepared_fetch_all($sql);
while ($row = db_row($r['result'])) {
foreach($r as $row) {
if ($row[1] == $field) { if ($row[1] == $field) {
return true; return true;
} }
@ -128,8 +119,7 @@ function printdebug($text) {
$table = table_by_key('config'); $table = table_by_key('config');
if ($CONF['database_type'] == 'pgsql') { if ($CONF['database_type'] == 'pgsql') {
// check if table already exists, if so, don't recreate it // check if table already exists, if so, don't recreate it
$r = db_query("SELECT relname FROM pg_class WHERE relname = '$table'"); if(!_pgsql_object_exists($table)) {
if ($r['rows'] == 0) {
$pgsql = " $pgsql = "
CREATE TABLE $table ( CREATE TABLE $table (
id SERIAL, id SERIAL,
@ -1420,18 +1410,13 @@ function upgrade_1284_mysql_pgsql() {
# migrate the ALL domain to the superadmin column # migrate the ALL domain to the superadmin column
# Note: The ALL domain is not (yet) deleted to stay backwards-compatible for now (will be done in a later upgrade function) # Note: The ALL domain is not (yet) deleted to stay backwards-compatible for now (will be done in a later upgrade function)
$result = db_query("SELECT username FROM " . table_by_key('domain_admins') . " where domain='ALL'"); $result = db_prepared_fetch_all("SELECT username FROM " . table_by_key('domain_admins') . " where domain='ALL'");
if ($result['rows'] > 0) {
while ($row = db_assoc($result['result'])) {
if (!is_array($row)) {
break;
}
foreach($result as $row) {
printdebug("Setting superadmin flag for " . $row['username']); printdebug("Setting superadmin flag for " . $row['username']);
db_update('admin', 'username', $row['username'], array('superadmin' => db_get_boolean(true))); db_update('admin', 'username', $row['username'], array('superadmin' => db_get_boolean(true)));
} }
}
} }
function upgrade_1345_mysql() { function upgrade_1345_mysql() {

@ -57,18 +57,22 @@ function sendCodebySMS($to, $username, $code) {
if ($_SERVER['REQUEST_METHOD'] === "POST") { if ($_SERVER['REQUEST_METHOD'] === "POST") {
$start_time = microtime(true); $start_time = microtime(true);
$tUsername = escape_string(safepost('fUsername'));
if (empty($tUsername) || !is_string($tUsername)) { $username = safepost('fUsername', null);
if (empty($sername) || !is_string($username)) {
die("fUsername field required"); die("fUsername field required");
} }
$tUsername = escape_string($username);
$handler = $context === 'admin' ? new AdminHandler : new MailboxHandler; $handler = $context === 'admin' ? new AdminHandler : new MailboxHandler;
$token = $handler->getPasswordRecoveryCode($tUsername); $token = $handler->getPasswordRecoveryCode($tUsername);
if ($token !== false) { if ($token !== false) {
$table = table_by_key($context === 'users' ? 'mailbox' : 'admin'); $table = table_by_key($context === 'users' ? 'mailbox' : 'admin');
$result = db_query("SELECT * FROM $table WHERE username='$tUsername'"); $row = db_prepared_fetch_one("SELECT * FROM $table WHERE username= :username", array('username' => $username));
$row = db_assoc($result['result']);
// $row must exist unless there's a race condition?
$email_other = isset($row['email_other']) ? trim($row['email_other']) : null; $email_other = isset($row['email_other']) ? trim($row['email_other']) : null;
$phone = isset($row['phone']) ? trim($row['phone']) : null; $phone = isset($row['phone']) ? trim($row['phone']) : null;

@ -61,20 +61,19 @@ if ($error != 1) {
$table_log = table_by_key('log'); $table_log = table_by_key('log');
$page_size = isset($CONF['page_size']) ? intval($CONF['page_size']) : 35; $page_size = isset($CONF['page_size']) ? intval($CONF['page_size']) : 35;
$query = "SELECT timestamp,username,domain,action,data FROM $table_log WHERE domain='$fDomain' ORDER BY timestamp DESC LIMIT $page_size"; $query = "SELECT timestamp,username,domain,action,data FROM $table_log WHERE domain= :domain ORDER BY timestamp DESC LIMIT $page_size";
if (db_pgsql()) { if (db_pgsql()) {
$query = "SELECT extract(epoch from timestamp) as timestamp,username,domain,action,data FROM $table_log WHERE domain='$fDomain' ORDER BY timestamp DESC LIMIT $page_size"; $query = "SELECT extract(epoch from timestamp) as timestamp,username,domain,action,data FROM $table_log WHERE domain= :domain ORDER BY timestamp DESC LIMIT $page_size";
} }
$result = db_query($query); $result = db_prepared_fetch_all($query, array('domain' => $fDomain));
if ($result['rows'] > 0) { foreach($result as $row) {
while ($row = db_assoc($result['result'])) {
if (is_array($row) && db_pgsql()) { if (is_array($row) && db_pgsql()) {
$row['timestamp'] = gmstrftime('%c %Z', $row['timestamp']); $row['timestamp'] = gmstrftime('%c %Z', $row['timestamp']);
} }
$tLog[] = $row; $tLog[] = $row;
} }
} }
}
foreach ($tLog as $k => $v) { foreach ($tLog as $k => $v) {
if (isset($v['action'])) { if (isset($v['action'])) {

@ -5,8 +5,7 @@ require_once('common.php');
class CheckOwnerTest extends \PHPUnit\Framework\TestCase { class CheckOwnerTest extends \PHPUnit\Framework\TestCase {
public function testBasic() { public function testBasic() {
$check = check_owner('random@example.com', 'test.com'); $check = check_owner('random@example.com', 'test.com');
$this->assertFalse($check, "there should be no entries in test.com as it's an invalid/non-existant domain");
$this->assertFalse($check);
} }
} }

@ -3,8 +3,20 @@
require_once('common.php'); require_once('common.php');
class DbBasicTest extends \PHPUnit\Framework\TestCase { class DbBasicTest extends \PHPUnit\Framework\TestCase {
private $test_domain;
public function setUp() {
$db = db_connect();
$test_domain = 'test' . uniqid() . '.com';
$this->test_domain = $test_domain;
$db->exec("DELETE FROM domain WHERE domain = '$test_domain'");
}
public function testInsertDeleteDomain() { public function testInsertDeleteDomain() {
$domain = "test". uniqid() . '.com';
$domain = $this->test_domain;
$username = 'testusername' . uniqid(); $username = 'testusername' . uniqid();
@ -12,7 +24,7 @@ class DbBasicTest extends \PHPUnit\Framework\TestCase {
1, 1,
db_insert( db_insert(
'domain', 'domain',
array('domain' => $domain, 'description' => '', 'transport' => '', 'password_expiry' => 99) array('domain' => $domain, 'description' => 'test', 'transport' => '', 'password_expiry' => 99)
) )
); );
@ -33,12 +45,16 @@ class DbBasicTest extends \PHPUnit\Framework\TestCase {
) )
); );
$ret = db_query("SELECT * FROM mailbox WHERE username = '$username'"); $ret = db_prepared_fetch_one("SELECT * FROM mailbox WHERE username = :username", array('username' => $username));
$this->assertTrue(!empty($ret));
$this->assertTrue(is_array($ret));
$this->assertEquals(1, $ret['rows']); $this->assertEquals($ret['name'], 'blah updated');
$data = db_assoc($ret['result']);
$this->assertEquals($data['name'], 'blah updated'); $this->assertEquals(0, db_delete('mailbox', 'username', 'blahblahinvalid'));
$this->assertEquals(1, db_delete('mailbox', 'username', $username)); $this->assertEquals(1, db_delete('mailbox', 'username', $username));
$this->assertEquals(1, db_delete('domain', 'domain', $domain)); $this->assertEquals(1, db_delete('domain', 'domain', $domain));

@ -10,7 +10,7 @@ require_once(dirname(__FILE__) . '/../common.php');
$CONF['default_language'] = 'en'; $CONF['default_language'] = 'en';
$CONF['language_hook'] = ''; $CONF['language_hook'] = '';
$db_file = '/tmp/postfixadmin.sqlite.test'; $db_file = dirname(__FILE__) . '/postfixadmin.sqlite.test';
$CONF['database_type'] = 'sqlite'; $CONF['database_type'] = 'sqlite';
$CONF['database_name'] = $db_file; $CONF['database_name'] = $db_file;
@ -18,9 +18,9 @@ Config::write('database_type', 'sqlite');
Config::write('database_name', $db_file); Config::write('database_name', $db_file);
clearstatcache(); clearstatcache();
if (file_exists($db_file)) { //if (file_exists($db_file)) {
unlink($db_file); // unlink($db_file);
} //}
require_once(dirname(__FILE__) . '/../public/upgrade.php'); require_once(dirname(__FILE__) . '/../public/upgrade.php');

Loading…
Cancel
Save