0
0
mirror of https://github.com/postfixadmin/postfixadmin.git synced 2024-09-19 19:22:14 +02:00

phpcs insists on some brace changes

This commit is contained in:
David Goodwin 2021-04-13 21:19:16 +01:00
parent bbec16aac1
commit 2edabc3e03
60 changed files with 926 additions and 466 deletions

View File

@ -13,9 +13,6 @@ return PhpCsFixer\Config::create()
->setFinder($finder) ->setFinder($finder)
->setRules(array( ->setRules(array(
'@PSR2' => true, '@PSR2' => true,
'braces' => array(
'position_after_functions_and_oop_constructs' => 'same',
),
'method_argument_space' => false, # don't break formatting in initStruct() 'method_argument_space' => false, # don't break formatting in initStruct()
'no_spaces_inside_parenthesis' => false, # don't break formatting in initStruct() 'no_spaces_inside_parenthesis' => false, # don't break formatting in initStruct()
)); ));

View File

@ -6,16 +6,19 @@
*/ */
function do_header() { function do_header()
{
global $color; global $color;
displayPageHeader($color, 'None'); displayPageHeader($color, 'None');
} }
function do_footer() { function do_footer()
{
echo "</body></html>"; echo "</body></html>";
} }
function _display_password_form() { function _display_password_form()
{
bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale'); bindtextdomain('postfixadmin', SM_PATH . 'plugins/postfixadmin/locale');
textdomain('postfixadmin'); textdomain('postfixadmin');
do_header('Postfixadmin Squirrelmail - Login'); do_header('Postfixadmin Squirrelmail - Login');
@ -31,7 +34,8 @@ function _display_password_form() {
/** /**
* This returns a Zend_XmlRpc_Client instance - unless we can't log you in... * This returns a Zend_XmlRpc_Client instance - unless we can't log you in...
*/ */
function get_xmlrpc() { function get_xmlrpc()
{
global $CONF; global $CONF;
require_once('Zend/XmlRpc/Client.php'); require_once('Zend/XmlRpc/Client.php');
$client = new Zend_XmlRpc_Client($CONF['xmlrpc_url']); $client = new Zend_XmlRpc_Client($CONF['xmlrpc_url']);
@ -73,7 +77,8 @@ function get_xmlrpc() {
return $client; return $client;
} }
function include_if_exists($filename) { function include_if_exists($filename)
{
if (file_exists($filename)) { if (file_exists($filename)) {
include_once($filename); include_once($filename);
} }
@ -87,7 +92,8 @@ $optmode = 'display';
// Action: Checks if email is valid and returns TRUE if this is the case. // Action: Checks if email is valid and returns TRUE if this is the case.
// Call: check_email (string email) // Call: check_email (string email)
// //
function check_email($email) { function check_email($email)
{
$return = filter_var($email, FILTER_VALIDATE_EMAIL); $return = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($return === false) { if ($return === false) {
return false; return false;

View File

@ -5,18 +5,21 @@ if (!defined('SM_PATH')) {
} }
include_once(SM_PATH . 'functions/i18n.php'); include_once(SM_PATH . 'functions/i18n.php');
function squirrelmail_plugin_init_postfixadmin() { function squirrelmail_plugin_init_postfixadmin()
{
include(dirname(__FILE__) . '/config.php'); include(dirname(__FILE__) . '/config.php');
global $squirrelmail_plugin_hooks; global $squirrelmail_plugin_hooks;
$squirrelmail_plugin_hooks['optpage_register_block']['postfixadmin'] = 'postfixadmin_optpage_register_block'; $squirrelmail_plugin_hooks['optpage_register_block']['postfixadmin'] = 'postfixadmin_optpage_register_block';
} }
function postfixadmin_version() { function postfixadmin_version()
{
return '2.3.0'; return '2.3.0';
} }
function postfixadmin_optpage_register_block() { function postfixadmin_optpage_register_block()
{
// Gets added to the user's OPTIONS page. // Gets added to the user's OPTIONS page.
global $optpage_blocks; global $optpage_blocks;
global $AllowVacation; global $AllowVacation;

View File

@ -46,7 +46,8 @@ if (! is_dir($homedir)) {
// //
// Recursive Delete Function // Recursive Delete Function
// //
function deldir($dir) { function deldir($dir)
{
$current_dir = opendir($dir); $current_dir = opendir($dir);
while ($entryname = readdir($current_dir)) { while ($entryname = readdir($current_dir)) {
if (is_dir("$dir/$entryname") and ($entryname != "." and $entryname!="..")) { if (is_dir("$dir/$entryname") and ($entryname != "." and $entryname!="..")) {

View File

@ -36,7 +36,8 @@ $incpath = dirname(__FILE__);
* @param string $class * @param string $class
* __autoload implementation, for use with spl_autoload_register(). * __autoload implementation, for use with spl_autoload_register().
*/ */
function postfixadmin_autoload($class) { function postfixadmin_autoload($class)
{
$PATH = dirname(__FILE__) . '/model/' . $class . '.php'; $PATH = dirname(__FILE__) . '/model/' . $class . '.php';
if (is_file($PATH)) { if (is_file($PATH)) {

View File

@ -23,7 +23,8 @@ $min_db_version = 1843; # update (at least) before a release with the latest fu
* Call: check_session () * Call: check_session ()
* @return String username (e.g. foo@example.com) * @return String username (e.g. foo@example.com)
*/ */
function authentication_get_username() { function authentication_get_username()
{
if (defined('POSTFIXADMIN_CLI')) { if (defined('POSTFIXADMIN_CLI')) {
return 'CLI'; return 'CLI';
} }
@ -45,7 +46,8 @@ function authentication_get_username() {
* Returns false if neither (E.g. if not logged in) * Returns false if neither (E.g. if not logged in)
* @return string|bool admin or user or (boolean) false. * @return string|bool admin or user or (boolean) false.
*/ */
function authentication_get_usertype() { function authentication_get_usertype()
{
if (isset($_SESSION['sessid'])) { if (isset($_SESSION['sessid'])) {
if (isset($_SESSION['sessid']['type'])) { if (isset($_SESSION['sessid']['type'])) {
return $_SESSION['sessid']['type']; return $_SESSION['sessid']['type'];
@ -60,7 +62,8 @@ function authentication_get_usertype() {
* @return boolean True if they have the requested role in their session. * @return boolean True if they have the requested role in their session.
* Note, user < admin < global-admin * Note, user < admin < global-admin
*/ */
function authentication_has_role($role) { function authentication_has_role($role)
{
if (isset($_SESSION['sessid'])) { if (isset($_SESSION['sessid'])) {
if (isset($_SESSION['sessid']['roles'])) { if (isset($_SESSION['sessid']['roles'])) {
if (in_array($role, $_SESSION['sessid']['roles'])) { if (in_array($role, $_SESSION['sessid']['roles'])) {
@ -80,7 +83,8 @@ function authentication_has_role($role) {
* @param string $role * @param string $role
* @return bool * @return bool
*/ */
function authentication_require_role($role) { function authentication_require_role($role)
{
// redirect to appropriate page? // redirect to appropriate page?
if (authentication_has_role($role)) { if (authentication_has_role($role)) {
return true; return true;
@ -97,7 +101,8 @@ function authentication_require_role($role) {
* @param boolean $is_admin true if the user is an admin, false otherwise * @param boolean $is_admin true if the user is an admin, false otherwise
* @return boolean true on success * @return boolean true on success
*/ */
function init_session($username, $is_admin = false) { function init_session($username, $is_admin = false)
{
$status = session_regenerate_id(true); $status = session_regenerate_id(true);
$_SESSION['sessid'] = array(); $_SESSION['sessid'] = array();
$_SESSION['sessid']['roles'] = array(); $_SESSION['sessid']['roles'] = array();
@ -116,7 +121,8 @@ function init_session($username, $is_admin = false) {
* @see _flash_string() * @see _flash_string()
* @return void * @return void
*/ */
function flash_error($string) { function flash_error($string)
{
_flash_string('error', $string); _flash_string('error', $string);
} }
@ -127,7 +133,8 @@ function flash_error($string) {
* @see _flash_string() * @see _flash_string()
* @return void * @return void
*/ */
function flash_info($string) { function flash_info($string)
{
_flash_string('info', $string); _flash_string('info', $string);
} }
/** /**
@ -136,7 +143,8 @@ function flash_info($string) {
* @param array|string $string * @param array|string $string
* @retrn void * @retrn void
*/ */
function _flash_string($type, $string) { function _flash_string($type, $string)
{
if (is_array($string)) { if (is_array($string)) {
foreach ($string as $singlestring) { foreach ($string as $singlestring) {
_flash_string($type, $singlestring); _flash_string($type, $singlestring);
@ -158,7 +166,8 @@ function _flash_string($type, $string) {
* @return string e.g en * @return string e.g en
* Try to figure out what language the user wants based on browser / cookie * Try to figure out what language the user wants based on browser / cookie
*/ */
function check_language($use_post = true) { function check_language($use_post = true)
{
global $supported_languages; # from languages/languages.php global $supported_languages; # from languages/languages.php
// prefer a $_POST['lang'] if present // prefer a $_POST['lang'] if present
@ -199,7 +208,8 @@ function check_language($use_post = true) {
* *
* *
*/ */
function language_selector() { function language_selector()
{
global $supported_languages; # from languages/languages.php global $supported_languages; # from languages/languages.php
$current_lang = check_language(); $current_lang = check_language();
@ -229,7 +239,8 @@ function language_selector() {
* @todo make check_domain able to handle as example .local domains * @todo make check_domain able to handle as example .local domains
* @todo skip DNS check if the domain exists in PostfixAdmin? * @todo skip DNS check if the domain exists in PostfixAdmin?
*/ */
function check_domain($domain) { function check_domain($domain)
{
if (!preg_match('/^([-0-9A-Z]+\.)+' . '([-0-9A-Z]){1,13}$/i', ($domain))) { if (!preg_match('/^([-0-9A-Z]+\.)+' . '([-0-9A-Z]){1,13}$/i', ($domain))) {
return sprintf(Config::lang('pInvalidDomainRegex'), htmlentities($domain)); return sprintf(Config::lang('pInvalidDomainRegex'), htmlentities($domain));
} }
@ -275,7 +286,8 @@ function check_domain($domain) {
* @param string $domain - a string that may be a domain * @param string $domain - a string that may be a domain
* @return int password expiration value for this domain (DAYS, or zero if not enabled) * @return int password expiration value for this domain (DAYS, or zero if not enabled)
*/ */
function get_password_expiration_value($domain) { function get_password_expiration_value($domain)
{
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$query = "SELECT password_expiry FROM $table_domain WHERE domain= :domain"; $query = "SELECT password_expiry FROM $table_domain WHERE domain= :domain";
@ -293,7 +305,8 @@ function get_password_expiration_value($domain) {
* @param string $email - a string that may be an email address. * @param string $email - a string that may be an email address.
* @return string empty if it's a valid email address, otherwise string with the errormessage * @return string empty if it's a valid email address, otherwise string with the errormessage
*/ */
function check_email($email) { function check_email($email)
{
$ce_email=$email; $ce_email=$email;
//strip the vacation domain out if we are using it //strip the vacation domain out if we are using it
@ -345,7 +358,8 @@ function check_email($email) {
* @param int|string $string_or_int parameters to escape * @param int|string $string_or_int parameters to escape
* @return string cleaned data, suitable for use within an SQL statement. * @return string cleaned data, suitable for use within an SQL statement.
*/ */
function escape_string($string_or_int) { function escape_string($string_or_int)
{
$link = db_connect(); $link = db_connect();
$string_or_int = (string) $string_or_int; $string_or_int = (string) $string_or_int;
$quoted = $link->quote($string_or_int); $quoted = $link->quote($string_or_int);
@ -364,7 +378,8 @@ function escape_string($string_or_int) {
* @param string $default (optional) - default value if key is not set. * @param string $default (optional) - default value if key is not set.
* @return string * @return string
*/ */
function safeget($param, $default = "") { function safeget($param, $default = "")
{
$retval = $default; $retval = $default;
if (isset($_GET[$param]) && is_string($_GET[$param])) { if (isset($_GET[$param]) && is_string($_GET[$param])) {
$retval = $_GET[$param]; $retval = $_GET[$param];
@ -379,7 +394,8 @@ function safeget($param, $default = "") {
* @param string $default (optional) default value (defaults to "") * @param string $default (optional) default value (defaults to "")
* @return string - value in $_POST[$param] or $default * @return string - value in $_POST[$param] or $default
*/ */
function safepost($param, $default = "") { function safepost($param, $default = "")
{
$retval = $default; $retval = $default;
if (isset($_POST[$param]) && is_string($_POST[$param])) { if (isset($_POST[$param]) && is_string($_POST[$param])) {
$retval = $_POST[$param]; $retval = $_POST[$param];
@ -394,7 +410,8 @@ function safepost($param, $default = "") {
* @param string $default (optional) * @param string $default (optional)
* @return string value from $_SERVER[$param] or $default * @return string value from $_SERVER[$param] or $default
*/ */
function safeserver($param, $default = "") { function safeserver($param, $default = "")
{
$retval = $default; $retval = $default;
if (isset($_SERVER[$param])) { if (isset($_SERVER[$param])) {
$retval = $_SERVER[$param]; $retval = $_SERVER[$param];
@ -409,7 +426,8 @@ function safeserver($param, $default = "") {
* @param string $default (optional) * @param string $default (optional)
* @return string value from $_COOKIE[$param] or $default * @return string value from $_COOKIE[$param] or $default
*/ */
function safecookie($param, $default = "") { function safecookie($param, $default = "")
{
$retval = $default; $retval = $default;
if (isset($_COOKIE[$param]) && is_string($_COOKIE[$param])) { if (isset($_COOKIE[$param]) && is_string($_COOKIE[$param])) {
$retval = $_COOKIE[$param]; $retval = $_COOKIE[$param];
@ -424,7 +442,8 @@ function safecookie($param, $default = "") {
* @param string $default (optional) * @param string $default (optional)
* @return string value from $_SESSION[$param] or $default * @return string value from $_SESSION[$param] or $default
*/ */
function safesession($param, $default = "") { function safesession($param, $default = "")
{
$retval = $default; $retval = $default;
if (isset($_SESSION[$param]) && is_string($_SESSION[$param])) { if (isset($_SESSION[$param]) && is_string($_SESSION[$param])) {
$retval = $_SESSION[$param]; $retval = $_SESSION[$param];
@ -446,7 +465,8 @@ function safesession($param, $default = "") {
* @param int or $not_in_db - if array, can contain the remaining parameters as associated array. Otherwise counts as $not_in_db * @param int or $not_in_db - if array, can contain the remaining parameters as associated array. Otherwise counts as $not_in_db
* @return array for $struct * @return array for $struct
*/ */
function pacol($allow_editing, $display_in_form, $display_in_list, $type, $PALANG_label, $PALANG_desc, $default = "", $options = array(), $multiopt=0, $dont_write_to_db=0, $select="", $extrafrom="", $linkto="") { function pacol($allow_editing, $display_in_form, $display_in_list, $type, $PALANG_label, $PALANG_desc, $default = "", $options = array(), $multiopt=0, $dont_write_to_db=0, $select="", $extrafrom="", $linkto="")
{
if ($PALANG_label != '') { if ($PALANG_label != '') {
$PALANG_label = Config::lang($PALANG_label); $PALANG_label = Config::lang($PALANG_label);
} }
@ -485,7 +505,8 @@ function pacol($allow_editing, $display_in_form, $display_in_list, $type, $PALAN
* @param string $domain * @param string $domain
* @return array * @return array
*/ */
function get_domain_properties($domain) { function get_domain_properties($domain)
{
$handler = new DomainHandler(); $handler = new DomainHandler();
if (!$handler->init($domain)) { if (!$handler->init($domain)) {
throw new Exception("Error: " . join("\n", $handler->errormsg)); throw new Exception("Error: " . join("\n", $handler->errormsg));
@ -508,7 +529,8 @@ function get_domain_properties($domain) {
* @param string $querypart - core part of the query (starting at "FROM") e.g. FROM alias WHERE address like ... * @param string $querypart - core part of the query (starting at "FROM") e.g. FROM alias WHERE address like ...
* @return array * @return array
*/ */
function create_page_browser($idxfield, $querypart, $sql_params = []) { function create_page_browser($idxfield, $querypart, $sql_params = [])
{
global $CONF; global $CONF;
$page_size = (int) $CONF['page_size']; $page_size = (int) $CONF['page_size'];
$label_len = 2; $label_len = 2;
@ -599,7 +621,8 @@ function create_page_browser($idxfield, $querypart, $sql_params = []) {
* @param int $quota * @param int $quota
* @return float * @return float
*/ */
function divide_quota($quota) { function divide_quota($quota)
{
if ($quota == -1) { if ($quota == -1) {
return $quota; return $quota;
} }
@ -614,7 +637,8 @@ function divide_quota($quota) {
* @param string $domain * @param string $domain
* @return bool * @return bool
*/ */
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');
$result = db_query_all( $result = db_query_all(
@ -641,7 +665,8 @@ function check_owner($username, $domain) {
* @param string $username * @param string $username
* @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');
@ -679,7 +704,8 @@ function list_domains_for_admin($username) {
* *
* @return array * @return array
*/ */
function list_domains() { function list_domains()
{
$list = array(); $list = array();
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
@ -702,7 +728,8 @@ function list_domains() {
// //
// was admin_list_admins // was admin_list_admins
// //
function list_admins() { function list_admins()
{
$handler = new AdminHandler(); $handler = new AdminHandler();
$handler->getList(''); $handler->getList('');
@ -717,7 +744,8 @@ function list_admins() {
// Action: Encode a string according to RFC 1522 for use in headers if it contains 8-bit characters. // Action: Encode a string according to RFC 1522 for use in headers if it contains 8-bit characters.
// Call: encode_header (string header, string charset) // Call: encode_header (string header, string charset)
// //
function encode_header($string, $default_charset = "utf-8") { function encode_header($string, $default_charset = "utf-8")
{
if (strtolower($default_charset) == 'iso-8859-1') { if (strtolower($default_charset) == 'iso-8859-1') {
$string = str_replace("\240", ' ', $string); $string = str_replace("\240", ' ', $string);
} }
@ -841,7 +869,8 @@ function encode_header($string, $default_charset = "utf-8") {
* @return string * @return string
* *
*/ */
function generate_password($length = 12) { function generate_password($length = 12)
{
// define possible characters // define possible characters
$possible = "2345678923456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; # skip 0 and 1 to avoid confusion with O and l $possible = "2345678923456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; # skip 0 and 1 to avoid confusion with O and l
@ -868,7 +897,8 @@ function generate_password($length = 12) {
* @param string $password * @param string $password
* @return array of error messages, or empty array if the password is ok * @return array of error messages, or empty array if the password is ok
*/ */
function validate_password($password) { function validate_password($password)
{
$result = array(); $result = array();
$val_conf = Config::read_array('password_validation'); $val_conf = Config::read_array('password_validation');
@ -906,7 +936,8 @@ function validate_password($password) {
* @param string $pw_db - encrypted hash * @param string $pw_db - encrypted hash
* @return string crypt'ed password, should equal $pw_db if $pw matches the original * @return string crypt'ed password, should equal $pw_db if $pw matches the original
*/ */
function _pacrypt_md5crypt($pw, $pw_db = '') { function _pacrypt_md5crypt($pw, $pw_db = '')
{
if ($pw_db) { if ($pw_db) {
$split_salt = preg_split('/\$/', $pw_db); $split_salt = preg_split('/\$/', $pw_db);
if (isset($split_salt[2])) { if (isset($split_salt[2])) {
@ -921,7 +952,8 @@ function _pacrypt_md5crypt($pw, $pw_db = '') {
/** /**
* @todo fix this to not throw an E_NOTICE or deprecate/remove. * @todo fix this to not throw an E_NOTICE or deprecate/remove.
*/ */
function _pacrypt_crypt($pw, $pw_db = '') { function _pacrypt_crypt($pw, $pw_db = '')
{
if ($pw_db) { if ($pw_db) {
return crypt($pw, $pw_db); return crypt($pw, $pw_db);
} }
@ -936,7 +968,8 @@ function _pacrypt_crypt($pw, $pw_db = '') {
* @param string $pw_db (hashed password) * @param string $pw_db (hashed password)
* @return string if $pw_db and the return value match then $pw matches the original password. * @return string if $pw_db and the return value match then $pw matches the original password.
*/ */
function _pacrypt_mysql_encrypt($pw, $pw_db = '') { function _pacrypt_mysql_encrypt($pw, $pw_db = '')
{
// See https://sourceforge.net/tracker/?func=detail&atid=937966&aid=1793352&group_id=191583 // See https://sourceforge.net/tracker/?func=detail&atid=937966&aid=1793352&group_id=191583
// this is apparently useful for pam_mysql etc. // this is apparently useful for pam_mysql etc.
@ -959,7 +992,8 @@ function _pacrypt_mysql_encrypt($pw, $pw_db = '') {
* @param string $pw_db (optional) * @param string $pw_db (optional)
* @return string crypted password - contains {xxx} prefix to identify mechanism. * @return string crypted password - contains {xxx} prefix to identify mechanism.
*/ */
function _pacrypt_authlib($pw, $pw_db) { function _pacrypt_authlib($pw, $pw_db)
{
global $CONF; global $CONF;
$flavor = $CONF['authlib_default_flavor']; $flavor = $CONF['authlib_default_flavor'];
$salt = substr(create_salt(), 0, 2); # courier-authlib supports only two-character salts $salt = substr(create_salt(), 0, 2); # courier-authlib supports only two-character salts
@ -991,7 +1025,8 @@ function _pacrypt_authlib($pw, $pw_db) {
* @param string $pw_db - encrypted password, or '' for generation. * @param string $pw_db - encrypted password, or '' for generation.
* @return string crypted password * @return string crypted password
*/ */
function _pacrypt_dovecot($pw, $pw_db = '') { function _pacrypt_dovecot($pw, $pw_db = '')
{
global $CONF; global $CONF;
$split_method = preg_split('/:/', $CONF['encrypt']); $split_method = preg_split('/:/', $CONF['encrypt']);
@ -1093,7 +1128,8 @@ function _pacrypt_dovecot($pw, $pw_db = '') {
* @param string $pw_db (can be empty if setting a new password) * @param string $pw_db (can be empty if setting a new password)
* @return string crypt'ed password; if it matches $pw_db then $pw is the original password. * @return string crypt'ed password; if it matches $pw_db then $pw is the original password.
*/ */
function _pacrypt_php_crypt($pw, $pw_db) { function _pacrypt_php_crypt($pw, $pw_db)
{
$configEncrypt = Config::read_string('encrypt'); $configEncrypt = Config::read_string('encrypt');
// use PHPs crypt(), which uses the system's crypt() // use PHPs crypt(), which uses the system's crypt()
@ -1148,7 +1184,8 @@ function _pacrypt_php_crypt($pw, $pw_db) {
* @param int hash difficulty * @param int hash difficulty
* @return string * @return string
*/ */
function _php_crypt_generate_crypt_salt($hash_type='SHA512', $hash_difficulty=null) { function _php_crypt_generate_crypt_salt($hash_type='SHA512', $hash_difficulty=null)
{
// generate a salt (with magic matching chosen hash algorithm) for the PHP crypt() function // generate a salt (with magic matching chosen hash algorithm) for the PHP crypt() function
// most commonly used alphabet // most commonly used alphabet
@ -1230,7 +1267,8 @@ function _php_crypt_generate_crypt_salt($hash_type='SHA512', $hash_difficulty=nu
* @param int $length * @param int $length
* @return string of given $length * @return string of given $length
*/ */
function _php_crypt_random_string($characters, $length) { function _php_crypt_random_string($characters, $length)
{
$string = ''; $string = '';
for ($p = 0; $p < $length; $p++) { for ($p = 0; $p < $length; $p++) {
$string .= $characters[random_int(0, strlen($characters) -1)]; $string .= $characters[random_int(0, strlen($characters) -1)];
@ -1250,7 +1288,8 @@ function _php_crypt_random_string($characters, $length) {
* @param string $pw_db optional encrypted password * @param string $pw_db optional encrypted password
* @return string encrypted password - if this matches $pw_db then the original password is $pw. * @return string encrypted password - if this matches $pw_db then the original password is $pw.
*/ */
function pacrypt($pw, $pw_db="") { function pacrypt($pw, $pw_db="")
{
global $CONF; global $CONF;
switch ($CONF['encrypt']) { switch ($CONF['encrypt']) {
@ -1284,7 +1323,8 @@ function pacrypt($pw, $pw_db="") {
/** /**
* @see https://github.com/postfixadmin/postfixadmin/issues/58 * @see https://github.com/postfixadmin/postfixadmin/issues/58
*/ */
function _pacrypt_sha512_b64($pw, $pw_db="") { function _pacrypt_sha512_b64($pw, $pw_db="")
{
if (!function_exists('random_bytes') || !function_exists('crypt') || !defined('CRYPT_SHA512') || !function_exists('mb_substr')) { if (!function_exists('random_bytes') || !function_exists('crypt') || !defined('CRYPT_SHA512') || !function_exists('mb_substr')) {
throw new Exception("sha512.b64 not supported!"); throw new Exception("sha512.b64 not supported!");
} }
@ -1318,7 +1358,8 @@ function _pacrypt_sha512_b64($pw, $pw_db="") {
* @param string $magic (optional) * @param string $magic (optional)
* @return string hashed password in crypt format. * @return string hashed password in crypt format.
*/ */
function md5crypt($pw, $salt="", $magic="") { function md5crypt($pw, $salt="", $magic="")
{
$MAGIC = "$1$"; $MAGIC = "$1$";
if ($magic == "") { if ($magic == "") {
@ -1388,7 +1429,8 @@ function md5crypt($pw, $salt="", $magic="") {
/** /**
* @return string - should be random, 8 chars long * @return string - should be random, 8 chars long
*/ */
function create_salt() { function create_salt()
{
srand((int) microtime()*1000000); srand((int) microtime()*1000000);
$salt = substr(md5("" . rand(0, 9999999)), 0, 8); $salt = substr(md5("" . rand(0, 9999999)), 0, 8);
return $salt; return $salt;
@ -1397,7 +1439,8 @@ function create_salt() {
/* /*
* remove item $item from array $array * remove item $item from array $array
*/ */
function remove_from_array($array, $item) { function remove_from_array($array, $item)
{
# array_diff might be faster, but doesn't provide an easy way to know if the value was found or not # array_diff might be faster, but doesn't provide an easy way to know if the value was found or not
# return array_diff($array, array($item)); # return array_diff($array, array($item));
$ret = array_search($item, $array); $ret = array_search($item, $array);
@ -1410,7 +1453,8 @@ function remove_from_array($array, $item) {
return array($found, $array); return array($found, $array);
} }
function to64($v, $n) { function to64($v, $n)
{
$ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; $ITOA64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$ret = ""; $ret = "";
while (($n - 1) >= 0) { while (($n - 1) >= 0) {
@ -1436,7 +1480,8 @@ function to64($v, $n) {
* @return bool - true on success, otherwise false * @return bool - true on success, otherwise false
* TODO: Replace this with something decent like PEAR::Mail or Zend_Mail. * TODO: Replace this with something decent like PEAR::Mail or Zend_Mail.
*/ */
function smtp_mail($to, $from, $data, $password = "", $body = "") { function smtp_mail($to, $from, $data, $password = "", $body = "")
{
global $CONF; global $CONF;
$smtpd_server = $CONF['smtp_server']; $smtpd_server = $CONF['smtp_server'];
@ -1516,7 +1561,8 @@ function smtp_mail($to, $from, $data, $password = "", $body = "") {
* Call: smtp_get_admin_email * Call: smtp_get_admin_email
* @return string - username/mail address * @return string - username/mail address
*/ */
function smtp_get_admin_email() { function smtp_get_admin_email()
{
$admin_email = Config::read_string('admin_email'); $admin_email = Config::read_string('admin_email');
if (!empty($admin_email)) { if (!empty($admin_email)) {
return $admin_email; return $admin_email;
@ -1531,7 +1577,8 @@ function smtp_get_admin_email() {
* Call: smtp_get_admin_password * Call: smtp_get_admin_password
* @return string - admin smtp password * @return string - admin smtp password
*/ */
function smtp_get_admin_password() { function smtp_get_admin_password()
{
return Config::read_string('admin_smtp_password'); return Config::read_string('admin_smtp_password');
} }
@ -1541,7 +1588,8 @@ function smtp_get_admin_password() {
// Action: Get response from mail server // Action: Get response from mail server
// Call: smtp_get_response (string FileHandle) // Call: smtp_get_response (string FileHandle)
// //
function smtp_get_response($fh) { function smtp_get_response($fh)
{
$res =''; $res ='';
do { do {
$line = fgets($fh, 256); $line = fgets($fh, 256);
@ -1565,7 +1613,8 @@ EOF;
* @return string - PDO DSN for PHP. * @return string - PDO DSN for PHP.
* @throws Exception * @throws Exception
*/ */
function db_connection_string() { function db_connection_string()
{
global $CONF; global $CONF;
$dsn = null; $dsn = null;
if (db_mysql()) { if (db_mysql()) {
@ -1610,7 +1659,8 @@ function db_connection_string() {
* *
* @return \PDO * @return \PDO
*/ */
function db_connect() { function db_connect()
{
global $CONF; global $CONF;
/* some attempt at not reopening an existing connection */ /* some attempt at not reopening an existing connection */
@ -1697,7 +1747,8 @@ function db_connect() {
* @param bool|string $bool * @param bool|string $bool
* @return string|int as appropriate for underlying db platform * @return string|int as appropriate for underlying db platform
*/ */
function db_get_boolean($bool) { function db_get_boolean($bool)
{
if (! (is_bool($bool) || $bool == '0' || $bool == '1')) { if (! (is_bool($bool) || $bool == '0' || $bool == '1')) {
error_log("Invalid usage of 'db_get_boolean($bool)'"); error_log("Invalid usage of 'db_get_boolean($bool)'");
throw new Exception("Invalid usage of 'db_get_boolean($bool)'"); throw new Exception("Invalid usage of 'db_get_boolean($bool)'");
@ -1726,7 +1777,8 @@ function db_get_boolean($bool) {
* @param string column that will contain "x / y" * @param string column that will contain "x / y"
* @return string * @return string
*/ */
function db_quota_text($count, $quota, $fieldname) { function db_quota_text($count, $quota, $fieldname)
{
if (db_pgsql() || db_sqlite()) { if (db_pgsql() || db_sqlite()) {
// SQLite and PostgreSQL use || to concatenate strings // SQLite and PostgreSQL use || to concatenate strings
return " CASE $quota return " CASE $quota
@ -1750,7 +1802,8 @@ function db_quota_text($count, $quota, $fieldname) {
* @param string column that will contain "x / y" * @param string column that will contain "x / y"
* @return string * @return string
*/ */
function db_quota_percent($count, $quota, $fieldname) { function db_quota_percent($count, $quota, $fieldname)
{
return " CASE $quota return " CASE $quota
WHEN '-1' THEN -1 WHEN '-1' THEN -1
WHEN '0' THEN -1 WHEN '0' THEN -1
@ -1761,7 +1814,8 @@ function db_quota_percent($count, $quota, $fieldname) {
/** /**
* @return boolean true if it's a MySQL database variant. * @return boolean true if it's a MySQL database variant.
*/ */
function db_mysql() { function db_mysql()
{
$type = Config::Read('database_type'); $type = Config::Read('database_type');
if ($type == 'mysql' || $type == 'mysqli') { if ($type == 'mysql' || $type == 'mysqli') {
@ -1773,14 +1827,16 @@ function db_mysql() {
/** /**
* @return bool true if PostgreSQL is used, false otherwise * @return bool true if PostgreSQL is used, false otherwise
*/ */
function db_pgsql() { function db_pgsql()
{
return Config::read_string('database_type') == 'pgsql'; return Config::read_string('database_type') == 'pgsql';
} }
/** /**
* returns true if SQLite is used, false otherwise * returns true if SQLite is used, false otherwise
*/ */
function db_sqlite() { function db_sqlite()
{
if (Config::Read('database_type')=='sqlite') { if (Config::Read('database_type')=='sqlite') {
return true; return true;
} else { } else {
@ -1793,7 +1849,8 @@ function db_sqlite() {
* @param array $values * @param array $values
* @return array * @return array
*/ */
function db_query_all($sql, array $values = []) { function db_query_all($sql, array $values = [])
{
$r = db_query($sql, $values); $r = db_query($sql, $values);
return $r['result']->fetchAll(PDO::FETCH_ASSOC); return $r['result']->fetchAll(PDO::FETCH_ASSOC);
} }
@ -1803,7 +1860,8 @@ function db_query_all($sql, array $values = []) {
* @param array $values * @param array $values
* @return array * @return array
*/ */
function db_query_one($sql, array $values = []) { function db_query_one($sql, array $values = [])
{
$r = db_query($sql, $values); $r = db_query($sql, $values);
return $r['result']->fetch(PDO::FETCH_ASSOC); return $r['result']->fetch(PDO::FETCH_ASSOC);
} }
@ -1815,7 +1873,8 @@ function db_query_one($sql, array $values = []) {
* @param bool $throw_exceptions * @param bool $throw_exceptions
* @return int number of rows affected by the query * @return int number of rows affected by the query
*/ */
function db_execute($sql, array $values = [], $throw_exceptions = false) { function db_execute($sql, array $values = [], $throw_exceptions = false)
{
$link = db_connect(); $link = db_connect();
try { try {
@ -1840,7 +1899,8 @@ function db_execute($sql, array $values = [], $throw_exceptions = false) {
* @param bool $ignore_errors - set to true to ignore errors. * @param bool $ignore_errors - set to true to ignore errors.
* @return array e.g. ['result' => PDOStatement, 'error' => string ] * @return array e.g. ['result' => PDOStatement, 'error' => string ]
*/ */
function db_query($sql, array $values = array(), $ignore_errors = false) { function db_query($sql, array $values = array(), $ignore_errors = false)
{
$link = db_connect(); $link = db_connect();
$error_text = ''; $error_text = '';
@ -1880,7 +1940,8 @@ function db_query($sql, array $values = array(), $ignore_errors = false) {
* @param string $additionalwhere (default ''). * @param string $additionalwhere (default '').
* @return int|mixed rows deleted. * @return int|mixed rows deleted.
*/ */
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 = ? $additionalwhere"; $query = "DELETE FROM $table WHERE $where = ? $additionalwhere";
@ -1901,7 +1962,8 @@ function db_delete($table, $where, $delete, $additionalwhere='') {
* @param boolean $throw_exceptions * @param boolean $throw_exceptions
* @return int - number of inserted rows * @return int - number of inserted rows
*/ */
function db_insert(string $table, array $values, array $timestamp = array('created', 'modified'), bool $throw_exceptions = false) : int { function db_insert(string $table, array $values, array $timestamp = array('created', 'modified'), bool $throw_exceptions = false) : int
{
$table = table_by_key($table); $table = table_by_key($table);
foreach ($timestamp as $key) { foreach ($timestamp as $key) {
@ -1944,7 +2006,8 @@ function db_insert(string $table, array $values, array $timestamp = array('creat
* @param array $timestamp (optional) - array of fields to set to now() - default: array('modified') * @param array $timestamp (optional) - array of fields to set to now() - default: array('modified')
* @return int - number of updated rows * @return int - number of updated rows
*/ */
function db_update(string $table, string $where_col, string $where_value, array $values, array $timestamp = array('modified'), bool $throw_exceptions = false):int { function db_update(string $table, string $where_col, string $where_value, array $values, array $timestamp = array('modified'), bool $throw_exceptions = false):int
{
$table_key = table_by_key($table); $table_key = table_by_key($table);
$pvalues = array(); $pvalues = array();
@ -1986,7 +2049,8 @@ function db_update(string $table, string $where_col, string $where_value, array
* Call: db_log (string domain, string action, string data) * Call: db_log (string domain, string action, string data)
* Possible actions are defined in $LANG["pViewlog_action_$action"] * Possible actions are defined in $LANG["pViewlog_action_$action"]
*/ */
function db_log($domain, $action, $data) { function db_log($domain, $action, $data)
{
if (!Config::bool('logging')) { if (!Config::bool('logging')) {
return true; return true;
} }
@ -2022,7 +2086,8 @@ function db_log($domain, $action, $data) {
* @param array $values * @param array $values
* @return string * @return string
*/ */
function db_in_clause($field, array $values) { function db_in_clause($field, array $values)
{
$v = array_map('escape_string', array_values($values)); $v = array_map('escape_string', array_values($values));
return " $field IN ('" . implode("','", $v) . "') "; return " $field IN ('" . implode("','", $v) . "') ";
} }
@ -2039,7 +2104,8 @@ function db_in_clause($field, array $values) {
* Note: the $searchmode operator will only be used if a $condition for that field is set. * Note: the $searchmode operator will only be used if a $condition for that field is set.
* This also means you'll need to set a (dummy) condition for NULL and NOTNULL. * This also means you'll need to set a (dummy) condition for NULL and NOTNULL.
*/ */
function db_where_clause(array $condition, array $struct, $additional_raw_where = '', array $searchmode = array()) { function db_where_clause(array $condition, array $struct, $additional_raw_where = '', array $searchmode = array())
{
if (count($condition) == 0 && trim($additional_raw_where) == '') { if (count($condition) == 0 && trim($additional_raw_where) == '') {
throw new Exception("db_where_cond: parameter is an empty array!"); throw new Exception("db_where_cond: parameter is an empty array!");
} }
@ -2109,7 +2175,8 @@ function db_where_clause(array $condition, array $struct, $additional_raw_where
* @param string database table name. * @param string database table name.
* @return string - database table name with appropriate prefix (and quoting if MySQL) * @return string - database table name with appropriate prefix (and quoting if MySQL)
*/ */
function table_by_key($table_key) { function table_by_key($table_key)
{
global $CONF; global $CONF;
$table = $table_key; $table = $table_key;
@ -2135,7 +2202,8 @@ function table_by_key($table_key) {
* @param bool $error_out * @param bool $error_out
* @return int * @return int
*/ */
function check_db_version($error_out = true) { function check_db_version($error_out = true)
{
global $min_db_version; global $min_db_version;
$table = table_by_key('config'); $table = table_by_key('config');
@ -2167,7 +2235,8 @@ function check_db_version($error_out = true) {
* @param string $show_alias * @param string $show_alias
* @return string * @return string
*/ */
function gen_show_status($show_alias) { function gen_show_status($show_alias)
{
global $CONF; global $CONF;
$table_alias = table_by_key('alias'); $table_alias = table_by_key('alias');
$stat_string = ""; $stat_string = "";
@ -2314,7 +2383,8 @@ function gen_show_status($show_alias) {
/** /**
* @return string * @return string
*/ */
function getRemoteAddr() { function getRemoteAddr()
{
$REMOTE_ADDR = 'localhost'; $REMOTE_ADDR = 'localhost';
if (isset($_SERVER['REMOTE_ADDR'])) { if (isset($_SERVER['REMOTE_ADDR'])) {
$REMOTE_ADDR = $_SERVER['REMOTE_ADDR']; $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
@ -2328,7 +2398,8 @@ function getRemoteAddr() {
* @param array $server * @param array $server
* @return string URL to Postfixadmin - will always end in a '/' * @return string URL to Postfixadmin - will always end in a '/'
*/ */
function getSiteUrl(array $server = []): string { function getSiteUrl(array $server = []): string
{
if (Config::has('site_url')) { if (Config::has('site_url')) {
$url = Config::read_string('site_url'); $url = Config::read_string('site_url');
if (!empty($url)) { if (!empty($url)) {

View File

@ -6,7 +6,8 @@ class AdminHandler extends PFAHandler
protected $db_table = 'admin'; protected $db_table = 'admin';
protected $id_field = 'username'; protected $id_field = 'username';
protected function validate_new_id() { protected function validate_new_id()
{
$email_check = check_email($this->id); $email_check = check_email($this->id);
if ($email_check == '') { if ($email_check == '') {
@ -18,12 +19,14 @@ class AdminHandler extends PFAHandler
} }
} }
protected function no_domain_field() { protected function no_domain_field()
{
# PFAHandler die()s if domain field is not set. Disable this behaviour for AdminHandler. # PFAHandler die()s if domain field is not set. Disable this behaviour for AdminHandler.
} }
# init $this->struct, $this->db_table and $this->id_field # init $this->struct, $this->db_table and $this->id_field
protected function initStruct() { protected function initStruct()
{
# NOTE: There are dependencies between domains and domain_count # NOTE: There are dependencies between domains and domain_count
# NOTE: If you disable "display in list" for domain_count, the SQL query for domains might break. # NOTE: If you disable "display in list" for domain_count, the SQL query for domains might break.
# NOTE: (Disabling both shouldn't be a problem.) # NOTE: (Disabling both shouldn't be a problem.)
@ -90,7 +93,8 @@ class AdminHandler extends PFAHandler
); );
} }
protected function initMsg() { protected function initMsg()
{
$this->msg['error_already_exists'] = 'admin_already_exists'; $this->msg['error_already_exists'] = 'admin_already_exists';
$this->msg['error_does_not_exist'] = 'admin_does_not_exist'; $this->msg['error_does_not_exist'] = 'admin_does_not_exist';
$this->msg['confirm_delete'] = 'confirm_delete_admin'; $this->msg['confirm_delete'] = 'confirm_delete_admin';
@ -106,7 +110,8 @@ class AdminHandler extends PFAHandler
} }
} }
public function webformConfig() { public function webformConfig()
{
return array( return array(
# $PALANG labels # $PALANG labels
'formtitle_create' => 'pAdminCreate_admin_welcome', 'formtitle_create' => 'pAdminCreate_admin_welcome',
@ -124,7 +129,8 @@ class AdminHandler extends PFAHandler
* called by $this->store() after storing $this->values in the database * called by $this->store() after storing $this->values in the database
* can be used to update additional tables, call scripts etc. * can be used to update additional tables, call scripts etc.
*/ */
protected function postSave() : bool { protected function postSave() : bool
{
# store list of allowed domains in the domain_admins table # store list of allowed domains in the domain_admins table
if (isset($this->values['domains'])) { if (isset($this->values['domains'])) {
if (is_array($this->values['domains'])) { if (is_array($this->values['domains'])) {
@ -168,7 +174,8 @@ class AdminHandler extends PFAHandler
return true; # TODO: don't hardcode return true; # TODO: don't hardcode
} }
protected function read_from_db_postprocess($db_result) { protected function read_from_db_postprocess($db_result)
{
foreach ($db_result as $key => $row) { foreach ($db_result as $key => $row) {
# convert 'domains' field to an array # convert 'domains' field to an array
if ($row['domains'] == '') { if ($row['domains'] == '') {
@ -186,7 +193,8 @@ class AdminHandler extends PFAHandler
/** /**
* @return bool * @return bool
*/ */
public function delete() { public function delete()
{
if (! $this->view()) { if (! $this->view()) {
$this->errormsg[] = Config::Lang($this->msg['error_does_not_exist']); $this->errormsg[] = Config::Lang($this->msg['error_does_not_exist']);
return false; return false;
@ -208,7 +216,8 @@ class AdminHandler extends PFAHandler
* compare password / password2 field * compare password / password2 field
* error message will be displayed at the password2 field * error message will be displayed at the password2 field
*/ */
protected function _validate_password2($field, $val) { protected function _validate_password2($field, $val)
{
return $this->compare_password_fields('password', 'password2'); return $this->compare_password_fields('password', 'password2');
} }
} }

View File

@ -9,16 +9,19 @@ class AdminpasswordHandler extends PFAHandler
# do not skip empty password fields # do not skip empty password fields
protected $skip_empty_pass = false; protected $skip_empty_pass = false;
protected function no_domain_field() { protected function no_domain_field()
{
return true; return true;
} }
protected function validate_new_id() { protected function validate_new_id()
{
return true; return true;
} }
# init $this->struct, $this->db_table and $this->id_field # init $this->struct, $this->db_table and $this->id_field
protected function initStruct() { protected function initStruct()
{
# TODO: shorter PALANG labels ;-) # TODO: shorter PALANG labels ;-)
$this->struct=array( $this->struct=array(
@ -36,7 +39,8 @@ class AdminpasswordHandler extends PFAHandler
); );
} }
public function init($id) :bool { public function init($id) :bool
{
# hardcode to logged in admin # hardcode to logged in admin
if ($this->admin_username == '') { if ($this->admin_username == '') {
die("No admin logged in"); die("No admin logged in");
@ -51,7 +55,8 @@ class AdminpasswordHandler extends PFAHandler
return parent::init($this->id); return parent::init($this->id);
} }
public function initMsg() { public function initMsg()
{
$this->msg['error_already_exists'] = 'admin_already_exists'; # probably unused $this->msg['error_already_exists'] = 'admin_already_exists'; # probably unused
$this->msg['error_does_not_exist'] = 'admin_does_not_exist'; # probably unused $this->msg['error_does_not_exist'] = 'admin_does_not_exist'; # probably unused
$this->msg['confirm_delete'] = 'confirm_delete_admin'; # probably unused $this->msg['confirm_delete'] = 'confirm_delete_admin'; # probably unused
@ -61,7 +66,8 @@ class AdminpasswordHandler extends PFAHandler
$this->msg['successmessage'] = 'pPassword_result_success'; $this->msg['successmessage'] = 'pPassword_result_success';
} }
public function webformConfig() { public function webformConfig()
{
return array( return array(
# $PALANG labels # $PALANG labels
'formtitle_create' => 'pPassword_welcome', 'formtitle_create' => 'pPassword_welcome',
@ -80,7 +86,8 @@ class AdminpasswordHandler extends PFAHandler
/** /**
* check if old password is correct * check if old password is correct
*/ */
protected function _validate_oldpass($field, $val) { protected function _validate_oldpass($field, $val)
{
$l = new Login('admin'); $l = new Login('admin');
if ($l->login($this->id, $val)) { if ($l->login($this->id, $val)) {
return true; return true;
@ -93,7 +100,8 @@ class AdminpasswordHandler extends PFAHandler
/** /**
* skip default validation (check if password is good enough) for old password * skip default validation (check if password is good enough) for old password
*/ */
protected function _inp_pass($field, $val) { protected function _inp_pass($field, $val)
{
if ($field == 'oldpass') { if ($field == 'oldpass') {
return true; return true;
} }
@ -105,7 +113,8 @@ class AdminpasswordHandler extends PFAHandler
* compare password / password2 field * compare password / password2 field
* error message will be displayed at the password2 field * error message will be displayed at the password2 field
*/ */
protected function _validate_password2($field, $val) { protected function _validate_password2($field, $val)
{
return $this->compare_password_fields('password', 'password2'); return $this->compare_password_fields('password', 'password2');
} }
} }

View File

@ -17,7 +17,8 @@ class AliasHandler extends PFAHandler
*/ */
public $return = null; public $return = null;
protected function initStruct() { protected function initStruct()
{
# hide 'goto_mailbox' if $this->new # hide 'goto_mailbox' if $this->new
# (for existing aliases, init() hides it for non-mailbox aliases) # (for existing aliases, init() hides it for non-mailbox aliases)
$mbgoto = 1 - $this->new; $mbgoto = 1 - $this->new;
@ -69,7 +70,8 @@ class AliasHandler extends PFAHandler
* When using this function to optimize the is_mailbox extrafrom, don't forget to reset it to the default value * When using this function to optimize the is_mailbox extrafrom, don't forget to reset it to the default value
* (all domains for this admin) afterwards. * (all domains for this admin) afterwards.
*/ */
private function set_is_mailbox_extrafrom($condition=array(), $searchmode=array()) { private function set_is_mailbox_extrafrom($condition=array(), $searchmode=array())
{
$extrafrom = 'LEFT JOIN ( ' . $extrafrom = 'LEFT JOIN ( ' .
' SELECT 1 as __is_mailbox, username as __mailbox_username ' . ' SELECT 1 as __is_mailbox, username as __mailbox_username ' .
' FROM ' . table_by_key('mailbox') . ' FROM ' . table_by_key('mailbox') .
@ -89,7 +91,8 @@ class AliasHandler extends PFAHandler
} }
protected function initMsg() { protected function initMsg()
{
$this->msg['error_already_exists'] = 'email_address_already_exists'; $this->msg['error_already_exists'] = 'email_address_already_exists';
$this->msg['error_does_not_exist'] = 'alias_does_not_exist'; $this->msg['error_does_not_exist'] = 'alias_does_not_exist';
$this->msg['confirm_delete'] = 'confirm_delete_alias'; $this->msg['confirm_delete'] = 'confirm_delete_alias';
@ -107,7 +110,8 @@ class AliasHandler extends PFAHandler
} }
public function webformConfig() { public function webformConfig()
{
if ($this->new) { # the webform will display a localpart field + domain dropdown on $new if ($this->new) { # the webform will display a localpart field + domain dropdown on $new
$this->struct['address']['display_in_form'] = 0; $this->struct['address']['display_in_form'] = 0;
$this->struct['localpart']['display_in_form'] = 1; $this->struct['localpart']['display_in_form'] = 1;
@ -137,7 +141,8 @@ class AliasHandler extends PFAHandler
* AliasHandler needs some special handling in init() and therefore overloads the function. * AliasHandler needs some special handling in init() and therefore overloads the function.
* It also calls parent::init() * It also calls parent::init()
*/ */
public function init(string $id) : bool { public function init(string $id) : bool
{
$bits = explode('@', $id); $bits = explode('@', $id);
if (sizeof($bits) == 2) { if (sizeof($bits) == 2) {
$local_part = $bits[0]; $local_part = $bits[0];
@ -175,12 +180,14 @@ class AliasHandler extends PFAHandler
return $retval; return $retval;
} }
protected function domain_from_id() { protected function domain_from_id()
{
list(/*NULL*/, $domain) = explode('@', $this->id); list(/*NULL*/, $domain) = explode('@', $this->id);
return $domain; return $domain;
} }
protected function validate_new_id() { protected function validate_new_id()
{
if ($this->id == '') { if ($this->id == '') {
$this->errormsg[$this->id_field] = Config::lang('pCreate_alias_address_text_error1'); $this->errormsg[$this->id_field] = Config::lang('pCreate_alias_address_text_error1');
return false; return false;
@ -217,7 +224,8 @@ class AliasHandler extends PFAHandler
/** /**
* check number of existing aliases for this domain - is one more allowed? * check number of existing aliases for this domain - is one more allowed?
*/ */
private function create_allowed($domain) { private function create_allowed($domain)
{
if ($this->called_by == 'MailboxHandler') { if ($this->called_by == 'MailboxHandler') {
return true; return true;
} # always allow creating an alias for a mailbox } # always allow creating an alias for a mailbox
@ -241,7 +249,8 @@ class AliasHandler extends PFAHandler
* merge localpart and domain to address * merge localpart and domain to address
* called by edit.php (if id_field is editable and hidden in editform) _before_ ->init * called by edit.php (if id_field is editable and hidden in editform) _before_ ->init
*/ */
public function mergeId($values) { public function mergeId($values)
{
if ($this->struct['localpart']['display_in_form'] == 1 && $this->struct['domain']['display_in_form']) { # webform mode - combine to 'address' field if ($this->struct['localpart']['display_in_form'] == 1 && $this->struct['domain']['display_in_form']) { # webform mode - combine to 'address' field
if (empty($values['localpart']) || empty($values['domain'])) { # localpart or domain not set if (empty($values['localpart']) || empty($values['domain'])) { # localpart or domain not set
return ""; return "";
@ -255,7 +264,8 @@ class AliasHandler extends PFAHandler
} }
} }
protected function setmore(array $values) { protected function setmore(array $values)
{
if ($this->new) { if ($this->new) {
if ($this->struct['address']['display_in_form'] == 1) { # default mode - split off 'domain' field from 'address' # TODO: do this unconditional? if ($this->struct['address']['display_in_form'] == 1) { # default mode - split off 'domain' field from 'address' # TODO: do this unconditional?
list(/*NULL*/, $domain) = explode('@', $values['address']); list(/*NULL*/, $domain) = explode('@', $values['address']);
@ -304,12 +314,14 @@ class AliasHandler extends PFAHandler
$this->values['goto'] = join(',', $values['goto']); $this->values['goto'] = join(',', $values['goto']);
} }
protected function postSave() : bool { protected function postSave() : bool
{
# TODO: if alias belongs to a mailbox, update mailbox active status # TODO: if alias belongs to a mailbox, update mailbox active status
return true; return true;
} }
protected function read_from_db_postprocess($db_result) { protected function read_from_db_postprocess($db_result)
{
foreach ($db_result as $key => $value) { foreach ($db_result as $key => $value) {
# split comma-separated 'goto' into an array # split comma-separated 'goto' into an array
$goto = $db_result[$key]['goto'] ?? null; $goto = $db_result[$key]['goto'] ?? null;
@ -344,7 +356,8 @@ class AliasHandler extends PFAHandler
return $db_result; return $db_result;
} }
private function condition_ignore_mailboxes($condition, $searchmode) { private function condition_ignore_mailboxes($condition, $searchmode)
{
# only list aliases that do not belong to mailboxes # only list aliases that do not belong to mailboxes
if (is_array($condition)) { if (is_array($condition)) {
$condition['__mailbox_username'] = 1; $condition['__mailbox_username'] = 1;
@ -358,7 +371,8 @@ class AliasHandler extends PFAHandler
return array($condition, $searchmode); return array($condition, $searchmode);
} }
public function getList($condition, $searchmode = array(), $limit=-1, $offset=-1) : bool { public function getList($condition, $searchmode = array(), $limit=-1, $offset=-1) : bool
{
list($condition, $searchmode) = $this->condition_ignore_mailboxes($condition, $searchmode); list($condition, $searchmode) = $this->condition_ignore_mailboxes($condition, $searchmode);
$this->set_is_mailbox_extrafrom($condition, $searchmode); $this->set_is_mailbox_extrafrom($condition, $searchmode);
$result = parent::getList($condition, $searchmode, $limit, $offset); $result = parent::getList($condition, $searchmode, $limit, $offset);
@ -366,7 +380,8 @@ class AliasHandler extends PFAHandler
return $result; return $result;
} }
public function getPagebrowser($condition, $searchmode = array()) { public function getPagebrowser($condition, $searchmode = array())
{
list($condition, $searchmode) = $this->condition_ignore_mailboxes($condition, $searchmode); list($condition, $searchmode) = $this->condition_ignore_mailboxes($condition, $searchmode);
$this->set_is_mailbox_extrafrom($condition, $searchmode); $this->set_is_mailbox_extrafrom($condition, $searchmode);
$result = parent::getPagebrowser($condition, $searchmode); $result = parent::getPagebrowser($condition, $searchmode);
@ -376,7 +391,8 @@ class AliasHandler extends PFAHandler
protected function _validate_goto($field, $val) { protected function _validate_goto($field, $val)
{
if (count($val) == 0) { if (count($val) == 0) {
# empty is ok for mailboxes - this is checked in setmore() which can clear the error message # empty is ok for mailboxes - this is checked in setmore() which can clear the error message
$this->errormsg[$field] = Config::lang('pEdit_alias_goto_text_error1'); $this->errormsg[$field] = Config::lang('pEdit_alias_goto_text_error1');
@ -420,7 +436,8 @@ class AliasHandler extends PFAHandler
/** /**
* on $this->new, set localpart based on address * on $this->new, set localpart based on address
*/ */
protected function _missing_localpart($field) { protected function _missing_localpart($field)
{
if (isset($this->RAWvalues['address'])) { if (isset($this->RAWvalues['address'])) {
$parts = explode('@', $this->RAWvalues['address']); $parts = explode('@', $this->RAWvalues['address']);
if (count($parts) == 2) { if (count($parts) == 2) {
@ -432,7 +449,8 @@ class AliasHandler extends PFAHandler
/** /**
* on $this->new, set domain based on address * on $this->new, set domain based on address
*/ */
protected function _missing_domain($field) { protected function _missing_domain($field)
{
if (isset($this->RAWvalues['address'])) { if (isset($this->RAWvalues['address'])) {
$parts = explode('@', $this->RAWvalues['address']); $parts = explode('@', $this->RAWvalues['address']);
if (count($parts) == 2) { if (count($parts) == 2) {
@ -449,7 +467,8 @@ class AliasHandler extends PFAHandler
* *
* @return string an email alias. * @return string an email alias.
*/ */
protected function getVacationAlias() { protected function getVacationAlias()
{
$vacation_goto = str_replace('@', '#', $this->id); $vacation_goto = str_replace('@', '#', $this->id);
return $vacation_goto . '@' . Config::read_string('vacation_domain'); return $vacation_goto . '@' . Config::read_string('vacation_domain');
} }
@ -457,7 +476,8 @@ class AliasHandler extends PFAHandler
/** /**
* @return boolean * @return boolean
*/ */
public function delete() { public function delete()
{
if (! $this->view()) { if (! $this->view()) {
$this->errormsg[] = Config::Lang('alias_does_not_exist'); $this->errormsg[] = Config::Lang('alias_does_not_exist');
return false; return false;

View File

@ -11,7 +11,8 @@ class AliasdomainHandler extends PFAHandler
protected $domain_field = 'alias_domain'; protected $domain_field = 'alias_domain';
protected $searchfields = array('alias_domain', 'target_domain'); protected $searchfields = array('alias_domain', 'target_domain');
protected function initStruct() { protected function initStruct()
{
$this->struct=array( $this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ... # field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list # editing? form list
@ -52,7 +53,8 @@ class AliasdomainHandler extends PFAHandler
} }
} }
public function init($id) : bool { public function init($id) : bool
{
$success = parent::init($id); $success = parent::init($id);
if ($success) { if ($success) {
if (count($this->struct['alias_domain']['options']) == 0 && $this->new) { if (count($this->struct['alias_domain']['options']) == 0 && $this->new) {
@ -64,7 +66,8 @@ class AliasdomainHandler extends PFAHandler
return $success; return $success;
} }
protected function initMsg() { protected function initMsg()
{
$this->msg['error_already_exists'] = 'alias_domain_already_exists'; $this->msg['error_already_exists'] = 'alias_domain_already_exists';
$this->msg['error_does_not_exist'] = 'alias_domain_does_not_exist'; $this->msg['error_does_not_exist'] = 'alias_domain_does_not_exist';
$this->msg['confirm_delete'] = 'confirm_delete_aliasdomain'; $this->msg['confirm_delete'] = 'confirm_delete_aliasdomain';
@ -80,7 +83,8 @@ class AliasdomainHandler extends PFAHandler
} }
} }
public function webformConfig() { public function webformConfig()
{
return array( return array(
# $PALANG labels # $PALANG labels
'formtitle_create' => 'pCreate_alias_domain_welcome', 'formtitle_create' => 'pCreate_alias_domain_welcome',
@ -95,7 +99,8 @@ class AliasdomainHandler extends PFAHandler
); );
} }
protected function validate_new_id() { protected function validate_new_id()
{
return true; # alias_domain is enum, so we don't need to check its syntax etc. return true; # alias_domain is enum, so we don't need to check its syntax etc.
} }
@ -103,7 +108,8 @@ class AliasdomainHandler extends PFAHandler
/** /**
* @return boolean * @return boolean
*/ */
public function delete() { public function delete()
{
if (! $this->view()) { if (! $this->view()) {
$this->errormsg[] = 'An alias domain with that name does not exist!'; # TODO: make translatable? (will a user ever see this?) $this->errormsg[] = 'An alias domain with that name does not exist!'; # TODO: make translatable? (will a user ever see this?)
return false; return false;
@ -121,7 +127,8 @@ class AliasdomainHandler extends PFAHandler
* validate target_domain field - it must be != $this->id to avoid a loop * validate target_domain field - it must be != $this->id to avoid a loop
* @return boolean * @return boolean
*/ */
protected function _validate_target_domain($field, $val) { protected function _validate_target_domain($field, $val)
{
if ($val == $this->id) { if ($val == $this->id) {
$this->errormsg[$field] = Config::lang('alias_domain_to_itsself'); $this->errormsg[$field] = Config::lang('alias_domain_to_itsself');
return false; return false;

View File

@ -10,7 +10,8 @@ class CliDelete extends Shell
/** /**
* Execution method always used for tasks * Execution method always used for tasks
*/ */
public function execute() { public function execute()
{
if (empty($this->args)) { if (empty($this->args)) {
return $this->__interactive(); return $this->__interactive();
} }
@ -23,7 +24,8 @@ class CliDelete extends Shell
/** /**
* Interactive mode * Interactive mode
*/ */
protected function __interactive() { protected function __interactive()
{
$module = preg_replace('/Handler$/', '', $this->handler_to_use); $module = preg_replace('/Handler$/', '', $this->handler_to_use);
$module = strtolower($module); $module = strtolower($module);
@ -43,7 +45,8 @@ class CliDelete extends Shell
* *
* @param string address to delete * @param string address to delete
*/ */
protected function __handle($address) { protected function __handle($address)
{
$handler = new $this->handler_to_use($this->new); $handler = new $this->handler_to_use($this->new);
if (!$handler->init($address)) { if (!$handler->init($address)) {
@ -64,7 +67,8 @@ class CliDelete extends Shell
* *
* @access public * @access public
*/ */
public function help() { public function help()
{
$module = preg_replace('/Handler$/', '', $this->handler_to_use); $module = preg_replace('/Handler$/', '', $this->handler_to_use);
$module = strtolower($module); $module = strtolower($module);

View File

@ -15,7 +15,8 @@ class CliEdit extends Shell
/** /**
* Execution method always used for tasks * Execution method always used for tasks
*/ */
public function execute() { public function execute()
{
if (empty($this->args)) { if (empty($this->args)) {
return $this->__interactive(); return $this->__interactive();
} else { } else {
@ -28,7 +29,8 @@ class CliEdit extends Shell
* read, check and handle all --* parameters * read, check and handle all --* parameters
* The list of allowed params is based on $handler->struct * The list of allowed params is based on $handler->struct
*/ */
private function __handle_params() { private function __handle_params()
{
$handler = new $this->handler_to_use($this->new); $handler = new $this->handler_to_use($this->new);
$form_fields = $handler->getStruct(); $form_fields = $handler->getStruct();
$id_field = $handler->getId_field(); $id_field = $handler->getId_field();
@ -69,7 +71,8 @@ class CliEdit extends Shell
/** /**
* Interactive mode * Interactive mode
*/ */
private function __interactive() { private function __interactive()
{
$handler = new $this->handler_to_use($this->new); $handler = new $this->handler_to_use($this->new);
$form_fields = $handler->getStruct(); $form_fields = $handler->getStruct();
@ -175,7 +178,8 @@ class CliEdit extends Shell
/** /**
* (try to) store values * (try to) store values
*/ */
private function __handle($id, $values) { private function __handle($id, $values)
{
$handler = new $this->handler_to_use($this->new); $handler = new $this->handler_to_use($this->new);
if (!$handler->init($id)) { if (!$handler->init($id)) {
$this->err($handler->errormsg); $this->err($handler->errormsg);
@ -201,7 +205,8 @@ class CliEdit extends Shell
/** /**
* Displays help contents * Displays help contents
*/ */
public function help() { public function help()
{
if ($this->new) { if ($this->new) {
$cmd = 'add'; $cmd = 'add';
$cmdtext = 'Adds'; $cmdtext = 'Adds';

View File

@ -10,11 +10,13 @@ class CliHelp extends Shell
* *
* @access public * @access public
*/ */
public function execute() { public function execute()
{
$this->help(); $this->help();
} }
public function help() { public function help()
{
$handler = new $this->handler_to_use; $handler = new $this->handler_to_use;
# TODO: adjust help text according to $handler->taskNames # TODO: adjust help text according to $handler->taskNames

View File

@ -15,7 +15,8 @@ class CliScheme extends Shell
/** /**
* Execution method always used for tasks * Execution method always used for tasks
*/ */
public function execute() { public function execute()
{
$module = preg_replace('/Handler$/', '', $this->handler_to_use); $module = preg_replace('/Handler$/', '', $this->handler_to_use);
$module = strtolower($module); $module = strtolower($module);
@ -82,7 +83,8 @@ class CliScheme extends Shell
/** /**
* Displays help contents * Displays help contents
*/ */
public function help() { public function help()
{
$module = preg_replace('/Handler$/', '', $this->handler_to_use); $module = preg_replace('/Handler$/', '', $this->handler_to_use);
$module = strtolower($module); $module = strtolower($module);

View File

@ -10,7 +10,8 @@ class CliView extends Shell
/** /**
* Execution method always used for tasks * Execution method always used for tasks
*/ */
public function execute() { public function execute()
{
if (empty($this->args)) { if (empty($this->args)) {
return $this->__interactive(); return $this->__interactive();
} }
@ -23,7 +24,8 @@ class CliView extends Shell
/** /**
* Interactive mode * Interactive mode
*/ */
protected function __interactive() { protected function __interactive()
{
$module = preg_replace('/Handler$/', '', $this->handler_to_use); $module = preg_replace('/Handler$/', '', $this->handler_to_use);
$module = strtolower($module); $module = strtolower($module);
@ -38,7 +40,8 @@ class CliView extends Shell
* *
* @param string address to view * @param string address to view
*/ */
protected function __handle($address) { protected function __handle($address)
{
$handler = new $this->handler_to_use($this->new); $handler = new $this->handler_to_use($this->new);
if (!$handler->init($address)) { if (!$handler->init($address)) {
@ -88,7 +91,8 @@ class CliView extends Shell
* *
* @access public * @access public
*/ */
public function help() { public function help()
{
$module = preg_replace('/Handler$/', '', $this->handler_to_use); $module = preg_replace('/Handler$/', '', $this->handler_to_use);
$module = strtolower($module); $module = strtolower($module);

View File

@ -21,7 +21,8 @@ final class Config
* Return a singleton instance of Config * Return a singleton instance of Config
* @return Config * @return Config
*/ */
public static function getInstance() { public static function getInstance()
{
if (self::$instance == null) { if (self::$instance == null) {
self::$instance = new self(); self::$instance = new self();
} }
@ -35,7 +36,8 @@ final class Config
* @param mixed $value to set for key. * @param mixed $value to set for key.
* @return void * @return void
*/ */
public static function write(string $key, $value = null) { public static function write(string $key, $value = null)
{
$_this = self::getInstance(); $_this = self::getInstance();
$newConfig = $_this->getAll(); $newConfig = $_this->getAll();
$newConfig[$key] = $value; $newConfig[$key] = $value;
@ -46,7 +48,8 @@ final class Config
* @param string $var * @param string $var
* @return array * @return array
*/ */
public static function read_array(string $var) : array { public static function read_array(string $var) : array
{
$stuff = self::read($var); $stuff = self::read($var);
if (!is_array($stuff)) { if (!is_array($stuff)) {
@ -56,7 +59,8 @@ final class Config
return $stuff; return $stuff;
} }
public static function has(string $var) : bool { public static function has(string $var) : bool
{
$x = self::getInstance()->getAll(); $x = self::getInstance()->getAll();
return array_key_exists($var, $x); return array_key_exists($var, $x);
} }
@ -64,7 +68,8 @@ final class Config
* @param string $var * @param string $var
* @return string * @return string
*/ */
public static function read_string(string $var) : string { public static function read_string(string $var) : string
{
$stuff = self::read($var); $stuff = self::read($var);
if ($stuff === null) { if ($stuff === null) {
@ -83,7 +88,8 @@ final class Config
* @param string $var Variable to obtain * @param string $var Variable to obtain
* @return callable|array|string|null|bool some value * @return callable|array|string|null|bool some value
*/ */
public static function read(string $var) { public static function read(string $var)
{
$_this = self::getInstance(); $_this = self::getInstance();
$config = $_this->getAll(); $config = $_this->getAll();
@ -111,7 +117,8 @@ final class Config
* @param string $value Value to use as sprintf parameter * @param string $value Value to use as sprintf parameter
* @return string value of Config::$var, parsed by sprintf * @return string value of Config::$var, parsed by sprintf
*/ */
public static function read_f(string $var, string $value) : string { public static function read_f(string $var, string $value) : string
{
$text = self::read_string($var); $text = self::read_string($var);
$newtext = sprintf($text, $value); $newtext = sprintf($text, $value);
@ -134,7 +141,8 @@ final class Config
* @param string $var Variable to obtain * @param string $var Variable to obtain
* @return bool value of Configure::$var (TRUE (on YES/yes) or FALSE (on NO/no/not set/unknown value) * @return bool value of Configure::$var (TRUE (on YES/yes) or FALSE (on NO/no/not set/unknown value)
*/ */
public static function bool(string $var) : bool { public static function bool(string $var) : bool
{
$value = self::read($var); $value = self::read($var);
if (is_bool($value)) { if (is_bool($value)) {
@ -165,7 +173,8 @@ final class Config
* Used to read Config::$var, converted to bool, returned as integer (0 or 1) * Used to read Config::$var, converted to bool, returned as integer (0 or 1)
* @see bool() * @see bool()
*/ */
public static function intbool($var) : int { public static function intbool($var) : int
{
return Config::bool($var) ? 1 : 0; return Config::bool($var) ? 1 : 0;
} }
@ -178,7 +187,8 @@ final class Config
* @return string value of $PALANG[$var] * @return string value of $PALANG[$var]
* @access public * @access public
*/ */
public static function lang(string $var) : string { public static function lang(string $var) : string
{
$languages = self::read_array('__LANG'); $languages = self::read_array('__LANG');
$value = $languages[$var] ?? ''; $value = $languages[$var] ?? '';
@ -198,7 +208,8 @@ final class Config
* @param string $value Value to use as sprintf parameter * @param string $value Value to use as sprintf parameter
* @return string value of $PALANG[$var], parsed by sprintf * @return string value of $PALANG[$var], parsed by sprintf
*/ */
public static function lang_f(string $var, $value) : string { public static function lang_f(string $var, $value) : string
{
$all = self::read_array('__LANG'); $all = self::read_array('__LANG');
$text = $all[$var] ?? ''; $text = $all[$var] ?? '';
@ -216,14 +227,16 @@ final class Config
/** /**
* @return array * @return array
*/ */
public function getAll() : array { public function getAll() : array
{
return $this->config; return $this->config;
} }
/** /**
* @param array $config * @param array $config
*/ */
public function setAll(array $config) { public function setAll(array $config)
{
$this->config = $config; $this->config = $config;
} }
} }

View File

@ -10,7 +10,8 @@ class DomainHandler extends PFAHandler
protected $id_field = 'domain'; protected $id_field = 'domain';
protected $domain_field = 'domain'; protected $domain_field = 'domain';
protected function validate_new_id() { protected function validate_new_id()
{
$domain_check = check_domain($this->id); $domain_check = check_domain($this->id);
if ($domain_check != '') { if ($domain_check != '') {
@ -27,7 +28,8 @@ class DomainHandler extends PFAHandler
return true; return true;
} }
protected function initStruct() { protected function initStruct()
{
# TODO: shorter PALANG labels ;-) # TODO: shorter PALANG labels ;-)
$super = $this->is_superadmin; $super = $this->is_superadmin;
@ -117,7 +119,8 @@ class DomainHandler extends PFAHandler
); );
} }
protected function initMsg() { protected function initMsg()
{
$this->msg['error_already_exists'] = 'pAdminCreate_domain_domain_text_error'; $this->msg['error_already_exists'] = 'pAdminCreate_domain_domain_text_error';
$this->msg['error_does_not_exist'] = 'domain_does_not_exist'; $this->msg['error_does_not_exist'] = 'domain_does_not_exist';
$this->msg['confirm_delete'] = 'confirm_delete_domain'; $this->msg['confirm_delete'] = 'confirm_delete_domain';
@ -134,7 +137,8 @@ class DomainHandler extends PFAHandler
$this->msg['can_create'] = $this->is_superadmin; $this->msg['can_create'] = $this->is_superadmin;
} }
public function webformConfig() { public function webformConfig()
{
return array( return array(
# $PALANG labels # $PALANG labels
'formtitle_create' => 'pAdminCreate_domain_welcome', 'formtitle_create' => 'pAdminCreate_domain_welcome',
@ -149,7 +153,8 @@ class DomainHandler extends PFAHandler
} }
protected function preSave() : bool { protected function preSave() : bool
{
# TODO: is this function superfluous? _can_edit should already cover this # TODO: is this function superfluous? _can_edit should already cover this
if ($this->is_superadmin) { if ($this->is_superadmin) {
return true; return true;
@ -162,7 +167,8 @@ class DomainHandler extends PFAHandler
* called by $this->store() after storing $this->values in the database * called by $this->store() after storing $this->values in the database
* can be used to update additional tables, call scripts etc. * can be used to update additional tables, call scripts etc.
*/ */
protected function postSave() : bool { protected function postSave() : bool
{
if ($this->new && $this->values['default_aliases']) { if ($this->new && $this->values['default_aliases']) {
foreach (Config::read_array('default_aliases') as $address=>$goto) { foreach (Config::read_array('default_aliases') as $address=>$goto) {
$address = $address . "@" . $this->id; $address = $address . "@" . $this->id;
@ -194,7 +200,8 @@ class DomainHandler extends PFAHandler
/** /**
* @return bool * @return bool
*/ */
public function delete() { public function delete()
{
# TODO: check for _can_delete instead # TODO: check for _can_delete instead
if (! $this->is_superadmin) { if (! $this->is_superadmin) {
$this->errormsg[] = Config::Lang_f('no_delete_permissions', $this->id); $this->errormsg[] = Config::Lang_f('no_delete_permissions', $this->id);
@ -256,13 +263,16 @@ class DomainHandler extends PFAHandler
* *
* @param array values of current item * @param array values of current item
*/ */
public function _formatted_aliases($item) { public function _formatted_aliases($item)
{
return $item['alias_count'] . ' / ' . $item['aliases'] ; return $item['alias_count'] . ' / ' . $item['aliases'] ;
} }
public function _formatted_mailboxes($item) { public function _formatted_mailboxes($item)
{
return $item['mailbox_count'] . ' / ' . $item['mailboxes']; return $item['mailbox_count'] . ' / ' . $item['mailboxes'];
} }
public function _formatted_quota($item) { public function _formatted_quota($item)
{
return $item['total_quota'] . ' / ' . $item['quota'] ; return $item['total_quota'] . ' / ' . $item['quota'] ;
} }
@ -271,7 +281,8 @@ class DomainHandler extends PFAHandler
* *
* @return boolean * @return boolean
*/ */
protected function domain_postcreation() { protected function domain_postcreation()
{
$script=Config::read_string('domain_postcreation_script'); $script=Config::read_string('domain_postcreation_script');
if (empty($script)) { if (empty($script)) {
@ -303,7 +314,8 @@ class DomainHandler extends PFAHandler
* *
* @return boolean * @return boolean
*/ */
protected function domain_postdeletion() { protected function domain_postdeletion()
{
$script=Config::read_string('domain_postdeletion_script'); $script=Config::read_string('domain_postdeletion_script');
if (empty($script)) { if (empty($script)) {

View File

@ -12,7 +12,8 @@ class FetchmailHandler extends PFAHandler
protected $order_by = 'domain, mailbox'; protected $order_by = 'domain, mailbox';
protected function initStruct() { protected function initStruct()
{
$src_auth_options = array('password','kerberos_v5','kerberos','kerberos_v4','gssapi','cram-md5','otp','ntlm','msn','ssh','any'); $src_auth_options = array('password','kerberos_v5','kerberos','kerberos_v4','gssapi','cram-md5','otp','ntlm','msn','ssh','any');
$src_protocol_options = array('POP3','IMAP','POP2','ETRN','AUTO'); $src_protocol_options = array('POP3','IMAP','POP2','ETRN','AUTO');
@ -54,7 +55,8 @@ class FetchmailHandler extends PFAHandler
$this->struct['mailbox']['options'] = array_keys($handler->result); $this->struct['mailbox']['options'] = array_keys($handler->result);
} }
protected function initMsg() { protected function initMsg()
{
$this->msg['error_already_exists'] = 'fetchmail_already_exists'; $this->msg['error_already_exists'] = 'fetchmail_already_exists';
$this->msg['error_does_not_exist'] = 'fetchmail_does_not_exist'; $this->msg['error_does_not_exist'] = 'fetchmail_does_not_exist';
$this->msg['confirm_delete'] = 'confirm_delete_fetchmail'; $this->msg['confirm_delete'] = 'confirm_delete_fetchmail';
@ -70,7 +72,8 @@ class FetchmailHandler extends PFAHandler
} }
} }
public function webformConfig() { public function webformConfig()
{
return array( return array(
# $PALANG labels # $PALANG labels
'formtitle_create' => 'pMenu_fetchmail', 'formtitle_create' => 'pMenu_fetchmail',
@ -86,7 +89,8 @@ class FetchmailHandler extends PFAHandler
} }
protected function setmore(array $values) { protected function setmore(array $values)
{
# set domain based on the target mailbox # set domain based on the target mailbox
if ($this->new || isset($values['mailbox'])) { if ($this->new || isset($values['mailbox'])) {
list(/*NULL*/, $domain) = explode('@', $values['mailbox']); list(/*NULL*/, $domain) = explode('@', $values['mailbox']);
@ -95,7 +99,8 @@ class FetchmailHandler extends PFAHandler
} }
} }
protected function validate_new_id() { protected function validate_new_id()
{
# auto_increment - any non-empty ID is an error # auto_increment - any non-empty ID is an error
if ($this->id != '') { if ($this->id != '') {
$this->errormsg[$this->id_field] = 'auto_increment value, you must pass an empty string!'; $this->errormsg[$this->id_field] = 'auto_increment value, you must pass an empty string!';
@ -110,7 +115,8 @@ class FetchmailHandler extends PFAHandler
/** /**
* @return boolean * @return boolean
*/ */
public function delete() { public function delete()
{
if (! $this->view()) { if (! $this->view()) {
$this->errormsg[] = Config::lang($this->msg['error_does_not_exist']); $this->errormsg[] = Config::lang($this->msg['error_does_not_exist']);
return false; return false;
@ -128,7 +134,8 @@ class FetchmailHandler extends PFAHandler
/** /**
* validate src_server - must be non-empty and survive check_domain() * validate src_server - must be non-empty and survive check_domain()
*/ */
protected function _validate_src_server($field, $val) { protected function _validate_src_server($field, $val)
{
if ($val == '') { if ($val == '') {
$msg = Config::Lang('pFetchmail_server_missing'); $msg = Config::Lang('pFetchmail_server_missing');
} else { } else {
@ -148,7 +155,8 @@ class FetchmailHandler extends PFAHandler
* (we can't assume anything about valid usernames and passwords on remote * (we can't assume anything about valid usernames and passwords on remote
* servers, so the validation can't be more strict) * servers, so the validation can't be more strict)
*/ */
protected function _validate_src_user($field, $val) { protected function _validate_src_user($field, $val)
{
if ($val == '') { if ($val == '') {
$this->errormsg[$field] = Config::lang('pFetchmail_user_missing'); $this->errormsg[$field] = Config::lang('pFetchmail_user_missing');
return false; return false;
@ -156,7 +164,8 @@ class FetchmailHandler extends PFAHandler
return true; return true;
} }
protected function _validate_src_password($field, $val) { protected function _validate_src_password($field, $val)
{
if ($val == '') { if ($val == '') {
$this->errormsg[$field] = Config::lang('pFetchmail_password_missing'); $this->errormsg[$field] = Config::lang('pFetchmail_password_missing');
return false; return false;
@ -167,7 +176,8 @@ class FetchmailHandler extends PFAHandler
/** /**
* validate poll interval - must be numeri and > 0 * validate poll interval - must be numeri and > 0
*/ */
protected function _validate_poll_time($field, $val) { protected function _validate_poll_time($field, $val)
{
# must be > 0 # must be > 0
if ($val < 1) { if ($val < 1) {
$this->errormsg[$field] = Config::Lang_f('must_be_numeric_bigger_than_null', $field); $this->errormsg[$field] = Config::Lang_f('must_be_numeric_bigger_than_null', $field);
@ -176,7 +186,8 @@ class FetchmailHandler extends PFAHandler
return true; return true;
} }
public function domain_from_id() { public function domain_from_id()
{
return ''; return '';
} }
} }

View File

@ -5,7 +5,8 @@ class Login
private $key_table; private $key_table;
private $table; private $table;
public function __construct(string $tableName) { public function __construct(string $tableName)
{
$ok = ['mailbox', 'admin']; $ok = ['mailbox', 'admin'];
if (!in_array($tableName, $ok)) { if (!in_array($tableName, $ok)) {
@ -22,7 +23,8 @@ class Login
* @param string $password * @param string $password
* @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): bool { public function login($username, $password): bool
{
$active = db_get_boolean(true); $active = db_get_boolean(true);
$query = "SELECT password FROM {$this->key_table} WHERE username = :username AND active = :active"; $query = "SELECT password FROM {$this->key_table} WHERE username = :username AND active = :active";
@ -62,7 +64,8 @@ class Login
* @return false|string * @return false|string
* @throws Exception * @throws Exception
*/ */
public function generatePasswordRecoveryCode(string $username) { public function generatePasswordRecoveryCode(string $username)
{
$sql = "SELECT count(1) FROM {$this->key_table} WHERE username = :username AND active = :active"; $sql = "SELECT count(1) FROM {$this->key_table} WHERE username = :username AND active = :active";
$active = db_get_boolean(true); $active = db_get_boolean(true);
@ -100,7 +103,8 @@ class Login
* @return boolean true on success; false on failure * @return boolean true on success; false on failure
* @throws \Exception if invalid user, or db update fails. * @throws \Exception if invalid user, or db update fails.
*/ */
public function changePassword($username, $new_password, $old_password): bool { public function changePassword($username, $new_password, $old_password): bool
{
list(/*NULL*/, $domain) = explode('@', $username); list(/*NULL*/, $domain) = explode('@', $username);
if (!$this->login($username, $old_password)) { if (!$this->login($username, $old_password)) {

View File

@ -12,7 +12,8 @@ class MailboxHandler extends PFAHandler
protected $searchfields = array('username'); protected $searchfields = array('username');
# init $this->struct, $this->db_table and $this->id_field # init $this->struct, $this->db_table and $this->id_field
protected function initStruct() { protected function initStruct()
{
$passwordReset = (int) ( Config::bool('forgotten_user_password_reset') && !Config::read('mailbox_postpassword_script') ); $passwordReset = (int) ( Config::bool('forgotten_user_password_reset') && !Config::read('mailbox_postpassword_script') );
$reset_by_sms = 0; $reset_by_sms = 0;
if ($passwordReset && Config::read_string('sms_send_function')) { if ($passwordReset && Config::read_string('sms_send_function')) {
@ -65,7 +66,8 @@ class MailboxHandler extends PFAHandler
} }
} }
public function init($id) : bool { public function init($id) : bool
{
if (!parent::init($id)) { if (!parent::init($id)) {
return false; return false;
} }
@ -81,7 +83,8 @@ class MailboxHandler extends PFAHandler
return true; # still here? good. return true; # still here? good.
} }
protected function domain_from_id() { protected function domain_from_id()
{
list(/*NULL*/, $domain) = explode('@', $this->id); list(/*NULL*/, $domain) = explode('@', $this->id);
return $domain; return $domain;
} }
@ -91,7 +94,8 @@ class MailboxHandler extends PFAHandler
* @param string - domain * @param string - domain
* @param int - current quota * @param int - current quota
*/ */
protected function updateMaxquota($domain, $currentquota) { protected function updateMaxquota($domain, $currentquota)
{
if ($domain == '') { if ($domain == '') {
return false; return false;
} }
@ -107,7 +111,8 @@ class MailboxHandler extends PFAHandler
} }
} }
protected function initMsg() { protected function initMsg()
{
$this->msg['error_already_exists'] = 'email_address_already_exists'; $this->msg['error_already_exists'] = 'email_address_already_exists';
$this->msg['error_does_not_exist'] = 'pCreate_mailbox_username_text_error1'; $this->msg['error_does_not_exist'] = 'pCreate_mailbox_username_text_error1';
$this->msg['confirm_delete'] = 'confirm_delete_mailbox'; $this->msg['confirm_delete'] = 'confirm_delete_mailbox';
@ -123,7 +128,8 @@ class MailboxHandler extends PFAHandler
} }
} }
public function webformConfig() { public function webformConfig()
{
if ($this->new) { # the webform will display a local_part field + domain dropdown on $new if ($this->new) { # the webform will display a local_part field + domain dropdown on $new
$this->struct['username']['display_in_form'] = 0; $this->struct['username']['display_in_form'] = 0;
$this->struct['local_part']['display_in_form'] = 1; $this->struct['local_part']['display_in_form'] = 1;
@ -145,7 +151,8 @@ class MailboxHandler extends PFAHandler
} }
protected function validate_new_id() { protected function validate_new_id()
{
if ($this->id == '') { if ($this->id == '') {
$this->errormsg[$this->id_field] = Config::lang('pCreate_mailbox_username_text_error1'); $this->errormsg[$this->id_field] = Config::lang('pCreate_mailbox_username_text_error1');
return false; return false;
@ -180,7 +187,8 @@ class MailboxHandler extends PFAHandler
/** /**
* check number of existing mailboxes for this domain - is one more allowed? * check number of existing mailboxes for this domain - is one more allowed?
*/ */
private function create_allowed($domain) { private function create_allowed($domain)
{
$limit = get_domain_properties($domain); $limit = get_domain_properties($domain);
if ($limit['mailboxes'] == 0) { if ($limit['mailboxes'] == 0) {
@ -199,7 +207,8 @@ class MailboxHandler extends PFAHandler
* merge local_part and domain to address * merge local_part and domain to address
* called by edit.php (if id_field is editable and hidden in editform) _before_ ->init * called by edit.php (if id_field is editable and hidden in editform) _before_ ->init
*/ */
public function mergeId($values) { public function mergeId($values)
{
if ($this->struct['local_part']['display_in_form'] == 1 && $this->struct['domain']['display_in_form']) { # webform mode - combine to 'address' field if ($this->struct['local_part']['display_in_form'] == 1 && $this->struct['domain']['display_in_form']) { # webform mode - combine to 'address' field
return $values['local_part'] . '@' . $values['domain']; return $values['local_part'] . '@' . $values['domain'];
} else { } else {
@ -208,7 +217,8 @@ class MailboxHandler extends PFAHandler
} }
protected function read_from_db_postprocess($db_result) { protected function read_from_db_postprocess($db_result)
{
foreach ($db_result as $key => $row) { foreach ($db_result as $key => $row) {
if (isset($row['quota']) && is_numeric($row['quota']) && $row['quota'] > -1) { # quota could be disabled in $struct if (isset($row['quota']) && is_numeric($row['quota']) && $row['quota'] > -1) { # quota could be disabled in $struct
$db_result[$key]['quotabytes'] = $row['quota']; $db_result[$key]['quotabytes'] = $row['quota'];
@ -222,7 +232,8 @@ class MailboxHandler extends PFAHandler
} }
protected function preSave() : bool { protected function preSave() : bool
{
if (isset($this->values['quota']) && $this->values['quota'] != -1 && is_numeric($this->values['quota'])) { if (isset($this->values['quota']) && $this->values['quota'] != -1 && is_numeric($this->values['quota'])) {
$multiplier = Config::read_string('quota_multiplier'); $multiplier = Config::read_string('quota_multiplier');
if ($multiplier == 0 || !is_numeric($multiplier)) { // or empty string, or null, or false... if ($multiplier == 0 || !is_numeric($multiplier)) { // or empty string, or null, or false...
@ -280,14 +291,16 @@ class MailboxHandler extends PFAHandler
return true; return true;
} }
protected function setmore(array $values) { protected function setmore(array $values)
{
if (array_key_exists('quota', $this->values)) { if (array_key_exists('quota', $this->values)) {
$this->values['quota'] = (int)$this->values['quota']; $this->values['quota'] = (int)$this->values['quota'];
} }
} }
// Could perhaps also use _validate_local_part($new_value) { .... } // Could perhaps also use _validate_local_part($new_value) { .... }
public function set(array $values) { public function set(array $values)
{
// See: https://github.com/postfixadmin/postfixadmin/issues/282 - ensure the 'local_part' does not contain an @ sign. // See: https://github.com/postfixadmin/postfixadmin/issues/282 - ensure the 'local_part' does not contain an @ sign.
$ok = true; $ok = true;
if (isset($values['local_part']) && strpos($values['local_part'], '@')) { if (isset($values['local_part']) && strpos($values['local_part'], '@')) {
@ -297,7 +310,8 @@ class MailboxHandler extends PFAHandler
return $ok && parent::set($values); return $ok && parent::set($values);
} }
protected function postSave() : bool { protected function postSave() : bool
{
if ($this->new) { if ($this->new) {
if (!$this->mailbox_post_script()) { if (!$this->mailbox_post_script()) {
# return false; # TODO: should this be fatal? # return false; # TODO: should this be fatal?
@ -343,7 +357,8 @@ class MailboxHandler extends PFAHandler
return true; # even if a hook failed, mark the overall operation as OK return true; # even if a hook failed, mark the overall operation as OK
} }
public function delete() { public function delete()
{
if (! $this->view()) { if (! $this->view()) {
$this->errormsg[] = Config::Lang('pFetchmail_invalid_mailbox'); # TODO: can users hit this message at all? init() should already fail... $this->errormsg[] = Config::Lang('pFetchmail_invalid_mailbox'); # TODO: can users hit this message at all? init() should already fail...
return false; return false;
@ -373,7 +388,8 @@ class MailboxHandler extends PFAHandler
protected function _prefill_domain($field, $val) { protected function _prefill_domain($field, $val)
{
if (in_array($val, $this->struct[$field]['options'])) { if (in_array($val, $this->struct[$field]['options'])) {
$this->struct[$field]['default'] = $val; $this->struct[$field]['default'] = $val;
$this->updateMaxquota($val, 0); $this->updateMaxquota($val, 0);
@ -383,7 +399,8 @@ class MailboxHandler extends PFAHandler
/** /**
* check if quota is allowed * check if quota is allowed
*/ */
protected function _validate_quota($field, $val) { protected function _validate_quota($field, $val)
{
if (!$this->check_quota($val)) { if (!$this->check_quota($val)) {
$this->errormsg[$field] = Config::lang('pEdit_mailbox_quota_text_error'); $this->errormsg[$field] = Config::lang('pEdit_mailbox_quota_text_error');
return false; return false;
@ -396,7 +413,8 @@ class MailboxHandler extends PFAHandler
* - autogenerate password if enabled in config and $new * - autogenerate password if enabled in config and $new
* - display password on $new if enabled in config or autogenerated * - display password on $new if enabled in config or autogenerated
*/ */
protected function _validate_password($field, $val) { protected function _validate_password($field, $val)
{
if (!$this->_validate_password2($field, $val)) { if (!$this->_validate_password2($field, $val)) {
return false; return false;
} }
@ -419,14 +437,16 @@ class MailboxHandler extends PFAHandler
* compare password / password2 field * compare password / password2 field
* error message will be displayed at the password2 field * error message will be displayed at the password2 field
*/ */
protected function _validate_password2($field, $val) { protected function _validate_password2($field, $val)
{
return $this->compare_password_fields('password', 'password2'); return $this->compare_password_fields('password', 'password2');
} }
/** /**
* on $this->new, set localpart based on address * on $this->new, set localpart based on address
*/ */
protected function _missing_local_part($field) { protected function _missing_local_part($field)
{
list($local_part, $domain) = explode('@', $this->id); list($local_part, $domain) = explode('@', $this->id);
$this->RAWvalues['local_part'] = $local_part; $this->RAWvalues['local_part'] = $local_part;
} }
@ -434,7 +454,8 @@ class MailboxHandler extends PFAHandler
/** /**
* on $this->new, set domain based on address * on $this->new, set domain based on address
*/ */
protected function _missing_domain($field) { protected function _missing_domain($field)
{
list($local_part, $domain) = explode('@', $this->id); list($local_part, $domain) = explode('@', $this->id);
$this->RAWvalues['domain'] = $domain; $this->RAWvalues['domain'] = $domain;
} }
@ -447,7 +468,8 @@ class MailboxHandler extends PFAHandler
/** /**
* calculate maildir path for the mailbox * calculate maildir path for the mailbox
*/ */
protected function _missing_maildir($field) { protected function _missing_maildir($field)
{
list($local_part, $domain) = explode('@', $this->id); list($local_part, $domain) = explode('@', $this->id);
$maildir_name_hook = Config::read('maildir_name_hook'); $maildir_name_hook = Config::read('maildir_name_hook');
@ -468,7 +490,8 @@ class MailboxHandler extends PFAHandler
$this->RAWvalues['maildir'] = $maildir; $this->RAWvalues['maildir'] = $maildir;
} }
private function send_welcome_mail() { private function send_welcome_mail()
{
$fTo = $this->id; $fTo = $this->id;
$fFrom = smtp_get_admin_email(); $fFrom = smtp_get_admin_email();
if (empty($fFrom) || $fFrom == 'CLI') { if (empty($fFrom) || $fFrom == 'CLI') {
@ -493,7 +516,8 @@ class MailboxHandler extends PFAHandler
* @return boolean - true if requested quota is OK, otherwise false * @return boolean - true if requested quota is OK, otherwise false
* @todo merge with allowed_quota? * @todo merge with allowed_quota?
*/ */
protected function check_quota($quota) { protected function check_quota($quota)
{
if (!Config::bool('quota')) { if (!Config::bool('quota')) {
return true; # enforcing quotas is disabled - just allow it return true; # enforcing quotas is disabled - just allow it
} }
@ -547,7 +571,8 @@ class MailboxHandler extends PFAHandler
* @param int $current_user_quota (in bytes) * @param int $current_user_quota (in bytes)
* @return int allowed maximum quota (in MB) * @return int allowed maximum quota (in MB)
*/ */
protected function allowed_quota($domain, $current_user_quota) { protected function allowed_quota($domain, $current_user_quota)
{
if (!Config::bool('quota')) { if (!Config::bool('quota')) {
return 0; # quota disabled means no limits - no need for more checks return 0; # quota disabled means no limits - no need for more checks
} }
@ -575,7 +600,8 @@ class MailboxHandler extends PFAHandler
* *
* @return boolean success/failure status * @return boolean success/failure status
*/ */
protected function mailbox_post_script() { protected function mailbox_post_script()
{
if ($this->new) { if ($this->new) {
$cmd = Config::read_string('mailbox_postcreation_script'); $cmd = Config::read_string('mailbox_postcreation_script');
$warnmsg = Config::Lang('mailbox_postcreate_failed'); $warnmsg = Config::Lang('mailbox_postcreate_failed');
@ -647,7 +673,8 @@ class MailboxHandler extends PFAHandler
* @return boolean true on success, false on failure * @return boolean true on success, false on failure
* also adds a detailed error message to $this->errormsg[] * also adds a detailed error message to $this->errormsg[]
*/ */
protected function mailbox_postdeletion() { protected function mailbox_postdeletion()
{
$cmd = Config::read_string('mailbox_postdeletion_script'); $cmd = Config::read_string('mailbox_postdeletion_script');
if (empty($cmd)) { if (empty($cmd)) {
@ -695,7 +722,8 @@ class MailboxHandler extends PFAHandler
* *
* @return boolean TRUE if everything succeeds, FALSE on all errors * @return boolean TRUE if everything succeeds, FALSE on all errors
*/ */
protected function create_mailbox_subfolders() { protected function create_mailbox_subfolders()
{
$create_mailbox_subdirs = Config::read('create_mailbox_subdirs'); $create_mailbox_subdirs = Config::read('create_mailbox_subdirs');
if (empty($create_mailbox_subdirs)) { if (empty($create_mailbox_subdirs)) {
return true; return true;

View File

@ -167,7 +167,8 @@ abstract class PFAHandler
* @param string $username - if an admin_username is specified, permissions will be restricted to the domains this admin may manage * @param string $username - if an admin_username is specified, permissions will be restricted to the domains this admin may manage
* @param int $is_admin - 0 if logged in as user, 1 if logged in as admin or superadmin * @param int $is_admin - 0 if logged in as user, 1 if logged in as admin or superadmin
*/ */
public function __construct($new = 0, $username = "", $is_admin = 1) { public function __construct($new = 0, $username = "", $is_admin = 1)
{
# set label_field if not explicitely set # set label_field if not explicitely set
if (empty($this->id_field)) { if (empty($this->id_field)) {
throw new \InvalidArgumentException("id_field must be defined"); throw new \InvalidArgumentException("id_field must be defined");
@ -253,7 +254,8 @@ abstract class PFAHandler
* *
* to intentionally disable the check if $this->domain_field is empty, override this function * to intentionally disable the check if $this->domain_field is empty, override this function
*/ */
protected function no_domain_field() { protected function no_domain_field()
{
if ($this->admin_username != "") { if ($this->admin_username != "") {
die('Attemp to restrict domains without setting $this->domain_field!'); die('Attemp to restrict domains without setting $this->domain_field!');
} }
@ -264,7 +266,8 @@ abstract class PFAHandler
* *
* to intentionally disable the check if $this->user_field is empty, override this function * to intentionally disable the check if $this->user_field is empty, override this function
*/ */
protected function no_user_field() { protected function no_user_field()
{
if ($this->username != '') { if ($this->username != '') {
die('Attemp to restrict users without setting $this->user_field!'); die('Attemp to restrict users without setting $this->user_field!');
} }
@ -330,7 +333,8 @@ abstract class PFAHandler
* *
* @param string calling class * @param string calling class
*/ */
public function calledBy($calling_class) { public function calledBy($calling_class)
{
$this->called_by = $calling_class; $this->called_by = $calling_class;
} }
@ -338,7 +342,8 @@ abstract class PFAHandler
* initialize with $id and check if it is valid * initialize with $id and check if it is valid
* @param string $id * @param string $id
*/ */
public function init(string $id) : bool { public function init(string $id) : bool
{
// postfix treats address lookups (aliases, mailboxes) as if they were lowercase. // postfix treats address lookups (aliases, mailboxes) as if they were lowercase.
// MySQL is normally case insenstive, PostgreSQL is case sensitive. // MySQL is normally case insenstive, PostgreSQL is case sensitive.
@ -388,7 +393,8 @@ abstract class PFAHandler
* must be overridden if $id_field != $domain_field * must be overridden if $id_field != $domain_field
* @return string the domain to use for logging * @return string the domain to use for logging
*/ */
protected function domain_from_id() { protected function domain_from_id()
{
if ($this->id_field == $this->domain_field) { if ($this->id_field == $this->domain_field) {
return $this->id; return $this->id;
} elseif ($this->domain_field == "") { } elseif ($this->domain_field == "") {
@ -404,7 +410,8 @@ abstract class PFAHandler
* @param string $field - field * @param string $field - field
* @param string $val - prefill value * @param string $val - prefill value
*/ */
public function prefill($field, $val) { public function prefill($field, $val)
{
$func="_prefill_".$field; $func="_prefill_".$field;
if (method_exists($this, $func)) { if (method_exists($this, $func)) {
$this->{$func}($field, $val); # call _missing_$fieldname() $this->{$func}($field, $val); # call _missing_$fieldname()
@ -419,7 +426,8 @@ abstract class PFAHandler
* @return bool - true if all values are valid, otherwise false * @return bool - true if all values are valid, otherwise false
* error messages (if any) are stored in $this->errormsg * error messages (if any) are stored in $this->errormsg
*/ */
public function set(array $values) { public function set(array $values)
{
if (!$this->can_edit) { if (!$this->can_edit) {
$this->errormsg[] = Config::Lang_f('edit_not_allowed', $this->label); $this->errormsg[] = Config::Lang_f('edit_not_allowed', $this->label);
return false; return false;
@ -522,7 +530,8 @@ abstract class PFAHandler
* can be used to update additional columns etc. * can be used to update additional columns etc.
* hint: modify $this->values and $this->errormsg directly as needed * hint: modify $this->values and $this->errormsg directly as needed
*/ */
protected function setmore(array $values) { protected function setmore(array $values)
{
# do nothing # do nothing
} }
@ -535,7 +544,8 @@ abstract class PFAHandler
* @return bool - true if all values were stored in the database, otherwise false * @return bool - true if all values were stored in the database, otherwise false
* error messages (if any) are stored in $this->errormsg * error messages (if any) are stored in $this->errormsg
*/ */
public function save() : bool { public function save() : bool
{
# backwards compability: save() was once (up to 3.2.x) named store(). If a child class still uses the old name, let it override save(). # backwards compability: save() was once (up to 3.2.x) named store(). If a child class still uses the old name, let it override save().
if (method_exists($this, 'store')) { if (method_exists($this, 'store')) {
error_log('store() is deprecated, please rename it to save()'); error_log('store() is deprecated, please rename it to save()');
@ -609,7 +619,8 @@ abstract class PFAHandler
* called by $this->save() before storing the values in the database * called by $this->save() before storing the values in the database
* @return bool - if false, save() will abort * @return bool - if false, save() will abort
*/ */
protected function preSave() : bool { protected function preSave() : bool
{
# backwards compability: preSave() was once (up to 3.2.x) named beforestore(). If a child class still uses the old name, let it override preSave(). # backwards compability: preSave() was once (up to 3.2.x) named beforestore(). If a child class still uses the old name, let it override preSave().
# Note: if a child class also has preSave(), it will override this function and obviously also the compability code. # Note: if a child class also has preSave(), it will override this function and obviously also the compability code.
if (method_exists($this, 'beforestore')) { if (method_exists($this, 'beforestore')) {
@ -624,7 +635,8 @@ abstract class PFAHandler
* called by $this->save() after storing $this->values in the database * called by $this->save() after storing $this->values in the database
* can be used to update additional tables, call scripts etc. * can be used to update additional tables, call scripts etc.
*/ */
protected function postSave() : bool { protected function postSave() : bool
{
# backwards compability: postSave() was once (up to 3.2.x) named storemore(). If a child class still uses the old name, let it override postSave(). # backwards compability: postSave() was once (up to 3.2.x) named storemore(). If a child class still uses the old name, let it override postSave().
# Note: if a child class also has postSave(), it will override this function and obviously also the compability code. # Note: if a child class also has postSave(), it will override this function and obviously also the compability code.
if (method_exists($this, 'storemore')) { if (method_exists($this, 'storemore')) {
@ -648,7 +660,8 @@ abstract class PFAHandler
* @param array searchmode - operators to use (=, <, >) if $condition is an array. Defaults to = if not specified for a field. * @param array searchmode - operators to use (=, <, >) if $condition is an array. Defaults to = if not specified for a field.
* @return array - contains query parts * @return array - contains query parts
*/ */
protected function build_select_query($condition, $searchmode) { protected function build_select_query($condition, $searchmode)
{
$select_cols = array(); $select_cols = array();
$yes = escape_string(Config::lang('YES')); $yes = escape_string(Config::lang('YES'));
@ -737,7 +750,8 @@ abstract class PFAHandler
* @param array searchmode - (see build_select_query() for details) * @param array searchmode - (see build_select_query() for details)
* @return array - pagebrowser keys ("aa-cz", "de-pf", ...) * @return array - pagebrowser keys ("aa-cz", "de-pf", ...)
*/ */
public function getPagebrowser($condition, $searchmode) { public function getPagebrowser($condition, $searchmode)
{
$queryparts = $this->build_select_query($condition, $searchmode); $queryparts = $this->build_select_query($condition, $searchmode);
return create_page_browser($this->label_field, $queryparts['from_where_order']); return create_page_browser($this->label_field, $queryparts['from_where_order']);
} }
@ -756,7 +770,8 @@ abstract class PFAHandler
* @param int $offset - number of first row to return * @param int $offset - number of first row to return
* @return array - rows (as associative array, with the ID as key) * @return array - rows (as associative array, with the ID as key)
*/ */
protected function read_from_db($condition, $searchmode = array(), $limit=-1, $offset=-1) : array { protected function read_from_db($condition, $searchmode = array(), $limit=-1, $offset=-1) : array
{
$queryparts = $this->build_select_query($condition, $searchmode); $queryparts = $this->build_select_query($condition, $searchmode);
$query = $queryparts['select_cols'] . $queryparts['from_where_order']; $query = $queryparts['select_cols'] . $queryparts['from_where_order'];
@ -785,7 +800,8 @@ abstract class PFAHandler
* @param array $db_result * @param array $db_result
* @return array * @return array
*/ */
protected function read_from_db_postprocess($db_result) { protected function read_from_db_postprocess($db_result)
{
return $db_result; return $db_result;
} }
@ -797,7 +813,8 @@ abstract class PFAHandler
* The data is stored in $this->result (as associative array of column => value) * The data is stored in $this->result (as associative array of column => value)
* error messages (if any) are stored in $this->errormsg * error messages (if any) are stored in $this->errormsg
*/ */
public function view($errors=true) { public function view($errors=true)
{
$result = $this->read_from_db(array($this->id_field => $this->id)); $result = $this->read_from_db(array($this->id_field => $this->id));
if (count($result) == 1) { if (count($result) == 1) {
$this->result = reset($result); $this->result = reset($result);
@ -821,7 +838,8 @@ abstract class PFAHandler
* @return bool - always true, no need to check ;-) (if $result is not an array, getList die()s) * @return bool - always true, no need to check ;-) (if $result is not an array, getList die()s)
* The data is stored in $this->result (as array of rows, each row is an associative array of column => value) * The data is stored in $this->result (as array of rows, each row is an associative array of column => value)
*/ */
public function getList($condition, $searchmode = array(), $limit=-1, $offset=-1) : bool { public function getList($condition, $searchmode = array(), $limit=-1, $offset=-1) : bool
{
if (is_array($condition)) { if (is_array($condition)) {
$real_condition = array(); $real_condition = array();
foreach ($condition as $key => $value) { foreach ($condition as $key => $value) {
@ -849,7 +867,8 @@ abstract class PFAHandler
* @param string $token * @param string $token
* @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)
{
$table = table_by_key($this->db_table); $table = table_by_key($this->db_table);
$active = db_get_boolean(true); $active = db_get_boolean(true);
@ -878,22 +897,26 @@ abstract class PFAHandler
/************************************************************************** /**************************************************************************
* functions to read protected variables * functions to read protected variables
*/ */
public function getStruct() { public function getStruct()
{
return $this->struct; return $this->struct;
} }
public function getMsg() { public function getMsg()
{
return $this->msg; return $this->msg;
} }
public function getId_field() { public function getId_field()
{
return $this->id_field; return $this->id_field;
} }
/** /**
* @return mixed return value of previously called method * @return mixed return value of previously called method
*/ */
public function result() { public function result()
{
return $this->result; return $this->result;
} }
@ -904,7 +927,8 @@ abstract class PFAHandler
* @param string $field1 - "password" field * @param string $field1 - "password" field
* @param string $field2 - "repeat password" field * @param string $field2 - "repeat password" field
*/ */
protected function compare_password_fields($field1, $field2) { protected function compare_password_fields($field1, $field2)
{
if ($this->RAWvalues[$field1] == $this->RAWvalues[$field2]) { if ($this->RAWvalues[$field1] == $this->RAWvalues[$field2]) {
unset($this->errormsg[$field2]); # no need to warn about too short etc. passwords - it's enough to display this message at the 'password' field unset($this->errormsg[$field2]); # no need to warn about too short etc. passwords - it's enough to display this message at the 'password' field
return true; return true;
@ -919,7 +943,8 @@ abstract class PFAHandler
* @param string $field - fieldname * @param string $field - fieldname
* @return void * @return void
*/ */
protected function set_default_value($field) { protected function set_default_value($field)
{
if (isset($this->struct[$field]['default'])) { if (isset($this->struct[$field]['default'])) {
$this->RAWvalues[$field] = $this->struct[$field]['default']; $this->RAWvalues[$field] = $this->struct[$field]['default'];
} }
@ -939,7 +964,8 @@ abstract class PFAHandler
* @param string $val * @param string $val
* @return boolean * @return boolean
*/ */
protected function _inp_num($field, $val) { protected function _inp_num($field, $val)
{
$valid = is_numeric($val); $valid = is_numeric($val);
if ($val < -1) { if ($val < -1) {
$valid = false; $valid = false;
@ -957,7 +983,8 @@ abstract class PFAHandler
* @param string $val * @param string $val
* @return boolean * @return boolean
*/ */
protected function _inp_bool($field, $val) { protected function _inp_bool($field, $val)
{
if ($val == "0" || $val == "1") { if ($val == "0" || $val == "1") {
return true; return true;
} }
@ -972,7 +999,8 @@ abstract class PFAHandler
* @param string $val * @param string $val
* @return boolean * @return boolean
*/ */
protected function _inp_enum($field, $val) { protected function _inp_enum($field, $val)
{
if (in_array($val, $this->struct[$field]['options'])) { if (in_array($val, $this->struct[$field]['options'])) {
return true; return true;
} }
@ -986,7 +1014,8 @@ abstract class PFAHandler
* @param string $val * @param string $val
* @return boolean * @return boolean
*/ */
protected function _inp_enma($field, $val) { protected function _inp_enma($field, $val)
{
if (array_key_exists($val, $this->struct[$field]['options'])) { if (array_key_exists($val, $this->struct[$field]['options'])) {
return true; return true;
} }
@ -1000,7 +1029,8 @@ abstract class PFAHandler
* @param string $val * @param string $val
* @return boolean * @return boolean
*/ */
protected function _inp_pass($field, $val) { protected function _inp_pass($field, $val)
{
$validpass = validate_password($val); # returns array of error messages, or empty array on success $validpass = validate_password($val); # returns array of error messages, or empty array on success
if (count($validpass) == 0) { if (count($validpass) == 0) {

View File

@ -11,7 +11,8 @@ class PFASmarty
*/ */
protected $template; protected $template;
public static function getInstance() { public static function getInstance()
{
if (self::$instance) { if (self::$instance) {
return self::$instance; return self::$instance;
} }
@ -21,7 +22,8 @@ class PFASmarty
} }
private function __construct() { private function __construct()
{
$CONF = Config::getInstance()->getAll(); $CONF = Config::getInstance()->getAll();
$theme = ''; $theme = '';
@ -57,7 +59,8 @@ class PFASmarty
/** /**
* @param string $rel_path - relative path for referenced css etc dependencies - e.g. users/edit.php needs '../' else, it's ''. * @param string $rel_path - relative path for referenced css etc dependencies - e.g. users/edit.php needs '../' else, it's ''.
*/ */
public function configureTheme(string $rel_path = '') { public function configureTheme(string $rel_path = '')
{
$CONF = Config::getInstance()->getAll(); $CONF = Config::getInstance()->getAll();
// see: https://github.com/postfixadmin/postfixadmin/issues/410 // see: https://github.com/postfixadmin/postfixadmin/issues/410
@ -87,7 +90,8 @@ class PFASmarty
* @param mixed $value * @param mixed $value
* @param bool $sanitise * @param bool $sanitise
*/ */
public function assign($key, $value, $sanitise = true) { public function assign($key, $value, $sanitise = true)
{
$this->template->assign("RAW_$key", $value); $this->template->assign("RAW_$key", $value);
if ($sanitise == false) { if ($sanitise == false) {
return $this->template->assign($key, $value); return $this->template->assign($key, $value);
@ -101,7 +105,8 @@ class PFASmarty
* @param string $template * @param string $template
* @return void * @return void
*/ */
public function display($template) { public function display($template)
{
$CONF = Config::getInstance()->getAll(); $CONF = Config::getInstance()->getAll();
$this->assign('PALANG', $CONF['__LANG'] ?? []); $this->assign('PALANG', $CONF['__LANG'] ?? []);
@ -129,7 +134,8 @@ class PFASmarty
* @param mixed $data - array or primitive type; objects not supported. * @param mixed $data - array or primitive type; objects not supported.
* @return mixed $data * @return mixed $data
* */ * */
public function sanitise($data) { public function sanitise($data)
{
if (is_object($data)) { if (is_object($data)) {
return $data; // can't handle return $data; // can't handle
} }

View File

@ -103,7 +103,8 @@ class Shell
* Constructs this Shell instance. * Constructs this Shell instance.
* *
*/ */
public function __construct(&$dispatch) { public function __construct(&$dispatch)
{
$vars = array('params', 'args', 'shell', 'shellCommand'=> 'command'); $vars = array('params', 'args', 'shell', 'shellCommand'=> 'command');
foreach ($vars as $key => $var) { foreach ($vars as $key => $var) {
if (is_string($key)) { if (is_string($key)) {
@ -129,7 +130,8 @@ class Shell
* *
* @access public * @access public
*/ */
public function startup() { public function startup()
{
if (empty($this->params['q'])) { if (empty($this->params['q'])) {
$this->_welcome(); $this->_welcome();
} }
@ -139,7 +141,8 @@ class Shell
* *
* @access protected * @access protected
*/ */
public function _welcome() { public function _welcome()
{
$this->out("\nWelcome to Postfixadmin-CLI v" . $this->Dispatch->version); $this->out("\nWelcome to Postfixadmin-CLI v" . $this->Dispatch->version);
$this->hr(); $this->hr();
} }
@ -152,7 +155,8 @@ class Shell
* @param string $default Default input value. * @param string $default Default input value.
* @return string either the default value, or the user-provided input. * @return string either the default value, or the user-provided input.
*/ */
public function in($prompt, $options = null, $default = '') { public function in($prompt, $options = null, $default = '')
{
if (!$this->interactive) { if (!$this->interactive) {
return $default; return $default;
} }
@ -185,7 +189,8 @@ class Shell
* @param string|array $string String to output. * @param string|array $string String to output.
* @param boolean $newline If true, the outputs gets an added newline. * @param boolean $newline If true, the outputs gets an added newline.
*/ */
public function out($string, $newline = true) { public function out($string, $newline = true)
{
if (is_array($string)) { if (is_array($string)) {
$str = ''; $str = '';
foreach ($string as $message) { foreach ($string as $message) {
@ -201,7 +206,8 @@ class Shell
* @param string|array $string Error text to output. * @param string|array $string Error text to output.
* @access public * @access public
*/ */
public function err($string) { public function err($string)
{
if (is_array($string)) { if (is_array($string)) {
$str = ''; $str = '';
foreach ($string as $message) { foreach ($string as $message) {
@ -217,7 +223,8 @@ class Shell
* @param boolean $newline If true, the outputs gets an added newline. * @param boolean $newline If true, the outputs gets an added newline.
* @access public * @access public
*/ */
public function hr($newline = false) { public function hr($newline = false)
{
if ($newline) { if ($newline) {
$this->out("\n"); $this->out("\n");
} }
@ -233,7 +240,8 @@ class Shell
* @param string $msg Error message * @param string $msg Error message
* @access public * @access public
*/ */
public function error($title, $msg) { public function error($title, $msg)
{
$out = "$title\n"; $out = "$title\n";
$out .= "$msg\n"; $out .= "$msg\n";
$out .= "\n"; $out .= "\n";
@ -245,7 +253,8 @@ class Shell
* *
* @access public * @access public
*/ */
public function help() { public function help()
{
if ($this->command != null) { if ($this->command != null) {
$this->err("Unknown {$this->name} command '$this->command'.\nFor usage, try 'postfixadmin-cli {$this->shell} help'.\n\n"); $this->err("Unknown {$this->name} command '$this->command'.\nFor usage, try 'postfixadmin-cli {$this->shell} help'.\n\n");
} else { } else {
@ -259,7 +268,8 @@ class Shell
* @return void * @return void
* @access public * @access public
*/ */
public function _stop($status = 0) { public function _stop($status = 0)
{
exit($status); exit($status);
} }
} }

View File

@ -19,14 +19,16 @@ class VacationHandler extends PFAHandler
*/ */
protected $domain_field = 'domain'; protected $domain_field = 'domain';
public function init($id) : bool { public function init($id) : bool
{
throw new \Exception('VacationHandler is not yet ready to be used with *Handler methods'); throw new \Exception('VacationHandler is not yet ready to be used with *Handler methods');
} }
/** /**
* @return void * @return void
*/ */
protected function initStruct() { protected function initStruct()
{
$this->struct=array( $this->struct=array(
# field name allow display in... type $PALANG label $PALANG description default / options / ... # field name allow display in... type $PALANG label $PALANG description default / options / ...
# editing? form list # editing? form list
@ -50,7 +52,8 @@ class VacationHandler extends PFAHandler
/** /**
* @return void * @return void
*/ */
protected function initMsg() { protected function initMsg()
{
$this->msg['error_already_exists'] = 'pCreate_mailbox_username_text_error1'; # TODO: better error message $this->msg['error_already_exists'] = 'pCreate_mailbox_username_text_error1'; # TODO: better error message
$this->msg['error_does_not_exist'] = 'pCreate_mailbox_username_text_error1'; # TODO: better error message $this->msg['error_does_not_exist'] = 'pCreate_mailbox_username_text_error1'; # TODO: better error message
$this->msg['confirm_delete'] = 'confirm_delete_vacation'; # unused? $this->msg['confirm_delete'] = 'confirm_delete_vacation'; # unused?
@ -69,7 +72,8 @@ class VacationHandler extends PFAHandler
/** /**
* @return array * @return array
*/ */
public function webformConfig() { public function webformConfig()
{
return array( return array(
# $PALANG labels # $PALANG labels
'formtitle_create' => 'pUsersVacation_welcome', 'formtitle_create' => 'pUsersVacation_welcome',
@ -83,7 +87,8 @@ class VacationHandler extends PFAHandler
); );
} }
protected function validate_new_id() { protected function validate_new_id()
{
# vacation can only be enabled if a mailbox with this name exists # vacation can only be enabled if a mailbox with this name exists
if ($this->is_admin) { if ($this->is_admin) {
$handler = new MailboxHandler(0, $this->admin_username); $handler = new MailboxHandler(0, $this->admin_username);
@ -104,7 +109,8 @@ class VacationHandler extends PFAHandler
/** /**
* @return bool * @return bool
*/ */
public function delete() { public function delete()
{
$this->errormsg[] = '*** deletion not implemented yet ***'; $this->errormsg[] = '*** deletion not implemented yet ***';
return false; # XXX function aborts here! XXX return false; # XXX function aborts here! XXX
} }
@ -120,7 +126,8 @@ class VacationHandler extends PFAHandler
/** /**
* @param string $username * @param string $username
*/ */
public function __construct($username) { public function __construct($username)
{
$this->username = $username; $this->username = $username;
$this->id = $username; $this->id = $username;
} }
@ -130,7 +137,8 @@ class VacationHandler extends PFAHandler
* set the vacation table record to false. * set the vacation table record to false.
* @return boolean true on success. * @return boolean true on success.
*/ */
public function remove() { public function remove()
{
if (!$this->updateAlias(0)) { if (!$this->updateAlias(0)) {
return false; return false;
} }
@ -149,7 +157,8 @@ class VacationHandler extends PFAHandler
/** /**
* @return boolean true indicates this server supports vacation messages, and users are able to change their own. * @return boolean true indicates this server supports vacation messages, and users are able to change their own.
*/ */
public function vacation_supported() { public function vacation_supported()
{
return Config::bool('vacation') && Config::bool('vacation_control'); return Config::bool('vacation') && Config::bool('vacation_control');
} }
@ -157,7 +166,8 @@ class VacationHandler extends PFAHandler
* @return boolean true if on vacation, otherwise false * @return boolean true if on vacation, otherwise false
* Why do we bother storing true/false in the vacation table if the alias dictates it anyway? * Why do we bother storing true/false in the vacation table if the alias dictates it anyway?
*/ */
public function check_vacation() { public function check_vacation()
{
$handler = new AliasHandler(); $handler = new AliasHandler();
if (!$handler->init($this->id)) { if (!$handler->init($this->id)) {
@ -183,7 +193,8 @@ class VacationHandler extends PFAHandler
* @return array|boolean stored information on vacation - array(subject - string, message - string, active - boolean, activeFrom - date, activeUntil - date) * @return array|boolean stored information on vacation - array(subject - string, message - string, active - boolean, activeFrom - date, activeUntil - date)
* 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');
$sql = "SELECT * FROM $table_vacation WHERE email = :username"; $sql = "SELECT * FROM $table_vacation WHERE email = :username";
@ -216,7 +227,8 @@ class VacationHandler extends PFAHandler
* @param string $activeUntil - something strtotime understands * @param string $activeUntil - something strtotime understands
* @return boolean * @return boolean
*/ */
public function set_away($subject, $body, $interval_time, $activeFrom, $activeUntil) { public function set_away($subject, $body, $interval_time, $activeFrom, $activeUntil)
{
$this->remove(); // clean out any notifications that might already have been sent. $this->remove(); // clean out any notifications that might already have been sent.
$E_username = escape_string($this->username); $E_username = escape_string($this->username);
@ -258,7 +270,8 @@ class VacationHandler extends PFAHandler
* @param int $vacationActive * @param int $vacationActive
* @return boolean * @return boolean
*/ */
protected function updateAlias($vacationActive) { protected function updateAlias($vacationActive)
{
$handler = new AliasHandler(); $handler = new AliasHandler();
if (!$handler->init($this->id)) { if (!$handler->init($this->id)) {

View File

@ -366,7 +366,8 @@ class cNav_bar
protected $arr_top; //* internal protected $arr_top; //* internal
protected $anchor; protected $anchor;
public function __construct($aTitle, $aLimit, $aPage_size, $aPages, $aSearch) { public function __construct($aTitle, $aLimit, $aPage_size, $aPages, $aSearch)
{
$this->count = count($aPages); $this->count = count($aPages);
$this->title = $aTitle; $this->title = $aTitle;
$this->limit = $aLimit; $this->limit = $aLimit;
@ -379,7 +380,8 @@ class cNav_bar
} }
} }
private function init() { private function init()
{
$this->anchor = 'a'.substr($this->title, 3); $this->anchor = 'a'.substr($this->title, 3);
$this->append_to_url .= '#'.$this->anchor; $this->append_to_url .= '#'.$this->anchor;
($this->limit >= $this->page_size) ? $this->arr_prev = '&nbsp;<a href="?limit='.($this->limit - $this->page_size).$this->search.$this->append_to_url.'"><img border="0" src="images/arrow-l.png" title="'.$GLOBALS ['PALANG']['pOverview_left_arrow'].'" alt="'.$GLOBALS ['PALANG']['pOverview_left_arrow'].'"/></a>&nbsp;' : $this->arr_prev = ''; ($this->limit >= $this->page_size) ? $this->arr_prev = '&nbsp;<a href="?limit='.($this->limit - $this->page_size).$this->search.$this->append_to_url.'"><img border="0" src="images/arrow-l.png" title="'.$GLOBALS ['PALANG']['pOverview_left_arrow'].'" alt="'.$GLOBALS ['PALANG']['pOverview_left_arrow'].'"/></a>&nbsp;' : $this->arr_prev = '';
@ -388,7 +390,8 @@ class cNav_bar
$this->have_run_init = true; $this->have_run_init = true;
} }
private function display_pre() { private function display_pre()
{
$ret_val = '<div class="nav_bar"'; $ret_val = '<div class="nav_bar"';
//$ret_val .= ' style="background-color:#ffa;"'; //$ret_val .= ' style="background-color:#ffa;"';
$ret_val .= '>'; $ret_val .= '>';
@ -397,12 +400,14 @@ class cNav_bar
return $ret_val; return $ret_val;
} }
private function display_post() { private function display_post()
{
$ret_val = '</td></tr></table></div>'; $ret_val = '</td></tr></table></div>';
return $ret_val; return $ret_val;
} }
public function display_top() { public function display_top()
{
$ret_val = ''; $ret_val = '';
if ($this->count < 1) { if ($this->count < 1) {
return $ret_val; return $ret_val;
@ -439,7 +444,8 @@ class cNav_bar
return $ret_val; return $ret_val;
} }
public function display_bottom() { public function display_bottom()
{
$ret_val = ''; $ret_val = '';
if ($this->count < 1) { if ($this->count < 1) {
return $ret_val; return $ret_val;
@ -518,7 +524,8 @@ $smarty->assign('tab', $_SESSION ['tab']);
$smarty->assign('smarty_template', 'list-virtual'); $smarty->assign('smarty_template', 'list-virtual');
$smarty->display('index.tpl'); $smarty->display('index.tpl');
function eval_size($aSize) { function eval_size($aSize)
{
if ($aSize == 0) { if ($aSize == 0) {
$ret_val = Config::Lang('pOverview_unlimited'); $ret_val = Config::Lang('pOverview_unlimited');
} elseif ($aSize < 0) { } elseif ($aSize < 0) {

View File

@ -514,7 +514,8 @@ EOF;
<?php <?php
function _error_field($errors, $key) { function _error_field($errors, $key)
{
if (!isset($errors[$key])) { if (!isset($errors[$key])) {
return ''; return '';
} }
@ -522,7 +523,8 @@ function _error_field($errors, $key) {
} }
function create_admin($values) { function create_admin($values)
{
define('POSTFIXADMIN_SETUP', 1); # avoids instant redirect to login.php after creating the admin define('POSTFIXADMIN_SETUP', 1); # avoids instant redirect to login.php after creating the admin
$handler = new AdminHandler(1, 'setup.php'); $handler = new AdminHandler(1, 'setup.php');
@ -550,7 +552,8 @@ function create_admin($values) {
/** /**
* @return array like: ['info' => string[], 'warn' => string[], 'error' => string[] ] * @return array like: ['info' => string[], 'warn' => string[], 'error' => string[] ]
*/ */
function do_software_environment_check() { function do_software_environment_check()
{
$CONF = Config::getInstance()->getAll(); $CONF = Config::getInstance()->getAll();
$warn = []; $warn = [];

View File

@ -15,7 +15,8 @@ if (empty($CONF)) {
* @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_one($sql); $r = db_query_one($sql);
return !empty($r); return !empty($r);
@ -26,7 +27,8 @@ function _pgsql_object_exists($name) {
* @param string $field * @param string $field
* @return bool * @return bool
*/ */
function _pgsql_field_exists($table, $field) { function _pgsql_field_exists($table, $field)
{
# $table = table_by_key($table); # _pgsql_field_exists is always called with the expanded table name - don't expand it twice # $table = table_by_key($table); # _pgsql_field_exists is always called with the expanded table name - don't expand it twice
$sql = ' $sql = '
SELECT SELECT
@ -50,7 +52,8 @@ function _pgsql_field_exists($table, $field) {
return !empty($r); return !empty($r);
} }
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 ?"; $sql = "SHOW COLUMNS FROM $table LIKE ?";
$r = db_query_all($sql, array( $field)); $r = db_query_all($sql, array( $field));
@ -58,7 +61,8 @@ function _mysql_field_exists($table, $field) {
return !empty($r); return !empty($r);
} }
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_all($sql); $r = db_query_all($sql);
@ -70,7 +74,8 @@ function _sqlite_field_exists($table, $field) {
return false; return false;
} }
function _db_field_exists($table, $field) { function _db_field_exists($table, $field)
{
global $CONF; global $CONF;
if ($CONF['database_type'] == 'pgsql') { if ($CONF['database_type'] == 'pgsql') {
return _pgsql_field_exists($table, $field); return _pgsql_field_exists($table, $field);
@ -80,11 +85,13 @@ function _db_field_exists($table, $field) {
return _mysql_field_exists($table, $field); return _mysql_field_exists($table, $field);
} }
} }
function _upgrade_filter_function($name) { function _upgrade_filter_function($name)
{
return preg_match('/upgrade_[\d]+(_mysql|_pgsql|_sqlite|_mysql_pgsql)?$/', $name) == 1; return preg_match('/upgrade_[\d]+(_mysql|_pgsql|_sqlite|_mysql_pgsql)?$/', $name) == 1;
} }
function _db_add_field($table, $field, $fieldtype, $after = '') { function _db_add_field($table, $field, $fieldtype, $after = '')
{
global $CONF; global $CONF;
$query = "ALTER TABLE " . table_by_key($table) . " ADD COLUMN $field $fieldtype"; $query = "ALTER TABLE " . table_by_key($table) . " ADD COLUMN $field $fieldtype";
@ -99,7 +106,8 @@ function _db_add_field($table, $field, $fieldtype, $after = '') {
} }
} }
function echo_out($text) { function echo_out($text)
{
if (defined('PHPUNIT_TEST')) { if (defined('PHPUNIT_TEST')) {
//error_log("" . $text); //error_log("" . $text);
} else { } else {
@ -107,7 +115,8 @@ function echo_out($text) {
} }
} }
function printdebug($text) { function printdebug($text)
{
if (safeget('debug') != "") { if (safeget('debug') != "") {
echo_out("<p style='color:#999'>$text</p>"); echo_out("<p style='color:#999'>$text</p>");
} }
@ -152,7 +161,8 @@ if ($CONF['database_type'] == 'pgsql') {
$version = check_db_version(false); $version = check_db_version(false);
_do_upgrade($version); _do_upgrade($version);
function _do_upgrade($current_version) { function _do_upgrade($current_version)
{
global $CONF; global $CONF;
$target_version = 0; $target_version = 0;
@ -235,7 +245,8 @@ function _do_upgrade($current_version) {
* @return void * @return void
*/ */
function db_query_parsed($sql, $ignore_errors = 0, $attach_mysql = "") { function db_query_parsed($sql, $ignore_errors = 0, $attach_mysql = "")
{
global $CONF; global $CONF;
if (db_mysql()) { if (db_mysql()) {
@ -338,7 +349,8 @@ function db_query_parsed($sql, $ignore_errors = 0, $attach_mysql = "") {
* @param string $index * @param string $index
* @return string * @return string
*/ */
function _drop_index($table, $index) { function _drop_index($table, $index)
{
global $CONF; global $CONF;
$table = table_by_key($table); $table = table_by_key($table);
@ -358,7 +370,8 @@ function _drop_index($table, $index) {
* @param string $indexname * @param string $indexname
* @param string $fieldlist * @param string $fieldlist
*/ */
function _add_index($table, $indexname, $fieldlist) { function _add_index($table, $indexname, $fieldlist)
{
global $CONF; global $CONF;
$table = table_by_key($table); $table = table_by_key($table);
@ -377,7 +390,8 @@ function _add_index($table, $indexname, $fieldlist) {
/** /**
* @return void * @return void
*/ */
function upgrade_1_mysql() { function upgrade_1_mysql()
{
# #
# creating the tables in this very old layout (pre 2.1) causes trouble if the MySQL charset is not latin1 (multibyte vs. index length) # creating the tables in this very old layout (pre 2.1) causes trouble if the MySQL charset is not latin1 (multibyte vs. index length)
# therefore: # therefore:
@ -487,7 +501,8 @@ function upgrade_1_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_2_mysql() { function upgrade_2_mysql()
{
# #
# updating the tables in this very old layout (pre 2.1) causes trouble if the MySQL charset is not latin1 (multibyte vs. index length) # updating the tables in this very old layout (pre 2.1) causes trouble if the MySQL charset is not latin1 (multibyte vs. index length)
# therefore: # therefore:
@ -510,7 +525,8 @@ function upgrade_2_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_2_pgsql() { function upgrade_2_pgsql()
{
if (!_pgsql_object_exists(table_by_key('domain'))) { if (!_pgsql_object_exists(table_by_key('domain'))) {
db_query_parsed(" db_query_parsed("
CREATE TABLE " . table_by_key('domain') . " ( CREATE TABLE " . table_by_key('domain') . " (
@ -627,7 +643,8 @@ function upgrade_2_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_3_mysql() { function upgrade_3_mysql()
{
# #
# updating the tables in this very old layout (pre 2.1) causes trouble if the MySQL charset is not latin1 (multibyte vs. index length) # updating the tables in this very old layout (pre 2.1) causes trouble if the MySQL charset is not latin1 (multibyte vs. index length)
# therefore: # therefore:
@ -703,7 +720,8 @@ function upgrade_3_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_4_mysql() { # MySQL only function upgrade_4_mysql()
{ # MySQL only
# changes between 2.1 and moving to sourceforge # changes between 2.1 and moving to sourceforge
return; // as the above _mysql functions are disabled; this one will just error for a new db. return; // as the above _mysql functions are disabled; this one will just error for a new db.
@ -718,7 +736,8 @@ function upgrade_4_mysql() { # MySQL only
* Changes between 2.1 and moving to sf.net * Changes between 2.1 and moving to sf.net
* @return void * @return void
*/ */
function upgrade_4_pgsql() { function upgrade_4_pgsql()
{
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$table_admin = table_by_key('admin'); $table_admin = table_by_key('admin');
$table_alias = table_by_key('alias'); $table_alias = table_by_key('alias');
@ -810,7 +829,8 @@ function upgrade_4_pgsql() {
* - removed creation of default superadmin * - removed creation of default superadmin
* @return void * @return void
*/ */
function upgrade_5_mysql() { function upgrade_5_mysql()
{
db_query_parsed(" db_query_parsed("
CREATE TABLE {IF_NOT_EXISTS} " . table_by_key('admin') . " ( CREATE TABLE {IF_NOT_EXISTS} " . table_by_key('admin') . " (
`username` varchar(255) NOT NULL default '', `username` varchar(255) NOT NULL default '',
@ -909,7 +929,8 @@ function upgrade_5_mysql() {
* drop useless indicies (already available as primary key) * drop useless indicies (already available as primary key)
* @return void * @return void
*/ */
function upgrade_79_mysql() { # MySQL only function upgrade_79_mysql()
{ # MySQL only
db_query_parsed(_drop_index('admin', 'username'), true); db_query_parsed(_drop_index('admin', 'username'), true);
db_query_parsed(_drop_index('alias', 'address'), true); db_query_parsed(_drop_index('alias', 'address'), true);
db_query_parsed(_drop_index('domain', 'domain'), true); db_query_parsed(_drop_index('domain', 'domain'), true);
@ -919,7 +940,8 @@ function upgrade_79_mysql() { # MySQL only
/** /**
* @return void * @return void
*/ */
function upgrade_81_mysql() { # MySQL only function upgrade_81_mysql()
{ # MySQL only
$table_vacation = table_by_key('vacation'); $table_vacation = table_by_key('vacation');
$table_vacation_notification = table_by_key('vacation_notification'); $table_vacation_notification = table_by_key('vacation_notification');
@ -943,7 +965,8 @@ function upgrade_81_mysql() { # MySQL only
* Make logging translatable - i.e. create alias => create_alias * Make logging translatable - i.e. create alias => create_alias
* @return void * @return void
*/ */
function upgrade_90_mysql_pgsql() { function upgrade_90_mysql_pgsql()
{
db_query_parsed("UPDATE " . table_by_key('log') . " SET action = REPLACE(action,' ','_')", true); db_query_parsed("UPDATE " . table_by_key('log') . " SET action = REPLACE(action,' ','_')", true);
# change edit_alias_state to edit_alias_active # change edit_alias_state to edit_alias_active
db_query_parsed("UPDATE " . table_by_key('log') . " SET action = 'edit_alias_state' WHERE action = 'edit_alias_active'", true); db_query_parsed("UPDATE " . table_by_key('log') . " SET action = 'edit_alias_state' WHERE action = 'edit_alias_active'", true);
@ -953,7 +976,8 @@ function upgrade_90_mysql_pgsql() {
* MySQL only allow quota > 2 GB * MySQL only allow quota > 2 GB
* @return void * @return void
*/ */
function upgrade_169_mysql() { function upgrade_169_mysql()
{
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$table_mailbox = table_by_key('mailbox'); $table_mailbox = table_by_key('mailbox');
db_query_parsed("ALTER TABLE $table_domain MODIFY COLUMN `quota` bigint(20) NOT NULL default '0'", true); db_query_parsed("ALTER TABLE $table_domain MODIFY COLUMN `quota` bigint(20) NOT NULL default '0'", true);
@ -968,7 +992,8 @@ function upgrade_169_mysql() {
* In this case, dropping the table is the easiest solution. * In this case, dropping the table is the easiest solution.
* @return void * @return void
*/ */
function upgrade_318_mysql() { function upgrade_318_mysql()
{
$table_vacation_notification = table_by_key('vacation_notification'); $table_vacation_notification = table_by_key('vacation_notification');
$table_vacation = table_by_key('vacation'); $table_vacation = table_by_key('vacation');
@ -1003,7 +1028,8 @@ function upgrade_318_mysql() {
* Create fetchmail table * Create fetchmail table
* @return void * @return void
*/ */
function upgrade_344_mysql() { function upgrade_344_mysql()
{
$table_fetchmail = table_by_key('fetchmail'); $table_fetchmail = table_by_key('fetchmail');
db_query_parsed(" db_query_parsed("
@ -1031,7 +1057,8 @@ function upgrade_344_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_344_pgsql() { function upgrade_344_pgsql()
{
$fetchmail = table_by_key('fetchmail'); $fetchmail = table_by_key('fetchmail');
// a field name called 'date' is probably a bad idea. // a field name called 'date' is probably a bad idea.
if (!_pgsql_object_exists('fetchmail')) { if (!_pgsql_object_exists('fetchmail')) {
@ -1073,7 +1100,8 @@ function upgrade_344_pgsql() {
* *
* @return void * @return void
*/ */
function upgrade_438_mysql() { function upgrade_438_mysql()
{
# Table structure for table alias_domain # Table structure for table alias_domain
# #
$table_alias_domain = table_by_key('alias_domain'); $table_alias_domain = table_by_key('alias_domain');
@ -1096,7 +1124,8 @@ function upgrade_438_mysql() {
* function upgrade_362_pgsql() # renamed to _438 to make sure it runs after an upgrade from 2.2.x * function upgrade_362_pgsql() # renamed to _438 to make sure it runs after an upgrade from 2.2.x
* @return void * @return void
*/ */
function upgrade_438_pgsql() { function upgrade_438_pgsql()
{
# Table structure for table alias_domain # Table structure for table alias_domain
$table_alias_domain = table_by_key('alias_domain'); $table_alias_domain = table_by_key('alias_domain');
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
@ -1119,7 +1148,8 @@ function upgrade_438_pgsql() {
* Change description fields to UTF-8 * Change description fields to UTF-8
* @return void * @return void
*/ */
function upgrade_373_mysql() { # MySQL only function upgrade_373_mysql()
{ # MySQL only
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$table_mailbox = table_by_key('mailbox'); $table_mailbox = table_by_key('mailbox');
@ -1138,7 +1168,8 @@ function upgrade_373_mysql() { # MySQL only
* add ssl option for fetchmail * add ssl option for fetchmail
* @return void * @return void
*/ */
function upgrade_439_mysql() { function upgrade_439_mysql()
{
$table_fetchmail = table_by_key('fetchmail'); $table_fetchmail = table_by_key('fetchmail');
if (!_mysql_field_exists($table_fetchmail, 'ssl')) { if (!_mysql_field_exists($table_fetchmail, 'ssl')) {
db_query_parsed("ALTER TABLE $table_fetchmail ADD `ssl` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' AFTER `protocol` ; "); db_query_parsed("ALTER TABLE $table_fetchmail ADD `ssl` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' AFTER `protocol` ; ");
@ -1148,7 +1179,8 @@ function upgrade_439_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_439_pgsql() { function upgrade_439_pgsql()
{
$table_fetchmail = table_by_key('fetchmail'); $table_fetchmail = table_by_key('fetchmail');
if (!_pgsql_field_exists($table_fetchmail, 'ssl')) { if (!_pgsql_field_exists($table_fetchmail, 'ssl')) {
db_query_parsed("ALTER TABLE $table_fetchmail ADD COLUMN ssl BOOLEAN NOT NULL DEFAULT false"); db_query_parsed("ALTER TABLE $table_fetchmail ADD COLUMN ssl BOOLEAN NOT NULL DEFAULT false");
@ -1158,7 +1190,8 @@ function upgrade_439_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_473_mysql() { function upgrade_473_mysql()
{
$table_admin = table_by_key('admin'); $table_admin = table_by_key('admin');
$table_alias = table_by_key('alias'); $table_alias = table_by_key('alias');
$table_al_dom = table_by_key('alias_domain'); $table_al_dom = table_by_key('alias_domain');
@ -1216,7 +1249,8 @@ function upgrade_473_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_479_mysql() { function upgrade_479_mysql()
{
# ssl is a reserved word in MySQL and causes several problems. Renaming the field... # ssl is a reserved word in MySQL and causes several problems. Renaming the field...
$table_fmail = table_by_key('fetchmail'); $table_fmail = table_by_key('fetchmail');
if (!_mysql_field_exists($table_fmail, 'usessl')) { if (!_mysql_field_exists($table_fmail, 'usessl')) {
@ -1228,7 +1262,8 @@ function upgrade_479_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_479_pgsql() { function upgrade_479_pgsql()
{
$table_fmail = table_by_key('fetchmail'); $table_fmail = table_by_key('fetchmail');
if (!_pgsql_field_exists($table_fmail, 'usessl')) { if (!_pgsql_field_exists($table_fmail, 'usessl')) {
db_query_parsed("alter table $table_fmail rename column ssl to usessl"); db_query_parsed("alter table $table_fmail rename column ssl to usessl");
@ -1238,7 +1273,8 @@ function upgrade_479_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_483_mysql() { function upgrade_483_mysql()
{
$table_log = table_by_key('log'); $table_log = table_by_key('log');
db_query_parsed("ALTER TABLE $table_log CHANGE `data` `data` TEXT {LATIN1} NOT NULL"); db_query_parsed("ALTER TABLE $table_log CHANGE `data` `data` TEXT {LATIN1} NOT NULL");
} }
@ -1249,7 +1285,8 @@ function upgrade_483_mysql() {
* See https://sourceforge.net/forum/message.php?msg_id=5394663 * See https://sourceforge.net/forum/message.php?msg_id=5394663
* @return void * @return void
*/ */
function upgrade_495_pgsql() { function upgrade_495_pgsql()
{
$table_mailbox = table_by_key('mailbox'); $table_mailbox = table_by_key('mailbox');
if (!_pgsql_field_exists($table_mailbox, 'local_part')) { if (!_pgsql_field_exists($table_mailbox, 'local_part')) {
db_query_parsed("ALTER TABLE $table_mailbox add column local_part varchar(255) "); db_query_parsed("ALTER TABLE $table_mailbox add column local_part varchar(255) ");
@ -1261,7 +1298,8 @@ function upgrade_495_pgsql() {
* See https://sourceforge.net/forum/message.php?msg_id=5394663 * See https://sourceforge.net/forum/message.php?msg_id=5394663
* @return void * @return void
*/ */
function upgrade_495_mysql() { function upgrade_495_mysql()
{
$table_mailbox = table_by_key('mailbox'); $table_mailbox = table_by_key('mailbox');
if (!_mysql_field_exists($table_mailbox, 'local_part')) { if (!_mysql_field_exists($table_mailbox, 'local_part')) {
db_query_parsed("ALTER TABLE $table_mailbox add local_part varchar(255) AFTER quota"); // allow to be null db_query_parsed("ALTER TABLE $table_mailbox add local_part varchar(255) AFTER quota"); // allow to be null
@ -1273,7 +1311,8 @@ function upgrade_495_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_504_mysql() { function upgrade_504_mysql()
{
$table_mailbox = table_by_key('mailbox'); $table_mailbox = table_by_key('mailbox');
db_query_parsed("ALTER TABLE $table_mailbox CHANGE `local_part` `local_part` VARCHAR( 255 ) {LATIN1} NOT NULL"); db_query_parsed("ALTER TABLE $table_mailbox CHANGE `local_part` `local_part` VARCHAR( 255 ) {LATIN1} NOT NULL");
} }
@ -1281,7 +1320,8 @@ function upgrade_504_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_655_mysql_pgsql() { function upgrade_655_mysql_pgsql()
{
db_query_parsed(_add_index('mailbox', 'domain', 'domain')); db_query_parsed(_add_index('mailbox', 'domain', 'domain'));
db_query_parsed(_add_index('alias', 'domain', 'domain')); db_query_parsed(_add_index('alias', 'domain', 'domain'));
} }
@ -1351,7 +1391,8 @@ function upgrade_727_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_729_mysql_pgsql() { function upgrade_729_mysql_pgsql()
{
$table_quota = table_by_key('quota'); $table_quota = table_by_key('quota');
$table_quota2 = table_by_key('quota2'); $table_quota2 = table_by_key('quota2');
@ -1382,7 +1423,8 @@ function upgrade_729_mysql_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_730_pgsql() { function upgrade_730_pgsql()
{
$table_quota = table_by_key('quota'); $table_quota = table_by_key('quota');
$table_quota2 = table_by_key('quota2'); $table_quota2 = table_by_key('quota2');
@ -1457,14 +1499,16 @@ function upgrade_730_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_945_mysql_pgsql() { function upgrade_945_mysql_pgsql()
{
_db_add_field('vacation', 'modified', '{DATECURRENT}', 'created'); _db_add_field('vacation', 'modified', '{DATECURRENT}', 'created');
} }
/** /**
* @return void * @return void
*/ */
function upgrade_946_mysql_pgsql() { function upgrade_946_mysql_pgsql()
{
# taken from upgrade_727_mysql, needs to be done for all databases # taken from upgrade_727_mysql, needs to be done for all databases
_db_add_field('vacation', 'activefrom', '{DATE}', 'body'); _db_add_field('vacation', 'activefrom', '{DATE}', 'body');
_db_add_field('vacation', 'activeuntil', '{DATEFUTURE}', 'activefrom'); _db_add_field('vacation', 'activeuntil', '{DATEFUTURE}', 'activefrom');
@ -1473,7 +1517,8 @@ function upgrade_946_mysql_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_968_pgsql() { function upgrade_968_pgsql()
{
# pgsql counterpart for upgrade_169_mysql() - allow really big quota # pgsql counterpart for upgrade_169_mysql() - allow really big quota
$table_domain = table_by_key('domain'); $table_domain = table_by_key('domain');
$table_mailbox = table_by_key('mailbox'); $table_mailbox = table_by_key('mailbox');
@ -1485,7 +1530,8 @@ function upgrade_968_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1050_mysql_pgsql() { function upgrade_1050_mysql_pgsql()
{
db_query_parsed(_add_index('log', 'domain_timestamp', 'domain,timestamp')); db_query_parsed(_add_index('log', 'domain_timestamp', 'domain,timestamp'));
} }
@ -1493,14 +1539,16 @@ function upgrade_1050_mysql_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1283_mysql_pgsql() { function upgrade_1283_mysql_pgsql()
{
_db_add_field('admin', 'superadmin', '{BOOLEAN}', 'password'); _db_add_field('admin', 'superadmin', '{BOOLEAN}', 'password');
} }
/** /**
* @return void * @return void
*/ */
function upgrade_1284_mysql_pgsql() { 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)
@ -1515,7 +1563,8 @@ function upgrade_1284_mysql_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1345_mysql() { function upgrade_1345_mysql()
{
# $table_vacation = table_by_key('vacation'); # $table_vacation = table_by_key('vacation');
# adding and usage of reply_type field removed in r1610 # adding and usage of reply_type field removed in r1610
# db_query_parsed("ALTER TABLE `$table_vacation` ADD `reply_type` VARCHAR( 20 ) NOT NULL AFTER `domain` "); # db_query_parsed("ALTER TABLE `$table_vacation` ADD `reply_type` VARCHAR( 20 ) NOT NULL AFTER `domain` ");
@ -1526,7 +1575,8 @@ function upgrade_1345_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1519_mysql_pgsql() { function upgrade_1519_mysql_pgsql()
{
_db_add_field('fetchmail', 'sslcertck', '{BOOLEAN}', 'usessl'); _db_add_field('fetchmail', 'sslcertck', '{BOOLEAN}', 'usessl');
_db_add_field('fetchmail', 'sslcertpath', "VARCHAR(255) {UTF-8} DEFAULT ''", 'sslcertck'); _db_add_field('fetchmail', 'sslcertpath', "VARCHAR(255) {UTF-8} DEFAULT ''", 'sslcertck');
_db_add_field('fetchmail', 'sslfingerprint', "VARCHAR(255) {LATIN1} DEFAULT ''", 'sslcertpath'); _db_add_field('fetchmail', 'sslfingerprint', "VARCHAR(255) {LATIN1} DEFAULT ''", 'sslcertpath');
@ -1535,7 +1585,8 @@ function upgrade_1519_mysql_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1610_mysql_pgsql() { function upgrade_1610_mysql_pgsql()
{
# obsoletes upgrade_1345_mysql() - which means debug mode could print "field already exists" # obsoletes upgrade_1345_mysql() - which means debug mode could print "field already exists"
_db_add_field('vacation', 'interval_time', '{INT}', 'domain'); _db_add_field('vacation', 'interval_time', '{INT}', 'domain');
} }
@ -1543,7 +1594,8 @@ function upgrade_1610_mysql_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1685_mysql() { function upgrade_1685_mysql()
{
# Fix existing log entries broken by https://sourceforge.net/p/postfixadmin/bugs/317/ # Fix existing log entries broken by https://sourceforge.net/p/postfixadmin/bugs/317/
$table = table_by_key('log'); $table = table_by_key('log');
db_query_parsed("UPDATE $table SET data = domain WHERE data = '' AND domain LIKE '%@%'"); db_query_parsed("UPDATE $table SET data = domain WHERE data = '' AND domain LIKE '%@%'");
@ -1553,7 +1605,8 @@ function upgrade_1685_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1685_pgsql() { function upgrade_1685_pgsql()
{
$table = table_by_key('log'); $table = table_by_key('log');
db_query_parsed("UPDATE $table SET data = domain WHERE data = '' AND domain LIKE '%@%'"); db_query_parsed("UPDATE $table SET data = domain WHERE data = '' AND domain LIKE '%@%'");
db_query_parsed("UPDATE $table SET domain=SPLIT_PART(domain, '@', 2) WHERE domain=data;"); db_query_parsed("UPDATE $table SET domain=SPLIT_PART(domain, '@', 2) WHERE domain=data;");
@ -1562,7 +1615,8 @@ function upgrade_1685_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1761_mysql() { function upgrade_1761_mysql()
{
# upgrade_1762 adds the 'modified' column as {DATECURRENT}, therefore we first need to change # upgrade_1762 adds the 'modified' column as {DATECURRENT}, therefore we first need to change
# 'date' to {DATE} (mysql only allows one {DATECURRENT} column per table) # 'date' to {DATE} (mysql only allows one {DATECURRENT} column per table)
$table_fetchmail = table_by_key('fetchmail'); $table_fetchmail = table_by_key('fetchmail');
@ -1572,7 +1626,8 @@ function upgrade_1761_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1762_mysql_pgsql() { function upgrade_1762_mysql_pgsql()
{
_db_add_field('fetchmail', 'domain', "VARCHAR(255) {LATIN1} DEFAULT ''", 'id'); _db_add_field('fetchmail', 'domain', "VARCHAR(255) {LATIN1} DEFAULT ''", 'id');
_db_add_field('fetchmail', 'active', '{BOOLEAN}', 'date'); _db_add_field('fetchmail', 'active', '{BOOLEAN}', 'date');
_db_add_field('fetchmail', 'created', '{DATE}', 'date'); _db_add_field('fetchmail', 'created', '{DATE}', 'date');
@ -1586,7 +1641,8 @@ function upgrade_1762_mysql_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1763_mysql() { function upgrade_1763_mysql()
{
$table = table_by_key('fetchmail'); $table = table_by_key('fetchmail');
db_query_parsed("UPDATE $table SET domain=SUBSTRING_INDEX(mailbox, '@', -1) WHERE domain='';"); db_query_parsed("UPDATE $table SET domain=SUBSTRING_INDEX(mailbox, '@', -1) WHERE domain='';");
} }
@ -1595,7 +1651,8 @@ function upgrade_1763_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1763_pgsql() { function upgrade_1763_pgsql()
{
$table = table_by_key('fetchmail'); $table = table_by_key('fetchmail');
db_query_parsed("UPDATE $table SET domain=SPLIT_PART(mailbox, '@', 2) WHERE domain='';"); db_query_parsed("UPDATE $table SET domain=SPLIT_PART(mailbox, '@', 2) WHERE domain='';");
} }
@ -1603,7 +1660,8 @@ function upgrade_1763_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1767_mysql_pgsql() { function upgrade_1767_mysql_pgsql()
{
# 'active' was just added, so make sure all existing jobs stay active # 'active' was just added, so make sure all existing jobs stay active
$table = table_by_key('fetchmail'); $table = table_by_key('fetchmail');
db_query_parsed("UPDATE $table SET active='{BOOL_TRUE}'"); db_query_parsed("UPDATE $table SET active='{BOOL_TRUE}'");
@ -1612,7 +1670,8 @@ function upgrade_1767_mysql_pgsql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1795_mysql() { function upgrade_1795_mysql()
{
# upgrade_1761_mysql() was added later (in r1795) - make sure it runs for everybody # upgrade_1761_mysql() was added later (in r1795) - make sure it runs for everybody
# (running it twice doesn't hurt) # (running it twice doesn't hurt)
upgrade_1761_mysql(); upgrade_1761_mysql();
@ -1621,7 +1680,8 @@ function upgrade_1795_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1824_sqlite() { function upgrade_1824_sqlite()
{
$admin_table = table_by_key('admin'); $admin_table = table_by_key('admin');
$alias_table = table_by_key('alias'); $alias_table = table_by_key('alias');
$alias_domain_table = table_by_key('alias_domain'); $alias_domain_table = table_by_key('alias_domain');
@ -1788,7 +1848,8 @@ function upgrade_1824_sqlite() {
/** /**
* @return void * @return void
*/ */
function upgrade_1835_mysql() { function upgrade_1835_mysql()
{
# change default values for existing datetime fields with a 0000-00-00 default to {DATETIME} # change default values for existing datetime fields with a 0000-00-00 default to {DATETIME}
foreach (array('domain_admins', 'vacation') as $table_to_change) { foreach (array('domain_admins', 'vacation') as $table_to_change) {
@ -1808,7 +1869,8 @@ function upgrade_1835_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1836_mysql() { function upgrade_1836_mysql()
{
$table_alias_domain = table_by_key('alias_domain'); $table_alias_domain = table_by_key('alias_domain');
$table_vacation_notification = table_by_key('vacation_notification'); $table_vacation_notification = table_by_key('vacation_notification');
@ -1826,7 +1888,8 @@ function upgrade_1836_mysql() {
/** /**
* @return void * @return void
*/ */
function upgrade_1837() { function upgrade_1837()
{
global $CONF; global $CONF;
if ($CONF['database_type'] == 'sqlite') { if ($CONF['database_type'] == 'sqlite') {
@ -1858,7 +1921,8 @@ function upgrade_1837() {
/** /**
* @return void * @return void
*/ */
function upgrade_1837_sqlite() { function upgrade_1837_sqlite()
{
# Add columns for the alternative contact to reset a forgotten password. # Add columns for the alternative contact to reset a forgotten password.
foreach (array('admin', 'mailbox') as $table_to_change) { foreach (array('admin', 'mailbox') as $table_to_change) {
$table = table_by_key($table_to_change); $table = table_by_key($table_to_change);
@ -1876,7 +1940,8 @@ function upgrade_1837_sqlite() {
* upgrade_1838_mysql() renamed to upgrade_1839() to keep all databases in sync * upgrade_1838_mysql() renamed to upgrade_1839() to keep all databases in sync
* @return void * @return void
*/ */
function upgrade_1839() { function upgrade_1839()
{
if (!db_sqlite()) { if (!db_sqlite()) {
_db_add_field('log', 'id', '{AUTOINCREMENT} {PRIMARY}', 'data'); _db_add_field('log', 'id', '{AUTOINCREMENT} {PRIMARY}', 'data');
return; return;
@ -1901,7 +1966,8 @@ function upgrade_1839() {
/** /**
* @return void * @return void
*/ */
function upgrade_1840_mysql_pgsql() { function upgrade_1840_mysql_pgsql()
{
# sqlite doesn't support changing the default value # sqlite doesn't support changing the default value
$vacation = table_by_key('vacation'); $vacation = table_by_key('vacation');
db_query_parsed("ALTER TABLE $vacation ALTER COLUMN activeuntil SET DEFAULT '2038-01-18'"); db_query_parsed("ALTER TABLE $vacation ALTER COLUMN activeuntil SET DEFAULT '2038-01-18'");
@ -1911,7 +1977,8 @@ function upgrade_1840_mysql_pgsql() {
* try and fix: https://github.com/postfixadmin/postfixadmin/issues/177 - sqlite missing columns * try and fix: https://github.com/postfixadmin/postfixadmin/issues/177 - sqlite missing columns
* @return void * @return void
*/ */
function upgrade_1841_sqlite() { function upgrade_1841_sqlite()
{
foreach (array('admin', 'mailbox') as $table) { foreach (array('admin', 'mailbox') as $table) {
_db_add_field($table, 'phone', "varchar(30) {UTF-8} NOT NULL DEFAULT ''", 'active'); _db_add_field($table, 'phone', "varchar(30) {UTF-8} NOT NULL DEFAULT ''", 'active');
_db_add_field($table, 'email_other', "varchar(255) {UTF-8} NOT NULL DEFAULT ''", 'phone'); _db_add_field($table, 'email_other', "varchar(255) {UTF-8} NOT NULL DEFAULT ''", 'phone');
@ -1923,7 +1990,8 @@ function upgrade_1841_sqlite() {
/** /**
* @return void * @return void
*/ */
function upgrade_1842() { function upgrade_1842()
{
_db_add_field('mailbox', 'password_expiry', "{DATETIME}"); // when a specific mailbox password expires _db_add_field('mailbox', 'password_expiry', "{DATETIME}"); // when a specific mailbox password expires
_db_add_field('domain', 'password_expiry', 'int DEFAULT 0'); // expiry applied to mailboxes within that domain _db_add_field('domain', 'password_expiry', 'int DEFAULT 0'); // expiry applied to mailboxes within that domain
} }
@ -1931,7 +1999,8 @@ function upgrade_1842() {
/** /**
* @return void * @return void
*/ */
function upgrade_1843() { function upgrade_1843()
{
# Additional field for fetchmail to allow server with non-standard port number # Additional field for fetchmail to allow server with non-standard port number
_db_add_field('fetchmail', 'src_port', "{INT}", 'src_server'); _db_add_field('fetchmail', 'src_port', "{INT}", 'src_server');
} }
@ -1940,7 +2009,8 @@ function upgrade_1843() {
/** /**
* @return void * @return void
*/ */
function upgrade_1844() { function upgrade_1844()
{
# See:https://github.com/postfixadmin/postfixadmin/issues/475 - add pkey to domain_admins. # See:https://github.com/postfixadmin/postfixadmin/issues/475 - add pkey to domain_admins.
_db_add_field('domain_admins', 'id', '{AUTOINCREMENT} {PRIMARY}'); _db_add_field('domain_admins', 'id', '{AUTOINCREMENT} {PRIMARY}');
} }

View File

@ -44,7 +44,8 @@ if ($context === 'admin' && !Config::read('forgotten_admin_password_reset') ||
die('Password reset is disabled by configuration option: forgotten_admin_password_reset or mailbox_postpassword_script'); die('Password reset is disabled by configuration option: forgotten_admin_password_reset or mailbox_postpassword_script');
} }
function sendCodebyEmail($to, $username, $code) { function sendCodebyEmail($to, $username, $code)
{
$url = getSiteUrl($_SERVER) . 'password-change.php?username=' . urlencode($username) . '&code=' . $code; $url = getSiteUrl($_SERVER) . 'password-change.php?username=' . urlencode($username) . '&code=' . $code;
return smtp_mail($to, return smtp_mail($to,
@ -54,7 +55,8 @@ function sendCodebyEmail($to, $username, $code) {
Config::lang_f('pPassword_recovery_email_body', $url)); Config::lang_f('pPassword_recovery_email_body', $url));
} }
function sendCodebySMS($to, $username, $code) { function sendCodebySMS($to, $username, $code)
{
$text = Config::lang_f('pPassword_recovery_sms_body', $code); $text = Config::lang_f('pPassword_recovery_sms_body', $code);
$function = Config::read('sms_send_function'); $function = Config::read('sms_send_function');

View File

@ -44,7 +44,8 @@ $server = new Zend_XmlRpc_Server();
* @param string $password * @param string $password
* @return boolean true on success, else false. * @return boolean true on success, else false.
*/ */
function login($username, $password) { function login($username, $password)
{
$login = new Login('mailbox'); $login = new Login('mailbox');
if ($login->login($username, $password)) { if ($login->login($username, $password)) {
session_regenerate_id(); session_regenerate_id();
@ -74,7 +75,8 @@ class UserProxy
* @param string $new_password * @param string $new_password
* @return boolean true on success * @return boolean true on success
*/ */
public function changePassword($old_password, $new_password) { public function changePassword($old_password, $new_password)
{
$uh = new MailboxHandler(); $uh = new MailboxHandler();
$username = $_SESSION['sessid']['username'] ?? ''; $username = $_SESSION['sessid']['username'] ?? '';
@ -100,7 +102,8 @@ class UserProxy
* @param string $password * @param string $password
* @return boolean true if successful. * @return boolean true if successful.
*/ */
public function login($username, $password) { public function login($username, $password)
{
$login = new Login('mailbox'); $login = new Login('mailbox');
return $login->login($username, $password); return $login->login($username, $password);
} }
@ -111,7 +114,8 @@ class VacationProxy
/** /**
* @return boolean true if the vacation is removed successfully. Else false. * @return boolean true if the vacation is removed successfully. Else false.
*/ */
public function remove() { public function remove()
{
$vh = new VacationHandler($_SESSION['sessid']['username']); $vh = new VacationHandler($_SESSION['sessid']['username']);
return $vh->remove(); return $vh->remove();
} }
@ -120,7 +124,8 @@ class VacationProxy
* @return boolean true if vacation stuff is enabled in this instance of postfixadmin * @return boolean true if vacation stuff is enabled in this instance of postfixadmin
* and the user has the ability to make changes to it. * and the user has the ability to make changes to it.
*/ */
public function isVacationSupported() { public function isVacationSupported()
{
$vh = new VacationHandler($_SESSION['sessid']['username']); $vh = new VacationHandler($_SESSION['sessid']['username']);
return $vh->vacation_supported(); return $vh->vacation_supported();
} }
@ -128,7 +133,8 @@ class VacationProxy
/** /**
* @return boolean true if the user has an active vacation record etc. * @return boolean true if the user has an active vacation record etc.
*/ */
public function checkVacation() { public function checkVacation()
{
$vh = new VacationHandler($_SESSION['sessid']['username']); $vh = new VacationHandler($_SESSION['sessid']['username']);
return $vh->check_vacation(); return $vh->check_vacation();
} }
@ -136,7 +142,8 @@ class VacationProxy
/** /**
* @return array|bool - either array of vacation details or boolean false if the user has none. * @return array|bool - either array of vacation details or boolean false if the user has none.
*/ */
public function getDetails() { public function getDetails()
{
$vh = new VacationHandler($_SESSION['sessid']['username']); $vh = new VacationHandler($_SESSION['sessid']['username']);
return $vh->get_details(); return $vh->get_details();
} }
@ -150,7 +157,8 @@ class VacationProxy
* @return boolean true on success. * @return boolean true on success.
* Whatiis @replyType?? for * Whatiis @replyType?? for
*/ */
public function setAway($subject, $body, $interval_time = 0, $activeFrom = '2000-01-01', $activeUntil = '2099-12-31') { public function setAway($subject, $body, $interval_time = 0, $activeFrom = '2000-01-01', $activeUntil = '2099-12-31')
{
$vh = new VacationHandler($_SESSION['sessid']['username']); $vh = new VacationHandler($_SESSION['sessid']['username']);
return $vh->set_away($subject, $body, $interval_time, $activeFrom, $activeUntil); return $vh->set_away($subject, $body, $interval_time, $activeFrom, $activeUntil);
} }
@ -161,7 +169,8 @@ class AliasProxy
/** /**
* @return array - array of aliases this user has. Array may be empty. * @return array - array of aliases this user has. Array may be empty.
*/ */
public function get() { public function get()
{
$ah = new AliasHandler(); $ah = new AliasHandler();
$ah->init($_SESSION['sessid']['username']); $ah->init($_SESSION['sessid']['username']);
/* I see no point in returning special addresses to the user. */ /* I see no point in returning special addresses to the user. */
@ -175,7 +184,8 @@ class AliasProxy
* @param string flag to set ('forward_and_store' or 'remote_only') * @param string flag to set ('forward_and_store' or 'remote_only')
* @return boolean true * @return boolean true
*/ */
public function update($addresses, $flags) { public function update($addresses, $flags)
{
$ah = new AliasHandler(); $ah = new AliasHandler();
$ah->init($_SESSION['sessid']['username']); $ah->init($_SESSION['sessid']['username']);
@ -201,7 +211,8 @@ class AliasProxy
* @return boolean true if the user has 'store_and_forward' set. * @return boolean true if the user has 'store_and_forward' set.
* (i.e. their email address is also in the alias table). IF it returns false, then it's 'remote_only' * (i.e. their email address is also in the alias table). IF it returns false, then it's 'remote_only'
*/ */
public function hasStoreAndForward() { public function hasStoreAndForward()
{
$ah = new AliasHandler(); $ah = new AliasHandler();
$ah->init($_SESSION['sessid']['username']); $ah->init($_SESSION['sessid']['username']);
$ah->view(); $ah->view();

View File

@ -110,7 +110,8 @@ class PostfixAdmin
* *
* @param array $args the argv. * @param array $args the argv.
*/ */
public function __construct($args = array()) { public function __construct($args = array())
{
set_time_limit(0); set_time_limit(0);
$this->__initConstants(); $this->__initConstants();
$this->parseParams($args); $this->parseParams($args);
@ -120,7 +121,8 @@ class PostfixAdmin
/** /**
* Defines core configuration. * Defines core configuration.
*/ */
private function __initConstants() { private function __initConstants()
{
ini_set('display_errors', '1'); ini_set('display_errors', '1');
ini_set('error_reporting', '' . E_ALL); ini_set('error_reporting', '' . E_ALL);
ini_set('html_errors', "0"); ini_set('html_errors', "0");
@ -131,7 +133,8 @@ class PostfixAdmin
/** /**
* Defines current working environment. * Defines current working environment.
*/ */
private function __initEnvironment() { private function __initEnvironment()
{
$this->stdin = fopen('php://stdin', 'r'); $this->stdin = fopen('php://stdin', 'r');
$this->stdout = fopen('php://stdout', 'w'); $this->stdout = fopen('php://stdout', 'w');
$this->stderr = fopen('php://stderr', 'w'); $this->stderr = fopen('php://stderr', 'w');
@ -152,7 +155,8 @@ class PostfixAdmin
* - and then a CliView object (Shell class) * - and then a CliView object (Shell class)
* - call CliView->view() ... which under the covers uses AdminHandler* * - call CliView->view() ... which under the covers uses AdminHandler*
*/ */
public function dispatch() { public function dispatch()
{
check_db_version(); # ensure the database layout is up to date check_db_version(); # ensure the database layout is up to date
if (!isset($this->args[0])) { if (!isset($this->args[0])) {
@ -264,7 +268,8 @@ class PostfixAdmin
* @param string $default Default input value. * @param string $default Default input value.
* @return string Either the default value, or the user-provided input. * @return string Either the default value, or the user-provided input.
*/ */
public function getInput($prompt, $options = null, $default = null) { public function getInput($prompt, $options = null, $default = null)
{
if (!is_array($options)) { if (!is_array($options)) {
$print_options = ''; $print_options = '';
} else { } else {
@ -295,7 +300,8 @@ class PostfixAdmin
* @param string $string String to output. * @param string $string String to output.
* @param boolean $newline If true, the outputs gets an added newline. * @param boolean $newline If true, the outputs gets an added newline.
*/ */
public function stdout($string, $newline = true) { public function stdout($string, $newline = true)
{
if ($newline) { if ($newline) {
fwrite($this->stdout, $string . "\n"); fwrite($this->stdout, $string . "\n");
} else { } else {
@ -308,7 +314,8 @@ class PostfixAdmin
* *
* @param string $string Error text to output. * @param string $string Error text to output.
*/ */
public function stderr($string) { public function stderr($string)
{
fwrite($this->stderr, 'Error: '. $string . "\n"); fwrite($this->stderr, 'Error: '. $string . "\n");
} }
@ -317,7 +324,8 @@ class PostfixAdmin
* *
* @param array $params Parameters to parse * @param array $params Parameters to parse
*/ */
public function parseParams($params) { public function parseParams($params)
{
$count = count($params); $count = count($params);
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
if ($params[$i] != '' && $params[$i][0] === '-' && $params[$i] != '-1') { if ($params[$i] != '' && $params[$i][0] === '-' && $params[$i] != '-1') {
@ -342,7 +350,8 @@ class PostfixAdmin
* *
* @return boolean False if there are no arguments * @return boolean False if there are no arguments
*/ */
public function shiftArgs() { public function shiftArgs()
{
if (empty($this->args)) { if (empty($this->args)) {
return false; return false;
} }
@ -354,7 +363,8 @@ class PostfixAdmin
/** /**
* prints help message and exits. * prints help message and exits.
*/ */
public function help() { public function help()
{
$this->stdout("\nWelcome to Postfixadmin-CLI v" . $this->version); $this->stdout("\nWelcome to Postfixadmin-CLI v" . $this->version);
$this->stdout("---------------------------------------------------------------"); $this->stdout("---------------------------------------------------------------");
$this->stdout("Usage:"); $this->stdout("Usage:");

View File

@ -16,18 +16,21 @@ class Crypt
protected $size; protected $size;
public function __construct($plaintext) { public function __construct($plaintext)
{
$this->plain = $plaintext; $this->plain = $plaintext;
} }
/** /**
* @return bool * @return bool
*/ */
public function crypt($algorithm) { public function crypt($algorithm)
{
return true; return true;
} }
public function get() { public function get()
{
return $this->password; return $this->password;
} }
} }

View File

@ -48,7 +48,8 @@ class DovecotCrypt extends Crypt
public function crypt($algorithm) { public function crypt($algorithm)
{
if (!array_key_exists($algorithm, $this->password_schemes)) { if (!array_key_exists($algorithm, $this->password_schemes)) {
$this->errormsg[] = "This password scheme isn't supported. Check our Wiki!"; $this->errormsg[] = "This password scheme isn't supported. Check our Wiki!";
return false; return false;
@ -62,7 +63,8 @@ class DovecotCrypt extends Crypt
return true; return true;
} }
public function verify($algorithm, $password) { public function verify($algorithm, $password)
{
if (!array_key_exists($algorithm, $this->password_schemes)) { if (!array_key_exists($algorithm, $this->password_schemes)) {
$this->errormsg[] = "This password scheme isn't supported. Check our Wiki!"; $this->errormsg[] = "This password scheme isn't supported. Check our Wiki!";
return false; return false;
@ -78,22 +80,28 @@ class DovecotCrypt extends Crypt
return $this->$func($this->plain, $password); return $this->$func($this->plain, $password);
} }
private function __crypt_verify($plaintext, $password) { private function __crypt_verify($plaintext, $password)
{
$crypted = crypt($plaintext, $password); $crypted = crypt($plaintext, $password);
return strcmp($crypted, $password) == 0; return strcmp($crypted, $password) == 0;
} }
private function __crypt_generate($plaintext) { private function __crypt_generate($plaintext)
{
$password = crypt($plaintext); $password = crypt($plaintext);
return $password; return $password;
} }
private function __md5_generate($plaintext) { private function __md5_generate($plaintext)
{
return $plaintext; return $plaintext;
} }
private function __sha1_generate() { private function __sha1_generate()
{
} }
private function __plain_generate() { private function __plain_generate()
{
} }
private function __cram_md5_generate($plaintext) { private function __cram_md5_generate($plaintext)
{
#http://hg.dovecot.org/dovecot-1.2/file/84373d238073/src/lib/hmac-md5.c #http://hg.dovecot.org/dovecot-1.2/file/84373d238073/src/lib/hmac-md5.c
#http://hg.dovecot.org/dovecot-1.2/file/84373d238073/src/auth/password-scheme.c cram_md5_generate #http://hg.dovecot.org/dovecot-1.2/file/84373d238073/src/auth/password-scheme.c cram_md5_generate
@ -110,7 +118,8 @@ class DovecotCrypt extends Crypt
/** /**
* @return string * @return string
*/ */
public function custom_hmac($algo, $data, $key, $raw_output = false) { public function custom_hmac($algo, $data, $key, $raw_output = false)
{
$algo = strtolower($algo); $algo = strtolower($algo);
$pack = 'H'.strlen($algo('test')); $pack = 'H'.strlen($algo('test'));
$size = 64; $size = 64;

View File

@ -2,12 +2,14 @@
class AdminHandlerTest extends \PHPUnit\Framework\TestCase class AdminHandlerTest extends \PHPUnit\Framework\TestCase
{ {
public function setUp() : void { public function setUp() : void
{
parent::setUp(); parent::setUp();
db_execute('DELETE FROM admin'); db_execute('DELETE FROM admin');
} }
public function testBasic() { public function testBasic()
{
$x = new AdminHandler(); $x = new AdminHandler();
$list = $x->getList(""); $list = $x->getList("");

View File

@ -2,7 +2,8 @@
class AdminpasswordHandlerTest extends \PHPUnit\Framework\TestCase class AdminpasswordHandlerTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$x = new AdminpasswordHandler(); $x = new AdminpasswordHandler();
$list = $x->getList(""); $list = $x->getList("");

View File

@ -2,7 +2,8 @@
class AliasHandlerTest extends \PHPUnit\Framework\TestCase class AliasHandlerTest extends \PHPUnit\Framework\TestCase
{ {
protected function setUp(): void { protected function setUp(): void
{
// Fake being an admin. // Fake being an admin.
$_SESSION = [ $_SESSION = [
'sessid' => [ 'sessid' => [
@ -12,7 +13,8 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase
parent::setUp(); parent::setUp();
} }
protected function tearDown(): void { protected function tearDown(): void
{
$_SESSION = []; $_SESSION = [];
db_query('DELETE FROM alias'); db_query('DELETE FROM alias');
db_query('DELETE FROM domain_admins'); db_query('DELETE FROM domain_admins');
@ -21,7 +23,8 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase
parent::tearDown(); parent::tearDown();
} }
public function testBasic() { public function testBasic()
{
$x = new AliasHandler(); $x = new AliasHandler();
$list = $x->getList(""); $list = $x->getList("");
$this->assertTrue($list); $this->assertTrue($list);
@ -30,7 +33,8 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase
} }
public function testCannotAddAliasUntilDomainIsThere() { public function testCannotAddAliasUntilDomainIsThere()
{
// Fake us being an admin. // Fake us being an admin.
@ -64,7 +68,8 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase
/** /**
* @see https://github.com/postfixadmin/postfixadmin/pull/375 and https://github.com/postfixadmin/postfixadmin/issues/358 * @see https://github.com/postfixadmin/postfixadmin/pull/375 and https://github.com/postfixadmin/postfixadmin/issues/358
*/ */
public function testCannotAddAliasThatPointsToItself() { public function testCannotAddAliasThatPointsToItself()
{
// Fake being an admin. // Fake being an admin.
$_SESSION = [ $_SESSION = [
'sessid' => [ 'sessid' => [
@ -147,7 +152,8 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase
], $x->errormsg); ], $x->errormsg);
} }
public function testAddingDataEtc() { public function testAddingDataEtc()
{
// Fake being an admin. // Fake being an admin.
$_SESSION = [ $_SESSION = [
@ -200,7 +206,8 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase
} }
private function addDomain(string $domain, string $username): void { private function addDomain(string $domain, string $username): void
{
// Fake being an admin. // Fake being an admin.
$_SESSION = [ $_SESSION = [
'sessid' => [ 'sessid' => [
@ -259,7 +266,8 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase
} }
} }
public function testYouCannotAddMoreAliasesThanTheDomainLimit() { public function testYouCannotAddMoreAliasesThanTheDomainLimit()
{
$this->addDomain('example.com', 'admin'); $this->addDomain('example.com', 'admin');
// default limit is 11 aliases.... so it should exit once we get past that. // default limit is 11 aliases.... so it should exit once we get past that.
@ -326,7 +334,8 @@ class AliasHandlerTest extends \PHPUnit\Framework\TestCase
} }
public function testLoadsOfAliasesGetHandledByPager() { public function testLoadsOfAliasesGetHandledByPager()
{
$this->addDomain('example.com', 'admin'); $this->addDomain('example.com', 'admin');
// default limit is 11 aliases.... so it should exit once we get past that. // default limit is 11 aliases.... so it should exit once we get past that.

View File

@ -2,7 +2,8 @@
class AliasdomainHandlerTest extends \PHPUnit\Framework\TestCase class AliasdomainHandlerTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$x = new AliasdomainHandler(); $x = new AliasdomainHandler();
$list = $x->getList(""); $list = $x->getList("");

View File

@ -6,7 +6,8 @@
*/ */
class CheckDomainTest extends \PHPUnit\Framework\TestCase class CheckDomainTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$this->assertEquals('', check_domain('example.com')); $this->assertEquals('', check_domain('example.com'));
$this->assertEquals('', check_domain('google.com')); $this->assertEquals('', check_domain('google.com'));
$this->assertRegExp('/ not discoverable in DNS/', check_domain('fishbeansblahblahblah' . uniqid() . '.com')); $this->assertRegExp('/ not discoverable in DNS/', check_domain('fishbeansblahblahblah' . uniqid() . '.com'));

View File

@ -5,7 +5,8 @@
*/ */
class CheckEmailTest extends \PHPUnit\Framework\TestCase class CheckEmailTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$this->assertEquals('', check_email('test@example.com')); $this->assertEquals('', check_email('test@example.com'));
$this->assertRegExp('/ not discoverable in DNS/', check_email('test@fishbeansblahblahblah' . uniqid() . '.com')); $this->assertRegExp('/ not discoverable in DNS/', check_email('test@fishbeansblahblahblah' . uniqid() . '.com'));
} }

View File

@ -2,7 +2,8 @@
class CheckLanguageTest extends \PHPUnit\Framework\TestCase class CheckLanguageTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
global $supported_languages; global $supported_languages;
$this->assertNotEmpty($supported_languages); $this->assertNotEmpty($supported_languages);
@ -22,7 +23,8 @@ class CheckLanguageTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('en', $lang); $this->assertEquals('en', $lang);
} }
public function testCookie() { public function testCookie()
{
global $supported_languages; global $supported_languages;
$this->assertNotEmpty($supported_languages); $this->assertNotEmpty($supported_languages);
@ -40,7 +42,8 @@ class CheckLanguageTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('en', $lang); $this->assertEquals('en', $lang);
} }
public function testPost() { public function testPost()
{
global $supported_languages; global $supported_languages;
$this->assertNotEmpty($supported_languages); $this->assertNotEmpty($supported_languages);

View File

@ -2,7 +2,8 @@
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, "there should be no entries in test.com as it's an invalid/non-existant domain");
} }

View File

@ -2,7 +2,8 @@
class ConfigTest extends \PHPUnit\Framework\TestCase class ConfigTest extends \PHPUnit\Framework\TestCase
{ {
public function setUp() : void { public function setUp() : void
{
$c = Config::getInstance(); $c = Config::getInstance();
$all = $c->getAll(); $all = $c->getAll();
@ -14,19 +15,22 @@ class ConfigTest extends \PHPUnit\Framework\TestCase
parent::setUp(); parent::setUp();
} }
public function testLangF() { public function testLangF()
{
$x = Config::lang_f('must_be_numeric', 'foo@bar'); $x = Config::lang_f('must_be_numeric', 'foo@bar');
$this->assertEquals('foo@bar must be numeric', $x); $this->assertEquals('foo@bar must be numeric', $x);
} }
public function testLang() { public function testLang()
{
$x = Config::lang('must_be_numeric', 'foo@bar'); $x = Config::lang('must_be_numeric', 'foo@bar');
$this->assertEquals('%s must be numeric', $x); $this->assertEquals('%s must be numeric', $x);
} }
public function testBool() { public function testBool()
{
$x = Config::bool('xmlrpc_enabled'); $x = Config::bool('xmlrpc_enabled');
$this->assertFalse($x); $this->assertFalse($x);

View File

@ -2,16 +2,19 @@
class CreatePageBrowserTest extends \PHPUnit\Framework\TestCase class CreatePageBrowserTest extends \PHPUnit\Framework\TestCase
{ {
public function tearDown() : void { public function tearDown() : void
{
$this->cleanup(); $this->cleanup();
} }
private function cleanup() { private function cleanup()
{
db_query('DELETE FROM mailbox WHERE domain = :domain', array('domain' => 'example.com')); db_query('DELETE FROM mailbox WHERE domain = :domain', array('domain' => 'example.com'));
db_query('DELETE FROM domain WHERE domain = :domain', array('domain' => 'example.com')); db_query('DELETE FROM domain WHERE domain = :domain', array('domain' => 'example.com'));
} }
public function testBasic() { public function testBasic()
{
global $CONF; global $CONF;
$CONF['page_size'] = 10; $CONF['page_size'] = 10;

View File

@ -4,14 +4,16 @@ class DbBasicTest extends \PHPUnit\Framework\TestCase
{ {
private $test_domain; private $test_domain;
public function setUp() : void { public function setUp() : void
{
$db = db_connect(); $db = db_connect();
$test_domain = 'test' . uniqid() . '.com'; $test_domain = 'test' . uniqid() . '.com';
$this->test_domain = $test_domain; $this->test_domain = $test_domain;
$db->exec("DELETE FROM domain WHERE domain = '$test_domain'"); $db->exec("DELETE FROM domain WHERE domain = '$test_domain'");
} }
public function testInsertDeleteDomain() { public function testInsertDeleteDomain()
{
$domain = $this->test_domain; $domain = $this->test_domain;
$username = 'testusername' . uniqid(); $username = 'testusername' . uniqid();

View File

@ -2,7 +2,8 @@
class DomainHandlerTest extends \PHPUnit\Framework\TestCase class DomainHandlerTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$x = new DomainHandler(); $x = new DomainHandler();
$list = $x->getList(""); $list = $x->getList("");
@ -14,7 +15,8 @@ class DomainHandlerTest extends \PHPUnit\Framework\TestCase
$this->assertEmpty($results); $this->assertEmpty($results);
} }
public function testAddAndUpdate() { public function testAddAndUpdate()
{
// Fake being an admin. // Fake being an admin.
$_SESSION = [ $_SESSION = [
'sessid' => [ 'sessid' => [

View File

@ -2,7 +2,8 @@
class FetchmailHandlerTest extends \PHPUnit\Framework\TestCase class FetchmailHandlerTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$x = new FetchmailHandler(); $x = new FetchmailHandler();
$list = $x->getList(""); $list = $x->getList("");

View File

@ -2,7 +2,8 @@
class GeneratePasswordTest extends \PHPUnit\Framework\TestCase class GeneratePasswordTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$one = generate_password(); $one = generate_password();
$two = generate_password(); $two = generate_password();
@ -13,7 +14,8 @@ class GeneratePasswordTest extends \PHPUnit\Framework\TestCase
$this->assertEquals(12, strlen($one)); $this->assertEquals(12, strlen($one));
} }
public function testLength() { public function testLength()
{
$one = generate_password(1); $one = generate_password(1);
$ten = generate_password(10); $ten = generate_password(10);

View File

@ -2,7 +2,8 @@
class GetSiteUrlTest extends \PHPUnit\Framework\TestCase class GetSiteUrlTest extends \PHPUnit\Framework\TestCase
{ {
public function testControlViaConfig() { public function testControlViaConfig()
{
$server = []; $server = [];
$orig = Config::getInstance()->getAll(); $orig = Config::getInstance()->getAll();
$orig['site_url'] = 'https://example.com/postfixadmin-1.2.3.4/'; $orig['site_url'] = 'https://example.com/postfixadmin-1.2.3.4/';
@ -11,7 +12,8 @@ class GetSiteUrlTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('https://example.com/postfixadmin-1.2.3.4/', getSiteUrl($server)); $this->assertEquals('https://example.com/postfixadmin-1.2.3.4/', getSiteUrl($server));
} }
public function testViaDiscovery() { public function testViaDiscovery()
{
$server = [ $server = [
'HTTP_HOST' => 'example.org', 'HTTP_HOST' => 'example.org',
'REQUEST_SCHEME' => 'https', 'REQUEST_SCHEME' => 'https',
@ -25,7 +27,8 @@ class GetSiteUrlTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('https://example.org/postfixadmin-1.2.3.4/', getSiteUrl($server)); $this->assertEquals('https://example.org/postfixadmin-1.2.3.4/', getSiteUrl($server));
} }
public function testViaDiscoveryNoPrefix() { public function testViaDiscoveryNoPrefix()
{
$server = [ $server = [
'HTTP_HOST' => 'example.org', 'HTTP_HOST' => 'example.org',
'REQUEST_SCHEME' => 'https', 'REQUEST_SCHEME' => 'https',
@ -39,7 +42,8 @@ class GetSiteUrlTest extends \PHPUnit\Framework\TestCase
$this->assertEquals('https://example.org/', getSiteUrl($server)); $this->assertEquals('https://example.org/', getSiteUrl($server));
} }
public function testViaDiscoveryhttp() { public function testViaDiscoveryhttp()
{
$server = [ $server = [
'HTTP_HOST' => 'example.org', 'HTTP_HOST' => 'example.org',
'REQUEST_SCHEME' => 'http', 'REQUEST_SCHEME' => 'http',

View File

@ -2,7 +2,8 @@
class ListAdminsTest extends \PHPUnit\Framework\TestCase class ListAdminsTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$list= list_admins(); $list= list_admins();
// may be empty, depending on db. // may be empty, depending on db.

View File

@ -2,7 +2,8 @@
class ListDomainsForAdminTest extends \PHPUnit\Framework\TestCase class ListDomainsForAdminTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$this->assertEquals([], list_domains_for_admin('test@test.com')); $this->assertEquals([], list_domains_for_admin('test@test.com'));
} }
} }

View File

@ -2,7 +2,8 @@
class ListDomainsTest extends \PHPUnit\Framework\TestCase class ListDomainsTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$domains = list_domains(); $domains = list_domains();
$this->assertTrue(is_array($domains)); $this->assertTrue(is_array($domains));

View File

@ -2,7 +2,8 @@
class LoginTest extends \PHPUnit\Framework\TestCase class LoginTest extends \PHPUnit\Framework\TestCase
{ {
public function setUp(): void { public function setUp(): void
{
global $CONF; global $CONF;
$this->cleanUp(); $this->cleanUp();
@ -27,12 +28,14 @@ class LoginTest extends \PHPUnit\Framework\TestCase
} }
public function tearDown(): void { public function tearDown(): void
{
$this->cleanUp(); $this->cleanUp();
parent::tearDown(); // TODO: Change the autogenerated stub parent::tearDown(); // TODO: Change the autogenerated stub
} }
private function cleanUp() { private function cleanUp()
{
db_query('DELETE FROM alias'); db_query('DELETE FROM alias');
db_query('DELETE FROM alias_domain'); db_query('DELETE FROM alias_domain');
db_query('DELETE FROM mailbox'); db_query('DELETE FROM mailbox');
@ -40,7 +43,8 @@ class LoginTest extends \PHPUnit\Framework\TestCase
db_query('DELETE FROM domain'); db_query('DELETE FROM domain');
} }
public function testPasswordchange() { public function testPasswordchange()
{
$login = new Login('mailbox'); $login = new Login('mailbox');
$this->assertTrue($login->login('test@example.com', 'foobar')); $this->assertTrue($login->login('test@example.com', 'foobar'));
@ -65,7 +69,8 @@ class LoginTest extends \PHPUnit\Framework\TestCase
} }
public function testInvalidUsers() { public function testInvalidUsers()
{
$login = new Login('mailbox'); $login = new Login('mailbox');
$this->assertFalse($login->login('test', 'password')); $this->assertFalse($login->login('test', 'password'));
@ -74,7 +79,8 @@ class LoginTest extends \PHPUnit\Framework\TestCase
} }
public function testEmptyStringWithDovecot() { public function testEmptyStringWithDovecot()
{
global $CONF; global $CONF;
if (!file_exists('/usr/bin/doveadm')) { if (!file_exists('/usr/bin/doveadm')) {
@ -100,7 +106,8 @@ class LoginTest extends \PHPUnit\Framework\TestCase
$this->assertFalse($l->login('test@fails.com', 'foobar')); $this->assertFalse($l->login('test@fails.com', 'foobar'));
} }
public function testValidLogin() { public function testValidLogin()
{
$login = new Login('mailbox'); $login = new Login('mailbox');
$this->assertFalse($login->login('test', 'password')); $this->assertFalse($login->login('test', 'password'));
@ -108,7 +115,8 @@ class LoginTest extends \PHPUnit\Framework\TestCase
$this->assertFalse($login->login('', '')); $this->assertFalse($login->login('', ''));
} }
public function testPasswordRecovery() { public function testPasswordRecovery()
{
$login = new Login('mailbox'); $login = new Login('mailbox');
$this->assertFalse($login->generatePasswordRecoveryCode('')); $this->assertFalse($login->generatePasswordRecoveryCode(''));
$this->assertFalse($login->generatePasswordRecoveryCode('doesnotexist')); $this->assertFalse($login->generatePasswordRecoveryCode('doesnotexist'));

View File

@ -2,7 +2,8 @@
class MailboxHandlerTest extends \PHPUnit\Framework\TestCase class MailboxHandlerTest extends \PHPUnit\Framework\TestCase
{ {
public function tearDown() : void { public function tearDown() : void
{
db_query('DELETE FROM mailbox'); db_query('DELETE FROM mailbox');
db_query('DELETE FROM alias'); db_query('DELETE FROM alias');
db_query('DELETE FROM domain_admins'); db_query('DELETE FROM domain_admins');
@ -11,14 +12,16 @@ class MailboxHandlerTest extends \PHPUnit\Framework\TestCase
parent::tearDown(); parent::tearDown();
} }
public function setUp() : void { public function setUp() : void
{
global $CONF; global $CONF;
parent::setUp(); parent::setUp();
$CONF['quota'] = 'YES'; $CONF['quota'] = 'YES';
} }
public function testBasic() { public function testBasic()
{
$x = new MailboxHandler(); $x = new MailboxHandler();
$list = $x->getList(""); $list = $x->getList("");
@ -31,7 +34,8 @@ class MailboxHandlerTest extends \PHPUnit\Framework\TestCase
} }
public function testAddingDataEtc() { public function testAddingDataEtc()
{
// Fake being an admin. // Fake being an admin.
$_SESSION = [ $_SESSION = [

View File

@ -2,7 +2,8 @@
class PaCryptTest extends \PHPUnit\Framework\TestCase class PaCryptTest extends \PHPUnit\Framework\TestCase
{ {
public function testMd5Crypt() { public function testMd5Crypt()
{
$hash = _pacrypt_md5crypt('test', ''); $hash = _pacrypt_md5crypt('test', '');
$this->assertNotEmpty($hash); $this->assertNotEmpty($hash);
@ -11,7 +12,8 @@ class PaCryptTest extends \PHPUnit\Framework\TestCase
$this->assertEquals($hash, _pacrypt_md5crypt('test', $hash)); $this->assertEquals($hash, _pacrypt_md5crypt('test', $hash));
} }
public function testCrypt() { public function testCrypt()
{
// E_NOTICE if we pass in '' for the salt // E_NOTICE if we pass in '' for the salt
$hash = _pacrypt_crypt('test', 'sa'); $hash = _pacrypt_crypt('test', 'sa');
@ -21,7 +23,8 @@ class PaCryptTest extends \PHPUnit\Framework\TestCase
$this->assertEquals($hash, _pacrypt_crypt('test', $hash)); $this->assertEquals($hash, _pacrypt_crypt('test', $hash));
} }
public function testMySQLEncrypt() { public function testMySQLEncrypt()
{
if (!db_mysql()) { if (!db_mysql()) {
$this->markTestSkipped('Not using MySQL'); $this->markTestSkipped('Not using MySQL');
} }
@ -39,7 +42,8 @@ class PaCryptTest extends \PHPUnit\Framework\TestCase
$this->assertTrue( hash_equals($hash, _pacrypt_mysql_encrypt('test1', $hash) ), "hashes should equal...."); $this->assertTrue( hash_equals($hash, _pacrypt_mysql_encrypt('test1', $hash) ), "hashes should equal....");
} }
public function testAuthlib() { public function testAuthlib()
{
global $CONF; global $CONF;
// too many options! // too many options!
@ -61,7 +65,8 @@ class PaCryptTest extends \PHPUnit\Framework\TestCase
} }
} }
public function testPacryptDovecot() { public function testPacryptDovecot()
{
global $CONF; global $CONF;
if (!file_exists('/usr/bin/doveadm')) { if (!file_exists('/usr/bin/doveadm')) {
$this->markTestSkipped("No /usr/bin/doveadm"); $this->markTestSkipped("No /usr/bin/doveadm");
@ -84,7 +89,8 @@ class PaCryptTest extends \PHPUnit\Framework\TestCase
$this->assertNotEquals($sha512, _pacrypt_dovecot('foobarbaz', $sha512)); $this->assertNotEquals($sha512, _pacrypt_dovecot('foobarbaz', $sha512));
} }
public function testPhpCrypt() { public function testPhpCrypt()
{
$config = Config::getInstance(); $config = Config::getInstance();
Config::write('encrypt', 'php_crypt:MD5'); Config::write('encrypt', 'php_crypt:MD5');
@ -100,7 +106,8 @@ class PaCryptTest extends \PHPUnit\Framework\TestCase
$fail = _pacrypt_php_crypt('bar', $expected); $fail = _pacrypt_php_crypt('bar', $expected);
} }
public function testPhpCryptHandlesPrefixAndOrRounds() { public function testPhpCryptHandlesPrefixAndOrRounds()
{
// try with 1000 rounds // try with 1000 rounds
Config::write('encrypt', 'php_crypt:SHA256:1000'); Config::write('encrypt', 'php_crypt:SHA256:1000');
$password = 'hello'; $password = 'hello';
@ -133,7 +140,8 @@ class PaCryptTest extends \PHPUnit\Framework\TestCase
$this->assertGreaterThan(20, strlen($enc)); $this->assertGreaterThan(20, strlen($enc));
} }
public function testPhpCryptRandomString() { public function testPhpCryptRandomString()
{
$str1 = _php_crypt_random_string('abcdefg123456789', 2); $str1 = _php_crypt_random_string('abcdefg123456789', 2);
$str2 = _php_crypt_random_string('abcdefg123456789', 2); $str2 = _php_crypt_random_string('abcdefg123456789', 2);
$str3 = _php_crypt_random_string('abcdefg123456789', 2); $str3 = _php_crypt_random_string('abcdefg123456789', 2);
@ -147,7 +155,8 @@ class PaCryptTest extends \PHPUnit\Framework\TestCase
$this->assertFalse(strcmp($str1, $str2) == 0 && strcmp($str1, $str3) == 0); $this->assertFalse(strcmp($str1, $str2) == 0 && strcmp($str1, $str3) == 0);
} }
public function testSha512B64() { public function testSha512B64()
{
$str1 = _pacrypt_sha512_b64('test', ''); $str1 = _pacrypt_sha512_b64('test', '');
$str2 = _pacrypt_sha512_b64('test', ''); $str2 = _pacrypt_sha512_b64('test', '');

View File

@ -2,7 +2,8 @@
class PasswordValidationCallableTEst extends \PHPUnit\Framework\TestCase class PasswordValidationCallableTEst extends \PHPUnit\Framework\TestCase
{ {
public function setUp(): void { public function setUp(): void
{
$c = Config::getInstance(); $c = Config::getInstance();
$all = $c->getAll(); $all = $c->getAll();
@ -20,7 +21,8 @@ class PasswordValidationCallableTEst extends \PHPUnit\Framework\TestCase
parent::setUp(); parent::setUp();
} }
public function testBasic() { public function testBasic()
{
// anything except 'fail' should work. // anything except 'fail' should work.
$this->assertEmpty(validate_password('str')); $this->assertEmpty(validate_password('str'));
$this->assertEquals([], validate_password('1234asdf')); $this->assertEquals([], validate_password('1234asdf'));

View File

@ -9,21 +9,25 @@ require_once('RemoteTest.php');
class RemoteAliasTest extends RemoteTest class RemoteAliasTest extends RemoteTest
{ {
public function __construct() { public function __construct()
{
parent::__construct(); parent::__construct();
global $CONF; global $CONF;
} }
public function testGet() { public function testGet()
{
/* although we created an alias record, for users, this isn't returned... */ /* although we created an alias record, for users, this isn't returned... */
$this->assertEquals($this->alias->get(), array()); $this->assertEquals($this->alias->get(), array());
} }
public function testHasStoreAndForward() { public function testHasStoreAndForward()
{
$this->assertTrue($this->alias->hasStoreAndForward()); $this->assertTrue($this->alias->hasStoreAndForward());
} }
public function testUpdateRemoteOnly() { public function testUpdateRemoteOnly()
{
$this->assertTrue($this->alias->update(array('roger@rabbit.com'), 'remote_only')); $this->assertTrue($this->alias->update(array('roger@rabbit.com'), 'remote_only'));
$this->assertFalse($this->alias->hasStoreAndForward()); $this->assertFalse($this->alias->hasStoreAndForward());
$this->assertTrue($this->alias->update(array('roger@rabbit.com'), 'remote_only')); $this->assertTrue($this->alias->update(array('roger@rabbit.com'), 'remote_only'));
@ -32,7 +36,8 @@ class RemoteAliasTest extends RemoteTest
$this->assertFalse($this->alias->hasStoreAndForward()); $this->assertFalse($this->alias->hasStoreAndForward());
} }
public function testUpdateForwardandStore() { public function testUpdateForwardandStore()
{
$orig_aliases = $this->alias->get(); $orig_aliases = $this->alias->get();
if (!is_array($orig_aliases)) { if (!is_array($orig_aliases)) {
$orig_aliases = array(); $orig_aliases = array();

View File

@ -13,7 +13,8 @@ abstract class RemoteTest extends \PHPUnit\Framework\TestCase
protected $xmlrpc_client; protected $xmlrpc_client;
public function setUp() : void { public function setUp() : void
{
parent::setUp(); parent::setUp();
if ($this->server_url == 'http://change.me/to/work') { if ($this->server_url == 'http://change.me/to/work') {

View File

@ -9,7 +9,8 @@ require_once('RemoteTest.php');
class RemoteUserTest extends RemoteTest class RemoteUserTest extends RemoteTest
{ {
public function testChangePassword() { public function testChangePassword()
{
$this->assertTrue($this->user->login($this->username, $this->password)); $this->assertTrue($this->user->login($this->username, $this->password));
$this->assertTrue($this->user->changePassword($this->password, 'foobar')); $this->assertTrue($this->user->changePassword($this->password, 'foobar'));
$this->assertTrue($this->user->login($this->username, 'foobar')); $this->assertTrue($this->user->login($this->username, 'foobar'));

View File

@ -14,7 +14,8 @@ class RemoteVacationTest extends RemoteTest
/** /**
* Adds the test recipient data to the database. * Adds the test recipient data to the database.
*/ */
public function setUp() : void { public function setUp() : void
{
// Ensure config.inc.php is vaguely correct. // Ensure config.inc.php is vaguely correct.
global $CONF; global $CONF;
if ($CONF['vacation'] != 'YES' || $CONF['vacation_control'] != "YES") { if ($CONF['vacation'] != 'YES' || $CONF['vacation_control'] != "YES") {
@ -26,21 +27,25 @@ class RemoteVacationTest extends RemoteTest
parent::setUp(); parent::setUp();
} }
public function testIsVacationSupported() { public function testIsVacationSupported()
{
$this->assertTrue($this->vacation->isVacationSupported()); $this->assertTrue($this->vacation->isVacationSupported());
} }
public function testCheckVacation() { public function testCheckVacation()
{
$this->assertFalse($this->vacation->checkVacation()); $this->assertFalse($this->vacation->checkVacation());
} }
public function testGetDetails() { public function testGetDetails()
{
$details = $this->vacation->getDetails(); $details = $this->vacation->getDetails();
$this->assertFalse($details); // empty by default (thanks to tearDown/setUp); $this->assertFalse($details); // empty by default (thanks to tearDown/setUp);
} }
public function testSetAway() { public function testSetAway()
{
$this->assertFalse($this->vacation->checkVacation()); $this->assertFalse($this->vacation->checkVacation());
$this->assertTrue($this->vacation->setAway('zzzz', 'aaaa')); $this->assertTrue($this->vacation->setAway('zzzz', 'aaaa'));
$this->assertTrue($this->vacation->checkVacation()); $this->assertTrue($this->vacation->checkVacation());

View File

@ -2,7 +2,8 @@
class RemoveFromArrayTest extends \PHPUnit\Framework\TestCase class RemoveFromArrayTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$list = array('a','b','c','d'); $list = array('a','b','c','d');
list($found, $new) = remove_from_array($list, 'd'); list($found, $new) = remove_from_array($list, 'd');

View File

@ -2,7 +2,8 @@
class ValidatePasswordTest extends \PHPUnit\Framework\TestCase class ValidatePasswordTest extends \PHPUnit\Framework\TestCase
{ {
public function testBasic() { public function testBasic()
{
$config = Config::getInstance(); $config = Config::getInstance();
// Set to the defaults, just to make sure. // Set to the defaults, just to make sure.